SailajaS commited on
Commit
141412b
·
verified ·
1 Parent(s): 9eb447a

Create app.py

Browse files
Files changed (1) hide show
  1. app.py +184 -0
app.py ADDED
@@ -0,0 +1,184 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import yfinance as yf
2
+ import pandas as pd
3
+ import numpy as np
4
+ import tensorflow as tf
5
+ from sklearn.preprocessing import MinMaxScaler
6
+ import matplotlib.pyplot as plt
7
+ import gradio as gr
8
+
9
+ # Step 1: Fetch stock data
10
+ def fetch_stock_data(ticker, start_date, end_date):
11
+ """
12
+ Fetch historical stock data from Yahoo Finance using the yfinance library.
13
+
14
+ Args:
15
+ ticker (str): Stock ticker symbol (e.g., 'AAPL').
16
+ start_date (str): Start date for fetching stock data (YYYY-MM-DD).
17
+ end_date (str): End date for fetching stock data (YYYY-MM-DD).
18
+
19
+ Returns:
20
+ pd.DataFrame: Stock data including Date, Open, High, Low, Close, and Volume.
21
+ """
22
+ stock_data = yf.download(ticker, start=start_date, end=end_date)
23
+ stock_data.reset_index(inplace=True)
24
+ return stock_data
25
+
26
+ # Step 2: Prepare data for the LSTM model
27
+ def prepare_data(df):
28
+ """
29
+ Prepares the stock data for the LSTM model by scaling the 'Close' price.
30
+
31
+ Args:
32
+ df (pd.DataFrame): DataFrame containing the stock data.
33
+
34
+ Returns:
35
+ scaled_data (np.array): Normalized stock prices for training the model.
36
+ scaler (MinMaxScaler): Scaler used to normalize and later denormalize predictions.
37
+ """
38
+ scaler = MinMaxScaler(feature_range=(0, 1))
39
+ close_prices = df['Close'].values.reshape(-1, 1)
40
+ scaled_data = scaler.fit_transform(close_prices)
41
+ return scaled_data, scaler
42
+
43
+ # Step 3: Build the LSTM model
44
+ def build_model(input_shape):
45
+ """
46
+ Builds and compiles the LSTM model for stock price prediction.
47
+
48
+ Args:
49
+ input_shape (tuple): Shape of the input data for the LSTM model.
50
+
51
+ Returns:
52
+ tf.keras.Model: Compiled LSTM model.
53
+ """
54
+ model = tf.keras.Sequential([
55
+ tf.keras.layers.LSTM(50, return_sequences=True, input_shape=input_shape),
56
+ tf.keras.layers.LSTM(50, return_sequences=False),
57
+ tf.keras.layers.Dense(25),
58
+ tf.keras.layers.Dense(1)
59
+ ])
60
+ model.compile(optimizer='adam', loss='mean_squared_error')
61
+ return model
62
+
63
+ # Step 4: Train the LSTM model
64
+ def train_model(model, train_data, epochs=5):
65
+ """
66
+ Trains the LSTM model using the scaled stock price data.
67
+
68
+ Args:
69
+ model (tf.keras.Model): The LSTM model to be trained.
70
+ train_data (np.array): Scaled stock price data for training.
71
+ epochs (int): Number of training epochs.
72
+
73
+ Returns:
74
+ model (tf.keras.Model): The trained LSTM model.
75
+ """
76
+ X_train, y_train = [], []
77
+ for i in range(60, len(train_data)):
78
+ X_train.append(train_data[i-60:i, 0])
79
+ y_train.append(train_data[i, 0])
80
+
81
+ X_train, y_train = np.array(X_train), np.array(y_train)
82
+ X_train = np.reshape(X_train, (X_train.shape[0], X_train.shape[1], 1))
83
+
84
+ model.fit(X_train, y_train, epochs=epochs, batch_size=32, verbose=0)
85
+ return model
86
+
87
+ # Step 5: Predict future stock prices
88
+ def predict_future(model, last_data, steps=90):
89
+ """
90
+ Predicts future stock prices using the trained LSTM model.
91
+
92
+ Args:
93
+ model (tf.keras.Model): The trained LSTM model.
94
+ last_data (np.array): The last 60 days of stock price data.
95
+ steps (int): Number of future days to predict.
96
+
97
+ Returns:
98
+ predictions (list): Predicted stock prices for the future.
99
+ """
100
+ predictions = []
101
+ input_data = last_data[-60:].reshape(1, -1)
102
+
103
+ for _ in range(steps):
104
+ predicted_price = model.predict(input_data.reshape(1, 60, 1), verbose=0)
105
+ predictions.append(predicted_price[0][0])
106
+ input_data = np.append(input_data[0][1:], predicted_price)
107
+
108
+ return predictions
109
+
110
+ # Step 6: Plot historical and predicted stock prices
111
+ def plot_predictions(data, predicted_prices, scaler):
112
+ """
113
+ Plots the historical stock prices and the predicted future stock prices.
114
+
115
+ Args:
116
+ data (pd.DataFrame): DataFrame containing historical stock data.
117
+ predicted_prices (list): Predicted stock prices for future dates.
118
+ scaler (MinMaxScaler): Scaler to inverse transform the predicted prices.
119
+ """
120
+ last_60_days = data['Close'][-60:].values.reshape(-1, 1)
121
+ predicted_prices = np.array(predicted_prices).reshape(-1, 1)
122
+ predicted_prices = scaler.inverse_transform(predicted_prices)
123
+
124
+ # Plot historical data
125
+ plt.figure(figsize=(14,6))
126
+ plt.plot(data['Close'], label="Historical Prices")
127
+
128
+ # Plot predicted data
129
+ future_days = range(len(data), len(data) + len(predicted_prices))
130
+ plt.plot(future_days, predicted_prices, label="Predicted Prices")
131
+ plt.title("Stock Price Prediction")
132
+ plt.xlabel("Days")
133
+ plt.ylabel("Stock Price")
134
+ plt.legend()
135
+ plt.show()
136
+
137
+ # Step 7: Gradio Interface Function
138
+ def stock_prediction_app(ticker, start_date, end_date):
139
+ """
140
+ The core function for the Gradio app. Fetches stock data, trains the LSTM model,
141
+ predicts future prices, and visualizes the results.
142
+
143
+ Args:
144
+ ticker (str): Stock ticker symbol selected by the user.
145
+ start_date (str): Start date selected by the user.
146
+ end_date (str): End date selected by the user.
147
+
148
+ Returns:
149
+ None (Displays a plot of historical and predicted stock prices).
150
+ """
151
+ # Fetch stock data
152
+ data = fetch_stock_data(ticker, start_date, end_date)
153
+
154
+ # Prepare data for the LSTM model
155
+ scaled_data, scaler = prepare_data(data)
156
+
157
+ # Build and train the LSTM model
158
+ model = build_model((60, 1))
159
+ model = train_model(model, scaled_data)
160
+
161
+ # Predict future prices for the next 90 days
162
+ predicted_prices = predict_future(model, scaled_data)
163
+
164
+ # Plot historical and predicted prices
165
+ plot_predictions(data, predicted_prices, scaler)
166
+
167
+ # Step 8: Gradio UI Setup
168
+ tickers = ["AAPL", "GOOGL", "MSFT", "AMZN", "TSLA", "META", "NFLX", "NVDA", "BABA", "BA"]
169
+
170
+ # Create the Gradio interface
171
+ ui = gr.Interface(
172
+ fn=stock_prediction_app,
173
+ inputs=[
174
+ gr.Dropdown(tickers, label="Select Stock Ticker"),
175
+ gr.inputs.Date(label="Start Date"),
176
+ gr.inputs.Date(label="End Date")
177
+ ],
178
+ outputs="plot",
179
+ title="Stock Prediction App",
180
+ description="Select a stock ticker and date range to predict future prices."
181
+ )
182
+
183
+ # Launch the app
184
+ ui.launch()