Rhythm05 commited on
Commit
f73838f
·
verified ·
1 Parent(s): ba29762

Create app.py

Browse files
Files changed (1) hide show
  1. app.py +144 -0
app.py ADDED
@@ -0,0 +1,144 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import gradio as gr
2
+ import yfinance as yf
3
+ import pandas as pd
4
+ import numpy as np
5
+ from statsmodels.tsa.arima.model import ARIMA
6
+ import joblib
7
+ from datetime import datetime, timedelta
8
+ import warnings
9
+ warnings.filterwarnings('ignore')
10
+
11
+ # Load the saved ARIMA model (upload 'arima_model.pkl' to your Space)
12
+ try:
13
+ checkpoint = joblib.load('arima_model.pkl')
14
+ loaded_fit = checkpoint['model_fit']
15
+ last_train_date = checkpoint['last_date']
16
+ order = checkpoint['order']
17
+ print(f"Model loaded successfully. Last training date: {last_train_date}")
18
+ except FileNotFoundError:
19
+ print("Model file not found. Starting with a fresh fit.")
20
+ loaded_fit = None
21
+ last_train_date = None
22
+ order = (5, 1, 0)
23
+
24
+ # Function to fetch S&P 500 data
25
+ def fetch_data(start_date=None, period="max"):
26
+ ticker = yf.Ticker("^GSPC")
27
+ if start_date:
28
+ data = ticker.history(start=start_date, period=period)
29
+ else:
30
+ data = ticker.history(period=period)
31
+ data = data['Close'].dropna()
32
+ # normalize index to tz-naive datetimes to avoid tz-aware vs tz-naive comparisons
33
+ try:
34
+ idx = data.index
35
+ # try removing timezone if present
36
+ if getattr(idx, 'tz', None) is not None:
37
+ try:
38
+ data.index = idx.tz_convert(None)
39
+ except Exception:
40
+ data.index = idx.tz_localize(None)
41
+ except Exception:
42
+ # fallback: ensure datetime conversion
43
+ data.index = pd.to_datetime(data.index)
44
+ return data
45
+
46
+ # Function to update model with new data if needed
47
+ def update_model(model_fit, new_data, order):
48
+ if hasattr(model_fit.model.endog, 'index'):
49
+ updated_fit = model_fit.append(new_data, refit=False)
50
+ else:
51
+ updated_fit = model_fit.append(new_data.values, refit=False)
52
+ return updated_fit
53
+
54
+ # Function to predict next n steps
55
+ def predict_arima(model_fit, n_steps=1):
56
+ predictions = model_fit.forecast(steps=n_steps)
57
+ return predictions
58
+
59
+ # Main prediction function for Gradio
60
+ def forecast_sp500_arima(n_days, refit=False):
61
+ global loaded_fit, last_train_date # To update global state if needed
62
+
63
+ data = fetch_data()
64
+
65
+ if refit or loaded_fit is None:
66
+ # Refit on full current data
67
+ model = ARIMA(data, order=order)
68
+ loaded_fit = model.fit()
69
+ last_train_date = data.index[-1].date()
70
+ print("Model refitted on latest data.")
71
+ else:
72
+ # Determine last model date
73
+ if hasattr(loaded_fit.model.endog, 'index'):
74
+ # ensure we have a pandas.Timestamp
75
+ last_model_date = pd.to_datetime(loaded_fit.model.endog.index[-1])
76
+ else:
77
+ # last_train_date was saved as a date object; convert to Timestamp
78
+ last_model_date = pd.to_datetime(last_train_date)
79
+
80
+ # Use date() for comparison to avoid tz-aware vs tz-naive issues
81
+ new_start_str = (last_model_date.date() + timedelta(days=1)).strftime('%Y-%m-%d')
82
+ new_data = fetch_data(start_date=new_start_str)
83
+
84
+ appended = False
85
+ if len(new_data) > 0:
86
+ new_first = pd.to_datetime(new_data.index[0])
87
+ # compare dates (tz-naive) to avoid TypeError when indices have tz info
88
+ if new_first.date() > last_model_date.date():
89
+ # Instead of using append (which can change the model's index to a RangeIndex),
90
+ # refit the ARIMA on the full current data to preserve a DatetimeIndex and
91
+ # avoid indexing issues during prediction.
92
+ try:
93
+ model = ARIMA(data, order=order)
94
+ loaded_fit = model.fit()
95
+ appended = True
96
+ print("Model refitted with new data.")
97
+ except Exception as e:
98
+ print(f"Refit failed: {e}. Using existing model.")
99
+ else:
100
+ print(f"New data starts at {new_first}, model ends at {last_model_date}; no extension.")
101
+ else:
102
+ print("No new data available.")
103
+
104
+ if appended:
105
+ # keep last_train_date as a date for consistency
106
+ last_train_date = data.index[-1].date()
107
+
108
+ predictions = predict_arima(loaded_fit, n_days)
109
+
110
+ last_date = data.index[-1]
111
+ future_dates = [last_date + timedelta(days=i+1) for i in range(n_days)]
112
+
113
+ results = pd.DataFrame({
114
+ 'Date': future_dates,
115
+ 'Predicted Close': predictions
116
+ })
117
+
118
+ # Last actual price
119
+ last_actual = data.iloc[-1]
120
+
121
+ return f"Last Actual Close ({last_date.date()}): ${last_actual:.2f}\n\nForecast:\n{results.to_string(index=False)}"
122
+
123
+ # Gradio interface
124
+ with gr.Blocks(title="S&P 500 ARIMA Forecaster (Saved Model)") as demo:
125
+ gr.Markdown("# S&P 500 Stock Price Forecaster\nUsing saved ARIMA model with optional updates. \n Use int number for Price Forecast Prediction.")
126
+
127
+ with gr.Row():
128
+ n_days = gr.Slider(minimum=1, maximum=30, value=5, label="Number of days to forecast")
129
+ refit_btn = gr.Checkbox(label="Refit model on latest data (ignores saved model)", value=False)
130
+
131
+ predict_btn = gr.Button("Generate Forecast")
132
+
133
+ output = gr.Textbox(label="Forecast Results")
134
+
135
+ predict_btn.click(
136
+ fn=forecast_sp500_arima,
137
+ inputs=[n_days, refit_btn],
138
+ outputs=output
139
+ )
140
+
141
+ gr.Markdown("### Notes:\n- Loads saved ARIMA model from 'arima_model.pkl'.\n- Checks and appends new data only if it extends the model's index.\n- Falls back gracefully if append fails.\n- Data fetched via yfinance.\n- ARIMA order (5,1,0) used.\n- Upload 'arima_model.pkl' to your Space.")
142
+
143
+ if __name__ == "__main__":
144
+ demo.launch()