Abhisesh7 commited on
Commit
b0bd1b7
·
verified ·
1 Parent(s): 971d03b

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +76 -228
app.py CHANGED
@@ -1,252 +1,100 @@
1
  import yfinance as yf
2
- import pandas as pd
3
- import numpy as np
4
  import tensorflow as tf
5
- from tensorflow.keras import layers, models
 
6
  import matplotlib.pyplot as plt
7
  import gradio as gr
8
- from datetime import datetime, timedelta
9
-
10
- # Ensure matplotlib does not require a display environment
11
- import matplotlib
12
- matplotlib.use('Agg')
13
-
14
- # Define the stock tickers
15
- STOCK_TICKERS = [
16
- 'AAPL', 'GOOGL', 'MSFT', 'AMZN', 'TSLA',
17
- 'FB', 'NVDA', 'JPM', 'V', 'DIS'
18
- ]
19
-
20
- def fetch_data(ticker, start_date, end_date):
21
- """
22
- Fetch historical stock data from yfinance.
23
 
24
- Args:
25
- ticker (str): Stock ticker symbol.
26
- start_date (str): Start date in 'YYYY-MM-DD'.
27
- end_date (str): End date in 'YYYY-MM-DD'.
28
 
29
- Returns:
30
- pd.DataFrame: Historical stock data.
31
- """
32
  data = yf.download(ticker, start=start_date, end=end_date)
33
  return data
34
 
35
- def preprocess_data(data):
36
- """
37
- Preprocess the stock data for model training.
38
-
39
- Args:
40
- data (pd.DataFrame): Raw stock data.
41
-
42
- Returns:
43
- np.ndarray, np.ndarray: Features and labels.
44
- """
45
- # Calculate moving averages
46
- data['MA10'] = data['Close'].rolling(window=10).mean()
47
- data['MA20'] = data['Close'].rolling(window=20).mean()
48
-
49
- # Drop NaN values
50
- data = data.dropna()
51
-
52
- # Features: Close, MA10, MA20
53
- features = data[['Close', 'MA10', 'MA20']].values
54
-
55
- # Labels: 1 if next day's Close > today's Close, else 0
56
- data['Target'] = np.where(data['Close'].shift(-1) > data['Close'], 1, 0)
57
- labels = data['Target'].values[:-1]
58
- features = features[:-1]
59
-
60
- return features, labels
61
-
62
- def build_model(input_shape):
63
- """
64
- Build and compile the TensorFlow model.
65
-
66
- Args:
67
- input_shape (int): Number of features.
68
-
69
- Returns:
70
- tf.keras.Model: Compiled model.
71
- """
72
- model = models.Sequential([
73
- layers.Dense(64, activation='relu', input_shape=(input_shape,)),
74
- layers.Dense(32, activation='relu'),
75
- layers.Dense(1, activation='sigmoid') # Binary classification
76
  ])
77
 
78
- model.compile(optimizer='adam',
79
- loss='binary_crossentropy',
80
- metrics=['accuracy'])
81
- return model
82
-
83
- # Train the model for each stock ticker and store in a dictionary
84
- models_dict = {}
85
-
86
- for ticker in STOCK_TICKERS:
87
- # Fetch data for the past 5 years
88
- end = datetime.today()
89
- start = end - timedelta(days=5*365)
90
- data = fetch_data(ticker, start.strftime('%Y-%m-%d'), end.strftime('%Y-%m-%d'))
91
-
92
- if data.empty:
93
- print(f"No data found for {ticker}. Skipping...")
94
- continue
95
-
96
- features, labels = preprocess_data(data)
97
- model = build_model(features.shape[1])
98
- model.fit(features, labels, epochs=10, batch_size=32, verbose=0)
99
-
100
- models_dict[ticker] = model
101
- print(f"Model trained for {ticker}")
102
-
103
- def predict_stock(ticker, start_date, end_date):
104
- """
105
- Predict whether to Buy or Sell the stock based on user input.
106
-
107
- Args:
108
- ticker (str): Selected stock ticker.
109
- start_date (str): Training start date.
110
- end_date (str): Training end date.
111
-
112
- Returns:
113
- dict: Prediction results and graph.
114
- """
115
- # Fetch data
116
- data = fetch_data(ticker, start_date, end_date)
117
-
118
- if data.empty:
119
- return {
120
- "Percentage Change": "No data available for the selected dates.",
121
- "Highest Price": "N/A",
122
- "Lowest Price": "N/A",
123
- "Prediction": "N/A",
124
- "Graph": None
125
- }
126
 
127
- # Preprocess data
128
- features, labels = preprocess_data(data)
 
129
 
130
- if features.size == 0:
131
- return {
132
- "Percentage Change": "Insufficient data after preprocessing.",
133
- "Highest Price": "N/A",
134
- "Lowest Price": "N/A",
135
- "Prediction": "N/A",
136
- "Graph": None
137
- }
138
 
139
- # Get the latest features for prediction
140
- latest_data = data[['Close', 'MA10', 'MA20']].values[-1].reshape(1, -1)
141
-
142
- # Predict using the trained model
143
- model = models_dict.get(ticker)
144
- if not model:
145
- return {
146
- "Percentage Change": "Model not found for the selected ticker.",
147
- "Highest Price": "N/A",
148
- "Lowest Price": "N/A",
149
- "Prediction": "N/A",
150
- "Graph": None
151
- }
152
-
153
- prediction = model.predict(latest_data)
154
- prediction_label = "Buy" if prediction[0][0] > 0.5 else "Sell"
155
-
156
- # Calculate percentage change
157
- start_close = data['Close'].iloc[0]
158
- latest_close = data['Close'].iloc[-1]
159
- percent_change = ((latest_close - start_close) / start_close) * 100
160
-
161
- # Highest and Lowest values
162
- highest = data['Close'].max()
163
- lowest = data['Close'].min()
164
-
165
- # Plot historical data
166
- plt.figure(figsize=(10,5))
167
- plt.plot(data.index, data['Close'], label='Historical Close')
168
-
169
- # Predict future 3 months (approx 63 trading days)
170
- future_days = 63
171
- # For simplicity, we'll extend the latest close with random walk
172
- future_prices = [latest_close]
173
- for _ in range(future_days):
174
- change_percent = np.random.uniform(-0.02, 0.02) # Simulate small changes
175
- new_price = future_prices[-1] * (1 + change_percent)
176
- future_prices.append(new_price)
177
-
178
- future_dates = pd.date_range(data.index[-1] + timedelta(days=1), periods=future_days+1, freq='B')
179
- plt.plot(future_dates, future_prices[1:], label='Predicted Close')
180
  plt.xlabel('Date')
181
- plt.ylabel('Price')
182
- plt.title(f'{ticker} Historical and Predicted Performance')
183
  plt.legend()
184
- plt.tight_layout()
185
- plt.savefig('performance.png')
186
- plt.close()
187
-
188
- # Prepare the result
189
- result = {
190
- "Percentage Change": f"{percent_change:.2f}%",
191
- "Highest Price": f"${highest:.2f}",
192
- "Lowest Price": f"${lowest:.2f}",
193
- "Prediction": prediction_label,
194
- "Graph": 'performance.png'
195
- }
196
-
197
- return result
198
-
199
- # Define Gradio Interface
200
- iface = gr.Interface(
201
- fn=predict_stock,
202
- inputs=[
203
- gr.Dropdown(choices=STOCK_TICKERS, label="Select Stock Ticker"),
204
- gr.DatePicker(label="Start Date"),
205
- gr.DatePicker(label="End Date")
206
- ],
207
- outputs=[
208
- gr.Textbox(label="Percentage Change"),
209
- gr.Textbox(label="Highest Price"),
210
- gr.Textbox(label="Lowest Price"),
211
- gr.Textbox(label="Buy/Sell Prediction"),
212
- gr.Image(label="Performance Graph")
213
- ],
214
- title="📈 Stock Buy/Sell Prediction App",
215
- description=(
216
- "Select a stock ticker and a date range to predict whether to **Buy** or **Sell** the stock. "
217
- "View the percentage change, highest and lowest prices, and a performance graph."
218
- )
219
- )
220
-
221
- # Launch the app
222
- iface.launch()
223
- from tensorflow.keras.models import Sequential
224
- from tensorflow.keras.layers import Dense, Input
225
-
226
- def create_model(input_shape):
227
- model = Sequential()
228
- model.add(Input(shape=(input_shape,))) # Explicitly define input shape
229
- model.add(Dense(64, activation='relu'))
230
- model.add(Dense(32, activation='relu'))
231
- model.add(Dense(1, activation='sigmoid'))
232
-
233
- model.compile(optimizer='adam', loss='binary_crossentropy', metrics=['accuracy'])
234
- return model
235
- data.loc[:, 'Target'] = np.where(data['Close'].shift(-1) > data['Close'], 1, 0)
236
- import gradio as gr
237
-
238
- def predict_stock(ticker, start_date, end_date):
239
- # Your prediction logic
240
- return "Prediction result"
241
 
 
242
  interface = gr.Interface(
243
- fn=predict_stock,
244
  inputs=[
245
- gr.inputs.Dropdown(['AAPL', 'MSFT', 'GOOG', 'AMZN', 'TSLA'], label="Stock Ticker"),
246
- gr.inputs.Date(label="Start Date"), # Replace DatePicker with Date
247
  gr.inputs.Date(label="End Date")
248
  ],
249
- outputs="text"
 
 
 
 
 
 
 
250
  )
251
 
252
  interface.launch()
 
 
1
  import yfinance as yf
 
 
2
  import tensorflow as tf
3
+ import numpy as np
4
+ import pandas as pd
5
  import matplotlib.pyplot as plt
6
  import gradio as gr
7
+ from datetime import datetime
 
 
 
 
 
 
 
 
 
 
 
 
 
 
8
 
9
+ # Stock tickers for dropdown
10
+ stock_tickers = ['AAPL', 'MSFT', 'GOOGL', 'AMZN', 'TSLA', 'NFLX', 'FB', 'NVDA', 'JPM', 'BAC']
 
 
11
 
12
+ # Function to download stock data from Yahoo Finance
13
+ def fetch_stock_data(ticker, start_date, end_date):
 
14
  data = yf.download(ticker, start=start_date, end=end_date)
15
  return data
16
 
17
+ # Function to train LSTM model and predict stock prices
18
+ def train_lstm(data):
19
+ # Preprocessing and creating training dataset
20
+ data['Close'] = data['Close'].fillna(method='ffill') # Forward-fill to handle NaNs
21
+ scaled_data = data['Close'].values.reshape(-1, 1)
22
+ training_data = scaled_data[:int(len(scaled_data) * 0.8)] # 80% data for training
23
+ test_data = scaled_data[int(len(scaled_data) * 0.8):]
24
+
25
+ # Creating sequences for LSTM input
26
+ def create_sequences(data, seq_length):
27
+ X, y = [], []
28
+ for i in range(len(data) - seq_length):
29
+ X.append(data[i:i + seq_length])
30
+ y.append(data[i + seq_length])
31
+ return np.array(X), np.array(y)
32
+
33
+ seq_length = 60 # Using 60 days for prediction
34
+ X_train, y_train = create_sequences(training_data, seq_length)
35
+
36
+ # Define the LSTM model
37
+ model = tf.keras.Sequential([
38
+ tf.keras.layers.LSTM(50, return_sequences=True, input_shape=(X_train.shape[1], 1)),
39
+ tf.keras.layers.LSTM(50, return_sequences=False),
40
+ tf.keras.layers.Dense(25),
41
+ tf.keras.layers.Dense(1)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
42
  ])
43
 
44
+ # Compile and train the model
45
+ model.compile(optimizer='adam', loss='mean_squared_error')
46
+ model.fit(X_train, y_train, batch_size=1, epochs=1) # Short training for demo, increase epochs for better results
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
47
 
48
+ # Predict future prices
49
+ X_test, _ = create_sequences(test_data, seq_length)
50
+ predictions = model.predict(X_test)
51
 
52
+ return predictions, data.index[-len(predictions):]
 
 
 
 
 
 
 
53
 
54
+ # Function to plot historical and predicted prices
55
+ def plot_stock_data(data, predictions, pred_dates):
56
+ plt.figure(figsize=(10,6))
57
+ plt.plot(data['Close'], label='Historical Data')
58
+ plt.plot(pred_dates, predictions, label='Predicted Data')
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
59
  plt.xlabel('Date')
60
+ plt.ylabel('Close Price (USD)')
 
61
  plt.legend()
62
+ plt.grid()
63
+ plt.show()
64
+
65
+ # Main function to wrap everything into Gradio interface
66
+ def stock_prediction(ticker, start_date, end_date):
67
+ data = fetch_stock_data(ticker, start_date, end_date)
68
+ predictions, pred_dates = train_lstm(data)
69
+ plot_stock_data(data, predictions, pred_dates)
70
+
71
+ # Calculate percentage change, highest and lowest values
72
+ percentage_change = ((data['Close'][-1] - data['Close'][0]) / data['Close'][0]) * 100
73
+ highest_value = data['Close'].max()
74
+ lowest_value = data['Close'].min()
75
+
76
+ # Buy/Sell decision based on prediction (buy if next value is higher)
77
+ decision = 'Buy' if predictions[-1] > data['Close'][-1] else 'Sell'
78
+
79
+ return f"Percentage Change: {percentage_change:.2f}%", f"Highest Value: {highest_value:.2f}", f"Lowest Value: {lowest_value:.2f}", f"Decision: {decision}"
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
80
 
81
+ # Gradio UI
82
  interface = gr.Interface(
83
+ fn=stock_prediction,
84
  inputs=[
85
+ gr.inputs.Dropdown(choices=stock_tickers, label="Select Stock Ticker"),
86
+ gr.inputs.Date(label="Start Date"),
87
  gr.inputs.Date(label="End Date")
88
  ],
89
+ outputs=[
90
+ gr.outputs.Textbox(label="Percentage Change"),
91
+ gr.outputs.Textbox(label="Highest Value"),
92
+ gr.outputs.Textbox(label="Lowest Value"),
93
+ gr.outputs.Textbox(label="Prediction: Buy/Sell")
94
+ ],
95
+ title="Stock Prediction App",
96
+ description="Predict if you should buy or sell a stock based on historical performance."
97
  )
98
 
99
  interface.launch()
100
+