Spaces:
Runtime error
Runtime error
Upload 7 files
Browse filesFiles changed (4)
- README.md+4-1
- app.py+80-19
- data/nifty50_1d.parquet+2-2
- data/tomorrow_test_predictions.parquetAdded+3
18 unmodified lines1920212223246 unmodified lines31323334353618 unmodified lines- `POST /prediction/refresh-first5`- `POST /data/refresh-daily`- `GET /cron/keepalive`## Data6 unmodified lines## RuntimeThe API starts a daily background refresh loop. It wakes after `09:20 Asia/Kolkata`, fetches Yahoo Finance `^NSEI` 1-minute candles for the `09:15-09:19` opening window, appends them to Parquet, and writes the latest prediction.Netlify also pings `/cron/keepalive` every 10 minutes through its scheduled function.18 unmodified lines192021222324256 unmodified lines323334353637383918 unmodified lines- `POST /prediction/refresh-first5`- `POST /data/refresh-daily`- `GET /cron/keepalive`- `POST /data/refresh-market-close`## Data6 unmodified lines## RuntimeThe API starts a daily background refresh loop. It wakes after `09:20 Asia/Kolkata`, fetches Yahoo Finance `^NSEI` 1-minute candles for the `09:15-09:19` opening window, appends them to Parquet, and writes the latest T+5 prediction.After market close it wakes again at `15:45 Asia/Kolkata`, refreshes the 1-minute and daily Parquet files, updates the opening training dataset with same-day close outcomes, and writes the saved prediction record used for the next trading session card. The `/cron/keepalive` endpoint also checks this close refresh so a Hugging Face Space that was idled still catches up when Netlify pings it.Netlify also pings `/cron/keepalive` every 10 minutes through its scheduled function.
12345678910111213141516171819202122232410 unmodified lines353637383940414243444555 unmodified lines10110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113232 unmodified lines16516616716816917016 unmodified lines18718818919019119221 unmodified lines21421521621721821914 unmodified lines23423523623723823924024112 unmodified lines254255256from __future__ import annotationsimport asynciofrom datetime import date, datetime, time, timedeltaimport sysfrom pathlib import Pathfrom fastapi import Queryfrom fastapi.middleware.cors import CORSMiddlewarefrom fastapi import FastAPIsys.path.insert(0, str(Path(__file__).resolve().parent))from nifty_backend.runtime import (IST,dashboard_payload,is_trading_day,latest_saved_prediction,next_trading_day,refresh_daily_data,refresh_first5_prediction,seconds_until_next_ist_run,warm_dashboard_payload_cache,)10 unmodified linesmarket_status = "Waiting for next session"MARKET_OPEN = time(9, 15)FIRST5_READY = time(9, 20)MARKET_CLOSE = time(15, 30)def latest_prediction_date(payload: dict | None = None) -> date | None:try:latest = payload if payload is not None else latest_saved_prediction()55 unmodified linespayload.setdefault("data_status", {})payload["data_status"].update(state)latest = payload.get("latest") or {}t5_available = bool(state["t5_available"] and latest.get("prediction"))market_closed = state["market_status"] == "Market Closed"unavailable_reason = "Market Closed" if market_closed else state["market_status"]tomorrow_available = bool(latest.get("prediction"))payload["predictions"] = {"tomorrow": {"available": tomorrow_available,"status": "Ready" if tomorrow_available else "Pending","reason": None if tomorrow_available else "No saved next-session signal is available.","target_date": state["next_session_date"],"input_date": latest.get("input_date"),"prediction": latest.get("prediction") if tomorrow_available else None,"prob_up": latest.get("prob_up") if tomorrow_available else None,"confidence": latest.get("confidence") if tomorrow_available else None,"threshold": latest.get("threshold") if tomorrow_available else None,},"t5": {"available": t5_available,"status": "Ready" if t5_available else unavailable_reason,"reason": None if t5_available else state["market_detail"],"input_date": latest.get("input_date"),"prediction": latest.get("prediction") if t5_available else None,"prob_up": latest.get("prob_up") if t5_available else None,"confidence": latest.get("confidence") if t5_available else None,"threshold": latest.get("threshold") if t5_available else None,},}return payload32 unmodified linesexcept Exception as exc:print(f"[scheduler] daily refresh failed: {exc}", flush=True)async def refresh_current_session_once() -> None:global market_status16 unmodified linesprint(f"[startup] daily refresh failed: {exc}", flush=True)async def warm_dashboard_payload_cache_once() -> None:try:await asyncio.to_thread(warm_dashboard_payload_cache)21 unmodified linesmarket_status = "Prediction Pending"asyncio.create_task(refresh_current_session_once())asyncio.create_task(warm_dashboard_payload_cache_once())asyncio.create_task(daily_ist_refresh_loop())14 unmodified lines@app.get("/cron/keepalive")def cron_keepalive() -> dict:return {"status": "awake", "market": current_market_state()}@app.get("/prediction/latest")12 unmodified lines@app.post("/data/refresh-daily")def data_refresh_daily() -> dict:return refresh_daily_data()1234567891011121314151617181920212223242526272810 unmodified lines39404142434445464748495051525354555657585960616255 unmodified lines11811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316432 unmodified lines19719819920020120220320420520620720820921016 unmodified lines22722822923023123223323423523623723823924024121 unmodified lines26326426526626726826914 unmodified lines28428528628728828929029129229329429512 unmodified lines308309310311312313314315316317from __future__ import annotationsimport asyncioimport threadingfrom datetime import date, datetime, time, timedeltaimport sysfrom pathlib import Pathfrom fastapi import BackgroundTasks, Queryfrom fastapi.middleware.cors import CORSMiddlewarefrom fastapi import FastAPIsys.path.insert(0, str(Path(__file__).resolve().parent))from nifty_backend.runtime import (CLOSE_REFRESH_READY,IST,close_refresh_due,dashboard_payload,is_trading_day,latest_saved_prediction,next_trading_day,refresh_daily_data,refresh_first5_prediction,refresh_market_close_data,seconds_until_next_ist_run,warm_dashboard_payload_cache,)10 unmodified linesmarket_status = "Waiting for next session"close_refresh_lock = threading.Lock()MARKET_OPEN = time(9, 15)FIRST5_READY = time(9, 20)MARKET_CLOSE = time(15, 30)def 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):return {"status": "skipped", "reason": "close refresh already running"}try:info = refresh_market_close_data()return {"status": "refreshed", **info}finally:close_refresh_lock.release()def latest_prediction_date(payload: dict | None = None) -> date | None:try:latest = payload if payload is not None else latest_saved_prediction()55 unmodified linespayload.setdefault("data_status", {})payload["data_status"].update(state)t5_latest = payload.get("latest") or {}tomorrow_latest = payload.get("tomorrow_latest") or {}t5_available = bool(state["t5_available"] and t5_latest.get("prediction"))market_closed = state["market_status"] == "Market Closed"unavailable_reason = "Market Closed" if market_closed else state["market_status"]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"tomorrow_reason = "Market close refresh is generating the next-session payload."else:tomorrow_status = "Ready" if tomorrow_available else "Pending"tomorrow_reason = None if tomorrow_available else "No saved next-session signal is available."payload["predictions"] = {"tomorrow": {"available": tomorrow_available,"status": tomorrow_status,"reason": tomorrow_reason,"target_date": tomorrow_latest.get("target_date") or state["next_session_date"],"input_date": tomorrow_latest.get("input_date"),"prediction": tomorrow_latest.get("prediction") if tomorrow_available else None,"prob_up": tomorrow_latest.get("prob_up") if tomorrow_available else None,"confidence": tomorrow_latest.get("confidence") if tomorrow_available else None,"threshold": tomorrow_latest.get("threshold") if tomorrow_available else None,"model_name": tomorrow_latest.get("model_name"),"source_model": tomorrow_latest.get("source_model"),"validation_accuracy": tomorrow_latest.get("validation_accuracy"),"test_accuracy": tomorrow_latest.get("test_accuracy"),},"t5": {"available": t5_available,"status": "Ready" if t5_available else unavailable_reason,"reason": None if t5_available else state["market_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,"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"),},}return payload32 unmodified linesexcept Exception as exc:print(f"[scheduler] daily 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:print(f"[scheduler] close refresh failed: {exc}", flush=True)async def refresh_current_session_once() -> None:global market_status16 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 warm_dashboard_payload_cache_once() -> None:try:await asyncio.to_thread(warm_dashboard_payload_cache)21 unmodified linesmarket_status = "Prediction Pending"asyncio.create_task(refresh_current_session_once())asyncio.create_task(refresh_market_close_once_if_due())asyncio.create_task(warm_dashboard_payload_cache_once())asyncio.create_task(daily_ist_refresh_loop())14 unmodified lines@app.get("/cron/keepalive")def cron_keepalive(background_tasks: BackgroundTasks) -> dict:close_refresh = {"status": "not_checked"}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(), "close_refresh": close_refresh}@app.get("/prediction/latest")12 unmodified lines@app.post("/data/refresh-daily")def data_refresh_daily() -> dict:return refresh_daily_data()@app.post("/data/refresh-market-close")def data_refresh_market_close(session_date: date | None = Query(default=None, description="Optional YYYY-MM-DD session date in IST."),) -> dict:return refresh_market_close_data(session_date=session_date)
123version https://git-lfs.github.com/spec/v1oid sha256:cae5a22e18a378933d815b7b22bb413eeb2e196cdb48504fe8136a4549f7b8a7size 78101123version https://git-lfs.github.com/spec/v1oid sha256:b57d445258fc7ff258e04869c7b233c2d8e483db82d93917a8c28f16b5ee0d19size 78241
123version https://git-lfs.github.com/spec/v1oid sha256:10065b1a9ef8b127e324103911731856946700e857f932ff8f54adb93c63c143size 9555README.md+4-1
app.py+80-19
data/nifty50_1d.parquet+2-2
data/tomorrow_test_predictions.parquetAdded+3