Spaces:
Sleeping
Sleeping
Update app.py
Browse files
app.py
CHANGED
|
@@ -67,17 +67,14 @@ def build_train_test_for_window(df: pd.DataFrame, start_sel: date, end_sel: date
|
|
| 67 |
Train = all history strictly before start_sel (business days).
|
| 68 |
Test = start_sel..end_sel inclusive (business days).
|
| 69 |
"""
|
| 70 |
-
#
|
| 71 |
-
idx = df.index
|
| 72 |
-
# align selection to nearest business days inside universe
|
| 73 |
start_sel = clip_to_universe(start_sel)
|
| 74 |
end_sel = clip_to_universe(end_sel)
|
| 75 |
if start_sel > end_sel:
|
| 76 |
raise ValueError("Selected start date must be <= end date.")
|
| 77 |
|
| 78 |
-
|
| 79 |
-
|
| 80 |
-
test_mask = (idx >= pd.Timestamp(start_sel)) & (idx <= pd.Timestamp(end_sel))
|
| 81 |
|
| 82 |
train_s = df.loc[train_mask, 'Close']
|
| 83 |
test_s = df.loc[test_mask, 'Close']
|
|
@@ -114,11 +111,11 @@ def arima_roll_eval(train_s: pd.Series, test_s: pd.Series, order=(2,1,2)):
|
|
| 114 |
preds, trues = [], []
|
| 115 |
for i in range(len(test_s)):
|
| 116 |
fcast = res.forecast(1)
|
| 117 |
-
fval = float(np.asarray(fcast).reshape(-1)[0]) # robust scalar
|
| 118 |
preds.append(fval)
|
| 119 |
trues.append(float(test_s.iloc[i]))
|
| 120 |
try:
|
| 121 |
-
res = res.append(test_s.iloc[i:i+1]) # update state with
|
| 122 |
except Exception:
|
| 123 |
res = ARIMA(pd.concat([train_s, test_s.iloc[:i+1]]), order=order,
|
| 124 |
enforce_stationarity=False, enforce_invertibility=False).fit()
|
|
@@ -212,7 +209,7 @@ def lstm_roll_eval(train_s: pd.Series, test_s: pd.Series):
|
|
| 212 |
return np.array(trues), np.array(preds)
|
| 213 |
|
| 214 |
# =========================
|
| 215 |
-
# Metrics &
|
| 216 |
# =========================
|
| 217 |
def metrics_df(y_true, y_pred) -> pd.DataFrame:
|
| 218 |
rmse = math.sqrt(mean_squared_error(y_true, y_pred))
|
|
@@ -233,7 +230,7 @@ def plot_series(dates, actual, pred, title):
|
|
| 233 |
# =========================
|
| 234 |
# Main callback
|
| 235 |
# =========================
|
| 236 |
-
def run_evaluation(ticker_choice: str,
|
| 237 |
"""
|
| 238 |
Evaluate pretrained ARIMA + LSTM on [start_sel, end_sel] inside the fixed universe.
|
| 239 |
Show metrics, two plots, and table (Date, Actual, ARIMA, LSTM).
|
|
@@ -243,9 +240,12 @@ def run_evaluation(ticker_choice: str, start_sel: str, end_sel: str):
|
|
| 243 |
if not ticker:
|
| 244 |
raise ValueError("Please choose a stock.")
|
| 245 |
|
| 246 |
-
# Parse user-
|
| 247 |
-
|
| 248 |
-
|
|
|
|
|
|
|
|
|
|
| 249 |
if s_sel > e_sel:
|
| 250 |
raise ValueError("Start date must be before or equal to end date.")
|
| 251 |
# Fetch universe data and build window train/test
|
|
@@ -291,7 +291,7 @@ def run_evaluation(ticker_choice: str, start_sel: str, end_sel: str):
|
|
| 291 |
kpi = (
|
| 292 |
f"**Ticker:** {ticker} | **Window:** {s_sel} → {e_sel} \n"
|
| 293 |
f"**ARIMA {order}** — RMSE: {ar_tbl['RMSE'][0]:.2f} | MAE: {ar_tbl['MAE'][0]:.2f} | MAPE: {ar_tbl['MAPE (%)'][0]:.2f}% \n"
|
| 294 |
-
f"**LSTM (lookback={lookback})** — RMSE: {lstm_tbl['RMSE'][0]:.2f} | MAE: {lstm_tbl['MAE'][0]:.2f} | MAPE: {lstm_tbl['MAPE (%)'][0]:.2f}%"
|
| 295 |
)
|
| 296 |
|
| 297 |
return kpi, fig_arima, fig_lstm, table
|
|
@@ -316,9 +316,18 @@ with gr.Blocks(title="DataSynthis_ML_JobTask", theme=gr.themes.Soft()) as demo:
|
|
| 316 |
with gr.Row():
|
| 317 |
ticker_choice = gr.Dropdown(choices=POPULAR, value="AAPL",
|
| 318 |
label="Choose a stock")
|
|
|
|
| 319 |
with gr.Row():
|
| 320 |
-
start_sel = gr.
|
| 321 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 322 |
|
| 323 |
run_btn = gr.Button("Run Evaluation", variant="primary")
|
| 324 |
|
|
|
|
| 67 |
Train = all history strictly before start_sel (business days).
|
| 68 |
Test = start_sel..end_sel inclusive (business days).
|
| 69 |
"""
|
| 70 |
+
# align selection to universe
|
|
|
|
|
|
|
| 71 |
start_sel = clip_to_universe(start_sel)
|
| 72 |
end_sel = clip_to_universe(end_sel)
|
| 73 |
if start_sel > end_sel:
|
| 74 |
raise ValueError("Selected start date must be <= end date.")
|
| 75 |
|
| 76 |
+
train_mask = df.index < pd.Timestamp(start_sel)
|
| 77 |
+
test_mask = (df.index >= pd.Timestamp(start_sel)) & (df.index <= pd.Timestamp(end_sel))
|
|
|
|
| 78 |
|
| 79 |
train_s = df.loc[train_mask, 'Close']
|
| 80 |
test_s = df.loc[test_mask, 'Close']
|
|
|
|
| 111 |
preds, trues = [], []
|
| 112 |
for i in range(len(test_s)):
|
| 113 |
fcast = res.forecast(1)
|
| 114 |
+
fval = float(np.asarray(fcast).reshape(-1)[0]) # robust scalar
|
| 115 |
preds.append(fval)
|
| 116 |
trues.append(float(test_s.iloc[i]))
|
| 117 |
try:
|
| 118 |
+
res = res.append(test_s.iloc[i:i+1]) # update state with realized value
|
| 119 |
except Exception:
|
| 120 |
res = ARIMA(pd.concat([train_s, test_s.iloc[:i+1]]), order=order,
|
| 121 |
enforce_stationarity=False, enforce_invertibility=False).fit()
|
|
|
|
| 209 |
return np.array(trues), np.array(preds)
|
| 210 |
|
| 211 |
# =========================
|
| 212 |
+
# Metrics & plotting
|
| 213 |
# =========================
|
| 214 |
def metrics_df(y_true, y_pred) -> pd.DataFrame:
|
| 215 |
rmse = math.sqrt(mean_squared_error(y_true, y_pred))
|
|
|
|
| 230 |
# =========================
|
| 231 |
# Main callback
|
| 232 |
# =========================
|
| 233 |
+
def run_evaluation(ticker_choice: str, start_sel_txt: str, end_sel_txt: str):
|
| 234 |
"""
|
| 235 |
Evaluate pretrained ARIMA + LSTM on [start_sel, end_sel] inside the fixed universe.
|
| 236 |
Show metrics, two plots, and table (Date, Actual, ARIMA, LSTM).
|
|
|
|
| 240 |
if not ticker:
|
| 241 |
raise ValueError("Please choose a stock.")
|
| 242 |
|
| 243 |
+
# Parse user-entered dates (text boxes) -> YYYY-MM-DD
|
| 244 |
+
def parse_date(s: str) -> date:
|
| 245 |
+
return datetime.strptime(s.strip(), "%Y-%m-%d").date()
|
| 246 |
+
|
| 247 |
+
s_sel = clip_to_universe(parse_date(start_sel_txt))
|
| 248 |
+
e_sel = clip_to_universe(parse_date(end_sel_txt))
|
| 249 |
if s_sel > e_sel:
|
| 250 |
raise ValueError("Start date must be before or equal to end date.")
|
| 251 |
# Fetch universe data and build window train/test
|
|
|
|
| 291 |
kpi = (
|
| 292 |
f"**Ticker:** {ticker} | **Window:** {s_sel} → {e_sel} \n"
|
| 293 |
f"**ARIMA {order}** — RMSE: {ar_tbl['RMSE'][0]:.2f} | MAE: {ar_tbl['MAE'][0]:.2f} | MAPE: {ar_tbl['MAPE (%)'][0]:.2f}% \n"
|
| 294 |
+
f"**LSTM (lookback={lookback})** — RMSE: {lstm_tbl['RMSE'][0]:.2f} | MAE: {lstm_tbl['MAE'][0]:.2f} | MAPE: {lstm_tbl['MAPE (%)'][0]::.2f}%"
|
| 295 |
)
|
| 296 |
|
| 297 |
return kpi, fig_arima, fig_lstm, table
|
|
|
|
| 316 |
with gr.Row():
|
| 317 |
ticker_choice = gr.Dropdown(choices=POPULAR, value="AAPL",
|
| 318 |
label="Choose a stock")
|
| 319 |
+
|
| 320 |
with gr.Row():
|
| 321 |
+
start_sel = gr.Textbox(
|
| 322 |
+
label="Start date (YYYY-MM-DD, inside universe)",
|
| 323 |
+
value=str(UNIVERSE_START),
|
| 324 |
+
placeholder="YYYY-MM-DD"
|
| 325 |
+
)
|
| 326 |
+
end_sel = gr.Textbox(
|
| 327 |
+
label="End date (YYYY-MM-DD, inside universe)",
|
| 328 |
+
value=str(UNIVERSE_END),
|
| 329 |
+
placeholder="YYYY-MM-DD"
|
| 330 |
+
)
|
| 331 |
|
| 332 |
run_btn = gr.Button("Run Evaluation", variant="primary")
|
| 333 |
|