Jitendra12421 commited on
Commit
fb71c47
·
verified ·
1 Parent(s): 60e67f4

Upload app.py

Browse files
Files changed (1) hide show
  1. app.py +249 -679
app.py CHANGED
@@ -1,679 +1,249 @@
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
-
 
1
+ import os
2
+ import json
3
+ from datetime import datetime, time, date
4
+ from fastapi import FastAPI, BackgroundTasks, HTTPException
5
+ from fastapi.middleware.cors import CORSMiddleware
6
+ from zoneinfo import ZoneInfo
7
+ from data_updater import update_daily_data, is_trading_day
8
+ from forecaster_engine import generate_predictions
9
+ from signal_generator import generate_signals
10
+ from t5_engine import run_t5_pipeline
11
+ from forecaster_cli import run_daemon, get_prediction
12
+
13
+ IST = ZoneInfo("Asia/Kolkata")
14
+ MARKET_CLOSE_BUFFER = time(15, 45) # Update runs after 3:45 PM
15
+ SIGNAL_TIME = time(9, 30) # Signal generation at 9:30 AM
16
+ PREDICTIONS_FILE = os.path.join(os.path.dirname(__file__), "predictions.json")
17
+ SIGNALS_FILE = os.path.join(os.path.dirname(__file__), "signals.json")
18
+ T5_PREDICTIONS_FILE = os.path.join(os.path.dirname(__file__), "t5_predictions.json")
19
+
20
+ app = FastAPI(title="HF NIFTY Forecaster Backend")
21
+
22
+ app.add_middleware(
23
+ CORSMiddleware,
24
+ allow_origins=["*"],
25
+ allow_methods=["*"],
26
+ allow_headers=["*"],
27
+ )
28
+
29
+ def run_update_pipeline():
30
+ try:
31
+ # Step 1: Update data
32
+ res = update_daily_data()
33
+ if res.get("status") == "error":
34
+ print(f"Update failed: {res.get('reason')}")
35
+ return
36
+
37
+ # Step 2: Generate predictions
38
+ generate_predictions()
39
+ except Exception as e:
40
+ print(f"Pipeline error: {e}")
41
+
42
+ def run_signal_pipeline():
43
+ """Run the 5-ticker signal generator."""
44
+ try:
45
+ result = generate_signals()
46
+ print(f"Signal generation result: {result.get('primary_signal', {}).get('action', 'UNKNOWN')}")
47
+ except Exception as e:
48
+ print(f"Signal pipeline error: {e}")
49
+
50
+ # ── Existing Endpoints ───────────────────────────────────────────────────────
51
+
52
+ @app.get("/predictions")
53
+ def get_predictions():
54
+ if not os.path.exists(PREDICTIONS_FILE):
55
+ raise HTTPException(status_code=404, detail="Predictions not yet generated")
56
+
57
+ with open(PREDICTIONS_FILE, "r") as f:
58
+ data = json.load(f)
59
+
60
+ return data
61
+
62
+ @app.post("/cron/update")
63
+ def cron_trigger(background_tasks: BackgroundTasks):
64
+ now = datetime.now(IST)
65
+ today = now.date()
66
+ current_time = now.time()
67
+
68
+ # 1. Check if it's a trading day
69
+ if not is_trading_day(today):
70
+ return {"status": "skipped", "reason": f"{today} is a holiday or weekend"}
71
+
72
+ # 2. Check if it's past 3:45 PM
73
+ if current_time < MARKET_CLOSE_BUFFER:
74
+ return {"status": "skipped", "reason": "Market is still open or buffer not reached. Runs after 3:45 PM IST."}
75
+
76
+ # Trigger the full pipeline in the background so Netlify doesn't timeout
77
+ background_tasks.add_task(run_update_pipeline)
78
+
79
+ return {"status": "triggered", "message": "Update and forecast pipeline started in the background."}
80
+
81
+ # ── NEW: T5 Forecaster Endpoints ─────────────────────────────────────────────
82
+
83
+ @app.get("/t5/predictions")
84
+ def get_t5_predictions():
85
+ """Get the latest first 5-minute (T5) predictions for all stocks."""
86
+ if not os.path.exists(T5_PREDICTIONS_FILE):
87
+ raise HTTPException(status_code=404, detail="T5 predictions not yet generated")
88
+
89
+ with open(T5_PREDICTIONS_FILE, "r") as f:
90
+ data = json.load(f)
91
+
92
+ return data
93
+
94
+ @app.post("/cron/t5_update")
95
+ def t5_update_trigger(background_tasks: BackgroundTasks):
96
+ """
97
+ Trigger T5 prediction generation. Should be called at or after 09:20 AM IST.
98
+ """
99
+ now = datetime.now(IST)
100
+ today = now.date()
101
+ current_time = now.time()
102
+
103
+ # 1. Check if it's a trading day
104
+ if not is_trading_day(today):
105
+ return {"status": "skipped", "reason": f"{today} is a holiday or weekend"}
106
+
107
+ # 2. Check if it's past 09:20 AM
108
+ T5_UPDATE_TIME = time(9, 20)
109
+ if current_time < T5_UPDATE_TIME:
110
+ return {"status": "skipped", "reason": "Market first 5 minutes not completed yet. Runs after 09:20 AM IST."}
111
+
112
+ background_tasks.add_task(run_t5_pipeline)
113
+
114
+ return {"status": "triggered", "message": "T5 update pipeline started in the background."}
115
+
116
+ # ── NEW: NIFTY 50 Multi-Tier Forecaster Endpoints ─────────────────────────────
117
+
118
+ @app.get("/nifty50")
119
+ def get_nifty50_predictions():
120
+ """Get the latest high-conviction BUY predictions for NIFTY 50."""
121
+ nifty_file = os.path.join(os.path.dirname(__file__), "nifty50_predictions.json")
122
+ if not os.path.exists(nifty_file):
123
+ return {
124
+ "last_updated": None,
125
+ "total_analyzed": 0,
126
+ "high_conviction_buys": 0,
127
+ "predictions": []
128
+ }
129
+
130
+ with open(nifty_file, "r") as f:
131
+ data = json.load(f)
132
+
133
+ # Filter for high conviction trades (BUY)
134
+ high_conviction = [p for p in data.get("predictions", []) if p.get("Decision") == "BUY"]
135
+
136
+ return {
137
+ "last_updated": data.get("last_updated"),
138
+ "total_analyzed": len(data.get("predictions", [])),
139
+ "high_conviction_buys": len(high_conviction),
140
+ "predictions": high_conviction
141
+ }
142
+
143
+ @app.post("/cron/nifty50_update")
144
+ def nifty50_update_trigger(background_tasks: BackgroundTasks):
145
+ """
146
+ Trigger the multi-tier Random Forest NIFTY 50 forecasting daemon.
147
+ Should be called every two weeks.
148
+ """
149
+ background_tasks.add_task(run_daemon)
150
+ return {"status": "triggered", "message": "NIFTY 50 forecasting daemon started in the background."}
151
+
152
+ @app.get("/predict/{ticker}")
153
+ def predict_single_ticker(ticker: str):
154
+ """
155
+ On-demand prediction for a single ticker.
156
+ """
157
+ res = get_prediction(ticker.upper())
158
+ if "error" in res:
159
+ raise HTTPException(status_code=400, detail=res["error"])
160
+ return res
161
+
162
+ # ── NEW: Signal Generator Endpoints ──────────────────────────────────────────
163
+
164
+ @app.get("/signals")
165
+ def get_signals():
166
+ """Get the latest generated trading signals for the 5-ticker system."""
167
+ if not os.path.exists(SIGNALS_FILE):
168
+ raise HTTPException(status_code=404, detail="Signals not yet generated. Trigger /cron/signal first.")
169
+
170
+ with open(SIGNALS_FILE, "r") as f:
171
+ data = json.load(f)
172
+
173
+ return data
174
+
175
+ @app.post("/cron/signal")
176
+ def signal_trigger(background_tasks: BackgroundTasks):
177
+ """
178
+ Trigger signal generation at 9:30 AM IST.
179
+ Trains models, fetches live candles, generates BUY/SELL signals.
180
+ """
181
+ now = datetime.now(IST)
182
+ today = now.date()
183
+
184
+ # Check if it's a trading day
185
+ if not is_trading_day(today):
186
+ return {"status": "skipped", "reason": f"{today} is a holiday or weekend"}
187
+
188
+ # Run signal generation in background
189
+ background_tasks.add_task(run_signal_pipeline)
190
+
191
+ return {
192
+ "status": "triggered",
193
+ "message": "Signal generation pipeline started. Check /signals for results.",
194
+ "trigger_time": now.isoformat(),
195
+ }
196
+
197
+ @app.post("/signals/generate-now")
198
+ def force_signal_generation(background_tasks: BackgroundTasks):
199
+ """Force signal generation immediately, bypassing time checks."""
200
+ background_tasks.add_task(run_signal_pipeline)
201
+ return {
202
+ "status": "triggered",
203
+ "message": "Signal generation forced. Check /signals for results.",
204
+ "trigger_time": datetime.now(IST).isoformat(),
205
+ }
206
+
207
+ @app.get("/portfolio")
208
+ def get_portfolio():
209
+ """Get current portfolio status from trade journal."""
210
+ trade_log = os.path.join(os.path.dirname(__file__), "data", "live_trades.json")
211
+ if not os.path.exists(trade_log):
212
+ return {
213
+ "starting_capital": 3692.0,
214
+ "current_capital": 3692.0,
215
+ "total_pnl": 0,
216
+ "trades_count": 0,
217
+ "win_rate": 0,
218
+ }
219
+
220
+ with open(trade_log, "r") as f:
221
+ data = json.load(f)
222
+
223
+ trades = data.get("trades", [])
224
+ starting_cap = data.get("starting_capital", 3692.0)
225
+
226
+ cap = starting_cap
227
+ for t in trades:
228
+ if "net_pnl" in t and t["net_pnl"] is not None:
229
+ cap += t["net_pnl"]
230
+
231
+ n_closed = len([t for t in trades if t.get("net_pnl") is not None])
232
+ n_wins = len([t for t in trades if (t.get("net_pnl") or 0) > 0])
233
+
234
+ return {
235
+ "starting_capital": starting_cap,
236
+ "current_capital": round(cap, 2),
237
+ "total_pnl": round(cap - starting_cap, 2),
238
+ "trades_count": n_closed,
239
+ "win_rate": round(n_wins / n_closed * 100, 1) if n_closed > 0 else 0,
240
+ "last_updated": data.get("last_updated"),
241
+ }
242
+
243
+ @app.get("/health")
244
+ def health_check():
245
+ return {"status": "alive", "server_time_ist": datetime.now(IST).isoformat()}
246
+
247
+ if __name__ == "__main__":
248
+ import uvicorn
249
+ uvicorn.run(app, host="0.0.0.0", port=7860)