Spaces:
Sleeping
Sleeping
Upload 7 files
Browse files- README.md +4 -1
- app.py +80 -19
- data/nifty50_1d.parquet +2 -2
- data/tomorrow_test_predictions.parquet +3 -0
README.md
CHANGED
|
@@ -19,6 +19,7 @@ FastAPI Hugging Face Docker Space for the NIFTY 50 first-five-minute direction f
|
|
| 19 |
- `POST /prediction/refresh-first5`
|
| 20 |
- `POST /data/refresh-daily`
|
| 21 |
- `GET /cron/keepalive`
|
|
|
|
| 22 |
|
| 23 |
## Data
|
| 24 |
|
|
@@ -31,6 +32,8 @@ Parquet files live in `data/`:
|
|
| 31 |
|
| 32 |
## Runtime
|
| 33 |
|
| 34 |
-
The 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.
|
|
|
|
|
|
|
| 35 |
|
| 36 |
Netlify also pings `/cron/keepalive` every 10 minutes through its scheduled function.
|
|
|
|
| 19 |
- `POST /prediction/refresh-first5`
|
| 20 |
- `POST /data/refresh-daily`
|
| 21 |
- `GET /cron/keepalive`
|
| 22 |
+
- `POST /data/refresh-market-close`
|
| 23 |
|
| 24 |
## Data
|
| 25 |
|
|
|
|
| 32 |
|
| 33 |
## Runtime
|
| 34 |
|
| 35 |
+
The 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.
|
| 36 |
+
|
| 37 |
+
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.
|
| 38 |
|
| 39 |
Netlify also pings `/cron/keepalive` every 10 minutes through its scheduled function.
|
app.py
CHANGED
|
@@ -1,24 +1,28 @@
|
|
| 1 |
from __future__ import annotations
|
| 2 |
|
| 3 |
import asyncio
|
|
|
|
| 4 |
from datetime import date, datetime, time, timedelta
|
| 5 |
|
| 6 |
import sys
|
| 7 |
from pathlib import Path
|
| 8 |
|
| 9 |
-
from fastapi import Query
|
| 10 |
from fastapi.middleware.cors import CORSMiddleware
|
| 11 |
from fastapi import FastAPI
|
| 12 |
|
| 13 |
sys.path.insert(0, str(Path(__file__).resolve().parent))
|
| 14 |
from nifty_backend.runtime import (
|
|
|
|
| 15 |
IST,
|
|
|
|
| 16 |
dashboard_payload,
|
| 17 |
is_trading_day,
|
| 18 |
latest_saved_prediction,
|
| 19 |
next_trading_day,
|
| 20 |
refresh_daily_data,
|
| 21 |
refresh_first5_prediction,
|
|
|
|
| 22 |
seconds_until_next_ist_run,
|
| 23 |
warm_dashboard_payload_cache,
|
| 24 |
)
|
|
@@ -35,11 +39,24 @@ app.add_middleware(
|
|
| 35 |
|
| 36 |
|
| 37 |
market_status = "Waiting for next session"
|
|
|
|
| 38 |
MARKET_OPEN = time(9, 15)
|
| 39 |
FIRST5_READY = time(9, 20)
|
| 40 |
MARKET_CLOSE = time(15, 30)
|
| 41 |
|
| 42 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 43 |
def latest_prediction_date(payload: dict | None = None) -> date | None:
|
| 44 |
try:
|
| 45 |
latest = payload if payload is not None else latest_saved_prediction()
|
|
@@ -101,32 +118,47 @@ def attach_market_state(payload: dict) -> dict:
|
|
| 101 |
payload.setdefault("data_status", {})
|
| 102 |
payload["data_status"].update(state)
|
| 103 |
|
| 104 |
-
|
| 105 |
-
|
|
|
|
| 106 |
market_closed = state["market_status"] == "Market Closed"
|
| 107 |
unavailable_reason = "Market Closed" if market_closed else state["market_status"]
|
| 108 |
-
tomorrow_available = bool(
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 109 |
payload["predictions"] = {
|
| 110 |
"tomorrow": {
|
| 111 |
"available": tomorrow_available,
|
| 112 |
-
"status":
|
| 113 |
-
"reason":
|
| 114 |
-
"target_date": state["next_session_date"],
|
| 115 |
-
"input_date":
|
| 116 |
-
"prediction":
|
| 117 |
-
"prob_up":
|
| 118 |
-
"confidence":
|
| 119 |
-
"threshold":
|
|
|
|
|
|
|
|
|
|
|
|
|
| 120 |
},
|
| 121 |
"t5": {
|
| 122 |
"available": t5_available,
|
| 123 |
"status": "Ready" if t5_available else unavailable_reason,
|
| 124 |
"reason": None if t5_available else state["market_detail"],
|
| 125 |
-
"input_date":
|
| 126 |
-
"prediction":
|
| 127 |
-
"prob_up":
|
| 128 |
-
"confidence":
|
| 129 |
-
"threshold":
|
|
|
|
|
|
|
|
|
|
| 130 |
},
|
| 131 |
}
|
| 132 |
return payload
|
|
@@ -165,6 +197,14 @@ async def daily_ist_refresh_loop() -> None:
|
|
| 165 |
except Exception as exc:
|
| 166 |
print(f"[scheduler] daily refresh failed: {exc}", flush=True)
|
| 167 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 168 |
|
| 169 |
async def refresh_current_session_once() -> None:
|
| 170 |
global market_status
|
|
@@ -187,6 +227,15 @@ async def refresh_current_session_once() -> None:
|
|
| 187 |
print(f"[startup] daily refresh failed: {exc}", flush=True)
|
| 188 |
|
| 189 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 190 |
async def warm_dashboard_payload_cache_once() -> None:
|
| 191 |
try:
|
| 192 |
await asyncio.to_thread(warm_dashboard_payload_cache)
|
|
@@ -214,6 +263,7 @@ async def start_scheduler() -> None:
|
|
| 214 |
market_status = "Prediction Pending"
|
| 215 |
|
| 216 |
asyncio.create_task(refresh_current_session_once())
|
|
|
|
| 217 |
asyncio.create_task(warm_dashboard_payload_cache_once())
|
| 218 |
asyncio.create_task(daily_ist_refresh_loop())
|
| 219 |
|
|
@@ -234,8 +284,12 @@ def dashboard() -> dict:
|
|
| 234 |
|
| 235 |
|
| 236 |
@app.get("/cron/keepalive")
|
| 237 |
-
def cron_keepalive() -> dict:
|
| 238 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
| 239 |
|
| 240 |
|
| 241 |
@app.get("/prediction/latest")
|
|
@@ -254,3 +308,10 @@ def prediction_refresh_first5(
|
|
| 254 |
@app.post("/data/refresh-daily")
|
| 255 |
def data_refresh_daily() -> dict:
|
| 256 |
return refresh_daily_data()
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 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, Query
|
| 11 |
from fastapi.middleware.cors import CORSMiddleware
|
| 12 |
from fastapi import FastAPI
|
| 13 |
|
| 14 |
sys.path.insert(0, str(Path(__file__).resolve().parent))
|
| 15 |
from nifty_backend.runtime import (
|
| 16 |
+
CLOSE_REFRESH_READY,
|
| 17 |
IST,
|
| 18 |
+
close_refresh_due,
|
| 19 |
dashboard_payload,
|
| 20 |
is_trading_day,
|
| 21 |
latest_saved_prediction,
|
| 22 |
next_trading_day,
|
| 23 |
refresh_daily_data,
|
| 24 |
refresh_first5_prediction,
|
| 25 |
+
refresh_market_close_data,
|
| 26 |
seconds_until_next_ist_run,
|
| 27 |
warm_dashboard_payload_cache,
|
| 28 |
)
|
|
|
|
| 39 |
|
| 40 |
|
| 41 |
market_status = "Waiting for next session"
|
| 42 |
+
close_refresh_lock = threading.Lock()
|
| 43 |
MARKET_OPEN = time(9, 15)
|
| 44 |
FIRST5_READY = time(9, 20)
|
| 45 |
MARKET_CLOSE = time(15, 30)
|
| 46 |
|
| 47 |
|
| 48 |
+
def refresh_market_close_data_if_due() -> dict:
|
| 49 |
+
if not close_refresh_due():
|
| 50 |
+
return {"status": "skipped", "reason": "close refresh is not due"}
|
| 51 |
+
if not close_refresh_lock.acquire(blocking=False):
|
| 52 |
+
return {"status": "skipped", "reason": "close refresh already running"}
|
| 53 |
+
try:
|
| 54 |
+
info = refresh_market_close_data()
|
| 55 |
+
return {"status": "refreshed", **info}
|
| 56 |
+
finally:
|
| 57 |
+
close_refresh_lock.release()
|
| 58 |
+
|
| 59 |
+
|
| 60 |
def latest_prediction_date(payload: dict | None = None) -> date | None:
|
| 61 |
try:
|
| 62 |
latest = payload if payload is not None else latest_saved_prediction()
|
|
|
|
| 118 |
payload.setdefault("data_status", {})
|
| 119 |
payload["data_status"].update(state)
|
| 120 |
|
| 121 |
+
t5_latest = payload.get("latest") or {}
|
| 122 |
+
tomorrow_latest = payload.get("tomorrow_latest") or {}
|
| 123 |
+
t5_available = bool(state["t5_available"] and t5_latest.get("prediction"))
|
| 124 |
market_closed = state["market_status"] == "Market Closed"
|
| 125 |
unavailable_reason = "Market Closed" if market_closed else state["market_status"]
|
| 126 |
+
tomorrow_available = bool(tomorrow_latest.get("prediction"))
|
| 127 |
+
refresh_phase = payload.get("data_status", {}).get("refresh_phase")
|
| 128 |
+
if refresh_phase in {"waiting_second_payload", "refreshing"}:
|
| 129 |
+
tomorrow_status = "WAITING FOR SECOND PAYLOAD"
|
| 130 |
+
tomorrow_reason = "Market close refresh is generating the next-session payload."
|
| 131 |
+
else:
|
| 132 |
+
tomorrow_status = "Ready" if tomorrow_available else "Pending"
|
| 133 |
+
tomorrow_reason = None if tomorrow_available else "No saved next-session signal is available."
|
| 134 |
payload["predictions"] = {
|
| 135 |
"tomorrow": {
|
| 136 |
"available": tomorrow_available,
|
| 137 |
+
"status": tomorrow_status,
|
| 138 |
+
"reason": tomorrow_reason,
|
| 139 |
+
"target_date": tomorrow_latest.get("target_date") or state["next_session_date"],
|
| 140 |
+
"input_date": tomorrow_latest.get("input_date"),
|
| 141 |
+
"prediction": tomorrow_latest.get("prediction") if tomorrow_available else None,
|
| 142 |
+
"prob_up": tomorrow_latest.get("prob_up") if tomorrow_available else None,
|
| 143 |
+
"confidence": tomorrow_latest.get("confidence") if tomorrow_available else None,
|
| 144 |
+
"threshold": tomorrow_latest.get("threshold") if tomorrow_available else None,
|
| 145 |
+
"model_name": tomorrow_latest.get("model_name"),
|
| 146 |
+
"source_model": tomorrow_latest.get("source_model"),
|
| 147 |
+
"validation_accuracy": tomorrow_latest.get("validation_accuracy"),
|
| 148 |
+
"test_accuracy": tomorrow_latest.get("test_accuracy"),
|
| 149 |
},
|
| 150 |
"t5": {
|
| 151 |
"available": t5_available,
|
| 152 |
"status": "Ready" if t5_available else unavailable_reason,
|
| 153 |
"reason": None if t5_available else state["market_detail"],
|
| 154 |
+
"input_date": t5_latest.get("input_date"),
|
| 155 |
+
"prediction": t5_latest.get("prediction") if t5_available else None,
|
| 156 |
+
"prob_up": t5_latest.get("prob_up") if t5_available else None,
|
| 157 |
+
"confidence": t5_latest.get("confidence") if t5_available else None,
|
| 158 |
+
"threshold": t5_latest.get("threshold") if t5_available else None,
|
| 159 |
+
"model_name": t5_latest.get("model_name"),
|
| 160 |
+
"validation_accuracy": (payload.get("summary") or {}).get("validation_accuracy"),
|
| 161 |
+
"test_accuracy": (payload.get("summary") or {}).get("test_accuracy"),
|
| 162 |
},
|
| 163 |
}
|
| 164 |
return payload
|
|
|
|
| 197 |
except Exception as exc:
|
| 198 |
print(f"[scheduler] daily refresh failed: {exc}", flush=True)
|
| 199 |
|
| 200 |
+
await asyncio.sleep(seconds_until_next_ist_run(CLOSE_REFRESH_READY))
|
| 201 |
+
print("[scheduler] 3:45 PM IST - Refreshing close data", flush=True)
|
| 202 |
+
try:
|
| 203 |
+
info = await asyncio.to_thread(refresh_market_close_data_if_due)
|
| 204 |
+
print(f"[scheduler] close refresh result: {info}", flush=True)
|
| 205 |
+
except Exception as exc:
|
| 206 |
+
print(f"[scheduler] close refresh failed: {exc}", flush=True)
|
| 207 |
+
|
| 208 |
|
| 209 |
async def refresh_current_session_once() -> None:
|
| 210 |
global market_status
|
|
|
|
| 227 |
print(f"[startup] daily refresh failed: {exc}", flush=True)
|
| 228 |
|
| 229 |
|
| 230 |
+
async def refresh_market_close_once_if_due() -> None:
|
| 231 |
+
try:
|
| 232 |
+
info = await asyncio.to_thread(refresh_market_close_data_if_due)
|
| 233 |
+
if info.get("status") == "refreshed":
|
| 234 |
+
print(f"[startup] close refresh result: {info}", flush=True)
|
| 235 |
+
except Exception as exc:
|
| 236 |
+
print(f"[startup] close refresh failed: {exc}", flush=True)
|
| 237 |
+
|
| 238 |
+
|
| 239 |
async def warm_dashboard_payload_cache_once() -> None:
|
| 240 |
try:
|
| 241 |
await asyncio.to_thread(warm_dashboard_payload_cache)
|
|
|
|
| 263 |
market_status = "Prediction Pending"
|
| 264 |
|
| 265 |
asyncio.create_task(refresh_current_session_once())
|
| 266 |
+
asyncio.create_task(refresh_market_close_once_if_due())
|
| 267 |
asyncio.create_task(warm_dashboard_payload_cache_once())
|
| 268 |
asyncio.create_task(daily_ist_refresh_loop())
|
| 269 |
|
|
|
|
| 284 |
|
| 285 |
|
| 286 |
@app.get("/cron/keepalive")
|
| 287 |
+
def cron_keepalive(background_tasks: BackgroundTasks) -> dict:
|
| 288 |
+
close_refresh = {"status": "not_checked"}
|
| 289 |
+
if close_refresh_due():
|
| 290 |
+
background_tasks.add_task(refresh_market_close_data_if_due)
|
| 291 |
+
close_refresh = {"status": "scheduled"}
|
| 292 |
+
return {"status": "awake", "market": current_market_state(), "close_refresh": close_refresh}
|
| 293 |
|
| 294 |
|
| 295 |
@app.get("/prediction/latest")
|
|
|
|
| 308 |
@app.post("/data/refresh-daily")
|
| 309 |
def data_refresh_daily() -> dict:
|
| 310 |
return refresh_daily_data()
|
| 311 |
+
|
| 312 |
+
|
| 313 |
+
@app.post("/data/refresh-market-close")
|
| 314 |
+
def data_refresh_market_close(
|
| 315 |
+
session_date: date | None = Query(default=None, description="Optional YYYY-MM-DD session date in IST."),
|
| 316 |
+
) -> dict:
|
| 317 |
+
return refresh_market_close_data(session_date=session_date)
|
data/nifty50_1d.parquet
CHANGED
|
@@ -1,3 +1,3 @@
|
|
| 1 |
version https://git-lfs.github.com/spec/v1
|
| 2 |
-
oid sha256:
|
| 3 |
-
size
|
|
|
|
| 1 |
version https://git-lfs.github.com/spec/v1
|
| 2 |
+
oid sha256:b57d445258fc7ff258e04869c7b233c2d8e483db82d93917a8c28f16b5ee0d19
|
| 3 |
+
size 78241
|
data/tomorrow_test_predictions.parquet
ADDED
|
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
version https://git-lfs.github.com/spec/v1
|
| 2 |
+
oid sha256:10065b1a9ef8b127e324103911731856946700e857f932ff8f54adb93c63c143
|
| 3 |
+
size 9555
|