Spaces:
Runtime error
Runtime error
Upload 2 files
Browse filesFiles changed (2)
- app.py+314-312
- runtime.py+13-2
6 unmodified lines789101112131415161718192021222324252627282930313233343536373839404142434445463 unmodified lines505152535455565758596061626364656667681 unmodified line7071727374757677787980818283848586878889909192939495969798991001011021031041051061071085 unmodified lines1141151161171181191203 unmodified lines12412512612712812913013118 unmodified lines1501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971 unmodified line19920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823917 unmodified lines25725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529621 unmodified lines31831932032132232332432532632732832933033133233333433533633733833921 unmodified lines36136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340411 unmodified lines4164174184194204214224234244254264276 unmodified lines4344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195206 unmodified linesimport sysfrom pathlib import Pathfrom fastapi import BackgroundTasks, HTTPException, Queryfrom fastapi.middleware.cors import CORSMiddlewarefrom fastapi import FastAPIfrom pydantic import BaseModelsys.path.insert(0, str(Path(__file__).resolve().parent))from nifty_backend.runtime import (CLOSE_REFRESH_READY,IST,STALE_CHECK_INTERVAL_SECONDS,TPLUS1_READY,close_refresh_due,dashboard_payload,is_trading_day,latest_saved_prediction,latest_tplus1_prediction,next_trading_day,refresh_daily_data,refresh_first5_prediction,refresh_market_close_data,refresh_stale_data_once,refresh_tplus1_prediction,seconds_until_next_ist_run,warm_dashboard_payload_cache,)from kotak_neo import (KotakNeoConfigError,KotakNeoError,KotakNeoSessionRequired,kotak_neo_manager,)app = FastAPI(title="NIFTY 50 Forecaster Backend")app.add_middleware(CORSMiddleware,allow_origins=["*"],3 unmodified lines)market_status = "Waiting for next session"close_refresh_lock = threading.Lock()tplus1_refresh_lock = threading.Lock()MARKET_OPEN = time(9, 15)FIRST5_READY = time(9, 20)MARKET_CLOSE = time(15, 30)class TotpRequest(BaseModel):totp: strdef refresh_market_close_data_if_due() -> dict:if not close_refresh_due():return {"status": "skipped", "reason": "close refresh is not due"}if not close_refresh_lock.acquire(blocking=False):1 unmodified linetry:info = refresh_market_close_data()return {"status": "refreshed", **info}finally:close_refresh_lock.release()def latest_tplus1_prediction_date(payload: dict | None = None) -> date | None:try:latest = payload if payload is not None else latest_tplus1_prediction()raw = latest.get("input_date")return date.fromisoformat(str(raw)[:10]) if raw else Noneexcept Exception:return Nonedef tplus1_refresh_due(now: datetime | None = None, latest_date: date | None = None) -> bool:now = now or datetime.now(IST)if not is_trading_day(now.date()) or not (TPLUS1_READY <= now.time() < MARKET_CLOSE):return Falselatest_date = latest_date if latest_date is not None else latest_tplus1_prediction_date()return latest_date != now.date()def refresh_tplus1_if_due() -> dict:now = datetime.now(IST)latest_date = latest_tplus1_prediction_date()if not tplus1_refresh_due(now=now, latest_date=latest_date):return {"status": "skipped", "reason": "tplus1 refresh is not due"}if not tplus1_refresh_lock.acquire(blocking=False):return {"status": "skipped", "reason": "tplus1 refresh already running"}try:prediction = refresh_tplus1_prediction(session_date=now.date())return {"status": "refreshed", "prediction": prediction}finally:tplus1_refresh_lock.release()def latest_prediction_date(payload: dict | None = None) -> date | None:5 unmodified linesreturn Nonedef current_market_state(now: datetime | None = None) -> dict:global market_statusnow = now or datetime.now(IST)today = now.date()3 unmodified linesmarket_is_open_for_t5 = trading_day and FIRST5_READY <= current_time < MARKET_CLOSEmarket_is_open_for_tplus1 = trading_day and TPLUS1_READY <= current_time < MARKET_CLOSEhas_current_first5 = market_is_open_for_t5 and latest_date == todaytplus1_latest_date = latest_tplus1_prediction_date()has_current_tplus1 = market_is_open_for_tplus1 and tplus1_latest_date == todaynext_session = today if trading_day and current_time < MARKET_CLOSE else next_trading_day(today + timedelta(days=1))if not trading_day:18 unmodified lineselse:status = "Prediction Pending"detail = "No current-session prediction has been generated yet."else:status = "Market Closed"detail = "Trading session has ended."if not trading_day:tplus1_status = "Market Closed"tplus1_detail = f"Next trading session is {next_session.isoformat()}."elif current_time < TPLUS1_READY:tplus1_status = "Waiting for 2:30 PM"tplus1_detail = "The T+1 forecast becomes available at 2:30 PM IST."elif current_time < MARKET_CLOSE:if has_current_tplus1:tplus1_status = "Ready"tplus1_detail = "Today's T+1 prediction is available."else:tplus1_status = "Pending"tplus1_detail = "No current-session T+1 prediction has been generated yet."else:tplus1_status = "Market Closed"tplus1_detail = "Trading session has ended."if not trading_day:t5_status = "Market Closed"t5_detail = f"Next trading session is {next_session.isoformat()}."elif current_time < FIRST5_READY:t5_status = "Waiting for 9:20 AM"t5_detail = "The T+5 forecast becomes available after the first five one-minute bars."elif current_time < MARKET_CLOSE:if market_status in {"Fetching T+5 Prediction Data...", "Prediction Failed"}:t5_status = market_statust5_detail = "The first-five-minute prediction job is still resolving."elif has_current_first5:t5_status = "Ready"t5_detail = "Today's first-five-minute prediction is available."else:t5_status = "Pending"t5_detail = "No current-session prediction has been generated yet."else:t5_status = "Market Closed"t5_detail = "Trading session has ended."return {"market_status": status,"market_detail": detail,"server_time_ist": now.isoformat(),1 unmodified line"session_date": today.isoformat(),"next_session_date": next_session.isoformat(),"latest_prediction_date": latest_date.isoformat() if latest_date else None,"t5_available": has_current_first5,"t5_status": t5_status,"t5_detail": t5_detail,"market_is_open_for_t5": market_is_open_for_t5,"tplus1_available": has_current_tplus1,"tplus1_status": tplus1_status,"tplus1_detail": tplus1_detail,"market_is_open_for_tplus1": market_is_open_for_tplus1,"latest_tplus1_prediction_date": tplus1_latest_date.isoformat() if tplus1_latest_date else None,}def attach_market_state(payload: dict) -> dict:state = current_market_state()payload.setdefault("data_status", {})payload["data_status"].update(state)try:payload["nifty_quote"] = kotak_neo_manager.fetch_nifty50_quote()payload["nifty_quote_error"] = Noneexcept KotakNeoSessionRequired as exc:payload["nifty_quote"] = Nonepayload["nifty_quote_error"] = {"status": 401, "message": str(exc)}except KotakNeoConfigError as exc:payload["nifty_quote"] = Nonepayload["nifty_quote_error"] = {"status": 503, "message": str(exc)}except KotakNeoError as exc:payload["nifty_quote"] = Nonepayload["nifty_quote_error"] = {"status": 502, "message": str(exc)}t5_latest = payload.get("latest") or {}tomorrow_latest = payload.get("tomorrow_latest") or {}tplus1_latest = payload.get("tplus1_latest") or {}t5_available = bool(state["t5_available"] and t5_latest.get("prediction"))tplus1_available = bool(state["tplus1_available"] and tplus1_latest.get("prediction"))tomorrow_available = bool(tomorrow_latest.get("prediction"))refresh_phase = payload.get("data_status", {}).get("refresh_phase")if refresh_phase in {"waiting_second_payload", "refreshing"}:tomorrow_status = "WAITING FOR SECOND PAYLOAD"17 unmodified lines"validation_accuracy": tomorrow_latest.get("validation_accuracy"),"test_accuracy": tomorrow_latest.get("test_accuracy"),},"t5": {"available": t5_available,"status": "Ready" if t5_available else state["t5_status"],"reason": None if t5_available else state["t5_detail"],"input_date": t5_latest.get("input_date"),"prediction": t5_latest.get("prediction") if t5_available else None,"prob_up": t5_latest.get("prob_up") if t5_available else None,"confidence": t5_latest.get("confidence") if t5_available else None,"threshold": t5_latest.get("threshold") if t5_available else None,"is_overridden": bool(t5_latest.get("is_overridden")) if t5_available else False,"model_name": t5_latest.get("model_name"),"validation_accuracy": (payload.get("summary") or {}).get("validation_accuracy"),"test_accuracy": (payload.get("summary") or {}).get("test_accuracy"),},"tplus1": {"available": tplus1_available,"status": "Ready" if tplus1_available else state["tplus1_status"],"reason": None if tplus1_available else state["tplus1_detail"],"target_date": tplus1_latest.get("target_date") or state["next_session_date"],"input_date": tplus1_latest.get("input_date"),"prediction": tplus1_latest.get("prediction") if tplus1_available else None,"prob_up": tplus1_latest.get("prob_up") if tplus1_available else None,"confidence": tplus1_latest.get("confidence") if tplus1_available else None,"threshold": tplus1_latest.get("threshold") if tplus1_available else None,"is_overridden": bool(tplus1_latest.get("overlay_changed")) if tplus1_available else False,"model_name": tplus1_latest.get("model_name"),"validation_accuracy": (payload.get("tplus1_summary") or {}).get("validation_accuracy"),"test_accuracy": (payload.get("tplus1_summary") or {}).get("test_accuracy"),},}return payloadasync def daily_ist_refresh_loop() -> None:global market_statuswhile True:# Wait until 9:00 AM IST21 unmodified linesprint(f"[scheduler] first5 refresh failed: {exc}", flush=True)market_status = "Prediction Failed"try:await asyncio.to_thread(refresh_daily_data)except Exception as exc:print(f"[scheduler] daily refresh failed: {exc}", flush=True)await asyncio.sleep(seconds_until_next_ist_run(TPLUS1_READY))print("[scheduler] 2:30 PM IST - Refreshing T+1 prediction", flush=True)try:info = await asyncio.to_thread(refresh_tplus1_if_due)print(f"[scheduler] tplus1 refresh result: {info}", flush=True)except Exception as exc:print(f"[scheduler] tplus1 refresh failed: {exc}", flush=True)await asyncio.sleep(seconds_until_next_ist_run(CLOSE_REFRESH_READY))print("[scheduler] 3:45 PM IST - Refreshing close data", flush=True)try:info = await asyncio.to_thread(refresh_market_close_data_if_due)print(f"[scheduler] close refresh result: {info}", flush=True)except Exception as exc:21 unmodified linesprint(f"[startup] daily refresh failed: {exc}", flush=True)async def refresh_market_close_once_if_due() -> None:try:info = await asyncio.to_thread(refresh_market_close_data_if_due)if info.get("status") == "refreshed":print(f"[startup] close refresh result: {info}", flush=True)except Exception as exc:print(f"[startup] close refresh failed: {exc}", flush=True)async def refresh_tplus1_once_if_due() -> None:try:info = await asyncio.to_thread(refresh_tplus1_if_due)if info.get("status") == "refreshed":print(f"[startup] tplus1 refresh result: {info}", flush=True)except Exception as exc:print(f"[startup] tplus1 refresh failed: {exc}", flush=True)async def warm_dashboard_payload_cache_once() -> None:try:await asyncio.to_thread(warm_dashboard_payload_cache)except Exception as exc:print(f"[startup] dashboard payload warmup failed: {exc}", flush=True)async def stale_data_watch_loop() -> None:while True:try:info = await asyncio.to_thread(refresh_stale_data_once)if info.get("status") == "refreshed":print(f"[stale-watch] refreshed stale data: {info}", flush=True)except Exception as exc:print(f"[stale-watch] stale refresh failed: {exc}", flush=True)await asyncio.sleep(STALE_CHECK_INTERVAL_SECONDS)@app.on_event("startup")async def start_scheduler() -> None:global market_status# Initialize correct status on startup based on current timenow = datetime.now(IST).time()11 unmodified lineselse:market_status = "Prediction Pending"asyncio.create_task(refresh_current_session_once())asyncio.create_task(refresh_tplus1_once_if_due())asyncio.create_task(refresh_market_close_once_if_due())asyncio.create_task(warm_dashboard_payload_cache_once())asyncio.create_task(stale_data_watch_loop())asyncio.create_task(daily_ist_refresh_loop())@app.get("/health")6 unmodified linesreturn {"service": "NIFTY 50 Forecaster Backend", "status": "ok"}@app.get("/dashboard")def dashboard() -> dict:try:refresh_stale_data_once()except Exception as exc:print(f"[dashboard] stale refresh failed: {exc}", flush=True)return attach_market_state(dashboard_payload())@app.get("/kotak/status")def kotak_status() -> dict:return kotak_neo_manager.status()@app.post("/kotak/auth/totp")def kotak_auth_totp(payload: TotpRequest) -> dict:try:return kotak_neo_manager.authenticate_with_totp(payload.totp)except KotakNeoConfigError as exc:raise HTTPException(status_code=503, detail=str(exc)) from excexcept KotakNeoError as exc:raise HTTPException(status_code=400, detail=str(exc)) from exc@app.get("/kotak/account")def kotak_account() -> dict:try:return kotak_neo_manager.fetch_account_snapshot()except KotakNeoConfigError as exc:raise HTTPException(status_code=503, detail=str(exc)) from excexcept KotakNeoSessionRequired as exc:raise HTTPException(status_code=401, detail=str(exc)) from excexcept KotakNeoError as exc:raise HTTPException(status_code=502, detail=str(exc)) from exc@app.get("/kotak/quote/nifty50")def kotak_nifty50_quote() -> dict:try:return kotak_neo_manager.fetch_nifty50_quote()except KotakNeoConfigError as exc:raise HTTPException(status_code=503, detail=str(exc)) from excexcept KotakNeoSessionRequired as exc:raise HTTPException(status_code=401, detail=str(exc)) from excexcept KotakNeoError as exc:raise HTTPException(status_code=502, detail=str(exc)) from exc@app.get("/kotak/activity-log")def kotak_activity_log() -> dict:try:snapshot = kotak_neo_manager.fetch_account_snapshot()return {"activity_log": snapshot.get("activity_log", {}),"trade_history": snapshot.get("trade_history", []),"order_book": snapshot.get("order_book", []),}except KotakNeoConfigError as exc:raise HTTPException(status_code=503, detail=str(exc)) from excexcept KotakNeoSessionRequired as exc:raise HTTPException(status_code=401, detail=str(exc)) from excexcept KotakNeoError as exc:raise HTTPException(status_code=502, detail=str(exc)) from exc@app.get("/cron/keepalive")def cron_keepalive(background_tasks: BackgroundTasks) -> dict:close_refresh = {"status": "not_checked"}tplus1_refresh = {"status": "not_checked"}if tplus1_refresh_due():background_tasks.add_task(refresh_tplus1_if_due)tplus1_refresh = {"status": "scheduled"}if close_refresh_due():background_tasks.add_task(refresh_market_close_data_if_due)close_refresh = {"status": "scheduled"}return {"status": "awake","market": current_market_state(),"tplus1_refresh": tplus1_refresh,"close_refresh": close_refresh,}@app.get("/prediction/latest")6 unmodified lines789101112131415161718192021222324252627282930313233343536373839404142434445463 unmodified lines505152535455565758596061626364656667681 unmodified line7071727374757677787980818283848586878889909192939495969798991001011021031041051061071085 unmodified lines1141151161171181191203 unmodified lines12412512612712812913013118 unmodified lines1501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971 unmodified line19920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823917 unmodified lines25725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529621 unmodified lines31831932032132232332432532632732832933033133233333433533633733833921 unmodified lines36136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340411 unmodified lines4164174184194204214224234244254264276 unmodified lines4344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215226 unmodified linesimport sysfrom pathlib import Pathfrom fastapi import BackgroundTasks, HTTPException, Query, Responsefrom fastapi.middleware.cors import CORSMiddlewarefrom fastapi import FastAPIfrom pydantic import BaseModelsys.path.insert(0, str(Path(__file__).resolve().parent))from nifty_backend.runtime import (CLOSE_REFRESH_READY,IST,STALE_CHECK_INTERVAL_SECONDS,TPLUS1_READY,close_refresh_due,dashboard_payload,is_trading_day,latest_saved_prediction,latest_tplus1_prediction,next_trading_day,refresh_daily_data,refresh_first5_prediction,refresh_market_close_data,refresh_stale_data_once,refresh_tplus1_prediction,seconds_until_next_ist_run,warm_dashboard_payload_cache,)from kotak_neo import (KotakNeoConfigError,KotakNeoError,KotakNeoSessionRequired,kotak_neo_manager,)app = FastAPI(title="NIFTY 50 Forecaster Backend")app.add_middleware(CORSMiddleware,allow_origins=["*"],3 unmodified lines)market_status = "Waiting for next session"close_refresh_lock = threading.Lock()tplus1_refresh_lock = threading.Lock()MARKET_OPEN = time(9, 15)FIRST5_READY = time(9, 20)MARKET_CLOSE = time(15, 30)class TotpRequest(BaseModel):totp: strdef refresh_market_close_data_if_due() -> dict:if not close_refresh_due():return {"status": "skipped", "reason": "close refresh is not due"}if not close_refresh_lock.acquire(blocking=False):1 unmodified linetry:info = refresh_market_close_data()return {"status": "refreshed", **info}finally:close_refresh_lock.release()def latest_tplus1_prediction_date(payload: dict | None = None) -> date | None:try:latest = payload if payload is not None else latest_tplus1_prediction()raw = latest.get("input_date")return date.fromisoformat(str(raw)[:10]) if raw else Noneexcept Exception:return Nonedef tplus1_refresh_due(now: datetime | None = None, latest_date: date | None = None) -> bool:now = now or datetime.now(IST)if not is_trading_day(now.date()) or not (TPLUS1_READY <= now.time() < MARKET_CLOSE):return Falselatest_date = latest_date if latest_date is not None else latest_tplus1_prediction_date()return latest_date != now.date()def refresh_tplus1_if_due() -> dict:now = datetime.now(IST)latest_date = latest_tplus1_prediction_date()if not tplus1_refresh_due(now=now, latest_date=latest_date):return {"status": "skipped", "reason": "tplus1 refresh is not due"}if not tplus1_refresh_lock.acquire(blocking=False):return {"status": "skipped", "reason": "tplus1 refresh already running"}try:prediction = refresh_tplus1_prediction(session_date=now.date())return {"status": "refreshed", "prediction": prediction}finally:tplus1_refresh_lock.release()def latest_prediction_date(payload: dict | None = None) -> date | None:5 unmodified linesreturn Nonedef current_market_state(now: datetime | None = None) -> dict:global market_statusnow = now or datetime.now(IST)today = now.date()3 unmodified linesmarket_is_open_for_t5 = trading_day and FIRST5_READY <= current_time < MARKET_CLOSEmarket_is_open_for_tplus1 = trading_day and TPLUS1_READY <= current_time < MARKET_CLOSEhas_current_first5 = market_is_open_for_t5 and latest_date == todaytplus1_latest_date = latest_tplus1_prediction_date()has_current_tplus1 = market_is_open_for_tplus1 and tplus1_latest_date == todaynext_session = today if trading_day and current_time < MARKET_CLOSE else next_trading_day(today + timedelta(days=1))if not trading_day:18 unmodified lineselse:status = "Prediction Pending"detail = "No current-session prediction has been generated yet."else:status = "Market Closed"detail = "Trading session has ended."if not trading_day:tplus1_status = "Market Closed"tplus1_detail = f"Next trading session is {next_session.isoformat()}."elif current_time < TPLUS1_READY:tplus1_status = "Waiting for 2:30 PM"tplus1_detail = "The T+1 forecast becomes available at 2:30 PM IST."elif current_time < MARKET_CLOSE:if has_current_tplus1:tplus1_status = "Ready"tplus1_detail = "Today's T+1 prediction is available."else:tplus1_status = "Pending"tplus1_detail = "No current-session T+1 prediction has been generated yet."else:tplus1_status = "Market Closed"tplus1_detail = "Trading session has ended."if not trading_day:t5_status = "Market Closed"t5_detail = f"Next trading session is {next_session.isoformat()}."elif current_time < FIRST5_READY:t5_status = "Waiting for 9:20 AM"t5_detail = "The T+5 forecast becomes available after the first five one-minute bars."elif current_time < MARKET_CLOSE:if market_status in {"Fetching T+5 Prediction Data...", "Prediction Failed"}:t5_status = market_statust5_detail = "The first-five-minute prediction job is still resolving."elif has_current_first5:t5_status = "Ready"t5_detail = "Today's first-five-minute prediction is available."else:t5_status = "Pending"t5_detail = "No current-session prediction has been generated yet."else:t5_status = "Market Closed"t5_detail = "Trading session has ended."return {"market_status": status,"market_detail": detail,"server_time_ist": now.isoformat(),1 unmodified line"session_date": today.isoformat(),"next_session_date": next_session.isoformat(),"latest_prediction_date": latest_date.isoformat() if latest_date else None,"t5_available": has_current_first5,"t5_status": t5_status,"t5_detail": t5_detail,"market_is_open_for_t5": market_is_open_for_t5,"tplus1_available": has_current_tplus1,"tplus1_status": tplus1_status,"tplus1_detail": tplus1_detail,"market_is_open_for_tplus1": market_is_open_for_tplus1,"latest_tplus1_prediction_date": tplus1_latest_date.isoformat() if tplus1_latest_date else None,}def attach_market_state(payload: dict) -> dict:state = current_market_state()payload.setdefault("data_status", {})payload["data_status"].update(state)try:payload["nifty_quote"] = kotak_neo_manager.fetch_nifty50_quote()payload["nifty_quote_error"] = Noneexcept KotakNeoSessionRequired as exc:payload["nifty_quote"] = Nonepayload["nifty_quote_error"] = {"status": 401, "message": str(exc)}except KotakNeoConfigError as exc:payload["nifty_quote"] = Nonepayload["nifty_quote_error"] = {"status": 503, "message": str(exc)}except KotakNeoError as exc:payload["nifty_quote"] = Nonepayload["nifty_quote_error"] = {"status": 502, "message": str(exc)}t5_latest = payload.get("latest") or {}tomorrow_latest = payload.get("tomorrow_latest") or {}tplus1_latest = payload.get("tplus1_latest") or {}t5_available = bool(state["t5_available"] and t5_latest.get("prediction"))tplus1_available = bool(state["tplus1_available"] and tplus1_latest.get("prediction"))tomorrow_available = bool(tomorrow_latest.get("prediction"))refresh_phase = payload.get("data_status", {}).get("refresh_phase")if refresh_phase in {"waiting_second_payload", "refreshing"}:tomorrow_status = "WAITING FOR SECOND PAYLOAD"17 unmodified lines"validation_accuracy": tomorrow_latest.get("validation_accuracy"),"test_accuracy": tomorrow_latest.get("test_accuracy"),},"t5": {"available": t5_available,"status": "Ready" if t5_available else state["t5_status"],"reason": None if t5_available else state["t5_detail"],"input_date": t5_latest.get("input_date"),"prediction": t5_latest.get("prediction") if t5_available else None,"prob_up": t5_latest.get("prob_up") if t5_available else None,"confidence": t5_latest.get("confidence") if t5_available else None,"threshold": t5_latest.get("threshold") if t5_available else None,"is_overridden": bool(t5_latest.get("is_overridden")) if t5_available else False,"model_name": t5_latest.get("model_name"),"validation_accuracy": (payload.get("summary") or {}).get("validation_accuracy"),"test_accuracy": (payload.get("summary") or {}).get("test_accuracy"),},"tplus1": {"available": tplus1_available,"status": "Ready" if tplus1_available else state["tplus1_status"],"reason": None if tplus1_available else state["tplus1_detail"],"target_date": tplus1_latest.get("target_date") or state["next_session_date"],"input_date": tplus1_latest.get("input_date"),"prediction": tplus1_latest.get("prediction") if tplus1_available else None,"prob_up": tplus1_latest.get("prob_up") if tplus1_available else None,"confidence": tplus1_latest.get("confidence") if tplus1_available else None,"threshold": tplus1_latest.get("threshold") if tplus1_available else None,"is_overridden": bool(tplus1_latest.get("overlay_changed")) if tplus1_available else False,"model_name": tplus1_latest.get("model_name"),"validation_accuracy": (payload.get("tplus1_summary") or {}).get("validation_accuracy"),"test_accuracy": (payload.get("tplus1_summary") or {}).get("test_accuracy"),},}return payloadasync def daily_ist_refresh_loop() -> None:global market_statuswhile True:# Wait until 9:00 AM IST21 unmodified linesprint(f"[scheduler] first5 refresh failed: {exc}", flush=True)market_status = "Prediction Failed"try:await asyncio.to_thread(refresh_daily_data)except Exception as exc:print(f"[scheduler] daily refresh failed: {exc}", flush=True)await asyncio.sleep(seconds_until_next_ist_run(TPLUS1_READY))print("[scheduler] 2:30 PM IST - Refreshing T+1 prediction", flush=True)try:info = await asyncio.to_thread(refresh_tplus1_if_due)print(f"[scheduler] tplus1 refresh result: {info}", flush=True)except Exception as exc:print(f"[scheduler] tplus1 refresh failed: {exc}", flush=True)await asyncio.sleep(seconds_until_next_ist_run(CLOSE_REFRESH_READY))print("[scheduler] 3:45 PM IST - Refreshing close data", flush=True)try:info = await asyncio.to_thread(refresh_market_close_data_if_due)print(f"[scheduler] close refresh result: {info}", flush=True)except Exception as exc:21 unmodified linesprint(f"[startup] daily refresh failed: {exc}", flush=True)async def refresh_market_close_once_if_due() -> None:try:info = await asyncio.to_thread(refresh_market_close_data_if_due)if info.get("status") == "refreshed":print(f"[startup] close refresh result: {info}", flush=True)except Exception as exc:print(f"[startup] close refresh failed: {exc}", flush=True)async def refresh_tplus1_once_if_due() -> None:try:info = await asyncio.to_thread(refresh_tplus1_if_due)if info.get("status") == "refreshed":print(f"[startup] tplus1 refresh result: {info}", flush=True)except Exception as exc:print(f"[startup] tplus1 refresh failed: {exc}", flush=True)async def warm_dashboard_payload_cache_once() -> None:try:await asyncio.to_thread(warm_dashboard_payload_cache)except Exception as exc:print(f"[startup] dashboard payload warmup failed: {exc}", flush=True)async def stale_data_watch_loop() -> None:while True:try:info = await asyncio.to_thread(refresh_stale_data_once)if info.get("status") == "refreshed":print(f"[stale-watch] refreshed stale data: {info}", flush=True)except Exception as exc:print(f"[stale-watch] stale refresh failed: {exc}", flush=True)await asyncio.sleep(STALE_CHECK_INTERVAL_SECONDS)@app.on_event("startup")async def start_scheduler() -> None:global market_status# Initialize correct status on startup based on current timenow = datetime.now(IST).time()11 unmodified lineselse:market_status = "Prediction Pending"asyncio.create_task(refresh_current_session_once())asyncio.create_task(refresh_tplus1_once_if_due())asyncio.create_task(refresh_market_close_once_if_due())asyncio.create_task(warm_dashboard_payload_cache_once())asyncio.create_task(stale_data_watch_loop())asyncio.create_task(daily_ist_refresh_loop())@app.get("/health")6 unmodified linesreturn {"service": "NIFTY 50 Forecaster Backend", "status": "ok"}@app.get("/dashboard")def dashboard(response: Response) -> dict:response.headers["Cache-Control"] = "no-store, no-cache, must-revalidate"response.headers["Pragma"] = "no-cache"try:refresh_stale_data_once()except Exception as exc:print(f"[dashboard] stale refresh failed: {exc}", flush=True)return attach_market_state(dashboard_payload())@app.get("/kotak/status")def kotak_status() -> dict:return kotak_neo_manager.status()@app.post("/kotak/auth/totp")def kotak_auth_totp(payload: TotpRequest) -> dict:try:return kotak_neo_manager.authenticate_with_totp(payload.totp)except KotakNeoConfigError as exc:raise HTTPException(status_code=503, detail=str(exc)) from excexcept KotakNeoError as exc:raise HTTPException(status_code=400, detail=str(exc)) from exc@app.get("/kotak/account")def kotak_account() -> dict:try:return kotak_neo_manager.fetch_account_snapshot()except KotakNeoConfigError as exc:raise HTTPException(status_code=503, detail=str(exc)) from excexcept KotakNeoSessionRequired as exc:raise HTTPException(status_code=401, detail=str(exc)) from excexcept KotakNeoError as exc:raise HTTPException(status_code=502, detail=str(exc)) from exc@app.get("/kotak/quote/nifty50")def kotak_nifty50_quote() -> dict:try:return kotak_neo_manager.fetch_nifty50_quote()except KotakNeoConfigError as exc:raise HTTPException(status_code=503, detail=str(exc)) from excexcept KotakNeoSessionRequired as exc:raise HTTPException(status_code=401, detail=str(exc)) from excexcept KotakNeoError as exc:raise HTTPException(status_code=502, detail=str(exc)) from exc@app.get("/kotak/activity-log")def kotak_activity_log() -> dict:try:snapshot = kotak_neo_manager.fetch_account_snapshot()return {"activity_log": snapshot.get("activity_log", {}),"trade_history": snapshot.get("trade_history", []),"order_book": snapshot.get("order_book", []),}except KotakNeoConfigError as exc:raise HTTPException(status_code=503, detail=str(exc)) from excexcept KotakNeoSessionRequired as exc:raise HTTPException(status_code=401, detail=str(exc)) from excexcept KotakNeoError as exc:raise HTTPException(status_code=502, detail=str(exc)) from exc@app.get("/cron/keepalive")def cron_keepalive(background_tasks: BackgroundTasks) -> dict:close_refresh = {"status": "not_checked"}tplus1_refresh = {"status": "not_checked"}if tplus1_refresh_due():background_tasks.add_task(refresh_tplus1_if_due)tplus1_refresh = {"status": "scheduled"}if close_refresh_due():background_tasks.add_task(refresh_market_close_data_if_due)close_refresh = {"status": "scheduled"}return {"status": "awake","market": current_market_state(),"tplus1_refresh": tplus1_refresh,"close_refresh": close_refresh,}@app.get("/prediction/latest")
1262 unmodified lines1263126412651266126712681269141 unmodified lines1411141214131414141514166 unmodified lines14231424142514261427142814291262 unmodified lineswith _dashboard_payload_lock:payload = copy.deepcopy(_dashboard_payload_cached(key))# Always rebuild track record (fresh Yahoo daily + calendar window), never serve from LRU cache.payload["charts"]["track_record"] = build_prediction_track_record(sessions=10)return payload141 unmodified lines)source = "Tomorrow (rolling)"records.append({"date": target_day.isoformat(),6 unmodified lines"correct": prediction == actual_direction,})return records@lru_cache(maxsize=4)1262 unmodified lines126312641265126612671268126912701271127212731274127512761277141 unmodified lines1419142014211422142314241425142614276 unmodified lines14341435143614371438143914401262 unmodified lineswith _dashboard_payload_lock:payload = copy.deepcopy(_dashboard_payload_cached(key))# Always rebuild track record (fresh Yahoo daily + calendar window), never serve from LRU cache.track_record = build_prediction_track_record(sessions=10)payload["charts"]["track_record"] = track_recordpayload["charts"]["track_record_meta"] = {"builder": "rolling_v1","sessions": 10,"count": len(track_record),"start": track_record[0]["date"] if track_record else None,"end": track_record[-1]["date"] if track_record else None,}return payload141 unmodified lines)source = "Tomorrow (rolling)"if prediction not in {"UP", "DOWN"}:continuerecords.append({"date": target_day.isoformat(),6 unmodified lines"correct": prediction == actual_direction,})return records[-sessions:]@lru_cache(maxsize=4)
app.py+314-312
runtime.py+13-2