Abhisesh7 commited on
Commit
84cc777
·
verified ·
1 Parent(s): 9d22c7a

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +66 -71
app.py CHANGED
@@ -1,102 +1,97 @@
1
  import yfinance as yf
2
- import pandas as pd
3
  import numpy as np
 
 
4
  from sklearn.preprocessing import MinMaxScaler
5
- from tensorflow.keras.models import Sequential
6
- from tensorflow.keras.layers import LSTM, Dense
7
- import matplotlib.pyplot as plt
8
  import gradio as gr
 
 
 
 
9
 
10
- # Fetch stock data from Yahoo Finance
11
- def get_stock_data(ticker, start_date, end_date):
 
12
  stock_data = yf.download(ticker, start=start_date, end=end_date)
 
 
13
  if stock_data.empty:
14
- raise ValueError("No data found for the given ticker and date range.")
15
- return stock_data
16
-
17
- # Preprocess stock data
18
- def preprocess_data(stock_data):
19
- scaler = MinMaxScaler(feature_range=(0, 1)) # Normalizing the close prices
20
- scaled_data = scaler.fit_transform(stock_data[['Close']].values)
21
- return scaled_data, scaler
22
-
23
- # Define and train an LSTM model
24
- def create_lstm_model(input_shape):
25
- model = Sequential()
26
- model.add(LSTM(units=50, return_sequences=True, input_shape=input_shape))
27
- model.add(LSTM(units=50))
28
- model.add(Dense(units=1)) # Predicting stock price
29
- model.compile(optimizer='adam', loss='mean_squared_error')
30
- return model
31
-
32
- # Prepare data for training the model
33
- def train_model(stock_data, window_size=60):
34
- X_train, y_train = [], []
35
- for i in range(window_size, len(stock_data)):
36
- X_train.append(stock_data[i-window_size:i, 0])
37
- y_train.append(stock_data[i, 0])
38
- X_train, y_train = np.array(X_train), np.array(y_train)
39
- X_train = X_train.reshape((X_train.shape[0], X_train.shape[1], 1))
40
-
41
- model = create_lstm_model((X_train.shape[1], 1))
42
- model.fit(X_train, y_train, epochs=10, batch_size=32)
43
- return model
44
-
45
- # Predict future stock prices
46
- def predict_future_prices(model, scaler, recent_data, days_to_predict=90):
47
- predictions = []
48
- input_data = recent_data[-60:].reshape(1, 60, 1)
49
- for _ in range(days_to_predict):
50
- pred_price = model.predict(input_data)[0, 0]
51
- predictions.append(pred_price)
52
- input_data = np.append(input_data[:, 1:, :], [[pred_price]], axis=1)
53
 
54
- predicted_prices = scaler.inverse_transform(np.array(predictions).reshape(-1, 1))
55
- return predicted_prices
 
 
 
 
 
 
 
56
 
57
- # Gradio function to predict stock prices and display results
58
- def stock_prediction_app(ticker, start_date, end_date):
59
- stock_data = get_stock_data(ticker, start_date, end_date)
60
- scaled_data, scaler = preprocess_data(stock_data)
61
 
62
- # Train the model on the selected stock data
63
- model = train_model(scaled_data)
 
 
 
 
 
64
 
65
- # Make predictions for the next 90 days
66
- future_prices = predict_future_prices(model, scaler, scaled_data)
67
 
68
- # Plot the historical and future stock prices
69
- plt.figure(figsize=(10, 6))
70
- plt.plot(stock_data.index, stock_data['Close'], label='Historical Prices')
71
- future_dates = pd.date_range(end=stock_data.index[-1], periods=90)
72
- plt.plot(future_dates, future_prices, label='Predicted Prices', linestyle='--')
 
 
 
 
 
 
73
  plt.title(f'{ticker} Stock Price Prediction')
74
- plt.xlabel('Date')
75
- plt.ylabel('Price')
76
  plt.legend()
77
- plt.savefig('stock_prediction.png')
78
 
79
- return f"The predicted stock price for the next 3 months is shown in the graph.", 'stock_prediction.png'
 
80
 
81
- # Define Gradio interface
82
- tickers = ['AAPL', 'MSFT', 'GOOGL', 'TSLA', 'AMZN', 'FB', 'NFLX', 'NVDA', 'INTC', 'IBM']
83
 
 
84
  app = gr.Blocks()
85
 
86
  with app:
87
  gr.Markdown("# Stock Buy/Sell Prediction App")
88
 
89
- ticker = gr.Dropdown(tickers, label="Select Stock Ticker") # Dropdown for stock tickers
90
- start_date = gr.DatePicker(label="Start Date") # Use DatePicker for selecting dates
91
- end_date = gr.DatePicker(label="End Date") # Use DatePicker for selecting dates
92
 
 
 
 
 
 
93
  predict_button = gr.Button("Predict")
94
 
 
95
  output_text = gr.Textbox(label="Prediction Result")
96
  output_image = gr.Image(label="Stock Price Graph")
97
 
 
98
  predict_button.click(fn=stock_prediction_app, inputs=[ticker, start_date, end_date], outputs=[output_text, output_image])
99
 
 
100
  app.launch()
101
- start_date = gr.Textbox(label="Start Date (YYYY-MM-DD)") # Textbox for manually entering dates
102
- end_date = gr.Textbox(label="End Date (YYYY-MM-DD)") # Textbox for manually entering dates
 
1
  import yfinance as yf
 
2
  import numpy as np
3
+ import pandas as pd
4
+ import tensorflow as tf
5
  from sklearn.preprocessing import MinMaxScaler
 
 
 
6
  import gradio as gr
7
+ import matplotlib.pyplot as plt
8
+
9
+ # Define stock tickers for the dropdown
10
+ tickers = ['AAPL', 'MSFT', 'GOOGL', 'TSLA', 'AMZN', 'FB', 'NFLX', 'NVDA', 'INTC', 'IBM']
11
 
12
+ # Function to fetch stock data and make predictions
13
+ def stock_prediction_app(ticker, start_date, end_date):
14
+ # Fetch historical stock data from Yahoo Finance
15
  stock_data = yf.download(ticker, start=start_date, end=end_date)
16
+
17
+ # Check if data is fetched correctly
18
  if stock_data.empty:
19
+ return "No data available for the selected date range.", None
20
+
21
+ # Prepare the data for LSTM model
22
+ df_close = stock_data[['Close']] # Use only the 'Close' column for prediction
23
+ scaler = MinMaxScaler(feature_range=(0, 1))
24
+ scaled_data = scaler.fit_transform(df_close)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
25
 
26
+ # Create datasets for training the LSTM model
27
+ def create_dataset(data, time_step=60):
28
+ X_train, y_train = [], []
29
+ for i in range(len(data)-time_step-1):
30
+ X_train.append(data[i:(i+time_step), 0])
31
+ y_train.append(data[i + time_step, 0])
32
+ return np.array(X_train), np.array(y_train)
33
+
34
+ X_train, y_train = create_dataset(scaled_data)
35
 
36
+ # Reshape the data for LSTM [samples, time steps, features]
37
+ X_train = X_train.reshape(X_train.shape[0], X_train.shape[1], 1)
 
 
38
 
39
+ # Define LSTM model
40
+ lstm_model = tf.keras.Sequential([
41
+ tf.keras.layers.LSTM(50, return_sequences=True, input_shape=(60, 1)),
42
+ tf.keras.layers.LSTM(50, return_sequences=False),
43
+ tf.keras.layers.Dense(25),
44
+ tf.keras.layers.Dense(1)
45
+ ])
46
 
47
+ # Compile the model
48
+ lstm_model.compile(optimizer='adam', loss='mean_squared_error')
49
 
50
+ # Train the model
51
+ lstm_model.fit(X_train, y_train, batch_size=1, epochs=1)
52
+
53
+ # Predict on the same data (just for demonstration)
54
+ predictions = lstm_model.predict(X_train)
55
+ predictions = scaler.inverse_transform(predictions) # Convert back to original scale
56
+
57
+ # Create a plot to show predictions
58
+ plt.figure(figsize=(10, 5))
59
+ plt.plot(df_close.values, label='Actual Stock Price')
60
+ plt.plot(predictions, label='Predicted Stock Price')
61
  plt.title(f'{ticker} Stock Price Prediction')
62
+ plt.xlabel('Days')
63
+ plt.ylabel('Stock Price')
64
  plt.legend()
 
65
 
66
+ # Save the plot to display in Gradio app
67
+ plt.savefig('stock_prediction_plot.png')
68
 
69
+ # Return a message and the path to the saved plot
70
+ return f"Prediction complete for {ticker} from {start_date} to {end_date}", 'stock_prediction_plot.png'
71
 
72
+ # Create the Gradio UI for the app
73
  app = gr.Blocks()
74
 
75
  with app:
76
  gr.Markdown("# Stock Buy/Sell Prediction App")
77
 
78
+ # Dropdown for stock tickers
79
+ ticker = gr.Dropdown(tickers, label="Select Stock Ticker")
 
80
 
81
+ # Textboxes for manual date input
82
+ start_date = gr.Textbox(label="Start Date (YYYY-MM-DD)")
83
+ end_date = gr.Textbox(label="End Date (YYYY-MM-DD)")
84
+
85
+ # Button to trigger the prediction
86
  predict_button = gr.Button("Predict")
87
 
88
+ # Output fields for text and image
89
  output_text = gr.Textbox(label="Prediction Result")
90
  output_image = gr.Image(label="Stock Price Graph")
91
 
92
+ # Set up button click event to run the prediction function
93
  predict_button.click(fn=stock_prediction_app, inputs=[ticker, start_date, end_date], outputs=[output_text, output_image])
94
 
95
+ # Launch the Gradio app
96
  app.launch()
97
+