Spaces:
Sleeping
Sleeping
Update app.py
Browse files
app.py
CHANGED
|
@@ -1,74 +1,106 @@
|
|
| 1 |
import gradio as gr
|
| 2 |
-
import torch
|
| 3 |
-
import torch.nn as nn
|
| 4 |
-
import numpy as np
|
| 5 |
-
from sklearn.preprocessing import MinMaxScaler
|
| 6 |
import pandas as pd
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 7 |
|
| 8 |
-
# Load data and scaler
|
| 9 |
-
df = pd.read_csv('HistoricalQuotes.csv')
|
| 10 |
-
df['Date'] = pd.to_datetime(df['Date'], format='%m/%d/%Y')
|
| 11 |
-
df = df.sort_index()
|
| 12 |
-
|
| 13 |
-
# Find the closing price column
|
| 14 |
-
possible_columns = [' Close/Last', 'Close', 'close', 'close_last']
|
| 15 |
-
close_column = None
|
| 16 |
-
for col in possible_columns:
|
| 17 |
-
if col in df.columns:
|
| 18 |
-
close_column = col
|
| 19 |
-
break
|
| 20 |
-
|
| 21 |
-
if close_column is None:
|
| 22 |
-
raise KeyError(f"None of {possible_columns} found in columns: {list(df.columns)}")
|
| 23 |
|
| 24 |
-
|
| 25 |
-
|
| 26 |
|
| 27 |
-
scaler = MinMaxScaler(feature_range=(0, 1))
|
| 28 |
-
scaler.fit(df['Close'].values.reshape(-1, 1))
|
| 29 |
|
| 30 |
-
# Define LSTM model
|
| 31 |
class LSTMModel(nn.Module):
|
| 32 |
-
def __init__(self, input_size=1, hidden_size=50, num_layers=2, output_size=1
|
| 33 |
-
super().__init__()
|
| 34 |
-
self.
|
| 35 |
-
self.num_layers = num_layers # Store num_layers as instance variable
|
| 36 |
-
self.lstm = nn.LSTM(input_size, hidden_size, num_layers, batch_first=True, dropout=dropout)
|
| 37 |
self.fc = nn.Linear(hidden_size, output_size)
|
| 38 |
|
| 39 |
def forward(self, x):
|
| 40 |
-
h0 = torch.zeros(
|
| 41 |
-
c0 = torch.zeros(
|
| 42 |
out, _ = self.lstm(x, (h0, c0))
|
| 43 |
-
|
| 44 |
-
|
| 45 |
-
|
| 46 |
-
|
| 47 |
-
|
| 48 |
-
|
| 49 |
-
|
| 50 |
-
|
| 51 |
-
|
| 52 |
-
|
| 53 |
-
|
| 54 |
-
|
| 55 |
-
|
| 56 |
-
|
| 57 |
-
|
| 58 |
-
|
| 59 |
-
|
| 60 |
-
|
| 61 |
-
|
| 62 |
-
|
| 63 |
-
|
| 64 |
-
|
| 65 |
-
|
| 66 |
-
|
| 67 |
-
|
| 68 |
-
|
| 69 |
-
|
| 70 |
-
|
| 71 |
-
|
| 72 |
-
|
| 73 |
-
|
| 74 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
import gradio as gr
|
|
|
|
|
|
|
|
|
|
|
|
|
| 2 |
import pandas as pd
|
| 3 |
+
import numpy as np
|
| 4 |
+
import torch
|
| 5 |
+
import pickle
|
| 6 |
+
import matplotlib.pyplot as plt
|
| 7 |
+
import io
|
| 8 |
+
from torch import nn
|
| 9 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 10 |
|
| 11 |
+
with open("arima.pkl", "rb") as f:
|
| 12 |
+
arima_model = pickle.load(f)
|
| 13 |
|
|
|
|
|
|
|
| 14 |
|
|
|
|
| 15 |
class LSTMModel(nn.Module):
|
| 16 |
+
def __init__(self, input_size=1, hidden_size=50, num_layers=2, output_size=1):
|
| 17 |
+
super(LSTMModel, self).__init__()
|
| 18 |
+
self.lstm = nn.LSTM(input_size, hidden_size, num_layers, batch_first=True)
|
|
|
|
|
|
|
| 19 |
self.fc = nn.Linear(hidden_size, output_size)
|
| 20 |
|
| 21 |
def forward(self, x):
|
| 22 |
+
h0 = torch.zeros(2, x.size(0), 50)
|
| 23 |
+
c0 = torch.zeros(2, x.size(0), 50)
|
| 24 |
out, _ = self.lstm(x, (h0, c0))
|
| 25 |
+
out = self.fc(out[:, -1, :])
|
| 26 |
+
return out
|
| 27 |
+
|
| 28 |
+
# Load trained LSTM
|
| 29 |
+
lstm_model = LSTMModel()
|
| 30 |
+
lstm_model.load_state_dict(torch.load("lstm.pth", map_location=torch.device('cpu')))
|
| 31 |
+
lstm_model.eval()
|
| 32 |
+
|
| 33 |
+
|
| 34 |
+
def predict_arima(values, horizon=10):
|
| 35 |
+
forecast = arima_model.forecast(steps=horizon)
|
| 36 |
+
return forecast.tolist()
|
| 37 |
+
|
| 38 |
+
def predict_lstm(values, horizon=10):
|
| 39 |
+
seq = torch.tensor(values[-50:], dtype=torch.float32).view(1, -1, 1)
|
| 40 |
+
preds = []
|
| 41 |
+
for _ in range(horizon):
|
| 42 |
+
with torch.no_grad():
|
| 43 |
+
pred = lstm_model(seq).item()
|
| 44 |
+
preds.append(pred)
|
| 45 |
+
seq = torch.cat([seq[:, 1:, :], torch.tensor([[[pred]]])], dim=1)
|
| 46 |
+
return preds
|
| 47 |
+
|
| 48 |
+
|
| 49 |
+
def forecast(file, horizon, model_choice):
|
| 50 |
+
df = pd.read_csv(file.name)
|
| 51 |
+
if "Close" not in df.columns:
|
| 52 |
+
return "❌ CSV must contain a 'Close' column", None
|
| 53 |
+
|
| 54 |
+
values = df["Close"].values.tolist()
|
| 55 |
+
|
| 56 |
+
# Run forecasts
|
| 57 |
+
preds_arima = predict_arima(values, horizon)
|
| 58 |
+
preds_lstm = predict_lstm(values, horizon)
|
| 59 |
+
|
| 60 |
+
# Prepare DataFrames
|
| 61 |
+
future_index = [f"t+{i+1}" for i in range(horizon)]
|
| 62 |
+
forecast_df = pd.DataFrame({
|
| 63 |
+
"Future": future_index,
|
| 64 |
+
"ARIMA Forecast": preds_arima,
|
| 65 |
+
"LSTM Forecast": preds_lstm
|
| 66 |
+
})
|
| 67 |
+
|
| 68 |
+
# Plot
|
| 69 |
+
plt.figure(figsize=(10,5))
|
| 70 |
+
plt.plot(range(len(values)), values, label="Historical")
|
| 71 |
+
if model_choice in ["ARIMA", "Compare Both"]:
|
| 72 |
+
plt.plot(range(len(values), len(values)+horizon), preds_arima, label="ARIMA Forecast")
|
| 73 |
+
if model_choice in ["LSTM", "Compare Both"]:
|
| 74 |
+
plt.plot(range(len(values), len(values)+horizon), preds_lstm, label="LSTM Forecast")
|
| 75 |
+
|
| 76 |
+
plt.title(f"{model_choice} Stock Forecast")
|
| 77 |
+
plt.xlabel("Time")
|
| 78 |
+
plt.ylabel("Price")
|
| 79 |
+
plt.legend()
|
| 80 |
+
|
| 81 |
+
buf = io.BytesIO()
|
| 82 |
+
plt.savefig(buf, format="png")
|
| 83 |
+
buf.seek(0)
|
| 84 |
+
|
| 85 |
+
return forecast_df, buf
|
| 86 |
+
|
| 87 |
+
|
| 88 |
+
with gr.Blocks() as demo:
|
| 89 |
+
gr.Markdown("# 📈 Stock Price Forecasting Demo")
|
| 90 |
+
gr.Markdown(
|
| 91 |
+
"Upload a CSV containing stock prices (must have a **'Close'** column). "
|
| 92 |
+
"Choose ARIMA, LSTM, or Compare Both, then set forecast horizon."
|
| 93 |
+
)
|
| 94 |
+
|
| 95 |
+
with gr.Row():
|
| 96 |
+
file = gr.File(label="Upload CSV", file_types=[".csv"])
|
| 97 |
+
horizon = gr.Slider(5, 30, value=10, step=1, label="Forecast Horizon (days)")
|
| 98 |
+
model_choice = gr.Radio(["ARIMA", "LSTM", "Compare Both"], label="Model", value="Compare Both")
|
| 99 |
+
|
| 100 |
+
output_table = gr.DataFrame(label="Forecasted Prices")
|
| 101 |
+
output_plot = gr.Image(type="pil", label="Forecast Plot")
|
| 102 |
+
|
| 103 |
+
submit = gr.Button("Run Forecast")
|
| 104 |
+
submit.click(forecast, inputs=[file, horizon, model_choice], outputs=[output_table, output_plot])
|
| 105 |
+
|
| 106 |
+
demo.launch()
|