Spaces:
Sleeping
Sleeping
Update app.py
Browse files
app.py
CHANGED
|
@@ -3,9 +3,13 @@ import pandas as pd
|
|
| 3 |
import numpy as np
|
| 4 |
from statsmodels.tsa.arima.model import ARIMA
|
| 5 |
from sklearn.metrics import mean_squared_error, mean_absolute_percentage_error
|
|
|
|
| 6 |
import plotly.graph_objects as go
|
|
|
|
|
|
|
|
|
|
| 7 |
|
| 8 |
-
def
|
| 9 |
df = pd.read_excel("Microsoft_stock_data.xlsx")
|
| 10 |
df['Date'] = pd.to_datetime(df['Date'])
|
| 11 |
df = df.sort_values('Date')
|
|
@@ -15,26 +19,136 @@ def forecast_stock(days_ahead):
|
|
| 15 |
model = ARIMA(data, order=(1,1,1))
|
| 16 |
fitted = model.fit()
|
| 17 |
|
| 18 |
-
|
| 19 |
forecast = fitted.forecast(steps=int(days_ahead))
|
| 20 |
|
| 21 |
-
|
| 22 |
fig = go.Figure()
|
| 23 |
-
fig.add_trace(go.Scatter(x=df['Date'].tail(100), y=data[-100:], name='Historical'))
|
| 24 |
future_dates = pd.date_range(start=df['Date'].iloc[-1], periods=int(days_ahead)+1)[1:]
|
| 25 |
-
fig.add_trace(go.Scatter(x=future_dates, y=forecast, name='Forecast'))
|
| 26 |
-
fig.update_layout(title='Stock Price Forecast', xaxis_title='Date', yaxis_title='Price')
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 27 |
|
| 28 |
return fig
|
| 29 |
|
| 30 |
with gr.Blocks() as demo:
|
| 31 |
gr.Markdown("# 📈 Time Series Forecasting: ARIMA vs LSTM")
|
| 32 |
-
gr.Markdown("**Microsoft Stock Price Forecasting** -
|
| 33 |
|
| 34 |
days = gr.Slider(1, 90, value=30, label="Days to Forecast")
|
| 35 |
-
plot = gr.Plot()
|
| 36 |
|
| 37 |
-
|
| 38 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 39 |
|
| 40 |
demo.launch()
|
|
|
|
| 3 |
import numpy as np
|
| 4 |
from statsmodels.tsa.arima.model import ARIMA
|
| 5 |
from sklearn.metrics import mean_squared_error, mean_absolute_percentage_error
|
| 6 |
+
from sklearn.preprocessing import MinMaxScaler
|
| 7 |
import plotly.graph_objects as go
|
| 8 |
+
from tensorflow import keras
|
| 9 |
+
from tensorflow.keras.models import Sequential
|
| 10 |
+
from tensorflow.keras.layers import LSTM, Dense, Dropout
|
| 11 |
|
| 12 |
+
def forecast_arima(days_ahead):
|
| 13 |
df = pd.read_excel("Microsoft_stock_data.xlsx")
|
| 14 |
df['Date'] = pd.to_datetime(df['Date'])
|
| 15 |
df = df.sort_values('Date')
|
|
|
|
| 19 |
model = ARIMA(data, order=(1,1,1))
|
| 20 |
fitted = model.fit()
|
| 21 |
|
|
|
|
| 22 |
forecast = fitted.forecast(steps=int(days_ahead))
|
| 23 |
|
|
|
|
| 24 |
fig = go.Figure()
|
| 25 |
+
fig.add_trace(go.Scatter(x=df['Date'].tail(100), y=data[-100:], name='Historical', line=dict(color='blue')))
|
| 26 |
future_dates = pd.date_range(start=df['Date'].iloc[-1], periods=int(days_ahead)+1)[1:]
|
| 27 |
+
fig.add_trace(go.Scatter(x=future_dates, y=forecast, name='ARIMA Forecast', line=dict(color='red')))
|
| 28 |
+
fig.update_layout(title='ARIMA Stock Price Forecast', xaxis_title='Date', yaxis_title='Price')
|
| 29 |
+
|
| 30 |
+
return fig
|
| 31 |
+
|
| 32 |
+
def forecast_lstm(days_ahead):
|
| 33 |
+
df = pd.read_excel("Microsoft_stock_data.xlsx")
|
| 34 |
+
df['Date'] = pd.to_datetime(df['Date'])
|
| 35 |
+
df = df.sort_values('Date')
|
| 36 |
+
|
| 37 |
+
data = df['Close'].values.reshape(-1, 1)
|
| 38 |
+
|
| 39 |
+
scaler = MinMaxScaler(feature_range=(0, 1))
|
| 40 |
+
scaled_data = scaler.fit_transform(data)
|
| 41 |
+
|
| 42 |
+
lookback = 60
|
| 43 |
+
X_train, y_train = [], []
|
| 44 |
+
for i in range(lookback, len(scaled_data)):
|
| 45 |
+
X_train.append(scaled_data[i-lookback:i, 0])
|
| 46 |
+
y_train.append(scaled_data[i, 0])
|
| 47 |
+
|
| 48 |
+
X_train, y_train = np.array(X_train), np.array(y_train)
|
| 49 |
+
X_train = np.reshape(X_train, (X_train.shape[0], X_train.shape[1], 1))
|
| 50 |
+
|
| 51 |
+
model = Sequential([
|
| 52 |
+
LSTM(units=50, return_sequences=True, input_shape=(X_train.shape[1], 1)),
|
| 53 |
+
Dropout(0.2),
|
| 54 |
+
LSTM(units=50, return_sequences=False),
|
| 55 |
+
Dropout(0.2),
|
| 56 |
+
Dense(units=25),
|
| 57 |
+
Dense(units=1)
|
| 58 |
+
])
|
| 59 |
+
|
| 60 |
+
model.compile(optimizer='adam', loss='mean_squared_error')
|
| 61 |
+
model.fit(X_train, y_train, batch_size=32, epochs=10, verbose=0)
|
| 62 |
+
|
| 63 |
+
last_sequence = scaled_data[-lookback:]
|
| 64 |
+
forecast = []
|
| 65 |
+
|
| 66 |
+
for _ in range(int(days_ahead)):
|
| 67 |
+
prediction = model.predict(last_sequence.reshape(1, lookback, 1), verbose=0)
|
| 68 |
+
forecast.append(prediction[0, 0])
|
| 69 |
+
last_sequence = np.append(last_sequence[1:], prediction)
|
| 70 |
+
|
| 71 |
+
forecast = scaler.inverse_transform(np.array(forecast).reshape(-1, 1))
|
| 72 |
+
|
| 73 |
+
fig = go.Figure()
|
| 74 |
+
fig.add_trace(go.Scatter(x=df['Date'].tail(100), y=data[-100:, 0], name='Historical', line=dict(color='blue')))
|
| 75 |
+
future_dates = pd.date_range(start=df['Date'].iloc[-1], periods=int(days_ahead)+1)[1:]
|
| 76 |
+
fig.add_trace(go.Scatter(x=future_dates, y=forecast.flatten(), name='LSTM Forecast', line=dict(color='green')))
|
| 77 |
+
fig.update_layout(title='LSTM Stock Price Forecast', xaxis_title='Date', yaxis_title='Price')
|
| 78 |
+
|
| 79 |
+
return fig
|
| 80 |
+
|
| 81 |
+
def forecast_comparison(days_ahead):
|
| 82 |
+
df = pd.read_excel("Microsoft_stock_data.xlsx")
|
| 83 |
+
df['Date'] = pd.to_datetime(df['Date'])
|
| 84 |
+
df = df.sort_values('Date')
|
| 85 |
+
|
| 86 |
+
data = df['Close'].values
|
| 87 |
+
|
| 88 |
+
arima_model = ARIMA(data, order=(1,1,1))
|
| 89 |
+
arima_fitted = arima_model.fit()
|
| 90 |
+
arima_forecast = arima_fitted.forecast(steps=int(days_ahead))
|
| 91 |
+
|
| 92 |
+
scaled_data = MinMaxScaler(feature_range=(0, 1)).fit_transform(data.reshape(-1, 1))
|
| 93 |
+
lookback = 60
|
| 94 |
+
X_train, y_train = [], []
|
| 95 |
+
for i in range(lookback, len(scaled_data)):
|
| 96 |
+
X_train.append(scaled_data[i-lookback:i, 0])
|
| 97 |
+
y_train.append(scaled_data[i, 0])
|
| 98 |
+
|
| 99 |
+
X_train, y_train = np.array(X_train), np.array(y_train)
|
| 100 |
+
X_train = np.reshape(X_train, (X_train.shape[0], X_train.shape[1], 1))
|
| 101 |
+
|
| 102 |
+
lstm_model = Sequential([
|
| 103 |
+
LSTM(units=50, return_sequences=True, input_shape=(X_train.shape[1], 1)),
|
| 104 |
+
Dropout(0.2),
|
| 105 |
+
LSTM(units=50, return_sequences=False),
|
| 106 |
+
Dropout(0.2),
|
| 107 |
+
Dense(units=25),
|
| 108 |
+
Dense(units=1)
|
| 109 |
+
])
|
| 110 |
+
|
| 111 |
+
lstm_model.compile(optimizer='adam', loss='mean_squared_error')
|
| 112 |
+
lstm_model.fit(X_train, y_train, batch_size=32, epochs=10, verbose=0)
|
| 113 |
+
|
| 114 |
+
scaler = MinMaxScaler(feature_range=(0, 1)).fit(data.reshape(-1, 1))
|
| 115 |
+
last_sequence = scaled_data[-lookback:]
|
| 116 |
+
lstm_forecast = []
|
| 117 |
+
|
| 118 |
+
for _ in range(int(days_ahead)):
|
| 119 |
+
prediction = lstm_model.predict(last_sequence.reshape(1, lookback, 1), verbose=0)
|
| 120 |
+
lstm_forecast.append(prediction[0, 0])
|
| 121 |
+
last_sequence = np.append(last_sequence[1:], prediction)
|
| 122 |
+
|
| 123 |
+
lstm_forecast = scaler.inverse_transform(np.array(lstm_forecast).reshape(-1, 1)).flatten()
|
| 124 |
+
|
| 125 |
+
fig = go.Figure()
|
| 126 |
+
fig.add_trace(go.Scatter(x=df['Date'].tail(100), y=data[-100:], name='Historical', line=dict(color='blue')))
|
| 127 |
+
future_dates = pd.date_range(start=df['Date'].iloc[-1], periods=int(days_ahead)+1)[1:]
|
| 128 |
+
fig.add_trace(go.Scatter(x=future_dates, y=arima_forecast, name='ARIMA Forecast', line=dict(color='red', dash='dash')))
|
| 129 |
+
fig.add_trace(go.Scatter(x=future_dates, y=lstm_forecast, name='LSTM Forecast', line=dict(color='green', dash='dot')))
|
| 130 |
+
fig.update_layout(title='ARIMA vs LSTM: Stock Price Forecast Comparison', xaxis_title='Date', yaxis_title='Price')
|
| 131 |
|
| 132 |
return fig
|
| 133 |
|
| 134 |
with gr.Blocks() as demo:
|
| 135 |
gr.Markdown("# 📈 Time Series Forecasting: ARIMA vs LSTM")
|
| 136 |
+
gr.Markdown("**Microsoft Stock Price Forecasting** - Compare ARIMA and LSTM models.")
|
| 137 |
|
| 138 |
days = gr.Slider(1, 90, value=30, label="Days to Forecast")
|
|
|
|
| 139 |
|
| 140 |
+
with gr.Tabs():
|
| 141 |
+
with gr.Tab("ARIMA Model"):
|
| 142 |
+
arima_plot = gr.Plot()
|
| 143 |
+
days.change(forecast_arima, days, arima_plot)
|
| 144 |
+
demo.load(forecast_arima, days, arima_plot)
|
| 145 |
+
|
| 146 |
+
with gr.Tab("LSTM Model"):
|
| 147 |
+
lstm_plot = gr.Plot()
|
| 148 |
+
days.change(forecast_lstm, days, lstm_plot)
|
| 149 |
+
|
| 150 |
+
with gr.Tab("Comparison"):
|
| 151 |
+
comparison_plot = gr.Plot()
|
| 152 |
+
days.change(forecast_comparison, days, comparison_plot)
|
| 153 |
|
| 154 |
demo.launch()
|