Spaces:
Sleeping
Sleeping
Update app.py
Browse files
app.py
CHANGED
|
@@ -2,12 +2,11 @@ import gradio as gr
|
|
| 2 |
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 |
-
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")
|
|
@@ -39,6 +38,7 @@ def forecast_lstm(days_ahead):
|
|
| 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)):
|
|
@@ -47,7 +47,7 @@ def forecast_lstm(days_ahead):
|
|
| 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),
|
|
@@ -60,6 +60,7 @@ def forecast_lstm(days_ahead):
|
|
| 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 |
|
|
@@ -70,6 +71,7 @@ def forecast_lstm(days_ahead):
|
|
| 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:]
|
|
@@ -85,11 +87,15 @@ def forecast_comparison(days_ahead):
|
|
| 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 |
-
|
|
|
|
|
|
|
|
|
|
| 93 |
lookback = 60
|
| 94 |
X_train, y_train = [], []
|
| 95 |
for i in range(lookback, len(scaled_data)):
|
|
@@ -111,7 +117,6 @@ def forecast_comparison(days_ahead):
|
|
| 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 |
|
|
@@ -122,15 +127,17 @@ def forecast_comparison(days_ahead):
|
|
| 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:
|
| 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.")
|
|
@@ -140,15 +147,22 @@ with gr.Blocks() as demo:
|
|
| 140 |
with gr.Tabs():
|
| 141 |
with gr.Tab("ARIMA Model"):
|
| 142 |
arima_plot = gr.Plot()
|
| 143 |
-
|
| 144 |
-
|
|
|
|
|
|
|
| 145 |
|
| 146 |
with gr.Tab("LSTM Model"):
|
| 147 |
lstm_plot = gr.Plot()
|
| 148 |
-
|
|
|
|
| 149 |
|
| 150 |
with gr.Tab("Comparison"):
|
| 151 |
comparison_plot = gr.Plot()
|
| 152 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
| 153 |
|
| 154 |
demo.launch()
|
|
|
|
| 2 |
import pandas as pd
|
| 3 |
import numpy as np
|
| 4 |
from statsmodels.tsa.arima.model import ARIMA
|
|
|
|
|
|
|
| 5 |
import plotly.graph_objects as go
|
| 6 |
from tensorflow import keras
|
| 7 |
from tensorflow.keras.models import Sequential
|
| 8 |
from tensorflow.keras.layers import LSTM, Dense, Dropout
|
| 9 |
+
from sklearn.preprocessing import MinMaxScaler
|
| 10 |
|
| 11 |
def forecast_arima(days_ahead):
|
| 12 |
df = pd.read_excel("Microsoft_stock_data.xlsx")
|
|
|
|
| 38 |
scaler = MinMaxScaler(feature_range=(0, 1))
|
| 39 |
scaled_data = scaler.fit_transform(data)
|
| 40 |
|
| 41 |
+
|
| 42 |
lookback = 60
|
| 43 |
X_train, y_train = [], []
|
| 44 |
for i in range(lookback, len(scaled_data)):
|
|
|
|
| 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),
|
|
|
|
| 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 |
+
|
| 64 |
last_sequence = scaled_data[-lookback:]
|
| 65 |
forecast = []
|
| 66 |
|
|
|
|
| 71 |
|
| 72 |
forecast = scaler.inverse_transform(np.array(forecast).reshape(-1, 1))
|
| 73 |
|
| 74 |
+
|
| 75 |
fig = go.Figure()
|
| 76 |
fig.add_trace(go.Scatter(x=df['Date'].tail(100), y=data[-100:, 0], name='Historical', line=dict(color='blue')))
|
| 77 |
future_dates = pd.date_range(start=df['Date'].iloc[-1], periods=int(days_ahead)+1)[1:]
|
|
|
|
| 87 |
|
| 88 |
data = df['Close'].values
|
| 89 |
|
| 90 |
+
|
| 91 |
arima_model = ARIMA(data, order=(1,1,1))
|
| 92 |
arima_fitted = arima_model.fit()
|
| 93 |
arima_forecast = arima_fitted.forecast(steps=int(days_ahead))
|
| 94 |
|
| 95 |
+
|
| 96 |
+
scaler = MinMaxScaler(feature_range=(0, 1))
|
| 97 |
+
scaled_data = scaler.fit_transform(data.reshape(-1, 1))
|
| 98 |
+
|
| 99 |
lookback = 60
|
| 100 |
X_train, y_train = [], []
|
| 101 |
for i in range(lookback, len(scaled_data)):
|
|
|
|
| 117 |
lstm_model.compile(optimizer='adam', loss='mean_squared_error')
|
| 118 |
lstm_model.fit(X_train, y_train, batch_size=32, epochs=10, verbose=0)
|
| 119 |
|
|
|
|
| 120 |
last_sequence = scaled_data[-lookback:]
|
| 121 |
lstm_forecast = []
|
| 122 |
|
|
|
|
| 127 |
|
| 128 |
lstm_forecast = scaler.inverse_transform(np.array(lstm_forecast).reshape(-1, 1)).flatten()
|
| 129 |
|
| 130 |
+
|
| 131 |
fig = go.Figure()
|
| 132 |
fig.add_trace(go.Scatter(x=df['Date'].tail(100), y=data[-100:], name='Historical', line=dict(color='blue')))
|
| 133 |
future_dates = pd.date_range(start=df['Date'].iloc[-1], periods=int(days_ahead)+1)[1:]
|
| 134 |
fig.add_trace(go.Scatter(x=future_dates, y=arima_forecast, name='ARIMA Forecast', line=dict(color='red', dash='dash')))
|
| 135 |
fig.add_trace(go.Scatter(x=future_dates, y=lstm_forecast, name='LSTM Forecast', line=dict(color='green', dash='dot')))
|
| 136 |
+
fig.update_layout(title='ARIMA vs LSTM: Comparison', xaxis_title='Date', yaxis_title='Price')
|
| 137 |
|
| 138 |
return fig
|
| 139 |
|
| 140 |
+
|
| 141 |
with gr.Blocks() as demo:
|
| 142 |
gr.Markdown("# 📈 Time Series Forecasting: ARIMA vs LSTM")
|
| 143 |
gr.Markdown("**Microsoft Stock Price Forecasting** - Compare ARIMA and LSTM models.")
|
|
|
|
| 147 |
with gr.Tabs():
|
| 148 |
with gr.Tab("ARIMA Model"):
|
| 149 |
arima_plot = gr.Plot()
|
| 150 |
+
arima_btn = gr.Button("Generate ARIMA Forecast")
|
| 151 |
+
arima_btn.click(forecast_arima, inputs=days, outputs=arima_plot)
|
| 152 |
+
|
| 153 |
+
demo.load(forecast_arima, inputs=days, outputs=arima_plot)
|
| 154 |
|
| 155 |
with gr.Tab("LSTM Model"):
|
| 156 |
lstm_plot = gr.Plot()
|
| 157 |
+
lstm_btn = gr.Button("Generate LSTM Forecast")
|
| 158 |
+
lstm_btn.click(forecast_lstm, inputs=days, outputs=lstm_plot)
|
| 159 |
|
| 160 |
with gr.Tab("Comparison"):
|
| 161 |
comparison_plot = gr.Plot()
|
| 162 |
+
compare_btn = gr.Button("Compare Both Models")
|
| 163 |
+
compare_btn.click(forecast_comparison, inputs=days, outputs=comparison_plot)
|
| 164 |
+
|
| 165 |
+
|
| 166 |
+
days.change(forecast_arima, inputs=days, outputs=arima_plot)
|
| 167 |
|
| 168 |
demo.launch()
|