Abhisesh7 commited on
Commit
70363ab
·
verified ·
1 Parent(s): d5ef4bc

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +199 -71
app.py CHANGED
@@ -2,93 +2,221 @@ import yfinance as yf
2
  import pandas as pd
3
  import numpy as np
4
  import tensorflow as tf
5
- import gradio as gr
6
  import matplotlib.pyplot as plt
7
- from sklearn.preprocessing import MinMaxScaler
 
 
 
 
 
 
 
 
 
 
 
8
 
9
  def fetch_data(ticker, start_date, end_date):
10
- # Fetch historical data for the given ticker symbol
 
 
 
 
 
 
 
 
 
 
11
  data = yf.download(ticker, start=start_date, end=end_date)
12
  return data
13
 
14
- def prepare_data(data):
15
- # Preprocessing
16
- scaler = MinMaxScaler(feature_range=(0, 1))
17
- scaled_data = scaler.fit_transform(data['Close'].values.reshape(-1, 1))
18
 
19
- x_train, y_train = [], []
20
- for i in range(60, len(scaled_data)):
21
- x_train.append(scaled_data[i-60:i, 0])
22
- y_train.append(scaled_data[i, 0])
23
-
24
- return np.array(x_train), np.array(y_train), scaler
25
-
26
- def create_model(input_shape):
27
- model = tf.keras.Sequential()
28
- model.add(tf.keras.layers.LSTM(units=50, return_sequences=True, input_shape=input_shape))
29
- model.add(tf.keras.layers.LSTM(units=50, return_sequences=False))
30
- model.add(tf.keras.layers.Dense(units=25))
31
- model.add(tf.keras.layers.Dense(units=1)) # Output layer
32
- model.compile(optimizer='adam', loss='mean_squared_error')
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
33
  return model
34
 
35
- def predict_next_days(model, last_60_days, scaler):
36
- last_60_days = np.array(last_60_days).reshape(-1, 1)
37
- last_60_days_scaled = scaler.transform(last_60_days)
 
 
 
 
 
 
 
 
 
38
 
39
- X_test = []
40
- X_test.append(last_60_days_scaled)
41
- X_test = np.array(X_test)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
42
 
43
- predicted_price = model.predict(X_test)
44
- predicted_price = scaler.inverse_transform(predicted_price) # Reverse scaling
45
- return predicted_price[0][0]
46
-
47
- def plot_graph(data, predicted_prices):
48
- plt.figure(figsize=(14, 5))
49
- plt.plot(data['Close'], label='Historical Prices', color='blue')
50
- plt.axhline(y=predicted_prices, color='red', linestyle='--', label='Predicted Price')
51
- plt.title('Stock Price Prediction')
 
 
52
  plt.xlabel('Date')
53
- plt.ylabel('Stock Price')
 
54
  plt.legend()
55
- plt.show()
 
 
56
 
57
- def stock_prediction(ticker, start_date, end_date):
58
- data = fetch_data(ticker, start_date, end_date)
59
- x_train, y_train, scaler = prepare_data(data)
60
- model = create_model((x_train.shape[1], 1))
61
- model.fit(x_train, y_train, batch_size=1, epochs=1)
62
-
63
- # Make predictions
64
- last_60_days = data['Close'].values[-60:]
65
- predicted_price = predict_next_days(model, last_60_days, scaler)
66
-
67
- # Calculate percentage change, highest, and lowest
68
- percentage_change = ((data['Close'][-1] - data['Close'][0]) / data['Close'][0]) * 100
69
- highest_value = data['Close'].max()
70
- lowest_value = data['Close'].min()
71
-
72
- plot_graph(data, predicted_price)
73
-
74
- return {
75
- "Predicted Price": predicted_price,
76
- "Percentage Change": percentage_change,
77
- "Highest Value": highest_value,
78
- "Lowest Value": lowest_value,
79
  }
80
 
81
- # UI setup
82
- stock_tickers = ["AAPL", "MSFT", "GOOGL", "AMZN", "TSLA", "FB", "NFLX", "NVDA", "INTC", "AMD"]
83
 
84
- gr.Interface(
85
- fn=stock_prediction,
 
86
  inputs=[
87
- gr.Dropdown(choices=stock_tickers, label="Stock Ticker"),
88
- gr.DatePicker(label="Start Date"), # Changed to DatePicker
89
- gr.DatePicker(label="End Date"), # Changed to DatePicker
90
  ],
91
- outputs="json",
92
- title="Stock Prediction App",
93
- description="This app predicts stock prices based on historical data."
94
- ).launch()
 
 
 
 
 
 
 
 
 
 
 
 
 
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()