Spaces:
Sleeping
Sleeping
Upload app.py
Browse files
app.py
CHANGED
|
@@ -1,234 +1,679 @@
|
|
| 1 |
-
import
|
| 2 |
-
|
| 3 |
-
|
| 4 |
-
|
| 5 |
-
from
|
| 6 |
-
|
| 7 |
-
|
| 8 |
-
from
|
| 9 |
-
|
| 10 |
-
from
|
| 11 |
-
from
|
| 12 |
-
|
| 13 |
-
|
| 14 |
-
|
| 15 |
-
|
| 16 |
-
|
| 17 |
-
|
| 18 |
-
|
| 19 |
-
|
| 20 |
-
|
| 21 |
-
|
| 22 |
-
|
| 23 |
-
|
| 24 |
-
|
| 25 |
-
|
| 26 |
-
|
| 27 |
-
|
| 28 |
-
|
| 29 |
-
|
| 30 |
-
|
| 31 |
-
|
| 32 |
-
|
| 33 |
-
|
| 34 |
-
|
| 35 |
-
|
| 36 |
-
|
| 37 |
-
|
| 38 |
-
|
| 39 |
-
|
| 40 |
-
|
| 41 |
-
|
| 42 |
-
|
| 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 |
-
if not
|
| 70 |
-
return {"status": "skipped", "reason":
|
| 71 |
-
|
| 72 |
-
|
| 73 |
-
|
| 74 |
-
|
| 75 |
-
|
| 76 |
-
|
| 77 |
-
|
| 78 |
-
|
| 79 |
-
|
| 80 |
-
|
| 81 |
-
|
| 82 |
-
|
| 83 |
-
|
| 84 |
-
|
| 85 |
-
|
| 86 |
-
|
| 87 |
-
|
| 88 |
-
|
| 89 |
-
|
| 90 |
-
|
| 91 |
-
|
| 92 |
-
return
|
| 93 |
-
|
| 94 |
-
|
| 95 |
-
def
|
| 96 |
-
|
| 97 |
-
|
| 98 |
-
|
| 99 |
-
|
| 100 |
-
|
| 101 |
-
|
| 102 |
-
|
| 103 |
-
|
| 104 |
-
|
| 105 |
-
|
| 106 |
-
|
| 107 |
-
|
| 108 |
-
|
| 109 |
-
|
| 110 |
-
|
| 111 |
-
|
| 112 |
-
|
| 113 |
-
|
| 114 |
-
|
| 115 |
-
|
| 116 |
-
|
| 117 |
-
|
| 118 |
-
|
| 119 |
-
|
| 120 |
-
|
| 121 |
-
|
| 122 |
-
|
| 123 |
-
|
| 124 |
-
|
| 125 |
-
|
| 126 |
-
|
| 127 |
-
|
| 128 |
-
|
| 129 |
-
|
| 130 |
-
|
| 131 |
-
|
| 132 |
-
|
| 133 |
-
|
| 134 |
-
"
|
| 135 |
-
|
| 136 |
-
|
| 137 |
-
|
| 138 |
-
|
| 139 |
-
|
| 140 |
-
|
| 141 |
-
|
| 142 |
-
|
| 143 |
-
|
| 144 |
-
|
| 145 |
-
|
| 146 |
-
|
| 147 |
-
|
| 148 |
-
|
| 149 |
-
|
| 150 |
-
|
| 151 |
-
|
| 152 |
-
|
| 153 |
-
|
| 154 |
-
|
| 155 |
-
|
| 156 |
-
|
| 157 |
-
|
| 158 |
-
|
| 159 |
-
|
| 160 |
-
|
| 161 |
-
|
| 162 |
-
|
| 163 |
-
|
| 164 |
-
|
| 165 |
-
|
| 166 |
-
|
| 167 |
-
|
| 168 |
-
|
| 169 |
-
|
| 170 |
-
|
| 171 |
-
|
| 172 |
-
|
| 173 |
-
|
| 174 |
-
|
| 175 |
-
|
| 176 |
-
|
| 177 |
-
"
|
| 178 |
-
|
| 179 |
-
"
|
| 180 |
-
|
| 181 |
-
|
| 182 |
-
|
| 183 |
-
|
| 184 |
-
|
| 185 |
-
|
| 186 |
-
|
| 187 |
-
|
| 188 |
-
|
| 189 |
-
|
| 190 |
-
|
| 191 |
-
|
| 192 |
-
|
| 193 |
-
|
| 194 |
-
|
| 195 |
-
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|
|
| 1 |
+
from __future__ import annotations
|
| 2 |
+
|
| 3 |
+
import asyncio
|
| 4 |
+
import threading
|
| 5 |
+
from datetime import date, datetime, time, timedelta
|
| 6 |
+
|
| 7 |
+
import sys
|
| 8 |
+
from pathlib import Path
|
| 9 |
+
|
| 10 |
+
from fastapi import BackgroundTasks, HTTPException, Query, Response
|
| 11 |
+
from fastapi.middleware.cors import CORSMiddleware
|
| 12 |
+
from fastapi import FastAPI
|
| 13 |
+
from pydantic import BaseModel
|
| 14 |
+
|
| 15 |
+
sys.path.insert(0, str(Path(__file__).resolve().parent))
|
| 16 |
+
from nifty_backend.runtime import (
|
| 17 |
+
CLOSE_REFRESH_READY,
|
| 18 |
+
IST,
|
| 19 |
+
STALE_CHECK_INTERVAL_SECONDS,
|
| 20 |
+
TPLUS1_READY,
|
| 21 |
+
close_refresh_due,
|
| 22 |
+
dashboard_payload,
|
| 23 |
+
is_trading_day,
|
| 24 |
+
latest_saved_prediction,
|
| 25 |
+
latest_tplus1_prediction,
|
| 26 |
+
next_trading_day,
|
| 27 |
+
refresh_daily_data,
|
| 28 |
+
refresh_first5_prediction,
|
| 29 |
+
refresh_market_close_data,
|
| 30 |
+
refresh_stale_data_once,
|
| 31 |
+
refresh_tplus1_prediction,
|
| 32 |
+
seconds_until_next_ist_run,
|
| 33 |
+
warm_dashboard_payload_cache,
|
| 34 |
+
)
|
| 35 |
+
from kotak_neo import (
|
| 36 |
+
KotakNeoConfigError,
|
| 37 |
+
KotakNeoError,
|
| 38 |
+
KotakNeoSessionRequired,
|
| 39 |
+
kotak_neo_manager,
|
| 40 |
+
)
|
| 41 |
+
from scraper import get_stock_info
|
| 42 |
+
|
| 43 |
+
|
| 44 |
+
app = FastAPI(title="NIFTY 50 Forecaster Backend")
|
| 45 |
+
app.add_middleware(
|
| 46 |
+
CORSMiddleware,
|
| 47 |
+
allow_origins=["*"],
|
| 48 |
+
allow_credentials=False,
|
| 49 |
+
allow_methods=["*"],
|
| 50 |
+
allow_headers=["*"],
|
| 51 |
+
)
|
| 52 |
+
|
| 53 |
+
|
| 54 |
+
market_status = "Waiting for next session"
|
| 55 |
+
close_refresh_lock = threading.Lock()
|
| 56 |
+
tplus1_refresh_lock = threading.Lock()
|
| 57 |
+
MARKET_OPEN = time(9, 15)
|
| 58 |
+
FIRST5_READY = time(9, 20)
|
| 59 |
+
MARKET_CLOSE = time(15, 30)
|
| 60 |
+
|
| 61 |
+
|
| 62 |
+
class TotpRequest(BaseModel):
|
| 63 |
+
totp: str
|
| 64 |
+
|
| 65 |
+
|
| 66 |
+
def refresh_market_close_data_if_due() -> dict:
|
| 67 |
+
if not close_refresh_due():
|
| 68 |
+
return {"status": "skipped", "reason": "close refresh is not due"}
|
| 69 |
+
if not close_refresh_lock.acquire(blocking=False):
|
| 70 |
+
return {"status": "skipped", "reason": "close refresh already running"}
|
| 71 |
+
try:
|
| 72 |
+
info = refresh_market_close_data()
|
| 73 |
+
return {"status": "refreshed", **info}
|
| 74 |
+
finally:
|
| 75 |
+
close_refresh_lock.release()
|
| 76 |
+
|
| 77 |
+
|
| 78 |
+
def latest_tplus1_prediction_date(payload: dict | None = None) -> date | None:
|
| 79 |
+
try:
|
| 80 |
+
latest = payload if payload is not None else latest_tplus1_prediction()
|
| 81 |
+
raw = latest.get("input_date")
|
| 82 |
+
return date.fromisoformat(str(raw)[:10]) if raw else None
|
| 83 |
+
except Exception:
|
| 84 |
+
return None
|
| 85 |
+
|
| 86 |
+
|
| 87 |
+
def tplus1_refresh_due(now: datetime | None = None, latest_date: date | None = None) -> bool:
|
| 88 |
+
now = now or datetime.now(IST)
|
| 89 |
+
if not is_trading_day(now.date()) or not (TPLUS1_READY <= now.time() < MARKET_CLOSE):
|
| 90 |
+
return False
|
| 91 |
+
latest_date = latest_date if latest_date is not None else latest_tplus1_prediction_date()
|
| 92 |
+
return latest_date != now.date()
|
| 93 |
+
|
| 94 |
+
|
| 95 |
+
def refresh_tplus1_if_due() -> dict:
|
| 96 |
+
now = datetime.now(IST)
|
| 97 |
+
latest_date = latest_tplus1_prediction_date()
|
| 98 |
+
if not tplus1_refresh_due(now=now, latest_date=latest_date):
|
| 99 |
+
return {"status": "skipped", "reason": "tplus1 refresh is not due"}
|
| 100 |
+
if not tplus1_refresh_lock.acquire(blocking=False):
|
| 101 |
+
return {"status": "skipped", "reason": "tplus1 refresh already running"}
|
| 102 |
+
try:
|
| 103 |
+
prediction = refresh_tplus1_prediction(session_date=now.date())
|
| 104 |
+
return {"status": "refreshed", "prediction": prediction}
|
| 105 |
+
finally:
|
| 106 |
+
tplus1_refresh_lock.release()
|
| 107 |
+
|
| 108 |
+
|
| 109 |
+
def latest_prediction_date(payload: dict | None = None) -> date | None:
|
| 110 |
+
try:
|
| 111 |
+
latest = payload if payload is not None else latest_saved_prediction()
|
| 112 |
+
raw = latest.get("input_date")
|
| 113 |
+
return date.fromisoformat(str(raw)) if raw else None
|
| 114 |
+
except Exception:
|
| 115 |
+
return None
|
| 116 |
+
|
| 117 |
+
|
| 118 |
+
def current_market_state(now: datetime | None = None) -> dict:
|
| 119 |
+
global market_status
|
| 120 |
+
now = now or datetime.now(IST)
|
| 121 |
+
today = now.date()
|
| 122 |
+
current_time = now.time()
|
| 123 |
+
trading_day = is_trading_day(today)
|
| 124 |
+
latest_date = latest_prediction_date()
|
| 125 |
+
market_is_open_for_t5 = trading_day and FIRST5_READY <= current_time < MARKET_CLOSE
|
| 126 |
+
market_is_open_for_tplus1 = trading_day and TPLUS1_READY <= current_time < MARKET_CLOSE
|
| 127 |
+
has_current_first5 = market_is_open_for_t5 and latest_date == today
|
| 128 |
+
tplus1_latest_date = latest_tplus1_prediction_date()
|
| 129 |
+
has_current_tplus1 = market_is_open_for_tplus1 and tplus1_latest_date == today
|
| 130 |
+
next_session = today if trading_day and current_time < MARKET_CLOSE else next_trading_day(today + timedelta(days=1))
|
| 131 |
+
|
| 132 |
+
if not trading_day:
|
| 133 |
+
status = "Market Closed"
|
| 134 |
+
detail = f"Next trading session is {next_session.isoformat()}."
|
| 135 |
+
elif current_time < time(9, 0):
|
| 136 |
+
status = "Waiting for 9:00 AM"
|
| 137 |
+
detail = "Market has not entered pre-open yet."
|
| 138 |
+
elif current_time < MARKET_OPEN:
|
| 139 |
+
status = "Market Pre-Open"
|
| 140 |
+
detail = "Market opens at 9:15 AM IST."
|
| 141 |
+
elif current_time < FIRST5_READY:
|
| 142 |
+
status = "Market Officially Opened"
|
| 143 |
+
detail = "Waiting for the first 5 one-minute bars."
|
| 144 |
+
elif current_time <= MARKET_CLOSE:
|
| 145 |
+
if market_status in {"Fetching T+5 Prediction Data...", "Prediction Failed"}:
|
| 146 |
+
status = market_status
|
| 147 |
+
detail = "The first-five-minute prediction job is still resolving."
|
| 148 |
+
elif has_current_first5:
|
| 149 |
+
status = "Prediction Ready"
|
| 150 |
+
detail = "Today's first-five-minute prediction is available."
|
| 151 |
+
else:
|
| 152 |
+
status = "Prediction Pending"
|
| 153 |
+
detail = "No current-session prediction has been generated yet."
|
| 154 |
+
else:
|
| 155 |
+
status = "Market Closed"
|
| 156 |
+
detail = "Trading session has ended."
|
| 157 |
+
|
| 158 |
+
if not trading_day:
|
| 159 |
+
tplus1_status = "Market Closed"
|
| 160 |
+
tplus1_detail = f"Next trading session is {next_session.isoformat()}."
|
| 161 |
+
elif current_time < TPLUS1_READY:
|
| 162 |
+
tplus1_status = "Waiting for 2:30 PM"
|
| 163 |
+
tplus1_detail = "The T+1 forecast becomes available at 2:30 PM IST."
|
| 164 |
+
elif current_time < MARKET_CLOSE:
|
| 165 |
+
if has_current_tplus1:
|
| 166 |
+
tplus1_status = "Ready"
|
| 167 |
+
tplus1_detail = "Today's T+1 prediction is available."
|
| 168 |
+
else:
|
| 169 |
+
tplus1_status = "Pending"
|
| 170 |
+
tplus1_detail = "No current-session T+1 prediction has been generated yet."
|
| 171 |
+
else:
|
| 172 |
+
tplus1_status = "Market Closed"
|
| 173 |
+
tplus1_detail = "Trading session has ended."
|
| 174 |
+
|
| 175 |
+
if not trading_day:
|
| 176 |
+
t5_status = "Market Closed"
|
| 177 |
+
t5_detail = f"Next trading session is {next_session.isoformat()}."
|
| 178 |
+
elif current_time < FIRST5_READY:
|
| 179 |
+
t5_status = "Waiting for 9:20 AM"
|
| 180 |
+
t5_detail = "The T+5 forecast becomes available after the first five one-minute bars."
|
| 181 |
+
elif current_time < MARKET_CLOSE:
|
| 182 |
+
if market_status in {"Fetching T+5 Prediction Data...", "Prediction Failed"}:
|
| 183 |
+
t5_status = market_status
|
| 184 |
+
t5_detail = "The first-five-minute prediction job is still resolving."
|
| 185 |
+
elif has_current_first5:
|
| 186 |
+
t5_status = "Ready"
|
| 187 |
+
t5_detail = "Today's first-five-minute prediction is available."
|
| 188 |
+
else:
|
| 189 |
+
t5_status = "Pending"
|
| 190 |
+
t5_detail = "No current-session prediction has been generated yet."
|
| 191 |
+
else:
|
| 192 |
+
t5_status = "Market Closed"
|
| 193 |
+
t5_detail = "Trading session has ended."
|
| 194 |
+
|
| 195 |
+
return {
|
| 196 |
+
"market_status": status,
|
| 197 |
+
"market_detail": detail,
|
| 198 |
+
"server_time_ist": now.isoformat(),
|
| 199 |
+
"is_trading_day": trading_day,
|
| 200 |
+
"session_date": today.isoformat(),
|
| 201 |
+
"next_session_date": next_session.isoformat(),
|
| 202 |
+
"latest_prediction_date": latest_date.isoformat() if latest_date else None,
|
| 203 |
+
"t5_available": has_current_first5,
|
| 204 |
+
"t5_status": t5_status,
|
| 205 |
+
"t5_detail": t5_detail,
|
| 206 |
+
"market_is_open_for_t5": market_is_open_for_t5,
|
| 207 |
+
"tplus1_available": has_current_tplus1,
|
| 208 |
+
"tplus1_status": tplus1_status,
|
| 209 |
+
"tplus1_detail": tplus1_detail,
|
| 210 |
+
"market_is_open_for_tplus1": market_is_open_for_tplus1,
|
| 211 |
+
"latest_tplus1_prediction_date": tplus1_latest_date.isoformat() if tplus1_latest_date else None,
|
| 212 |
+
}
|
| 213 |
+
|
| 214 |
+
|
| 215 |
+
def attach_market_state(payload: dict) -> dict:
|
| 216 |
+
state = current_market_state()
|
| 217 |
+
payload.setdefault("data_status", {})
|
| 218 |
+
payload["data_status"].update(state)
|
| 219 |
+
try:
|
| 220 |
+
payload["nifty_quote"] = kotak_neo_manager.fetch_nifty50_quote()
|
| 221 |
+
payload["nifty_quote_error"] = None
|
| 222 |
+
except KotakNeoSessionRequired as exc:
|
| 223 |
+
payload["nifty_quote"] = None
|
| 224 |
+
payload["nifty_quote_error"] = {"status": 401, "message": str(exc)}
|
| 225 |
+
except KotakNeoConfigError as exc:
|
| 226 |
+
payload["nifty_quote"] = None
|
| 227 |
+
payload["nifty_quote_error"] = {"status": 503, "message": str(exc)}
|
| 228 |
+
except KotakNeoError as exc:
|
| 229 |
+
payload["nifty_quote"] = None
|
| 230 |
+
payload["nifty_quote_error"] = {"status": 502, "message": str(exc)}
|
| 231 |
+
|
| 232 |
+
import json
|
| 233 |
+
import pandas as pd
|
| 234 |
+
from pathlib import Path
|
| 235 |
+
|
| 236 |
+
# AGGRESSIVE FALLBACK: If runtime.py fails to load it (due to path resolution issues on Hugging Face),
|
| 237 |
+
# we forcefully load it directly from app.py's relative path.
|
| 238 |
+
mfe_summary_fallback = {}
|
| 239 |
+
mfe_latest_fallback = {}
|
| 240 |
+
mfe_history_fallback = []
|
| 241 |
+
try:
|
| 242 |
+
models_dir = Path(__file__).resolve().parent / "models"
|
| 243 |
+
mfe_out = models_dir / "nifty_opening_mfe_regressor" / "outputs"
|
| 244 |
+
data_dir = Path(__file__).resolve().parent / "data"
|
| 245 |
+
if (mfe_out / "summary.json").exists():
|
| 246 |
+
mfe_summary_fallback = json.loads((mfe_out / "summary.json").read_text(encoding="utf-8"))
|
| 247 |
+
if (mfe_out / "latest_prediction.csv").exists():
|
| 248 |
+
row = pd.read_csv(mfe_out / "latest_prediction.csv").iloc[-1].to_dict()
|
| 249 |
+
mfe_latest_fallback = {k: (None if pd.isna(v) else v) for k, v in row.items()}
|
| 250 |
+
|
| 251 |
+
hist_records = []
|
| 252 |
+
import numpy as np
|
| 253 |
+
if (mfe_out / "test_predictions.csv").exists():
|
| 254 |
+
hist_df = pd.read_csv(mfe_out / "test_predictions.csv")
|
| 255 |
+
for _, r in hist_df.iterrows():
|
| 256 |
+
try:
|
| 257 |
+
dt = str(r["date"])
|
| 258 |
+
f5c = float(r["first5_close"])
|
| 259 |
+
pred_up = float(r["predicted_up_points"])
|
| 260 |
+
pred_dn = float(r["predicted_down_points"])
|
| 261 |
+
act_hi = float(r["day_high"])
|
| 262 |
+
act_lo = float(r["day_low"])
|
| 263 |
+
hist_records.append({
|
| 264 |
+
"date": dt,
|
| 265 |
+
"first5_close": f5c,
|
| 266 |
+
"predicted_up_points": pred_up,
|
| 267 |
+
"predicted_down_points": pred_dn,
|
| 268 |
+
"actual_high": act_hi,
|
| 269 |
+
"predicted_high": f5c + pred_up,
|
| 270 |
+
"actual_low": act_lo,
|
| 271 |
+
"predicted_low": f5c - pred_dn
|
| 272 |
+
})
|
| 273 |
+
except Exception:
|
| 274 |
+
continue
|
| 275 |
+
|
| 276 |
+
# Load live history if it exists
|
| 277 |
+
if (mfe_out / "mfe_live_history.csv").exists():
|
| 278 |
+
live_df = pd.read_csv(mfe_out / "mfe_live_history.csv")
|
| 279 |
+
daily_df = None
|
| 280 |
+
if (data_dir / "nifty50_1d.parquet").exists():
|
| 281 |
+
daily_df = pd.read_parquet(data_dir / "nifty50_1d.parquet")
|
| 282 |
+
daily_df["date"] = pd.to_datetime(daily_df["date"]).dt.strftime("%Y-%m-%d")
|
| 283 |
+
daily_df = daily_df.set_index("date")
|
| 284 |
+
|
| 285 |
+
for _, r in live_df.iterrows():
|
| 286 |
+
try:
|
| 287 |
+
dt = str(r["input_date"])
|
| 288 |
+
if daily_df is not None and dt in daily_df.index:
|
| 289 |
+
# Extract as scalar float using .iloc[0] or .item() in case of duplicates
|
| 290 |
+
act_hi_raw = daily_df.loc[dt, "high"]
|
| 291 |
+
act_lo_raw = daily_df.loc[dt, "low"]
|
| 292 |
+
act_hi = float(act_hi_raw.iloc[0] if isinstance(act_hi_raw, pd.Series) else act_hi_raw)
|
| 293 |
+
act_lo = float(act_lo_raw.iloc[0] if isinstance(act_lo_raw, pd.Series) else act_lo_raw)
|
| 294 |
+
f5c = float(r["first5_close"])
|
| 295 |
+
pred_up = float(r["predicted_up_points"])
|
| 296 |
+
pred_dn = float(r["predicted_down_points"])
|
| 297 |
+
hist_records.append({
|
| 298 |
+
"date": dt,
|
| 299 |
+
"first5_close": f5c,
|
| 300 |
+
"predicted_up_points": pred_up,
|
| 301 |
+
"predicted_down_points": pred_dn,
|
| 302 |
+
"actual_high": act_hi,
|
| 303 |
+
"predicted_high": f5c + pred_up,
|
| 304 |
+
"actual_low": act_lo,
|
| 305 |
+
"predicted_low": f5c - pred_dn
|
| 306 |
+
})
|
| 307 |
+
except Exception as ex:
|
| 308 |
+
print(f"Error appending live row: {ex}")
|
| 309 |
+
continue
|
| 310 |
+
|
| 311 |
+
mfe_history_fallback = hist_records
|
| 312 |
+
|
| 313 |
+
# Recalculate RMSE and MAE over the combined history
|
| 314 |
+
if hist_records:
|
| 315 |
+
up_errors = []
|
| 316 |
+
down_errors = []
|
| 317 |
+
for r in hist_records:
|
| 318 |
+
pred_up_pts = r["predicted_up_points"]
|
| 319 |
+
pred_dn_pts = r["predicted_down_points"]
|
| 320 |
+
act_up_pts = r["actual_high"] - r["first5_close"]
|
| 321 |
+
act_dn_pts = r["first5_close"] - r["actual_low"]
|
| 322 |
+
up_errors.append(act_up_pts - pred_up_pts)
|
| 323 |
+
down_errors.append(act_dn_pts - pred_dn_pts)
|
| 324 |
+
|
| 325 |
+
up_errors = np.array(up_errors)
|
| 326 |
+
down_errors = np.array(down_errors)
|
| 327 |
+
|
| 328 |
+
up_rmse = float(np.sqrt(np.mean(up_errors**2)))
|
| 329 |
+
up_mae = float(np.mean(np.abs(up_errors)))
|
| 330 |
+
down_rmse = float(np.sqrt(np.mean(down_errors**2)))
|
| 331 |
+
down_mae = float(np.mean(np.abs(down_errors)))
|
| 332 |
+
|
| 333 |
+
if "up" not in mfe_summary_fallback:
|
| 334 |
+
mfe_summary_fallback["up"] = {}
|
| 335 |
+
if "down" not in mfe_summary_fallback:
|
| 336 |
+
mfe_summary_fallback["down"] = {}
|
| 337 |
+
|
| 338 |
+
mfe_summary_fallback["up"]["test_rmse_points"] = up_rmse
|
| 339 |
+
mfe_summary_fallback["up"]["test_mae_points"] = up_mae
|
| 340 |
+
mfe_summary_fallback["down"]["test_rmse_points"] = down_rmse
|
| 341 |
+
mfe_summary_fallback["down"]["test_mae_points"] = down_mae
|
| 342 |
+
|
| 343 |
+
except Exception as exc:
|
| 344 |
+
print(f"Fallback MFE load failed: {exc}", flush=True)
|
| 345 |
+
|
| 346 |
+
t5_latest = payload.get("predictions", {}).get("t5", {}).get("latest") or payload.get("latest") or {}
|
| 347 |
+
tomorrow_latest = payload.get("predictions", {}).get("tomorrow", {}).get("latest") or payload.get("tomorrow_latest") or {}
|
| 348 |
+
tplus1_latest = payload.get("predictions", {}).get("tplus1", {}).get("latest") or payload.get("tplus1_latest") or {}
|
| 349 |
+
mfe_latest = payload.get("predictions", {}).get("mfe", {}).get("latest") or mfe_latest_fallback
|
| 350 |
+
mfe_summary = payload.get("predictions", {}).get("mfe", {}).get("summary") or mfe_summary_fallback
|
| 351 |
+
mfe_history = payload.get("predictions", {}).get("mfe", {}).get("history") or mfe_history_fallback
|
| 352 |
+
t5_available = bool(state["t5_available"] and t5_latest.get("prediction"))
|
| 353 |
+
tplus1_available = bool(state["tplus1_available"] and tplus1_latest.get("prediction"))
|
| 354 |
+
tomorrow_available = bool(tomorrow_latest.get("prediction"))
|
| 355 |
+
refresh_phase = payload.get("data_status", {}).get("refresh_phase")
|
| 356 |
+
if refresh_phase in {"waiting_second_payload", "refreshing"}:
|
| 357 |
+
tomorrow_status = "WAITING FOR SECOND PAYLOAD"
|
| 358 |
+
tomorrow_reason = "Market close refresh is generating the next-session payload."
|
| 359 |
+
else:
|
| 360 |
+
tomorrow_status = "Ready" if tomorrow_available else "Pending"
|
| 361 |
+
tomorrow_reason = None if tomorrow_available else "No saved next-session signal is available."
|
| 362 |
+
payload["predictions"] = {
|
| 363 |
+
"tomorrow": {
|
| 364 |
+
"available": tomorrow_available,
|
| 365 |
+
"status": tomorrow_status,
|
| 366 |
+
"reason": tomorrow_reason,
|
| 367 |
+
"target_date": tomorrow_latest.get("target_date") or state["next_session_date"],
|
| 368 |
+
"input_date": tomorrow_latest.get("input_date"),
|
| 369 |
+
"prediction": tomorrow_latest.get("prediction") if tomorrow_available else None,
|
| 370 |
+
"prob_up": tomorrow_latest.get("prob_up") if tomorrow_available else None,
|
| 371 |
+
"confidence": tomorrow_latest.get("confidence") if tomorrow_available else None,
|
| 372 |
+
"threshold": tomorrow_latest.get("threshold") if tomorrow_available else None,
|
| 373 |
+
"model_name": tomorrow_latest.get("model_name"),
|
| 374 |
+
"source_model": tomorrow_latest.get("source_model"),
|
| 375 |
+
"validation_accuracy": tomorrow_latest.get("validation_accuracy"),
|
| 376 |
+
"test_accuracy": tomorrow_latest.get("test_accuracy"),
|
| 377 |
+
},
|
| 378 |
+
"t5": {
|
| 379 |
+
"available": t5_available,
|
| 380 |
+
"status": "Ready" if t5_available else state["t5_status"],
|
| 381 |
+
"reason": None if t5_available else state["t5_detail"],
|
| 382 |
+
"input_date": t5_latest.get("input_date"),
|
| 383 |
+
"prediction": t5_latest.get("prediction") if t5_available else None,
|
| 384 |
+
"prob_up": t5_latest.get("prob_up") if t5_available else None,
|
| 385 |
+
"confidence": t5_latest.get("confidence") if t5_available else None,
|
| 386 |
+
"threshold": t5_latest.get("threshold") if t5_available else None,
|
| 387 |
+
"is_overridden": bool(t5_latest.get("is_overridden")) if t5_available else False,
|
| 388 |
+
"model_name": t5_latest.get("model_name"),
|
| 389 |
+
"validation_accuracy": (payload.get("summary") or {}).get("validation_accuracy"),
|
| 390 |
+
"test_accuracy": (payload.get("summary") or {}).get("test_accuracy"),
|
| 391 |
+
},
|
| 392 |
+
"tplus1": {
|
| 393 |
+
"available": tplus1_available,
|
| 394 |
+
"status": "Ready" if tplus1_available else state["tplus1_status"],
|
| 395 |
+
"reason": None if tplus1_available else state["tplus1_detail"],
|
| 396 |
+
"target_date": tplus1_latest.get("target_date") or state["next_session_date"],
|
| 397 |
+
"input_date": tplus1_latest.get("input_date"),
|
| 398 |
+
"prediction": tplus1_latest.get("prediction") if tplus1_available else None,
|
| 399 |
+
"prob_up": tplus1_latest.get("prob_up") if tplus1_available else None,
|
| 400 |
+
"confidence": tplus1_latest.get("confidence") if tplus1_available else None,
|
| 401 |
+
"threshold": tplus1_latest.get("threshold") if tplus1_available else None,
|
| 402 |
+
"is_overridden": bool(tplus1_latest.get("overlay_changed")) if tplus1_available else False,
|
| 403 |
+
"model_name": tplus1_latest.get("model_name"),
|
| 404 |
+
"validation_accuracy": (payload.get("tplus1_summary") or {}).get("validation_accuracy"),
|
| 405 |
+
"test_accuracy": (payload.get("tplus1_summary") or {}).get("test_accuracy"),
|
| 406 |
+
},
|
| 407 |
+
"mfe": {
|
| 408 |
+
"available": t5_available,
|
| 409 |
+
"status": "Ready" if t5_available else state["t5_status"],
|
| 410 |
+
"reason": None if t5_available else state["t5_detail"],
|
| 411 |
+
"latest": mfe_latest,
|
| 412 |
+
"summary": mfe_summary,
|
| 413 |
+
"history": mfe_history,
|
| 414 |
+
},
|
| 415 |
+
}
|
| 416 |
+
return payload
|
| 417 |
+
|
| 418 |
+
|
| 419 |
+
async def daily_ist_refresh_loop() -> None:
|
| 420 |
+
global market_status
|
| 421 |
+
while True:
|
| 422 |
+
# Wait until 9:00 AM IST
|
| 423 |
+
await asyncio.sleep(seconds_until_next_ist_run(time(9, 0)))
|
| 424 |
+
if not is_trading_day(datetime.now(IST).date()):
|
| 425 |
+
market_status = "Market Closed"
|
| 426 |
+
continue
|
| 427 |
+
market_status = "Market Pre-Open"
|
| 428 |
+
print("[scheduler] 9:00 AM IST - Market Pre-Open", flush=True)
|
| 429 |
+
|
| 430 |
+
# Wait until 9:15 AM IST
|
| 431 |
+
await asyncio.sleep(seconds_until_next_ist_run(time(9, 15)))
|
| 432 |
+
market_status = "Market Officially Opened"
|
| 433 |
+
print("[scheduler] 9:15 AM IST - Market Officially Opened", flush=True)
|
| 434 |
+
|
| 435 |
+
# Wait until 9:20 AM IST
|
| 436 |
+
await asyncio.sleep(seconds_until_next_ist_run(time(9, 20)))
|
| 437 |
+
market_status = "Fetching T+5 Prediction Data..."
|
| 438 |
+
print("[scheduler] 9:20 AM IST - Fetching Data", flush=True)
|
| 439 |
+
|
| 440 |
+
try:
|
| 441 |
+
await asyncio.to_thread(refresh_first5_prediction)
|
| 442 |
+
market_status = "Prediction Ready"
|
| 443 |
+
except Exception as exc:
|
| 444 |
+
print(f"[scheduler] first5 refresh failed: {exc}", flush=True)
|
| 445 |
+
market_status = "Prediction Failed"
|
| 446 |
+
|
| 447 |
+
try:
|
| 448 |
+
await asyncio.to_thread(refresh_daily_data)
|
| 449 |
+
except Exception as exc:
|
| 450 |
+
print(f"[scheduler] daily refresh failed: {exc}", flush=True)
|
| 451 |
+
|
| 452 |
+
await asyncio.sleep(seconds_until_next_ist_run(TPLUS1_READY))
|
| 453 |
+
print("[scheduler] 2:30 PM IST - Refreshing T+1 prediction", flush=True)
|
| 454 |
+
try:
|
| 455 |
+
info = await asyncio.to_thread(refresh_tplus1_if_due)
|
| 456 |
+
print(f"[scheduler] tplus1 refresh result: {info}", flush=True)
|
| 457 |
+
except Exception as exc:
|
| 458 |
+
print(f"[scheduler] tplus1 refresh failed: {exc}", flush=True)
|
| 459 |
+
|
| 460 |
+
await asyncio.sleep(seconds_until_next_ist_run(CLOSE_REFRESH_READY))
|
| 461 |
+
print("[scheduler] 3:45 PM IST - Refreshing close data", flush=True)
|
| 462 |
+
try:
|
| 463 |
+
info = await asyncio.to_thread(refresh_market_close_data_if_due)
|
| 464 |
+
print(f"[scheduler] close refresh result: {info}", flush=True)
|
| 465 |
+
except Exception as exc:
|
| 466 |
+
print(f"[scheduler] close refresh failed: {exc}", flush=True)
|
| 467 |
+
|
| 468 |
+
|
| 469 |
+
async def refresh_current_session_once() -> None:
|
| 470 |
+
global market_status
|
| 471 |
+
now = datetime.now(IST)
|
| 472 |
+
if not is_trading_day(now.date()) or now.time() < FIRST5_READY:
|
| 473 |
+
return
|
| 474 |
+
if latest_prediction_date() == now.date():
|
| 475 |
+
return
|
| 476 |
+
market_status = "Fetching T+5 Prediction Data..."
|
| 477 |
+
print("[startup] Current session needs first-five refresh; fetching now.", flush=True)
|
| 478 |
+
try:
|
| 479 |
+
await asyncio.to_thread(refresh_first5_prediction)
|
| 480 |
+
market_status = "Prediction Ready"
|
| 481 |
+
except Exception as exc:
|
| 482 |
+
print(f"[startup] first5 refresh failed: {exc}", flush=True)
|
| 483 |
+
market_status = "Prediction Failed"
|
| 484 |
+
try:
|
| 485 |
+
await asyncio.to_thread(refresh_daily_data)
|
| 486 |
+
except Exception as exc:
|
| 487 |
+
print(f"[startup] daily refresh failed: {exc}", flush=True)
|
| 488 |
+
|
| 489 |
+
|
| 490 |
+
async def refresh_market_close_once_if_due() -> None:
|
| 491 |
+
try:
|
| 492 |
+
info = await asyncio.to_thread(refresh_market_close_data_if_due)
|
| 493 |
+
if info.get("status") == "refreshed":
|
| 494 |
+
print(f"[startup] close refresh result: {info}", flush=True)
|
| 495 |
+
except Exception as exc:
|
| 496 |
+
print(f"[startup] close refresh failed: {exc}", flush=True)
|
| 497 |
+
|
| 498 |
+
|
| 499 |
+
async def refresh_tplus1_once_if_due() -> None:
|
| 500 |
+
try:
|
| 501 |
+
info = await asyncio.to_thread(refresh_tplus1_if_due)
|
| 502 |
+
if info.get("status") == "refreshed":
|
| 503 |
+
print(f"[startup] tplus1 refresh result: {info}", flush=True)
|
| 504 |
+
except Exception as exc:
|
| 505 |
+
print(f"[startup] tplus1 refresh failed: {exc}", flush=True)
|
| 506 |
+
|
| 507 |
+
|
| 508 |
+
async def warm_dashboard_payload_cache_once() -> None:
|
| 509 |
+
try:
|
| 510 |
+
await asyncio.to_thread(warm_dashboard_payload_cache)
|
| 511 |
+
except Exception as exc:
|
| 512 |
+
print(f"[startup] dashboard payload warmup failed: {exc}", flush=True)
|
| 513 |
+
|
| 514 |
+
|
| 515 |
+
async def stale_data_watch_loop() -> None:
|
| 516 |
+
while True:
|
| 517 |
+
try:
|
| 518 |
+
info = await asyncio.to_thread(refresh_stale_data_once)
|
| 519 |
+
if info.get("status") == "refreshed":
|
| 520 |
+
print(f"[stale-watch] refreshed stale data: {info}", flush=True)
|
| 521 |
+
except Exception as exc:
|
| 522 |
+
print(f"[stale-watch] stale refresh failed: {exc}", flush=True)
|
| 523 |
+
await asyncio.sleep(STALE_CHECK_INTERVAL_SECONDS)
|
| 524 |
+
|
| 525 |
+
|
| 526 |
+
@app.on_event("startup")
|
| 527 |
+
async def start_scheduler() -> None:
|
| 528 |
+
global market_status
|
| 529 |
+
# Initialize correct status on startup based on current time
|
| 530 |
+
now = datetime.now(IST).time()
|
| 531 |
+
today = datetime.now(IST).date()
|
| 532 |
+
if not is_trading_day(today):
|
| 533 |
+
market_status = "Market Closed"
|
| 534 |
+
elif now < time(9, 0):
|
| 535 |
+
market_status = "Waiting for 9:00 AM"
|
| 536 |
+
elif now < time(9, 15):
|
| 537 |
+
market_status = "Market Pre-Open"
|
| 538 |
+
elif now < time(9, 20):
|
| 539 |
+
market_status = "Market Officially Opened"
|
| 540 |
+
elif latest_prediction_date() == today:
|
| 541 |
+
market_status = "Prediction Ready"
|
| 542 |
+
else:
|
| 543 |
+
market_status = "Prediction Pending"
|
| 544 |
+
|
| 545 |
+
asyncio.create_task(refresh_current_session_once())
|
| 546 |
+
asyncio.create_task(refresh_tplus1_once_if_due())
|
| 547 |
+
asyncio.create_task(refresh_market_close_once_if_due())
|
| 548 |
+
asyncio.create_task(warm_dashboard_payload_cache_once())
|
| 549 |
+
asyncio.create_task(stale_data_watch_loop())
|
| 550 |
+
asyncio.create_task(daily_ist_refresh_loop())
|
| 551 |
+
|
| 552 |
+
|
| 553 |
+
@app.get("/health")
|
| 554 |
+
def health() -> dict[str, str]:
|
| 555 |
+
return {"status": "ok"}
|
| 556 |
+
|
| 557 |
+
|
| 558 |
+
@app.get("/")
|
| 559 |
+
def root() -> dict[str, str]:
|
| 560 |
+
return {"service": "NIFTY 50 Forecaster Backend", "status": "ok"}
|
| 561 |
+
|
| 562 |
+
|
| 563 |
+
@app.get("/dashboard")
|
| 564 |
+
def dashboard(response: Response) -> dict:
|
| 565 |
+
response.headers["Cache-Control"] = "no-store, no-cache, must-revalidate"
|
| 566 |
+
response.headers["Pragma"] = "no-cache"
|
| 567 |
+
try:
|
| 568 |
+
refresh_stale_data_once()
|
| 569 |
+
except Exception as exc:
|
| 570 |
+
print(f"[dashboard] stale refresh failed: {exc}", flush=True)
|
| 571 |
+
return attach_market_state(dashboard_payload())
|
| 572 |
+
|
| 573 |
+
|
| 574 |
+
@app.get("/kotak/status")
|
| 575 |
+
def kotak_status() -> dict:
|
| 576 |
+
return kotak_neo_manager.status()
|
| 577 |
+
|
| 578 |
+
|
| 579 |
+
@app.post("/kotak/auth/totp")
|
| 580 |
+
def kotak_auth_totp(payload: TotpRequest) -> dict:
|
| 581 |
+
try:
|
| 582 |
+
return kotak_neo_manager.authenticate_with_totp(payload.totp)
|
| 583 |
+
except KotakNeoConfigError as exc:
|
| 584 |
+
raise HTTPException(status_code=503, detail=str(exc)) from exc
|
| 585 |
+
except KotakNeoError as exc:
|
| 586 |
+
raise HTTPException(status_code=400, detail=str(exc)) from exc
|
| 587 |
+
|
| 588 |
+
|
| 589 |
+
@app.get("/kotak/account")
|
| 590 |
+
def kotak_account() -> dict:
|
| 591 |
+
try:
|
| 592 |
+
return kotak_neo_manager.fetch_account_snapshot()
|
| 593 |
+
except KotakNeoConfigError as exc:
|
| 594 |
+
raise HTTPException(status_code=503, detail=str(exc)) from exc
|
| 595 |
+
except KotakNeoSessionRequired as exc:
|
| 596 |
+
raise HTTPException(status_code=401, detail=str(exc)) from exc
|
| 597 |
+
except KotakNeoError as exc:
|
| 598 |
+
raise HTTPException(status_code=502, detail=str(exc)) from exc
|
| 599 |
+
|
| 600 |
+
|
| 601 |
+
@app.get("/kotak/quote/nifty50")
|
| 602 |
+
def kotak_nifty50_quote() -> dict:
|
| 603 |
+
try:
|
| 604 |
+
return kotak_neo_manager.fetch_nifty50_quote()
|
| 605 |
+
except KotakNeoConfigError as exc:
|
| 606 |
+
raise HTTPException(status_code=503, detail=str(exc)) from exc
|
| 607 |
+
except KotakNeoSessionRequired as exc:
|
| 608 |
+
raise HTTPException(status_code=401, detail=str(exc)) from exc
|
| 609 |
+
except KotakNeoError as exc:
|
| 610 |
+
raise HTTPException(status_code=502, detail=str(exc)) from exc
|
| 611 |
+
|
| 612 |
+
|
| 613 |
+
@app.get("/kotak/activity-log")
|
| 614 |
+
def kotak_activity_log() -> dict:
|
| 615 |
+
try:
|
| 616 |
+
snapshot = kotak_neo_manager.fetch_account_snapshot()
|
| 617 |
+
return {
|
| 618 |
+
"activity_log": snapshot.get("activity_log", {}),
|
| 619 |
+
"trade_history": snapshot.get("trade_history", []),
|
| 620 |
+
"order_book": snapshot.get("order_book", []),
|
| 621 |
+
}
|
| 622 |
+
except KotakNeoConfigError as exc:
|
| 623 |
+
raise HTTPException(status_code=503, detail=str(exc)) from exc
|
| 624 |
+
except KotakNeoSessionRequired as exc:
|
| 625 |
+
raise HTTPException(status_code=401, detail=str(exc)) from exc
|
| 626 |
+
except KotakNeoError as exc:
|
| 627 |
+
raise HTTPException(status_code=502, detail=str(exc)) from exc
|
| 628 |
+
|
| 629 |
+
|
| 630 |
+
@app.get("/cron/keepalive")
|
| 631 |
+
def cron_keepalive(background_tasks: BackgroundTasks) -> dict:
|
| 632 |
+
close_refresh = {"status": "not_checked"}
|
| 633 |
+
tplus1_refresh = {"status": "not_checked"}
|
| 634 |
+
if tplus1_refresh_due():
|
| 635 |
+
background_tasks.add_task(refresh_tplus1_if_due)
|
| 636 |
+
tplus1_refresh = {"status": "scheduled"}
|
| 637 |
+
if close_refresh_due():
|
| 638 |
+
background_tasks.add_task(refresh_market_close_data_if_due)
|
| 639 |
+
close_refresh = {"status": "scheduled"}
|
| 640 |
+
return {
|
| 641 |
+
"status": "awake",
|
| 642 |
+
"market": current_market_state(),
|
| 643 |
+
"tplus1_refresh": tplus1_refresh,
|
| 644 |
+
"close_refresh": close_refresh,
|
| 645 |
+
}
|
| 646 |
+
|
| 647 |
+
|
| 648 |
+
@app.get("/prediction/latest")
|
| 649 |
+
def prediction_latest() -> dict:
|
| 650 |
+
return latest_saved_prediction()
|
| 651 |
+
|
| 652 |
+
|
| 653 |
+
@app.post("/prediction/refresh-first5")
|
| 654 |
+
def prediction_refresh_first5(
|
| 655 |
+
session_date: date | None = Query(default=None, description="Optional YYYY-MM-DD session date in IST."),
|
| 656 |
+
) -> dict:
|
| 657 |
+
prediction = refresh_first5_prediction(session_date=session_date)
|
| 658 |
+
return prediction.to_dict()
|
| 659 |
+
|
| 660 |
+
|
| 661 |
+
@app.post("/data/refresh-daily")
|
| 662 |
+
def data_refresh_daily() -> dict:
|
| 663 |
+
return refresh_daily_data()
|
| 664 |
+
|
| 665 |
+
|
| 666 |
+
@app.post("/data/refresh-market-close")
|
| 667 |
+
def data_refresh_market_close(
|
| 668 |
+
session_date: date | None = Query(default=None, description="Optional YYYY-MM-DD session date in IST."),
|
| 669 |
+
) -> dict:
|
| 670 |
+
return refresh_market_close_data(session_date=session_date)
|
| 671 |
+
|
| 672 |
+
|
| 673 |
+
@app.get("/info/{ticker}")
|
| 674 |
+
def stock_info(ticker: str) -> dict:
|
| 675 |
+
data = get_stock_info(ticker)
|
| 676 |
+
if "error" in data:
|
| 677 |
+
raise HTTPException(status_code=404, detail=data["error"])
|
| 678 |
+
return data
|
| 679 |
+
|