Upload 2 files
Browse files- app.py +75 -2
- runtime.py +15 -0
app.py
CHANGED
|
@@ -240,14 +240,17 @@ def attach_market_state(payload: dict) -> dict:
|
|
| 240 |
try:
|
| 241 |
models_dir = Path(__file__).resolve().parent / "models"
|
| 242 |
mfe_out = models_dir / "nifty_opening_mfe_regressor" / "outputs"
|
|
|
|
| 243 |
if (mfe_out / "summary.json").exists():
|
| 244 |
mfe_summary_fallback = json.loads((mfe_out / "summary.json").read_text(encoding="utf-8"))
|
| 245 |
if (mfe_out / "latest_prediction.csv").exists():
|
| 246 |
row = pd.read_csv(mfe_out / "latest_prediction.csv").iloc[-1].to_dict()
|
| 247 |
mfe_latest_fallback = {k: (None if pd.isna(v) else v) for k, v in row.items()}
|
|
|
|
|
|
|
|
|
|
| 248 |
if (mfe_out / "test_predictions.csv").exists():
|
| 249 |
hist_df = pd.read_csv(mfe_out / "test_predictions.csv")
|
| 250 |
-
hist_records = []
|
| 251 |
for _, r in hist_df.iterrows():
|
| 252 |
try:
|
| 253 |
dt = str(r["date"])
|
|
@@ -258,6 +261,9 @@ def attach_market_state(payload: dict) -> dict:
|
|
| 258 |
act_lo = float(r["day_low"])
|
| 259 |
hist_records.append({
|
| 260 |
"date": dt,
|
|
|
|
|
|
|
|
|
|
| 261 |
"actual_high": act_hi,
|
| 262 |
"predicted_high": f5c + pred_up,
|
| 263 |
"actual_low": act_lo,
|
|
@@ -265,7 +271,74 @@ def attach_market_state(payload: dict) -> dict:
|
|
| 265 |
})
|
| 266 |
except Exception:
|
| 267 |
continue
|
| 268 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 269 |
except Exception as exc:
|
| 270 |
print(f"Fallback MFE load failed: {exc}", flush=True)
|
| 271 |
|
|
|
|
| 240 |
try:
|
| 241 |
models_dir = Path(__file__).resolve().parent / "models"
|
| 242 |
mfe_out = models_dir / "nifty_opening_mfe_regressor" / "outputs"
|
| 243 |
+
data_dir = Path(__file__).resolve().parent / "data"
|
| 244 |
if (mfe_out / "summary.json").exists():
|
| 245 |
mfe_summary_fallback = json.loads((mfe_out / "summary.json").read_text(encoding="utf-8"))
|
| 246 |
if (mfe_out / "latest_prediction.csv").exists():
|
| 247 |
row = pd.read_csv(mfe_out / "latest_prediction.csv").iloc[-1].to_dict()
|
| 248 |
mfe_latest_fallback = {k: (None if pd.isna(v) else v) for k, v in row.items()}
|
| 249 |
+
|
| 250 |
+
hist_records = []
|
| 251 |
+
import numpy as np
|
| 252 |
if (mfe_out / "test_predictions.csv").exists():
|
| 253 |
hist_df = pd.read_csv(mfe_out / "test_predictions.csv")
|
|
|
|
| 254 |
for _, r in hist_df.iterrows():
|
| 255 |
try:
|
| 256 |
dt = str(r["date"])
|
|
|
|
| 261 |
act_lo = float(r["day_low"])
|
| 262 |
hist_records.append({
|
| 263 |
"date": dt,
|
| 264 |
+
"first5_close": f5c,
|
| 265 |
+
"predicted_up_points": pred_up,
|
| 266 |
+
"predicted_down_points": pred_dn,
|
| 267 |
"actual_high": act_hi,
|
| 268 |
"predicted_high": f5c + pred_up,
|
| 269 |
"actual_low": act_lo,
|
|
|
|
| 271 |
})
|
| 272 |
except Exception:
|
| 273 |
continue
|
| 274 |
+
|
| 275 |
+
# Load live history if it exists
|
| 276 |
+
if (mfe_out / "mfe_live_history.csv").exists():
|
| 277 |
+
live_df = pd.read_csv(mfe_out / "mfe_live_history.csv")
|
| 278 |
+
daily_df = None
|
| 279 |
+
if (data_dir / "nifty50_1d.parquet").exists():
|
| 280 |
+
daily_df = pd.read_parquet(data_dir / "nifty50_1d.parquet")
|
| 281 |
+
daily_df["date"] = pd.to_datetime(daily_df["date"]).dt.strftime("%Y-%m-%d")
|
| 282 |
+
daily_df = daily_df.set_index("date")
|
| 283 |
+
|
| 284 |
+
for _, r in live_df.iterrows():
|
| 285 |
+
try:
|
| 286 |
+
dt = str(r["input_date"])
|
| 287 |
+
if daily_df is not None and dt in daily_df.index:
|
| 288 |
+
# Extract as scalar float using .iloc[0] or .item() in case of duplicates
|
| 289 |
+
act_hi_raw = daily_df.loc[dt, "high"]
|
| 290 |
+
act_lo_raw = daily_df.loc[dt, "low"]
|
| 291 |
+
act_hi = float(act_hi_raw.iloc[0] if isinstance(act_hi_raw, pd.Series) else act_hi_raw)
|
| 292 |
+
act_lo = float(act_lo_raw.iloc[0] if isinstance(act_lo_raw, pd.Series) else act_lo_raw)
|
| 293 |
+
f5c = float(r["first5_close"])
|
| 294 |
+
pred_up = float(r["predicted_up_points"])
|
| 295 |
+
pred_dn = float(r["predicted_down_points"])
|
| 296 |
+
hist_records.append({
|
| 297 |
+
"date": dt,
|
| 298 |
+
"first5_close": f5c,
|
| 299 |
+
"predicted_up_points": pred_up,
|
| 300 |
+
"predicted_down_points": pred_dn,
|
| 301 |
+
"actual_high": act_hi,
|
| 302 |
+
"predicted_high": f5c + pred_up,
|
| 303 |
+
"actual_low": act_lo,
|
| 304 |
+
"predicted_low": f5c - pred_dn
|
| 305 |
+
})
|
| 306 |
+
except Exception as ex:
|
| 307 |
+
print(f"Error appending live row: {ex}")
|
| 308 |
+
continue
|
| 309 |
+
|
| 310 |
+
mfe_history_fallback = hist_records
|
| 311 |
+
|
| 312 |
+
# Recalculate RMSE and MAE over the combined history
|
| 313 |
+
if hist_records:
|
| 314 |
+
up_errors = []
|
| 315 |
+
down_errors = []
|
| 316 |
+
for r in hist_records:
|
| 317 |
+
pred_up_pts = r["predicted_up_points"]
|
| 318 |
+
pred_dn_pts = r["predicted_down_points"]
|
| 319 |
+
act_up_pts = r["actual_high"] - r["first5_close"]
|
| 320 |
+
act_dn_pts = r["first5_close"] - r["actual_low"]
|
| 321 |
+
up_errors.append(act_up_pts - pred_up_pts)
|
| 322 |
+
down_errors.append(act_dn_pts - pred_dn_pts)
|
| 323 |
+
|
| 324 |
+
up_errors = np.array(up_errors)
|
| 325 |
+
down_errors = np.array(down_errors)
|
| 326 |
+
|
| 327 |
+
up_rmse = float(np.sqrt(np.mean(up_errors**2)))
|
| 328 |
+
up_mae = float(np.mean(np.abs(up_errors)))
|
| 329 |
+
down_rmse = float(np.sqrt(np.mean(down_errors**2)))
|
| 330 |
+
down_mae = float(np.mean(np.abs(down_errors)))
|
| 331 |
+
|
| 332 |
+
if "up" not in mfe_summary_fallback:
|
| 333 |
+
mfe_summary_fallback["up"] = {}
|
| 334 |
+
if "down" not in mfe_summary_fallback:
|
| 335 |
+
mfe_summary_fallback["down"] = {}
|
| 336 |
+
|
| 337 |
+
mfe_summary_fallback["up"]["test_rmse_points"] = up_rmse
|
| 338 |
+
mfe_summary_fallback["up"]["test_mae_points"] = up_mae
|
| 339 |
+
mfe_summary_fallback["down"]["test_rmse_points"] = down_rmse
|
| 340 |
+
mfe_summary_fallback["down"]["test_mae_points"] = down_mae
|
| 341 |
+
|
| 342 |
except Exception as exc:
|
| 343 |
print(f"Fallback MFE load failed: {exc}", flush=True)
|
| 344 |
|
runtime.py
CHANGED
|
@@ -61,6 +61,7 @@ MFE_SUMMARY_PATH = MFE_OUTPUT_DIR / "summary.json"
|
|
| 61 |
MFE_LATEST_PATH = MFE_OUTPUT_DIR / "latest_prediction.csv"
|
| 62 |
MFE_TEST_PREDICTIONS_PATH = MFE_OUTPUT_DIR / "test_predictions.csv"
|
| 63 |
MFE_MODEL_PATH = MFE_OUTPUT_DIR / "nifty_opening_mfe_regressor.joblib"
|
|
|
|
| 64 |
TPLUS1_MODEL_PATH = MODEL_DIR / "nifty_1420_tplus1_logistic_model.joblib"
|
| 65 |
TPLUS1_LATEST_PATH = MODEL_DIR / "tplus1_latest_prediction.csv"
|
| 66 |
TPLUS1_SUMMARY_PATH = MODEL_DIR / "tplus1_summary.json"
|
|
@@ -1002,6 +1003,20 @@ def refresh_mfe_prediction(session_date: date | None = None) -> dict[str, Any]:
|
|
| 1002 |
"predicted_down_points": pred_down,
|
| 1003 |
}
|
| 1004 |
pd.DataFrame([out]).to_csv(MFE_LATEST_PATH, index=False)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1005 |
clear_dashboard_payload_cache()
|
| 1006 |
return out
|
| 1007 |
|
|
|
|
| 61 |
MFE_LATEST_PATH = MFE_OUTPUT_DIR / "latest_prediction.csv"
|
| 62 |
MFE_TEST_PREDICTIONS_PATH = MFE_OUTPUT_DIR / "test_predictions.csv"
|
| 63 |
MFE_MODEL_PATH = MFE_OUTPUT_DIR / "nifty_opening_mfe_regressor.joblib"
|
| 64 |
+
MFE_LIVE_HISTORY_PATH = MFE_OUTPUT_DIR / "mfe_live_history.csv"
|
| 65 |
TPLUS1_MODEL_PATH = MODEL_DIR / "nifty_1420_tplus1_logistic_model.joblib"
|
| 66 |
TPLUS1_LATEST_PATH = MODEL_DIR / "tplus1_latest_prediction.csv"
|
| 67 |
TPLUS1_SUMMARY_PATH = MODEL_DIR / "tplus1_summary.json"
|
|
|
|
| 1003 |
"predicted_down_points": pred_down,
|
| 1004 |
}
|
| 1005 |
pd.DataFrame([out]).to_csv(MFE_LATEST_PATH, index=False)
|
| 1006 |
+
|
| 1007 |
+
# Append to live history
|
| 1008 |
+
live_df = pd.DataFrame([out])
|
| 1009 |
+
if MFE_LIVE_HISTORY_PATH.exists():
|
| 1010 |
+
try:
|
| 1011 |
+
existing = pd.read_csv(MFE_LIVE_HISTORY_PATH)
|
| 1012 |
+
# Avoid duplicates if refreshed multiple times in the same session
|
| 1013 |
+
existing = existing[existing["input_date"] != out["input_date"]]
|
| 1014 |
+
pd.concat([existing, live_df], ignore_index=True).to_csv(MFE_LIVE_HISTORY_PATH, index=False)
|
| 1015 |
+
except Exception:
|
| 1016 |
+
live_df.to_csv(MFE_LIVE_HISTORY_PATH, index=False)
|
| 1017 |
+
else:
|
| 1018 |
+
live_df.to_csv(MFE_LIVE_HISTORY_PATH, index=False)
|
| 1019 |
+
|
| 1020 |
clear_dashboard_payload_cache()
|
| 1021 |
return out
|
| 1022 |
|