Abhisesh7 commited on
Commit
45a55d4
·
verified ·
1 Parent(s): cc21881

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +63 -59
app.py CHANGED
@@ -1,96 +1,100 @@
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()
 
1
+ import gradio as gr
2
  import numpy as np
3
  import pandas as pd
4
+ import yfinance as yf
 
 
5
  import matplotlib.pyplot as plt
6
+ from sklearn.preprocessing import MinMaxScaler
7
+ from tensorflow.keras.models import Sequential
8
+ from tensorflow.keras.layers import LSTM, Dense
9
 
10
+ # Define the available stock tickers
11
  tickers = ['AAPL', 'MSFT', 'GOOGL', 'TSLA', 'AMZN', 'FB', 'NFLX', 'NVDA', 'INTC', 'IBM']
12
 
13
+ def train_model(data):
14
+ # Prepare data for LSTM
 
 
 
 
 
 
 
 
 
15
  scaler = MinMaxScaler(feature_range=(0, 1))
16
+ scaled_data = scaler.fit_transform(data['Close'].values.reshape(-1, 1))
 
 
 
 
 
 
 
 
17
 
18
+ # Create training data
19
+ train_data = []
20
+ for i in range(60, len(scaled_data)):
21
+ train_data.append(scaled_data[i-60:i, 0])
22
 
23
+ train_data = np.array(train_data)
 
24
 
25
+ # Reshape data for LSTM
26
+ X_train = train_data.reshape((train_data.shape[0], train_data.shape[1], 1))
27
+
28
  # Define LSTM model
29
+ model = Sequential()
30
+ model.add(LSTM(50, return_sequences=True, input_shape=(X_train.shape[1], 1)))
31
+ model.add(LSTM(50, return_sequences=False))
32
+ model.add(Dense(25))
33
+ model.add(Dense(1))
34
+
35
+ # Compile model
36
+ model.compile(optimizer='adam', loss='mean_squared_error')
37
+ model.fit(X_train, np.array(data['Close'][60:]), batch_size=1, epochs=1)
38
+
39
+ return model, scaler
40
+
41
+ def stock_prediction_app(ticker, start_date, end_date):
42
+ # Fetch stock data
43
+ data = yf.download(ticker, start=start_date, end=end_date)
44
+ if data.empty:
45
+ return "No data found for the selected dates.", None
46
 
47
  # Train the model
48
+ model, scaler = train_model(data)
49
+
50
+ # Predict future prices
51
+ last_60_days = data['Close'][-60:].values.reshape(-1, 1)
52
+ last_60_days_scaled = scaler.transform(last_60_days)
53
+ X_test = []
54
+ X_test.append(last_60_days_scaled)
55
+ X_test = np.array(X_test).reshape((1, X_test.shape[1], 1))
56
+
57
+ # Predicting the price
58
+ predicted_price = model.predict(X_test)
59
+ predicted_price = scaler.inverse_transform(predicted_price)
60
 
61
+ # Calculate additional information
62
+ current_price = data['Close'].iloc[-1]
63
+ highest_price = data['Close'].max()
64
+ lowest_price = data['Close'].min()
65
+ percentage_change = ((predicted_price[0][0] - current_price) / current_price) * 100
66
 
67
+ # Plotting historical and predicted prices
68
  plt.figure(figsize=(10, 5))
69
+ plt.plot(data['Close'], label='Historical Prices')
70
+ plt.axhline(y=predicted_price[0][0], color='r', linestyle='--', label='Predicted Price')
71
  plt.title(f'{ticker} Stock Price Prediction')
72
+ plt.xlabel('Date')
73
+ plt.ylabel('Price')
74
  plt.legend()
75
+ plt.grid()
76
 
77
+ # Save the plot
78
+ plt.savefig("predicted_stock_price.png")
79
+ plt.close()
80
 
81
+ return f"Predicted Price: ${predicted_price[0][0]:.2f}\nCurrent Price: ${current_price:.2f}\nPercentage Change: {percentage_change:.2f}%\nHighest Price: ${highest_price:.2f}\nLowest Price: ${lowest_price:.2f}", "predicted_stock_price.png"
 
82
 
83
+ # Gradio UI
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")
 
 
90
  start_date = gr.Textbox(label="Start Date (YYYY-MM-DD)")
91
  end_date = gr.Textbox(label="End Date (YYYY-MM-DD)")
92
 
 
93
  predict_button = gr.Button("Predict")
94
 
95
+ output_text = gr.Textbox(label="Prediction Result", interactive=False)
 
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()