Spaces:
Sleeping
Sleeping
Create app.py
Browse files
app.py
ADDED
|
@@ -0,0 +1,67 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import gradio as gr
|
| 2 |
+
import torch
|
| 3 |
+
import numpy as np
|
| 4 |
+
from sklearn.preprocessing import MinMaxScaler
|
| 5 |
+
import pandas as pd
|
| 6 |
+
|
| 7 |
+
# Load and preprocess data
|
| 8 |
+
df = pd.read_csv('HistoricalQuotes.csv')
|
| 9 |
+
df['Date'] = pd.to_datetime(df['Date'], format='%m/%d/%Y')
|
| 10 |
+
df.set_index('Date', inplace=True)
|
| 11 |
+
df = df[[' Close/Last']].rename(columns={' Close/Last': 'Close'})
|
| 12 |
+
df = df.sort_index()
|
| 13 |
+
df['Close'] = df['Close'].replace({r'\$': ''}, regex=True).astype(float)
|
| 14 |
+
|
| 15 |
+
scaler = MinMaxScaler(feature_range=(0, 1))
|
| 16 |
+
scaled_data = scaler.fit_transform(df['Close'].values.reshape(-1, 1))
|
| 17 |
+
|
| 18 |
+
# Define LSTM model
|
| 19 |
+
class LSTMModel(nn.Module):
|
| 20 |
+
def __init__(self, input_size=1, hidden_size=50, num_layers=2, output_size=1, dropout=0.2):
|
| 21 |
+
super().__init__()
|
| 22 |
+
self.lstm = nn.LSTM(input_size, hidden_size, num_layers, batch_first=True, dropout=dropout)
|
| 23 |
+
self.fc = nn.Linear(hidden_size, output_size)
|
| 24 |
+
|
| 25 |
+
def forward(self, x):
|
| 26 |
+
h0 = torch.zeros(num_layers, x.size(0), 50)
|
| 27 |
+
c0 = torch.zeros(num_layers, x.size(0), 50)
|
| 28 |
+
out, _ = self.lstm(x, (h0, c0))
|
| 29 |
+
return self.fc(out[:, -1, :])
|
| 30 |
+
|
| 31 |
+
# Load trained model
|
| 32 |
+
model = LSTMModel()
|
| 33 |
+
model.load_state_dict(torch.load('lstm_model.pth'))
|
| 34 |
+
model.eval()
|
| 35 |
+
|
| 36 |
+
def forecast(past_prices, steps=30):
|
| 37 |
+
try:
|
| 38 |
+
# Parse input (comma-separated prices)
|
| 39 |
+
prices = [float(x.strip().replace('$', '')) for x in past_prices.split(',')]
|
| 40 |
+
if len(prices) < 60:
|
| 41 |
+
return "Error: Please provide at least 60 prices."
|
| 42 |
+
|
| 43 |
+
# Scale and prepare sequence
|
| 44 |
+
prices_scaled = scaler.transform(np.array(prices).reshape(-1, 1))
|
| 45 |
+
current_seq = torch.from_numpy(prices_scaled[-60:].reshape(1, 60, 1)).float()
|
| 46 |
+
|
| 47 |
+
# Forecast
|
| 48 |
+
predictions = []
|
| 49 |
+
for _ in range(steps):
|
| 50 |
+
with torch.no_grad():
|
| 51 |
+
pred_scaled = model(current_seq).item()
|
| 52 |
+
predictions.append(pred_scaled)
|
| 53 |
+
current_seq = torch.cat((current_seq[:, 1:, :], torch.tensor([[[pred_scaled]]]).float()), dim=1)
|
| 54 |
+
|
| 55 |
+
# Inverse transform
|
| 56 |
+
predictions = scaler.inverse_transform(np.array(predictions).reshape(-1, 1)).flatten()
|
| 57 |
+
return pd.DataFrame({'Forecast': predictions}).to_string()
|
| 58 |
+
except Exception as e:
|
| 59 |
+
return f"Error: {str(e)}"
|
| 60 |
+
|
| 61 |
+
# Create Gradio interface
|
| 62 |
+
iface = gr.Interface(
|
| 63 |
+
fn=forecast,
|
| 64 |
+
inputs=gr.Textbox(label="Past Prices (comma-separated, at least 60, e.g., 273.36,273.52,...)"),
|
| 65 |
+
outputs=gr.Textbox(label="Forecasted Prices")
|
| 66 |
+
)
|
| 67 |
+
iface.launch(share=True)
|