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+
import numpy as np
|
| 4 |
+
import matplotlib.pyplot as plt
|
| 5 |
+
import yfinance as yf
|
| 6 |
+
from sklearn.metrics import mean_squared_error, mean_absolute_percentage_error
|
| 7 |
+
import math, warnings
|
| 8 |
+
|
| 9 |
+
from statsmodels.tsa.arima.model import ARIMA
|
| 10 |
+
from prophet import Prophet
|
| 11 |
+
from sklearn.preprocessing import MinMaxScaler
|
| 12 |
+
from tensorflow.keras.models import Sequential
|
| 13 |
+
from tensorflow.keras.layers import LSTM, Dense, Dropout
|
| 14 |
+
|
| 15 |
+
warnings.filterwarnings("ignore")
|
| 16 |
+
|
| 17 |
+
# Utility functions
|
| 18 |
+
def rmse(a, b):
|
| 19 |
+
return math.sqrt(mean_squared_error(a, b))
|
| 20 |
+
|
| 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()
|
| 24 |
+
df.index = pd.to_datetime(df.index)
|
| 25 |
+
df.rename(columns={'Close': 'close'}, inplace=True)
|
| 26 |
+
return df
|
| 27 |
+
|
| 28 |
+
def forecast_models(ticker="AAPL", test_len=180):
|
| 29 |
+
df = download_data(ticker)
|
| 30 |
+
series = df['close']
|
| 31 |
+
train, test = series[:-test_len], series[-test_len:]
|
| 32 |
+
|
| 33 |
+
results = {}
|
| 34 |
+
|
| 35 |
+
# ========== ARIMA ==========
|
| 36 |
+
try:
|
| 37 |
+
arima_model = ARIMA(train, order=(5,1,0))
|
| 38 |
+
arima_fit = arima_model.fit()
|
| 39 |
+
arima_forecast = arima_fit.forecast(steps=len(test))
|
| 40 |
+
arima_forecast = pd.Series(arima_forecast, index=test.index)
|
| 41 |
+
results['ARIMA'] = {
|
| 42 |
+
"forecast": arima_forecast,
|
| 43 |
+
"RMSE": rmse(test, arima_forecast),
|
| 44 |
+
"MAPE": mean_absolute_percentage_error(test, arima_forecast)
|
| 45 |
+
}
|
| 46 |
+
except Exception as e:
|
| 47 |
+
results['ARIMA'] = {"error": str(e)}
|
| 48 |
+
|
| 49 |
+
# ========== Prophet ==========
|
| 50 |
+
try:
|
| 51 |
+
prophet_df = train.reset_index()
|
| 52 |
+
prophet_df.columns = ['ds', 'y']
|
| 53 |
+
m = Prophet(daily_seasonality=True, weekly_seasonality=True, yearly_seasonality=True)
|
| 54 |
+
m.fit(prophet_df)
|
| 55 |
+
future = m.make_future_dataframe(periods=len(test), freq='D')
|
| 56 |
+
forecast = m.predict(future)
|
| 57 |
+
prophet_forecast = forecast.set_index('ds').reindex(test.index)['yhat'].fillna(method='ffill')
|
| 58 |
+
results['Prophet'] = {
|
| 59 |
+
"forecast": prophet_forecast,
|
| 60 |
+
"RMSE": rmse(test, prophet_forecast),
|
| 61 |
+
"MAPE": mean_absolute_percentage_error(test, prophet_forecast)
|
| 62 |
+
}
|
| 63 |
+
except Exception as e:
|
| 64 |
+
results['Prophet'] = {"error": str(e)}
|
| 65 |
+
|
| 66 |
+
# ========== LSTM ==========
|
| 67 |
+
try:
|
| 68 |
+
scaler = MinMaxScaler(feature_range=(0,1))
|
| 69 |
+
scaled_series = scaler.fit_transform(series.values.reshape(-1,1))
|
| 70 |
+
|
| 71 |
+
def create_windows(data, window_size=60):
|
| 72 |
+
X, y = [], []
|
| 73 |
+
for i in range(window_size, len(data)):
|
| 74 |
+
X.append(data[i-window_size:i, 0])
|
| 75 |
+
y.append(data[i,0])
|
| 76 |
+
X, y = np.array(X), np.array(y)
|
| 77 |
+
X = X.reshape((X.shape[0], X.shape[1], 1))
|
| 78 |
+
return X, y
|
| 79 |
+
|
| 80 |
+
window_size = 60
|
| 81 |
+
X_all, y_all = create_windows(scaled_series, window_size=window_size)
|
| 82 |
+
split_index = len(train) - window_size
|
| 83 |
+
X_train, y_train = X_all[:split_index], y_all[:split_index]
|
| 84 |
+
X_test, y_test = X_all[split_index:], y_all[split_index:]
|
| 85 |
+
|
| 86 |
+
model = Sequential([
|
| 87 |
+
LSTM(64, return_sequences=True, input_shape=(window_size,1)),
|
| 88 |
+
Dropout(0.2),
|
| 89 |
+
LSTM(32),
|
| 90 |
+
Dropout(0.2),
|
| 91 |
+
Dense(1)
|
| 92 |
+
])
|
| 93 |
+
model.compile(optimizer='adam', loss='mse')
|
| 94 |
+
model.fit(X_train, y_train, epochs=5, batch_size=32, verbose=0) # smaller epochs for demo
|
| 95 |
+
|
| 96 |
+
pred_scaled = model.predict(X_test, verbose=0)
|
| 97 |
+
pred = scaler.inverse_transform(pred_scaled)
|
| 98 |
+
lstm_forecast = pd.Series(pred.flatten(), index=test.index[:len(pred)])
|
| 99 |
+
|
| 100 |
+
results['LSTM'] = {
|
| 101 |
+
"forecast": lstm_forecast,
|
| 102 |
+
"RMSE": rmse(test[:len(pred)], lstm_forecast),
|
| 103 |
+
"MAPE": mean_absolute_percentage_error(test[:len(pred)], lstm_forecast)
|
| 104 |
+
}
|
| 105 |
+
except Exception as e:
|
| 106 |
+
results['LSTM'] = {"error": str(e)}
|
| 107 |
+
|
| 108 |
+
# ===== Plot comparison =====
|
| 109 |
+
plt.figure(figsize=(12,5))
|
| 110 |
+
plt.plot(train.index[-400:], train[-400:], label="Train")
|
| 111 |
+
plt.plot(test.index, test, label="Test")
|
| 112 |
+
for model_name, res in results.items():
|
| 113 |
+
if "forecast" in res:
|
| 114 |
+
plt.plot(res["forecast"].index, res["forecast"], label=f"{model_name} forecast")
|
| 115 |
+
plt.legend()
|
| 116 |
+
plt.title(f"{ticker} Stock Forecasts")
|
| 117 |
+
plt.xlabel("Date"); plt.ylabel("Price")
|
| 118 |
+
plt.tight_layout()
|
| 119 |
+
plot_path = "forecast_plot.png"
|
| 120 |
+
plt.savefig(plot_path)
|
| 121 |
+
plt.close()
|
| 122 |
+
|
| 123 |
+
# ===== Metrics Table =====
|
| 124 |
+
metrics = {}
|
| 125 |
+
for model_name, res in results.items():
|
| 126 |
+
if "RMSE" in res:
|
| 127 |
+
metrics[model_name] = {"RMSE": round(res["RMSE"],2), "MAPE": round(res["MAPE"],4)}
|
| 128 |
+
else:
|
| 129 |
+
metrics[model_name] = {"Error": res["error"]}
|
| 130 |
+
|
| 131 |
+
metrics_df = pd.DataFrame(metrics).T
|
| 132 |
+
|
| 133 |
+
return plot_path, metrics_df
|
| 134 |
+
|
| 135 |
+
|
| 136 |
+
# Gradio UI
|
| 137 |
+
def run_app(ticker):
|
| 138 |
+
plot_path, metrics_df = forecast_models(ticker)
|
| 139 |
+
return plot_path, metrics_df
|
| 140 |
+
|
| 141 |
+
demo = gr.Interface(
|
| 142 |
+
fn=run_app,
|
| 143 |
+
inputs=gr.Textbox(label="Enter Stock Ticker (e.g., AAPL, MSFT, TSLA)", value="AAPL"),
|
| 144 |
+
outputs=[
|
| 145 |
+
gr.Image(type="filepath", label="Forecast Plot"),
|
| 146 |
+
gr.Dataframe(label="Performance Metrics")
|
| 147 |
+
],
|
| 148 |
+
title="📈 Stock Price Forecasting (ARIMA, Prophet, LSTM)",
|
| 149 |
+
description="This app compares ARIMA, Prophet, and LSTM models on stock closing prices using RMSE & MAPE."
|
| 150 |
+
)
|
| 151 |
+
|
| 152 |
+
if __name__ == "__main__":
|
| 153 |
+
demo.launch()
|