Abhisesh7 commited on
Commit
f2f0925
·
verified ·
1 Parent(s): c447ebf

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +69 -56
app.py CHANGED
@@ -1,104 +1,117 @@
1
  import yfinance as yf
2
  import pandas as pd
3
- import numpy as np
4
- import matplotlib.pyplot as plt
5
- from sklearn.preprocessing import MinMaxScaler
6
- from tensorflow.keras.models import Sequential
7
- from tensorflow.keras.layers import Dense, LSTM
8
 
9
- # Fetch stock data using yfinance
10
  def get_stock_data(ticker, start_date, end_date):
11
  stock_data = yf.download(ticker, start=start_date, end=end_date)
 
 
12
  return stock_data
13
 
14
- # Example usage:
15
  ticker = 'AAPL'
16
- start_date = '2022-01-01'
17
- end_date = '2023-01-01'
18
- stock_data = get_stock_data(ticker, start_date, end_date)
19
- print(stock_data.head())
20
- def preprocess_data(data):
21
- scaler = MinMaxScaler(feature_range=(0, 1))
22
- scaled_data = scaler.fit_transform(data[['Close']].values)
23
- return scaled_data, scaler
24
 
25
  # Preprocess stock data
26
- scaled_data, scaler = preprocess_data(stock_data)
 
 
 
 
 
 
 
 
 
 
27
  def create_lstm_model(input_shape):
28
  model = Sequential()
29
  model.add(LSTM(units=50, return_sequences=True, input_shape=input_shape))
30
  model.add(LSTM(units=50))
31
- model.add(Dense(units=1)) # Predict the stock price
32
  model.compile(optimizer='adam', loss='mean_squared_error')
33
  return model
34
 
35
- # Train the LSTM model
36
  def train_model(stock_data, window_size=60):
37
  X_train, y_train = [], []
38
  for i in range(window_size, len(stock_data)):
39
  X_train.append(stock_data[i-window_size:i, 0])
40
  y_train.append(stock_data[i, 0])
41
  X_train, y_train = np.array(X_train), np.array(y_train)
42
- X_train = np.reshape(X_train, (X_train.shape[0], X_train.shape[1], 1))
43
-
44
  model = create_lstm_model((X_train.shape[1], 1))
45
- model.fit(X_train, y_train, epochs=5, batch_size=32)
46
-
47
  return model
48
 
49
- # Train and prepare the model
50
- model = train_model(scaled_data)
51
- def make_prediction(model, scaler, stock_data, last_data, prediction_days=90):
52
- # Prepare last data for prediction
53
- input_data = last_data[-60:].reshape(1, 60, 1)
54
- predicted_prices = []
55
-
56
- for _ in range(prediction_days):
57
- predicted_price = model.predict(input_data)
58
- predicted_prices.append(predicted_price[0, 0])
59
- input_data = np.append(input_data[:, 1:], [[predicted_price]], axis=1)
60
-
61
- # Rescale to original prices
62
- predicted_prices = scaler.inverse_transform(np.array(predicted_prices).reshape(-1, 1))
63
  return predicted_prices
64
 
65
- # Predict future prices
66
- last_data = scaled_data[-60:] # Last 60 days data
67
- future_prices = make_prediction(model, scaler, scaled_data, last_data)
68
  import gradio as gr
 
69
 
70
- def predict_stock(ticker, start_date, end_date):
 
71
  stock_data = get_stock_data(ticker, start_date, end_date)
72
  scaled_data, scaler = preprocess_data(stock_data)
 
 
73
  model = train_model(scaled_data)
74
- future_prices = make_prediction(model, scaler, scaled_data, scaled_data[-60:])
75
 
76
- # Generate a plot of historical and future prices
77
- plt.figure(figsize=(14,5))
78
- plt.plot(stock_data['Close'], label='Historical Prices')
79
- future_dates = pd.date_range(end=end_date, periods=90, freq='B')
 
 
 
80
  plt.plot(future_dates, future_prices, label='Predicted Prices', linestyle='--')
81
- plt.title(f"Stock Prices for {ticker}")
82
  plt.xlabel('Date')
83
  plt.ylabel('Price')
84
  plt.legend()
85
- plt.savefig('stock_plot.png')
86
- return future_prices, 'stock_plot.png'
 
87
 
88
- # Define UI components
89
  tickers = ['AAPL', 'MSFT', 'GOOGL', 'TSLA', 'AMZN', 'FB', 'NFLX', 'NVDA', 'INTC', 'IBM']
90
- with gr.Blocks() as app:
91
- gr.Markdown("## Stock Buy/Sell Prediction App")
 
 
 
92
 
93
- ticker = gr.Dropdown(tickers, label="Stock Ticker")
94
  start_date = gr.Date(label="Start Date")
95
  end_date = gr.Date(label="End Date")
96
 
97
- predict_btn = gr.Button("Predict")
98
 
99
- predicted_values = gr.Textbox(label="Predicted Stock Values")
100
- stock_plot = gr.Image(label="Stock Performance Graph")
101
 
102
- predict_btn.click(fn=predict_stock, inputs=[ticker, start_date, end_date], outputs=[predicted_values, stock_plot])
103
 
104
  app.launch()
 
1
  import yfinance as yf
2
  import pandas as pd
 
 
 
 
 
3
 
4
+ # Fetch stock data from Yahoo Finance
5
  def get_stock_data(ticker, start_date, end_date):
6
  stock_data = yf.download(ticker, start=start_date, end=end_date)
7
+ if stock_data.empty:
8
+ raise ValueError("No data found for the given ticker and date range.")
9
  return stock_data
10
 
11
+ # Example usage
12
  ticker = 'AAPL'
13
+ start_date = '2023-01-01'
14
+ end_date = '2024-01-01'
15
+ data = get_stock_data(ticker, start_date, end_date)
16
+ print(data.head())
17
+ from sklearn.preprocessing import MinMaxScaler
 
 
 
18
 
19
  # Preprocess stock data
20
+ def preprocess_data(stock_data):
21
+ scaler = MinMaxScaler(feature_range=(0, 1)) # Normalizing the close prices
22
+ scaled_data = scaler.fit_transform(stock_data[['Close']].values)
23
+ return scaled_data, scaler
24
+
25
+ # Preprocess the stock data
26
+ scaled_data, scaler = preprocess_data(data)
27
+ from tensorflow.keras.models import Sequential
28
+ from tensorflow.keras.layers import LSTM, Dense
29
+
30
+ # Define and train an LSTM model
31
  def create_lstm_model(input_shape):
32
  model = Sequential()
33
  model.add(LSTM(units=50, return_sequences=True, input_shape=input_shape))
34
  model.add(LSTM(units=50))
35
+ model.add(Dense(units=1)) # Predicting stock price
36
  model.compile(optimizer='adam', loss='mean_squared_error')
37
  return model
38
 
39
+ # Prepare data for training the model
40
  def train_model(stock_data, window_size=60):
41
  X_train, y_train = [], []
42
  for i in range(window_size, len(stock_data)):
43
  X_train.append(stock_data[i-window_size:i, 0])
44
  y_train.append(stock_data[i, 0])
45
  X_train, y_train = np.array(X_train), np.array(y_train)
46
+ X_train = X_train.reshape((X_train.shape[0], X_train.shape[1], 1))
47
+
48
  model = create_lstm_model((X_train.shape[1], 1))
49
+ model.fit(X_train, y_train, epochs=10, batch_size=32)
 
50
  return model
51
 
52
+ # Train the LSTM model
53
+ lstm_model = train_model(scaled_data)
54
+ import numpy as np
55
+
56
+ def predict_future_prices(model, scaler, recent_data, days_to_predict=90):
57
+ predictions = []
58
+ input_data = recent_data[-60:].reshape(1, 60, 1) # Using the last 60 days to predict
59
+ for _ in range(days_to_predict):
60
+ pred_price = model.predict(input_data)[0, 0]
61
+ predictions.append(pred_price)
62
+ input_data = np.append(input_data[:, 1:, :], [[pred_price]], axis=1)
63
+
64
+ # Inverse transform to get the original prices
65
+ predicted_prices = scaler.inverse_transform(np.array(predictions).reshape(-1, 1))
66
  return predicted_prices
67
 
68
+ # Predict future stock prices
69
+ recent_data = scaled_data[-60:]
70
+ future_prices = predict_future_prices(lstm_model, scaler, recent_data)
71
  import gradio as gr
72
+ import matplotlib.pyplot as plt
73
 
74
+ # Gradio function to predict stock prices and display results
75
+ def stock_prediction_app(ticker, start_date, end_date):
76
  stock_data = get_stock_data(ticker, start_date, end_date)
77
  scaled_data, scaler = preprocess_data(stock_data)
78
+
79
+ # Train the model on the selected stock data
80
  model = train_model(scaled_data)
 
81
 
82
+ # Make predictions for the next 90 days
83
+ future_prices = predict_future_prices(model, scaler, scaled_data)
84
+
85
+ # Plot the historical and future stock prices
86
+ plt.figure(figsize=(10, 6))
87
+ plt.plot(stock_data.index, stock_data['Close'], label='Historical Prices')
88
+ future_dates = pd.date_range(end=stock_data.index[-1], periods=90)
89
  plt.plot(future_dates, future_prices, label='Predicted Prices', linestyle='--')
90
+ plt.title(f'{ticker} Stock Price Prediction')
91
  plt.xlabel('Date')
92
  plt.ylabel('Price')
93
  plt.legend()
94
+ plt.savefig('stock_prediction.png')
95
+
96
+ return f"The predicted stock price for the next 3 months is shown in the graph.", 'stock_prediction.png'
97
 
98
+ # Define Gradio interface
99
  tickers = ['AAPL', 'MSFT', 'GOOGL', 'TSLA', 'AMZN', 'FB', 'NFLX', 'NVDA', 'INTC', 'IBM']
100
+
101
+ app = gr.Blocks()
102
+
103
+ with app:
104
+ gr.Markdown("# Stock Buy/Sell Prediction App")
105
 
106
+ ticker = gr.Dropdown(tickers, label="Select Stock Ticker")
107
  start_date = gr.Date(label="Start Date")
108
  end_date = gr.Date(label="End Date")
109
 
110
+ predict_button = gr.Button("Predict")
111
 
112
+ output_text = gr.Textbox(label="Prediction Result")
113
+ output_image = gr.Image(label="Stock Price Graph")
114
 
115
+ predict_button.click(fn=stock_prediction_app, inputs=[ticker, start_date, end_date], outputs=[output_text, output_image])
116
 
117
  app.launch()