rasel-harun commited on
Commit
a361a2a
·
verified ·
1 Parent(s): 094b8bb

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +46 -116
app.py CHANGED
@@ -4,6 +4,7 @@ import numpy as np
4
  import matplotlib.pyplot as plt
5
  import yfinance as yf
6
  import joblib
 
7
  from tensorflow.keras.models import Sequential
8
  from tensorflow.keras.layers import LSTM, Dense, Dropout
9
  from sklearn.metrics import mean_squared_error, mean_absolute_percentage_error
@@ -12,11 +13,11 @@ import warnings
12
 
13
  warnings.filterwarnings("ignore")
14
 
15
- # Utility functions
16
  def rmse(a, b):
17
  return math.sqrt(mean_squared_error(a, b))
18
 
19
- # Download stock data
20
  def download_data(ticker, start="2015-01-01", end=None):
21
  df = yf.download(ticker, start=start, end=end, progress=False)
22
  df = df[['Close']].dropna()
@@ -24,7 +25,7 @@ def download_data(ticker, start="2015-01-01", end=None):
24
  df.rename(columns={'Close': 'close'}, inplace=True)
25
  return df
26
 
27
- # Build the same architecture as training
28
  def build_lstm(window_size=60):
29
  model = Sequential([
30
  LSTM(64, return_sequences=True, input_shape=(window_size,1)),
@@ -36,131 +37,48 @@ def build_lstm(window_size=60):
36
  model.compile(optimizer="adam", loss="mse")
37
  return model
38
 
39
- # Forecast using saved models
40
- def forecast_models(ticker="AAPL", test_len=180):
41
- df = download_data(ticker)
42
- series = df['close']
43
- train, test = series[:-test_len], series[-test_len:]
44
-
45
- results = {}
46
-
47
- # ====== ARIMA ======
48
- try:
49
- arima_model = joblib.load("arima_model.pkl")
50
- arima_forecast = arima_model.forecast(steps=len(test))
51
- arima_forecast = pd.Series(arima_forecast, index=test.index)
52
- results['ARIMA'] = {
53
- "forecast": arima_forecast,
54
- "RMSE": rmse(test, arima_forecast),
55
- "MAPE": mean_absolute_percentage_error(test, arima_forecast)
56
- }
57
- except Exception as e:
58
- results['ARIMA'] = {"error": str(e)}
59
-
60
- # ====== Prophet ======
61
- try:
62
- prophet_model = joblib.load("prophet_model.pkl")
63
- future = prophet_model.make_future_dataframe(periods=len(test), freq='D')
64
- forecast = prophet_model.predict(future)
65
- prophet_forecast = forecast.set_index('ds').reindex(test.index)['yhat'].fillna(method='ffill')
66
- results['Prophet'] = {
67
- "forecast": prophet_forecast,
68
- "RMSE": rmse(test, prophet_forecast),
69
- "MAPE": mean_absolute_percentage_error(test, prophet_forecast)
70
- }
71
- except Exception as e:
72
- results['Prophet'] = {"error": str(e)}
73
-
74
- # ====== LSTM (weights only) ======
75
- # try:
76
- # scaler = joblib.load("scaler.pkl")
77
- # lstm_model = build_lstm(window_size=60)
78
- # lstm_model.load_weights("lstm_model.weights.h5") # ✅ weights-only loading
79
-
80
- # scaled_series = scaler.transform(series.values.reshape(-1,1))
81
-
82
- # window_size = 60
83
- # X = []
84
- # for i in range(window_size, len(scaled_series)):
85
- # X.append(scaled_series[i-window_size:i,0])
86
- # X = np.array(X).reshape((-1, window_size, 1))
87
-
88
- # split_index = len(train) - window_size
89
- # X_test = X[split_index:]
90
-
91
- # pred_scaled = lstm_model.predict(X_test, verbose=0)
92
- # pred = scaler.inverse_transform(pred_scaled)
93
- # lstm_forecast = pd.Series(pred.flatten(), index=test.index[:len(pred)])
94
-
95
- # results['LSTM'] = {
96
- # "forecast": lstm_forecast,
97
- # "RMSE": rmse(test[:len(pred)], lstm_forecast),
98
- # "MAPE": mean_absolute_percentage_error(test[:len(pred)], lstm_forecast)
99
- # }
100
- # except Exception as e:
101
- # results['LSTM'] = {"error": str(e)}
102
-
103
- # ===== Plot comparison =====
104
- plt.figure(figsize=(12,5))
105
- plt.plot(train.index[-400:], train[-400:], label="Train")
106
- plt.plot(test.index, test, label="Test")
107
- for model_name, res in results.items():
108
- if "forecast" in res:
109
- plt.plot(res["forecast"].index, res["forecast"], label=f"{model_name} forecast")
110
- plt.legend()
111
- plt.title(f"{ticker} Stock Forecasts")
112
- plt.xlabel("Date"); plt.ylabel("Price")
113
- plt.tight_layout()
114
- plot_path = "forecast_plot.png"
115
- plt.savefig(plot_path)
116
- plt.close()
117
-
118
- # ===== Metrics table =====
119
- metrics = {}
120
- for model_name, res in results.items():
121
- if "RMSE" in res:
122
- metrics[model_name] = {"RMSE": round(res["RMSE"],2), "MAPE": round(res["MAPE"],4)}
123
- else:
124
- metrics[model_name] = {"Error": res["error"]}
125
-
126
- metrics_df = pd.DataFrame(metrics).T
127
-
128
- return plot_path, metrics_df
129
-
130
- # ===== Gradio UI =====
131
  def run_app(ticker):
132
  stock_data = yf.download(ticker, start="2015-01-01", end="2023-01-01")
133
  stock_data = stock_data[['Close']].dropna()
134
 
135
  results = []
136
 
137
- # ARIMA
138
- with open("arima_model.pkl", "rb") as f:
139
- arima_model = pickle.load(f)
140
- arima_forecast = arima_model.forecast(steps=30)
141
- arima_rmse = np.sqrt(mean_squared_error(stock_data['Close'][-30:], arima_forecast))
142
- arima_mape = mean_absolute_percentage_error(stock_data['Close'][-30:], arima_forecast)
143
- results.append(["ARIMA", arima_rmse, arima_mape])
 
 
 
144
 
145
- # Prophet
146
- with open("prophet_model.pkl", "rb") as f:
147
- prophet_model = pickle.load(f)
148
- prophet_future = prophet_model.make_future_dataframe(periods=30)
149
- prophet_forecast = prophet_model.predict(prophet_future)
150
- prophet_forecast = prophet_forecast.set_index("ds").loc[stock_data.index[-30:]]
151
- prophet_rmse = np.sqrt(mean_squared_error(stock_data['Close'][-30:], prophet_forecast['yhat']))
152
- prophet_mape = mean_absolute_percentage_error(stock_data['Close'][-30:], prophet_forecast['yhat'])
153
- results.append(["Prophet", prophet_rmse, prophet_mape])
 
 
 
154
 
155
- # Create metrics table
156
  df_results = pd.DataFrame(results, columns=["Model", "RMSE", "MAPE"])
157
- df_results = df_results.dropna() # remove any NaN rows
158
 
159
- # Plot
160
  plt.figure(figsize=(10, 5))
161
  plt.plot(stock_data.index, stock_data['Close'], label="Actual")
162
- plt.plot(stock_data.index[-30:], arima_forecast, label="ARIMA Forecast")
163
- plt.plot(prophet_forecast.index, prophet_forecast['yhat'], label="Prophet Forecast")
 
 
164
  plt.legend()
165
  plt.title(f"{ticker} - Stock Price Forecasting")
166
  plt.xlabel("Date")
@@ -171,5 +89,17 @@ def run_app(ticker):
171
  return "forecast_plot.png", df_results
172
 
173
 
 
 
 
 
 
 
 
 
 
 
 
 
174
  if __name__ == "__main__":
175
  demo.launch()
 
4
  import matplotlib.pyplot as plt
5
  import yfinance as yf
6
  import joblib
7
+ import pickle
8
  from tensorflow.keras.models import Sequential
9
  from tensorflow.keras.layers import LSTM, Dense, Dropout
10
  from sklearn.metrics import mean_squared_error, mean_absolute_percentage_error
 
13
 
14
  warnings.filterwarnings("ignore")
15
 
16
+ # ===== Utility functions =====
17
  def rmse(a, b):
18
  return math.sqrt(mean_squared_error(a, b))
19
 
20
+ # ===== Download stock data =====
21
  def download_data(ticker, start="2015-01-01", end=None):
22
  df = yf.download(ticker, start=start, end=end, progress=False)
23
  df = df[['Close']].dropna()
 
25
  df.rename(columns={'Close': 'close'}, inplace=True)
26
  return df
27
 
28
+ # ===== LSTM architecture =====
29
  def build_lstm(window_size=60):
30
  model = Sequential([
31
  LSTM(64, return_sequences=True, input_shape=(window_size,1)),
 
37
  model.compile(optimizer="adam", loss="mse")
38
  return model
39
 
40
+ # ===== Forecast function =====
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
41
  def run_app(ticker):
42
  stock_data = yf.download(ticker, start="2015-01-01", end="2023-01-01")
43
  stock_data = stock_data[['Close']].dropna()
44
 
45
  results = []
46
 
47
+ # ===== ARIMA =====
48
+ try:
49
+ with open("arima_model.pkl", "rb") as f:
50
+ arima_model = pickle.load(f)
51
+ arima_forecast = arima_model.forecast(steps=30)
52
+ arima_rmse = np.sqrt(mean_squared_error(stock_data['Close'][-30:], arima_forecast))
53
+ arima_mape = mean_absolute_percentage_error(stock_data['Close'][-30:], arima_forecast)
54
+ results.append(["ARIMA", arima_rmse, arima_mape])
55
+ except Exception as e:
56
+ results.append(["ARIMA", None, f"Error: {str(e)}"])
57
 
58
+ # ===== Prophet =====
59
+ try:
60
+ with open("prophet_model.pkl", "rb") as f:
61
+ prophet_model = pickle.load(f)
62
+ prophet_future = prophet_model.make_future_dataframe(periods=30)
63
+ prophet_forecast = prophet_model.predict(prophet_future)
64
+ prophet_forecast = prophet_forecast.set_index("ds").loc[stock_data.index[-30:]]
65
+ prophet_rmse = np.sqrt(mean_squared_error(stock_data['Close'][-30:], prophet_forecast['yhat']))
66
+ prophet_mape = mean_absolute_percentage_error(stock_data['Close'][-30:], prophet_forecast['yhat'])
67
+ results.append(["Prophet", prophet_rmse, prophet_mape])
68
+ except Exception as e:
69
+ results.append(["Prophet", None, f"Error: {str(e)}"])
70
 
71
+ # ===== Results Table =====
72
  df_results = pd.DataFrame(results, columns=["Model", "RMSE", "MAPE"])
73
+ df_results = df_results.dropna(how="all") # remove any empty rows
74
 
75
+ # ===== Plot =====
76
  plt.figure(figsize=(10, 5))
77
  plt.plot(stock_data.index, stock_data['Close'], label="Actual")
78
+ if "arima_forecast" in locals():
79
+ plt.plot(stock_data.index[-30:], arima_forecast, label="ARIMA Forecast")
80
+ if "prophet_forecast" in locals():
81
+ plt.plot(prophet_forecast.index, prophet_forecast['yhat'], label="Prophet Forecast")
82
  plt.legend()
83
  plt.title(f"{ticker} - Stock Price Forecasting")
84
  plt.xlabel("Date")
 
89
  return "forecast_plot.png", df_results
90
 
91
 
92
+ # ===== Gradio Interface =====
93
+ demo = gr.Interface(
94
+ fn=run_app,
95
+ inputs=gr.Textbox(label="Stock Ticker", placeholder="Enter ticker (e.g. AAPL)"),
96
+ outputs=[
97
+ gr.Image(type="filepath", label="Forecast Plot"),
98
+ gr.Dataframe(label="Performance Metrics")
99
+ ],
100
+ title="📈 Stock Price Forecasting (ARIMA & Prophet)",
101
+ description="This app compares ARIMA and Prophet models on stock closing prices using RMSE & MAPE."
102
+ )
103
+
104
  if __name__ == "__main__":
105
  demo.launch()