geethareddy commited on
Commit
2c4da9a
·
verified ·
1 Parent(s): d0f0c5d

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +26 -33
app.py CHANGED
@@ -10,7 +10,6 @@ from datetime import datetime, timedelta
10
  import joblib
11
  import os
12
  import re
13
- import matplotlib.dates as mdates
14
 
15
  # Define stock tickers
16
  STOCK_TICKERS = [
@@ -63,7 +62,7 @@ def preprocess_data(data: pd.DataFrame) -> (np.ndarray, np.ndarray):
63
  for i in range(1, 6):
64
  data[f'Close_{i}'] = data['Close'].shift(i)
65
 
66
- # Example of adding a 7-day moving average
67
  data['MA_7'] = data['Close'].rolling(window=7).mean()
68
 
69
  # Drop rows with any NaN values
@@ -116,10 +115,12 @@ def make_prediction(model: RandomForestRegressor, recent_data: pd.DataFrame) ->
116
  # Use the last 5 days' close prices as features
117
  recent_close = recent_data['Close'].values[-5:]
118
  recent_ma7 = recent_data['MA_7'].values[-1] # Latest 7-day moving average
 
 
119
  if len(recent_close) < 5 or np.isnan(recent_ma7):
120
  raise ValueError("Not enough data to make a prediction.")
121
 
122
- # Prepare feature array
123
  X_new = np.append(recent_close[::-1], recent_ma7).reshape(1, -1) # Reverse to match feature order
124
  predicted_price = model.predict(X_new)[0]
125
  return predicted_price
@@ -207,7 +208,7 @@ def stock_prediction_app(ticker: str, start_date: str, end_date: str):
207
  try:
208
  X, y = preprocess_data(data)
209
  except Exception as e:
210
- return f"Error in preprocessing data: {e}", "N/A", "N/A", "Error", None
211
 
212
  if len(X) == 0:
213
  return f"{percentage_change:.2f}%", highest_price, lowest_price, "No Prediction", None
@@ -229,56 +230,48 @@ def stock_prediction_app(ticker: str, start_date: str, end_date: str):
229
  decision = buy_or_sell(current_price, predicted_price)
230
 
231
  # Plotting historical prices and predicted tomorrow's price
232
- plt.figure(figsize=(12, 6))
233
- plt.plot(data.index, data['Close'], label='Historical Close Price', color='blue')
234
 
235
  # Add predicted price for tomorrow
236
  tomorrow_date = data.index[-1] + timedelta(days=1)
237
  # Ensure tomorrow is a business day
238
- while tomorrow_date.weekday() >= 5: # Saturday=5, Sunday=6
239
  tomorrow_date += timedelta(days=1)
240
 
241
- plt.scatter(tomorrow_date, predicted_price, color='red', label='Predicted Close Price (Tomorrow)', zorder=5)
242
-
243
- # Formatting the x-axis with better date formatting
244
- plt.gca().xaxis.set_major_locator(mdates.AutoDateLocator())
245
- plt.gca().xaxis.set_major_formatter(mdates.DateFormatter('%Y-%m-%d'))
246
- plt.xticks(rotation=45)
247
-
248
- plt.title(f'{ticker} Price Prediction for Tomorrow')
249
  plt.xlabel('Date')
250
- plt.ylabel('Price ($)')
 
251
  plt.legend()
252
- plt.grid(True, linestyle='--', alpha=0.5)
253
- plt.tight_layout()
254
 
255
- # Create the figure
256
- fig = plt.gcf()
 
257
  plt.close()
258
 
259
- # Formatting outputs
260
- percentage_change_str = f"{percentage_change:.2f}%"
261
-
262
- return percentage_change_str, highest_price, lowest_price, decision, fig
263
 
264
- # Define the Gradio interface
265
  iface = gr.Interface(
266
  fn=stock_prediction_app,
267
  inputs=[
268
  gr.Dropdown(choices=STOCK_TICKERS, label="Select Stock Ticker"),
269
- gr.Textbox(label="Enter Start Date (YYYY-MM-DD)", placeholder="e.g., 2020-01-01"),
270
- gr.Textbox(label="Enter End Date (YYYY-MM-DD)", placeholder="e.g., 2023-09-30")
271
  ],
272
  outputs=[
273
  gr.Textbox(label="Percentage Change"),
274
- gr.Number(label="Highest Closing Price"),
275
- gr.Number(label="Lowest Closing Price"),
276
  gr.Textbox(label="Decision (Buy/Sell)"),
277
- gr.Plot(label="Stock Performance")
278
  ],
279
- title="Stock Prediction App",
280
- description="Predict whether to buy or sell a stock based on historical data. Please enter dates in YYYY-MM-DD format."
281
  )
282
 
283
- # Launch the interface
284
  iface.launch()
 
10
  import joblib
11
  import os
12
  import re
 
13
 
14
  # Define stock tickers
15
  STOCK_TICKERS = [
 
62
  for i in range(1, 6):
63
  data[f'Close_{i}'] = data['Close'].shift(i)
64
 
65
+ # Add a 7-day moving average
66
  data['MA_7'] = data['Close'].rolling(window=7).mean()
67
 
68
  # Drop rows with any NaN values
 
115
  # Use the last 5 days' close prices as features
116
  recent_close = recent_data['Close'].values[-5:]
117
  recent_ma7 = recent_data['MA_7'].values[-1] # Latest 7-day moving average
118
+
119
+ # Prepare feature array
120
  if len(recent_close) < 5 or np.isnan(recent_ma7):
121
  raise ValueError("Not enough data to make a prediction.")
122
 
123
+ # Prepare feature for the model
124
  X_new = np.append(recent_close[::-1], recent_ma7).reshape(1, -1) # Reverse to match feature order
125
  predicted_price = model.predict(X_new)[0]
126
  return predicted_price
 
208
  try:
209
  X, y = preprocess_data(data)
210
  except Exception as e:
211
+ return f"Error in preprocessing data: {e}", highest_price, lowest_price, "Error", None
212
 
213
  if len(X) == 0:
214
  return f"{percentage_change:.2f}%", highest_price, lowest_price, "No Prediction", None
 
230
  decision = buy_or_sell(current_price, predicted_price)
231
 
232
  # Plotting historical prices and predicted tomorrow's price
233
+ plt.figure(figsize=(10,5))
234
+ plt.plot(data['Close'], label='Historical Close Price', color='blue')
235
 
236
  # Add predicted price for tomorrow
237
  tomorrow_date = data.index[-1] + timedelta(days=1)
238
  # Ensure tomorrow is a business day
239
+ while tomorrow_date.weekday() >= 5: # Saturday or Sunday
240
  tomorrow_date += timedelta(days=1)
241
 
242
+ plt.scatter(tomorrow_date, predicted_price, color='red', label='Predicted Price for Tomorrow', zorder=5)
243
+ plt.title(f'Stock Price Prediction for {ticker}')
 
 
 
 
 
 
244
  plt.xlabel('Date')
245
+ plt.ylabel('Price')
246
+ plt.xticks(rotation=45)
247
  plt.legend()
248
+ plt.grid()
 
249
 
250
+ # Save plot to a file and return
251
+ plot_path = f'{ticker}_prediction_plot.png'
252
+ plt.savefig(plot_path)
253
  plt.close()
254
 
255
+ return f"{percentage_change:.2f}%", highest_price, lowest_price, decision, plot_path
 
 
 
256
 
257
+ # Gradio interface
258
  iface = gr.Interface(
259
  fn=stock_prediction_app,
260
  inputs=[
261
  gr.Dropdown(choices=STOCK_TICKERS, label="Select Stock Ticker"),
262
+ gr.Textbox(label="Start Date (YYYY-MM-DD)", placeholder="2023-01-01"),
263
+ gr.Textbox(label="End Date (YYYY-MM-DD)", placeholder="2023-10-01"),
264
  ],
265
  outputs=[
266
  gr.Textbox(label="Percentage Change"),
267
+ gr.Number(label="Highest Price"),
268
+ gr.Number(label="Lowest Price"),
269
  gr.Textbox(label="Decision (Buy/Sell)"),
270
+ gr.Image(label="Stock Price Prediction Plot"),
271
  ],
272
+ title="Stock Price Prediction App",
273
+ description="Predict stock prices and get buy/sell recommendations."
274
  )
275
 
276
+ # Launch the Gradio app
277
  iface.launch()