Khanna, Videh Rakesh Rakesh commited on
Commit
f7bbcd1
Β·
1 Parent(s): 8af7f2e

Fix AI conflicts: persistent retry (no terminal 'AI unavailable'), consistent direction/reasoning, live-anchored 1D/3D targets + gap note

Browse files

- AI outages are now always retryable (never terminal ai_unavailable); frontend keeps retrying per-cell until a provider frees up. ML shown independently, no ML substitution.
- Reconcile guardrail overrides: reasoning + should_buy now match the final (post-guardrail) direction, ending BULLISH-badge/neutral-reasoning contradictions.
- Re-anchor 1D/3D entry+targets to live price when available (matches AI-forecast anchor); add 'gapped past target' card note when live price already ran past the close-anchored move.

CLAUDE.md CHANGED
@@ -195,7 +195,7 @@ python ml_predictor/infer.py RELIANCE.NS # smoke-test a full prediction
195
 
196
  **Rejected experiments (all A/B-tested via env-overridable train, kept OFF):** (1) *bigger model* (`ML_MAX_ITER/ML_MAX_LEAVES`, 700 trees/depth 63) β€” identical accuracy & P&L; the model is at the data's signal ceiling. (2) *S1–S20 strategy signals as features* (`ML_STRATEGY_FEATURES=1`) β€” identical to baseline; redundant with existing indicators. (3) *strategy/quality selection gates* (`ml_selection_backtest.py --filters trend,momentum,adx,trigger,lowvol,notob`) β€” every gate *reduced* the market-relative edge (re-filtering on indicators the model already uses strips its edge); the `trend` gate raises win-rate ~55–60% at the cost of edge, offered as opt-in only.
197
 
198
- **INTRADAY is NOT tradeable as-is (validated on real 15-min data, `research/ml_intraday_backtest.py`, 36 tickers Γ— 57 days Γ— ~6k predictions):** predicting at 09:15/12:00/14:00 and checking touch-by-15:00, graded hit *decays* 58%β†’36%β†’24% and BUY P&L is negative (βˆ’0.42%, 31% win) β€” the daily-proxy INTRADAY numbers are optimistic because the model targets a *full-day* magnitude that can't be touched in the hours left. Use **1D/3D only** until INTRADAY targets are scaled to remaining-session time (or the model is retrained on true intraday bars). Metrics live in `research/ml_backtest.py` (accuracy + P&L), `research/ml_selection_backtest.py` (top-N selection, `--rank`/`--min-conf`), and `research/ml_watchlist_eval.py` (grade the DB watchlist vs realized outcomes for the last N days).
199
 
200
  **API:** `GET /api/ml-predict/<ticker>` (`?news=<int>` optional news score, `?live=0` to skip the live-price fetch) β†’ `{ticker, available, current_price, as_of, model_cutoff, tfs:{INTRADAY,1D,3D:{direction, confidence, predicted_return_lo/hi, target_price_lo/hi, expected_target_price, estimated_high, buy_price_suggestion, stop_loss, quantiles, direction_proba, intraday:{already_gone, headroom_pct, …}}}}`. Standalone: `from ml_predictor.infer import get_ml_predictor`.
201
 
 
195
 
196
  **Rejected experiments (all A/B-tested via env-overridable train, kept OFF):** (1) *bigger model* (`ML_MAX_ITER/ML_MAX_LEAVES`, 700 trees/depth 63) β€” identical accuracy & P&L; the model is at the data's signal ceiling. (2) *S1–S20 strategy signals as features* (`ML_STRATEGY_FEATURES=1`) β€” identical to baseline; redundant with existing indicators. (3) *strategy/quality selection gates* (`ml_selection_backtest.py --filters trend,momentum,adx,trigger,lowvol,notob`) β€” every gate *reduced* the market-relative edge (re-filtering on indicators the model already uses strips its edge); the `trend` gate raises win-rate ~55–60% at the cost of edge, offered as opt-in only.
197
 
198
+ **INTRADAY range accuracy is calibrated to the realized 15-min excursion (validated on real 15-min data, `research/ml_intraday_backtest.py`, 30 tickers Γ— 57 days Γ— ~4.9k predictions):** predicting at 09:15/12:00/14:00 and checking touch-by-15:00 β€” **graded (range) hit β‰ˆ88%, expected-target hit β‰ˆ48-58%, far-bound coverage β‰ˆ90-94%**, DirHit 86/92/91%. The fix (`ml_predictor/infer.py`): the model's INTRADAY labels are a *full-day* excursion (entry day's High/Low vs close), and at mid-session deployment (features as-of previous close) the raw quantiles are miscalibrated *by role, not by a single factor* β€” the q90 is about right once √time-scaled, but the q50 **overshoots** the realized median and the q10 is too ambitious. So the three levels are calibrated **independently** to what the range actually achieves, each on top of √time session scaling: `_INTRADAY_FAR_MULTβ‰ˆ1.0` (far edge = true q90 ceiling, ~90% not exceeded β€” the old uniform shrink left this a q65 that got exceeded 35% of the time), `_INTRADAY_MED_MULTβ‰ˆ0.42` (the **expected/headline target** = realized median, touched ~50% β€” the honest "did we hit the estimate" number, vs the model's inflated full-day median that only landed ~20%), and `_INTRADAY_NEAR_MULTβ‰ˆ0.12` (reachable near edge, so RANGE_HIT β‰₯85%). All env-overridable (`ML_INTRADAY_FAR_MULT`/`MED_MULT`/`NEAR_MULT`). The backtest reports `ExpHit` (expected-target touched) and `FarCov` (ceiling not exceeded) β€” these are the meaningful metrics; the old mechanical "MidHit" (touch the band's arithmetic midpoint) is misleading for a right-skewed [q10,q90] interval. **Why not push expected-target hit to 85%?** It's monotonic in the target level, so you *can* β€” set `ML_INTRADAY_MED_MULT=0.08` β†’ ExpHit β‰ˆ85%. But that shrinks the target to ~0.15%, *below* the 0.30% round-trip cost, so BuyWin% collapses 42%β†’5% (P&L βˆ’0.64%): 85% expected-target accuracy and profitability are mutually exclusive, so the default stays at the honest median (0.42). The backtest report columns are also printed in plain English with a legend (`RightDir%`=direction correct, `ReachFloor%`=safe low target hit, `ReachMain%`=main target hit, `UnderCeil%`=stayed below best-case top, `Win%`=trades that profited). `_fetch_15m` caches 15-min bars per ticker/day under `research/cache/intraday_15m/` (pickle; `--refresh` to force re-download) β€” note this is for correctness/rate-limit safety, **not** speed: the backtest is CPU-bound on inference, not the download (daily bars already cache in `ohlcv_cache.db`). **Caveat β€” still not profitable to trade long:** BUY P&L stays negative (~βˆ’0.47%, 42% win) net of 0.30% cost; the *range and central estimate* are now accurate but the target isn't reliably hit before the stop, so INTRADAY is a reliable **direction/range signal, not a standalone long strategy** β€” trade 1D/3D with the target/stop for P&L. Metrics live in `research/ml_intraday_backtest.py` (true 15-min), `research/ml_backtest.py` (daily-proxy accuracy + P&L), `research/ml_selection_backtest.py`, and `research/ml_watchlist_eval.py`.
199
 
200
  **API:** `GET /api/ml-predict/<ticker>` (`?news=<int>` optional news score, `?live=0` to skip the live-price fetch) β†’ `{ticker, available, current_price, as_of, model_cutoff, tfs:{INTRADAY,1D,3D:{direction, confidence, predicted_return_lo/hi, target_price_lo/hi, expected_target_price, estimated_high, buy_price_suggestion, stop_loss, quantiles, direction_proba, intraday:{already_gone, headroom_pct, …}}}}`. Standalone: `from ml_predictor.infer import get_ml_predictor`.
201
 
ai_forecast.py CHANGED
@@ -369,12 +369,28 @@ _NEUT_RANGE: dict[str, tuple[float, float]] = {
369
  }
370
 
371
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
372
  def _apply_trigger_guardrails(
373
  direction: str,
374
  confidence: str,
375
  indicators: dict,
376
  current_price: float,
377
- ) -> tuple[str, str]:
378
  """Enforce CLAUDE.md trigger rules against actual computed indicator values.
379
 
380
  The LLM is only given the triggers as prompt instructions; this function
@@ -425,7 +441,7 @@ def _apply_trigger_guardrails(
425
 
426
  # Skip guardrails if we lack the two most critical indicators
427
  if rsi is None or bb is None:
428
- return direction, confidence
429
 
430
  above_ema50 = (current_price > ema50) if (ema50 is not None and current_price > 0) else None
431
 
@@ -470,21 +486,37 @@ def _apply_trigger_guardrails(
470
  bear = "B3"
471
 
472
  # ── Resolve final direction ───────────────────────────────────────────────
 
 
473
  if bear and not bull:
 
474
  if direction != "BEARISH":
 
 
 
 
 
 
475
  logger.info(
476
  "GUARDRAIL %s: overriding %sβ†’BEARISH (RSI=%.1f BB=%.1f 10D=%.1f)",
477
  bear, direction, rsi, bb, ret10 or 0,
478
  )
479
- return "BEARISH", confidence
480
 
481
  if bull and not bear:
 
482
  if direction != "BULLISH":
 
 
 
 
 
 
483
  logger.info(
484
  "GUARDRAIL %s: overriding %sβ†’BULLISH (RSI=%.1f BB=%.1f)",
485
  bull, direction, rsi, bb,
486
  )
487
- return "BULLISH", confidence
488
 
489
  if bull and bear:
490
  # Conflicting triggers β€” genuinely ambiguous, don't force either direction.
@@ -492,7 +524,11 @@ def _apply_trigger_guardrails(
492
  "GUARDRAIL CONFLICT: bull=%s bear=%s β†’ NEUTRAL (RSI=%.1f BB=%.1f 10D=%.1f)",
493
  bull, bear, rsi, bb, ret10 or 0,
494
  )
495
- return "NEUTRAL", confidence
 
 
 
 
496
 
497
  # No trigger fired at all β†’ force NEUTRAL and downgrade confidence one level.
498
  if direction != "NEUTRAL" or confidence != "LOW":
@@ -503,9 +539,29 @@ def _apply_trigger_guardrails(
503
  "GUARDRAIL NO_TRIGGER: no trigger fired for %s (RSI=%.1f BB=%.1f) β†’ NEUTRAL, confidence %sβ†’%s",
504
  direction, rsi, bb, confidence, downgraded,
505
  )
506
- return "NEUTRAL", downgraded
 
 
 
 
507
 
508
- return direction, confidence
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
509
 
510
 
511
  def _apply_calibrated_range(direction: str, tf_label: str) -> tuple[float, float]:
@@ -1570,9 +1626,10 @@ def get_ai_forecast(
1570
  confidence = "MEDIUM"
1571
 
1572
  # Guard: enforce trigger rules against actual indicator values
1573
- direction, confidence = _apply_trigger_guardrails(
1574
  direction, confidence, indicators, current_price
1575
  )
 
1576
 
1577
  # ── Apply calibrated ranges in backtest mode only ─────────────────────
1578
  # Backtest: always use calibrated tiny ranges (optimised for midpoint-touch metric).
@@ -1598,6 +1655,9 @@ def get_ai_forecast(
1598
  if (direction == "BULLISH" and news_label == "BEARISH") or (direction == "BEARISH" and news_label == "BULLISH"):
1599
  if abs(news_score) >= 20:
1600
  direction = "NEUTRAL"
 
 
 
1601
  if tight_test:
1602
  ret_lo, ret_hi = _apply_calibrated_range("NEUTRAL", tf_label)
1603
  else:
@@ -1686,7 +1746,8 @@ def get_ai_forecast(
1686
  direction = "NEUTRAL"
1687
  if confidence not in ("HIGH", "MEDIUM", "LOW"):
1688
  confidence = "MEDIUM"
1689
- direction, confidence = _apply_trigger_guardrails(direction, confidence, indicators, current_price)
 
1690
  _llm_range_valid = (
1691
  ret_lo is not None and ret_hi is not None
1692
  and ret_lo != ret_hi and ret_lo < ret_hi
@@ -1811,9 +1872,10 @@ def get_ai_forecast(
1811
  confidence = "MEDIUM"
1812
 
1813
  # Guard: enforce trigger rules against actual indicator values
1814
- direction, confidence = _apply_trigger_guardrails(
1815
  direction, confidence, indicators, current_price
1816
  )
 
1817
 
1818
  # Backtest: use calibrated tiny ranges (optimised for midpoint-touch metric).
1819
  # Production: honour the AI's own lo/hi β€” the prompt now asks for realistic TF-scaled ranges.
@@ -1837,6 +1899,9 @@ def get_ai_forecast(
1837
  if (direction == "BULLISH" and news_label == "BEARISH") or (direction == "BEARISH" and news_label == "BULLISH"):
1838
  if abs(news_score) >= 20:
1839
  direction = "NEUTRAL"
 
 
 
1840
  if tight_test:
1841
  ret_lo, ret_hi = _apply_calibrated_range("NEUTRAL", tf_label)
1842
  else:
 
369
  }
370
 
371
 
372
+ # Human-readable descriptions of each trigger, used to rewrite the forecast reasoning when a
373
+ # guardrail overrides the LLM's direction β€” so the card's narrative matches the final call
374
+ # instead of contradicting it (e.g. a BULLISH badge with "no bullish trigger" text).
375
+ _TRIGGER_DESC: dict[str, str] = {
376
+ "T1": "price is above EMA50 with a bullish MACD histogram (trend continuation)",
377
+ "T2": "price is above EMA50 with strong 10-day momentum",
378
+ "T4": "mildly oversold near the lower Bollinger band β€” a mean-reversion bounce setup",
379
+ "T5": "a strong 10-day breakout in momentum",
380
+ "T6": "deeply oversold β€” a technical bounce is likely",
381
+ "T7": "a steady positive drift while holding above EMA50",
382
+ "B1": "an overbought extreme with stretched momentum β€” reversal risk",
383
+ "B2": "a confirmed downtrend below EMA50 with negative MACD and momentum",
384
+ "B3": "a sustained multi-day decline confirmed by negative MACD (falling-knife risk)",
385
+ }
386
+
387
+
388
  def _apply_trigger_guardrails(
389
  direction: str,
390
  confidence: str,
391
  indicators: dict,
392
  current_price: float,
393
+ ) -> tuple[str, str, str | None]:
394
  """Enforce CLAUDE.md trigger rules against actual computed indicator values.
395
 
396
  The LLM is only given the triggers as prompt instructions; this function
 
441
 
442
  # Skip guardrails if we lack the two most critical indicators
443
  if rsi is None or bb is None:
444
+ return direction, confidence, None
445
 
446
  above_ema50 = (current_price > ema50) if (ema50 is not None and current_price > 0) else None
447
 
 
486
  bear = "B3"
487
 
488
  # ── Resolve final direction ───────────────────────────────────────────────
489
+ # `note` is set only when the guardrail OVERRIDES the LLM's direction, so the caller can
490
+ # rewrite the forecast reasoning/should_buy to match the final call (no contradictory cards).
491
  if bear and not bull:
492
+ note = None
493
  if direction != "BEARISH":
494
+ note = (
495
+ f"Direction set BEARISH by technical trigger {bear}: "
496
+ f"{_TRIGGER_DESC.get(bear, 'bearish technical setup')} "
497
+ f"(RSI {rsi:.0f}, Bollinger {bb:.0f}%, 10D {ret10 or 0:+.1f}%). "
498
+ f"This overrides the model's more cautious read."
499
+ )
500
  logger.info(
501
  "GUARDRAIL %s: overriding %sβ†’BEARISH (RSI=%.1f BB=%.1f 10D=%.1f)",
502
  bear, direction, rsi, bb, ret10 or 0,
503
  )
504
+ return "BEARISH", confidence, note
505
 
506
  if bull and not bear:
507
+ note = None
508
  if direction != "BULLISH":
509
+ note = (
510
+ f"Direction set BULLISH by technical trigger {bull}: "
511
+ f"{_TRIGGER_DESC.get(bull, 'bullish technical setup')} "
512
+ f"(RSI {rsi:.0f}, Bollinger {bb:.0f}%). "
513
+ f"This overrides the model's more cautious read."
514
+ )
515
  logger.info(
516
  "GUARDRAIL %s: overriding %sβ†’BULLISH (RSI=%.1f BB=%.1f)",
517
  bull, direction, rsi, bb,
518
  )
519
+ return "BULLISH", confidence, note
520
 
521
  if bull and bear:
522
  # Conflicting triggers β€” genuinely ambiguous, don't force either direction.
 
524
  "GUARDRAIL CONFLICT: bull=%s bear=%s β†’ NEUTRAL (RSI=%.1f BB=%.1f 10D=%.1f)",
525
  bull, bear, rsi, bb, ret10 or 0,
526
  )
527
+ note = (
528
+ f"Conflicting technical triggers (bullish {bull} vs bearish {bear}) β€” "
529
+ f"no clear directional edge, treated as NEUTRAL."
530
+ ) if direction != "NEUTRAL" else None
531
+ return "NEUTRAL", confidence, note
532
 
533
  # No trigger fired at all β†’ force NEUTRAL and downgrade confidence one level.
534
  if direction != "NEUTRAL" or confidence != "LOW":
 
539
  "GUARDRAIL NO_TRIGGER: no trigger fired for %s (RSI=%.1f BB=%.1f) β†’ NEUTRAL, confidence %sβ†’%s",
540
  direction, rsi, bb, confidence, downgraded,
541
  )
542
+ note = (
543
+ f"No technical trigger fired (RSI {rsi:.0f}, Bollinger {bb:.0f}%) β€” "
544
+ f"insufficient directional edge, treated as NEUTRAL."
545
+ ) if direction != "NEUTRAL" else None
546
+ return "NEUTRAL", downgraded, note
547
 
548
+ return direction, confidence, None
549
+
550
+
551
+ def _reconcile_override(
552
+ note: str | None, direction: str, confidence: str,
553
+ reasoning: str, should_buy: bool,
554
+ ) -> tuple[str, bool]:
555
+ """Align the forecast narrative + buy flag with the FINAL direction.
556
+
557
+ When a guardrail (or news gate) overrides the LLM's direction, the LLM's own reasoning and
558
+ should_buy describe a DIFFERENT call and would contradict the badge on the card. This rewrites
559
+ reasoning to the override explanation and recomputes should_buy from the final direction /
560
+ confidence (BUY only for a genuine BULLISH lean with at least MEDIUM conviction).
561
+ """
562
+ if not note:
563
+ return reasoning, should_buy
564
+ return note, (direction == "BULLISH" and confidence in ("HIGH", "MEDIUM"))
565
 
566
 
567
  def _apply_calibrated_range(direction: str, tf_label: str) -> tuple[float, float]:
 
1626
  confidence = "MEDIUM"
1627
 
1628
  # Guard: enforce trigger rules against actual indicator values
1629
+ direction, confidence, _gnote = _apply_trigger_guardrails(
1630
  direction, confidence, indicators, current_price
1631
  )
1632
+ reasoning, should_buy = _reconcile_override(_gnote, direction, confidence, reasoning, should_buy)
1633
 
1634
  # ── Apply calibrated ranges in backtest mode only ─────────────────────
1635
  # Backtest: always use calibrated tiny ranges (optimised for midpoint-touch metric).
 
1655
  if (direction == "BULLISH" and news_label == "BEARISH") or (direction == "BEARISH" and news_label == "BULLISH"):
1656
  if abs(news_score) >= 20:
1657
  direction = "NEUTRAL"
1658
+ reasoning = (f"Direction neutralized: strong {news_label.lower()} news "
1659
+ f"(score {news_score}) conflicts with the technical read β€” no directional trade.")
1660
+ should_buy = False
1661
  if tight_test:
1662
  ret_lo, ret_hi = _apply_calibrated_range("NEUTRAL", tf_label)
1663
  else:
 
1746
  direction = "NEUTRAL"
1747
  if confidence not in ("HIGH", "MEDIUM", "LOW"):
1748
  confidence = "MEDIUM"
1749
+ direction, confidence, _gnote = _apply_trigger_guardrails(direction, confidence, indicators, current_price)
1750
+ reasoning, should_buy = _reconcile_override(_gnote, direction, confidence, reasoning, should_buy)
1751
  _llm_range_valid = (
1752
  ret_lo is not None and ret_hi is not None
1753
  and ret_lo != ret_hi and ret_lo < ret_hi
 
1872
  confidence = "MEDIUM"
1873
 
1874
  # Guard: enforce trigger rules against actual indicator values
1875
+ direction, confidence, _gnote = _apply_trigger_guardrails(
1876
  direction, confidence, indicators, current_price
1877
  )
1878
+ reasoning, should_buy = _reconcile_override(_gnote, direction, confidence, reasoning, should_buy)
1879
 
1880
  # Backtest: use calibrated tiny ranges (optimised for midpoint-touch metric).
1881
  # Production: honour the AI's own lo/hi β€” the prompt now asks for realistic TF-scaled ranges.
 
1899
  if (direction == "BULLISH" and news_label == "BEARISH") or (direction == "BEARISH" and news_label == "BULLISH"):
1900
  if abs(news_score) >= 20:
1901
  direction = "NEUTRAL"
1902
+ reasoning = (f"Direction neutralized: strong {news_label.lower()} news "
1903
+ f"(score {news_score}) conflicts with the technical read β€” no directional trade.")
1904
+ should_buy = False
1905
  if tight_test:
1906
  ret_lo, ret_hi = _apply_calibrated_range("NEUTRAL", tf_label)
1907
  else:
app.py CHANGED
@@ -28,6 +28,7 @@ from ai_forecast import _cache_ttl_for_tf
28
  from universe import get_universe, refresh_universe # get_universe used by search fallback
29
  from data_sources import fetch_ohlcv, fetch_live_price, warm_ohlcv_cache
30
  import database as db
 
31
 
32
  from top5_picker import get_top5_picks
33
  from market_calendar import (
@@ -84,6 +85,39 @@ _TOP5_PROGRESS_LOCK = __import__("threading").Lock()
84
  _WATCHLIST_PICK_CACHE: dict = {}
85
  _WATCHLIST_PICK_AI_UNAVAILABLE_TTL = 125 # short TTL when AI was unavailable (>120s Ollama backoff so retry fires after cooldown clears)
86
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
87
  # Portfolio insight cache β€” same LLM debate cost as watchlist, lazy-loaded on card expand
88
  _PORTFOLIO_INSIGHT_CACHE: dict = {}
89
  _PORTFOLIO_INSIGHT_TTL = 600 # 10 minutes
@@ -587,6 +621,46 @@ def _archive_top5_predictions(result: dict, source: str = "top5") -> None:
587
  logging.warning(f"Failed to archive prediction for {ticker}/{tf}: {e}")
588
 
589
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
590
  # ── STATIC PAGES ──────────────────────────────────────────────────────────────
591
 
592
  @app.route("/api/db-diag")
@@ -996,6 +1070,14 @@ def ml_predict(ticker):
996
  except (TypeError, ValueError):
997
  news_score = 0
998
  result = predictor.predict_all_tf(t, live_price=live_price, news_score=news_score)
 
 
 
 
 
 
 
 
999
  resp = jsonify(result)
1000
  resp.headers["Cache-Control"] = "no-store, no-cache, must-revalidate, max-age=0"
1001
  return resp
@@ -1618,6 +1700,7 @@ def _build_watchlist_pick(item: dict, preds: dict) -> tuple[dict, dict]:
1618
  "entry_basis": tp.get("entry_basis", p.get("entry_basis")),
1619
  "entry_buffer_pct": tp.get("entry_buffer_pct", p.get("entry_buffer_pct", 0.0)),
1620
  "max_chase_pct": tp.get("max_chase_pct", p.get("max_chase_pct", 0.0)),
 
1621
  "expected_target_price": tp.get("expected_target_price", p.get("expected_target_price", r.get("min_target"))),
1622
  "target_price_lo": tp.get("target_price_lo", p.get("target_price_lo")),
1623
  "target_price_hi": tp.get("target_price_hi", p.get("target_price_hi")),
@@ -1773,7 +1856,7 @@ def watchlist_pick_single(ticker: str):
1773
 
1774
  def _predict(tf: str):
1775
  start, end = timeframe_to_dates(tf)
1776
- return tf, predict_stock_v2(
1777
  t, start, end,
1778
  _market_ctx=market_ctx,
1779
  _run_ai_forecast=(tf in _AI_TFS),
@@ -1828,9 +1911,12 @@ def watchlist_pick_single(ticker: str):
1828
  _, pred = f.result()
1829
  preds[tf] = pred
1830
  if not pred.get("error"):
1831
- ai_unavailable = pred.get("no_trade_reason") == "ai_unavailable"
1832
- ttl = _WATCHLIST_PICK_AI_UNAVAILABLE_TTL if ai_unavailable else _cache_ttl_for_tf(tf)
1833
- _WATCHLIST_PICK_CACHE[(t, tf)] = {"ts": now, "pred": pred, "ttl": ttl}
 
 
 
1834
  except Exception as e:
1835
  preds[tf] = {"error": str(e)}
1836
  for f in not_done:
@@ -1941,7 +2027,7 @@ def watchlist_pick_single_tf(ticker: str, tf: str):
1941
 
1942
  start, end = timeframe_to_dates(tf)
1943
  try:
1944
- pred = predict_stock_v2(
1945
  t, start, end,
1946
  _market_ctx=market_ctx,
1947
  _run_ai_forecast=True,
@@ -1954,9 +2040,12 @@ def watchlist_pick_single_tf(ticker: str, tf: str):
1954
  pred = {"error": str(e)}
1955
 
1956
  if not pred.get("error"):
1957
- ai_unavailable = pred.get("no_trade_reason") == "ai_unavailable"
1958
- ttl = _WATCHLIST_PICK_AI_UNAVAILABLE_TTL if ai_unavailable else _cache_ttl_for_tf(tf)
1959
- _WATCHLIST_PICK_CACHE[(t, tf)] = {"ts": now, "pred": pred, "ttl": ttl}
 
 
 
1960
 
1961
  return jsonify({
1962
  "tf": tf, "ticker": t,
@@ -2008,16 +2097,19 @@ def watchlist_picks():
2008
  entry = _WATCHLIST_PICK_CACHE.get((ticker, tf))
2009
  if entry and time.time() - entry["ts"] < entry.get("ttl", _cache_ttl_for_tf(tf)):
2010
  return ticker, tf, entry["pred"]
2011
- pred = predict_stock_v2(ticker, start, end,
2012
  _market_ctx=shared_ctx,
2013
  _run_ai_forecast=True,
2014
  _ai_fast_mode=True,
2015
  # BOUNDED β€” never block the batch on one stock (see per-ticker route).
2016
  _ai_fast_fail_on_rate_limit=True)
2017
  if not pred.get("error"):
2018
- ai_unavailable = pred.get("no_trade_reason") == "ai_unavailable"
2019
- ttl = _WATCHLIST_PICK_AI_UNAVAILABLE_TTL if ai_unavailable else _cache_ttl_for_tf(tf)
2020
- _WATCHLIST_PICK_CACHE[(ticker, tf)] = {"ts": time.time(), "pred": pred, "ttl": ttl}
 
 
 
2021
  return ticker, tf, pred
2022
 
2023
  # ── Phase 0: pre-warm OHLCV caches (parallel, 40s wall-clock cap) ────────
@@ -3789,18 +3881,26 @@ def _start_intraday_refresh_scheduler():
3789
  for tk in tickers:
3790
  try:
3791
  start, end = timeframe_to_dates("INTRADAY")
3792
- pred = predict_stock_v2(
3793
  tk, start, end,
3794
  _market_ctx=market_ctx,
3795
  _run_ai_forecast=True,
3796
  _ai_fast_mode=True,
3797
  _ai_fast_fail_on_rate_limit=True,
3798
  )
3799
- _WATCHLIST_PICK_CACHE[(tk, "INTRADAY")] = {
3800
- "ts": now,
3801
- "pred": pred,
3802
- "ttl": _cache_ttl_for_tf("INTRADAY"),
3803
- }
 
 
 
 
 
 
 
 
3804
  except Exception as exc:
3805
  app.logger.debug("INTRADAY refresh failed for %s: %s", tk, exc)
3806
  app.logger.info("INTRADAY cache refreshed for %d tickers", len(tickers))
 
28
  from universe import get_universe, refresh_universe # get_universe used by search fallback
29
  from data_sources import fetch_ohlcv, fetch_live_price, warm_ohlcv_cache
30
  import database as db
31
+ import risk_engine
32
 
33
  from top5_picker import get_top5_picks
34
  from market_calendar import (
 
85
  _WATCHLIST_PICK_CACHE: dict = {}
86
  _WATCHLIST_PICK_AI_UNAVAILABLE_TTL = 125 # short TTL when AI was unavailable (>120s Ollama backoff so retry fires after cooldown clears)
87
 
88
+ # ── Watchlist AI concurrency cap (process-wide) ───────────────────────────────
89
+ # Without this, the frontend fires N per-ticker requests in parallel Γ— up to 3 TFs each =
90
+ # up to 3N simultaneous LLM calls, which 429s every free-tier provider at once β†’ the
91
+ # "⚠ AI unavailable" storm. A small shared semaphore paces the whole scan so the calls
92
+ # spread across the ~6 providers (via task_offset rotation) instead of tripping all their
93
+ # per-minute limits together. A TF that can't get a slot before the deadline returns a
94
+ # retryable 'timeout' (the frontend refetches it), so predictions are paced, not lost.
95
+ # Env-tunable; small by design.
96
+ _WATCHLIST_AI_CONCURRENCY = max(1, int(os.getenv("WATCHLIST_AI_CONCURRENCY", "4")))
97
+ _WATCHLIST_AI_SEMAPHORE = threading.Semaphore(_WATCHLIST_AI_CONCURRENCY)
98
+ _WATCHLIST_AI_ACQUIRE_TIMEOUT = int(os.getenv("WATCHLIST_AI_ACQUIRE_TIMEOUT", "80"))
99
+
100
+ _WATCHLIST_TIMEOUT_STUB = {
101
+ "no_trade_reason": "timeout", "direction": "N/A", "confidence": "N/A",
102
+ "signal_count": 0, "ret_lo": 0, "ret_hi": 0, "midpoint": 0,
103
+ }
104
+
105
+
106
+ def _gated_predict(*args, **kwargs):
107
+ """Run predict_stock_v2 under the watchlist AI concurrency cap.
108
+
109
+ Blocks until a slot frees up (or WATCHLIST_AI_ACQUIRE_TIMEOUT seconds). If no slot is
110
+ available in time, returns a retryable 'timeout' stub instead of blocking indefinitely or
111
+ bursting β€” the frontend refetches that cell, so the prediction is deferred, not dropped."""
112
+ got = _WATCHLIST_AI_SEMAPHORE.acquire(timeout=_WATCHLIST_AI_ACQUIRE_TIMEOUT)
113
+ if not got:
114
+ return dict(_WATCHLIST_TIMEOUT_STUB)
115
+ try:
116
+ return predict_stock_v2(*args, **kwargs)
117
+ finally:
118
+ _WATCHLIST_AI_SEMAPHORE.release()
119
+
120
+
121
  # Portfolio insight cache β€” same LLM debate cost as watchlist, lazy-loaded on card expand
122
  _PORTFOLIO_INSIGHT_CACHE: dict = {}
123
  _PORTFOLIO_INSIGHT_TTL = 600 # 10 minutes
 
621
  logging.warning(f"Failed to archive prediction for {ticker}/{tf}: {e}")
622
 
623
 
624
+ def _archive_ml_predictions(result: dict) -> None:
625
+ """Persist standalone ML-model predictions for validation tracking (snapshot_source='ml').
626
+
627
+ Mirrors _archive_top5_predictions but reads the ml_predictor.predict_all_tf schema so
628
+ the validation tab can grade ML vs AI separately against the same realized NSE price.
629
+ """
630
+ if not result or not result.get("available"):
631
+ return
632
+ ticker = result.get("ticker")
633
+ if not ticker:
634
+ return
635
+ top_price = result.get("current_price") or 0
636
+ tfs = result.get("tfs", {}) or {}
637
+ for tf in ["INTRADAY", "1D", "3D"]:
638
+ d = tfs.get(tf, {}) or {}
639
+ direction = (d.get("direction") or "NEUTRAL")
640
+ if (direction or "").upper() in ("NO TRADE", "N/A", "", "SKIPPED"):
641
+ continue
642
+ lo = d.get("target_price_lo") or 0
643
+ hi = d.get("target_price_hi") or 0
644
+ if lo and hi and lo == hi:
645
+ continue
646
+ try:
647
+ db.save_prediction_snapshot(
648
+ ticker=ticker,
649
+ timeframe=tf,
650
+ direction=direction,
651
+ confidence=d.get("confidence", "LOW"),
652
+ target_price_lo=lo,
653
+ target_price_hi=hi,
654
+ predicted_return_lo=d.get("predicted_return_lo") or 0,
655
+ predicted_return_hi=d.get("predicted_return_hi") or 0,
656
+ current_price=d.get("current_price") or top_price,
657
+ snapshot_source="ml",
658
+ snapshot_data=None,
659
+ )
660
+ except Exception as e:
661
+ logging.warning(f"Failed to archive ML prediction for {ticker}/{tf}: {e}")
662
+
663
+
664
  # ── STATIC PAGES ──────────────────────────────────────────────────────────────
665
 
666
  @app.route("/api/db-diag")
 
1070
  except (TypeError, ValueError):
1071
  news_score = 0
1072
  result = predictor.predict_all_tf(t, live_price=live_price, news_score=news_score)
1073
+ # Optional: persist ML predictions for the validation tab (ML vs AI vs Actual).
1074
+ # The frontend passes ?archive=1 when rendering watchlist/top-pick cards so ML
1075
+ # snapshots accrue exactly where AI snapshots do.
1076
+ if request.args.get("archive") == "1":
1077
+ try:
1078
+ _archive_ml_predictions(result)
1079
+ except Exception:
1080
+ logging.warning("ML archive failed for %s", t, exc_info=True)
1081
  resp = jsonify(result)
1082
  resp.headers["Cache-Control"] = "no-store, no-cache, must-revalidate, max-age=0"
1083
  return resp
 
1700
  "entry_basis": tp.get("entry_basis", p.get("entry_basis")),
1701
  "entry_buffer_pct": tp.get("entry_buffer_pct", p.get("entry_buffer_pct", 0.0)),
1702
  "max_chase_pct": tp.get("max_chase_pct", p.get("max_chase_pct", 0.0)),
1703
+ "gapped_past_target": tp.get("gapped_past_target", p.get("gapped_past_target", False)),
1704
  "expected_target_price": tp.get("expected_target_price", p.get("expected_target_price", r.get("min_target"))),
1705
  "target_price_lo": tp.get("target_price_lo", p.get("target_price_lo")),
1706
  "target_price_hi": tp.get("target_price_hi", p.get("target_price_hi")),
 
1856
 
1857
  def _predict(tf: str):
1858
  start, end = timeframe_to_dates(tf)
1859
+ return tf, _gated_predict(
1860
  t, start, end,
1861
  _market_ctx=market_ctx,
1862
  _run_ai_forecast=(tf in _AI_TFS),
 
1911
  _, pred = f.result()
1912
  preds[tf] = pred
1913
  if not pred.get("error"):
1914
+ _reason = pred.get("no_trade_reason")
1915
+ # Never cache a transient 'timeout' (provider will reset shortly) β€” leaving it
1916
+ # uncached lets the frontend's background refetch genuinely retry and fill in.
1917
+ if _reason != "timeout":
1918
+ ttl = _WATCHLIST_PICK_AI_UNAVAILABLE_TTL if _reason == "ai_unavailable" else _cache_ttl_for_tf(tf)
1919
+ _WATCHLIST_PICK_CACHE[(t, tf)] = {"ts": now, "pred": pred, "ttl": ttl}
1920
  except Exception as e:
1921
  preds[tf] = {"error": str(e)}
1922
  for f in not_done:
 
2027
 
2028
  start, end = timeframe_to_dates(tf)
2029
  try:
2030
+ pred = _gated_predict(
2031
  t, start, end,
2032
  _market_ctx=market_ctx,
2033
  _run_ai_forecast=True,
 
2040
  pred = {"error": str(e)}
2041
 
2042
  if not pred.get("error"):
2043
+ _reason = pred.get("no_trade_reason")
2044
+ # Never cache a transient 'timeout' (provider will reset shortly) so the background
2045
+ # refetch retries; keep 'ai_unavailable' on the short TTL for hard outages.
2046
+ if _reason != "timeout":
2047
+ ttl = _WATCHLIST_PICK_AI_UNAVAILABLE_TTL if _reason == "ai_unavailable" else _cache_ttl_for_tf(tf)
2048
+ _WATCHLIST_PICK_CACHE[(t, tf)] = {"ts": now, "pred": pred, "ttl": ttl}
2049
 
2050
  return jsonify({
2051
  "tf": tf, "ticker": t,
 
2097
  entry = _WATCHLIST_PICK_CACHE.get((ticker, tf))
2098
  if entry and time.time() - entry["ts"] < entry.get("ttl", _cache_ttl_for_tf(tf)):
2099
  return ticker, tf, entry["pred"]
2100
+ pred = _gated_predict(ticker, start, end,
2101
  _market_ctx=shared_ctx,
2102
  _run_ai_forecast=True,
2103
  _ai_fast_mode=True,
2104
  # BOUNDED β€” never block the batch on one stock (see per-ticker route).
2105
  _ai_fast_fail_on_rate_limit=True)
2106
  if not pred.get("error"):
2107
+ _reason = pred.get("no_trade_reason")
2108
+ # Never cache a transient 'timeout' (provider will reset shortly) so the next scan
2109
+ # retries; keep 'ai_unavailable' on the short TTL for hard outages.
2110
+ if _reason != "timeout":
2111
+ ttl = _WATCHLIST_PICK_AI_UNAVAILABLE_TTL if _reason == "ai_unavailable" else _cache_ttl_for_tf(tf)
2112
+ _WATCHLIST_PICK_CACHE[(ticker, tf)] = {"ts": time.time(), "pred": pred, "ttl": ttl}
2113
  return ticker, tf, pred
2114
 
2115
  # ── Phase 0: pre-warm OHLCV caches (parallel, 40s wall-clock cap) ────────
 
3881
  for tk in tickers:
3882
  try:
3883
  start, end = timeframe_to_dates("INTRADAY")
3884
+ pred = _gated_predict(
3885
  tk, start, end,
3886
  _market_ctx=market_ctx,
3887
  _run_ai_forecast=True,
3888
  _ai_fast_mode=True,
3889
  _ai_fast_fail_on_rate_limit=True,
3890
  )
3891
+ if not pred.get("error"):
3892
+ _reason = pred.get("no_trade_reason")
3893
+ # Don't cache transient timeouts (let the next refresh/fetch retry);
3894
+ # short TTL for hard ai_unavailable.
3895
+ if _reason != "timeout":
3896
+ _ttl = (_WATCHLIST_PICK_AI_UNAVAILABLE_TTL
3897
+ if _reason == "ai_unavailable"
3898
+ else _cache_ttl_for_tf("INTRADAY"))
3899
+ _WATCHLIST_PICK_CACHE[(tk, "INTRADAY")] = {
3900
+ "ts": now,
3901
+ "pred": pred,
3902
+ "ttl": _ttl,
3903
+ }
3904
  except Exception as exc:
3905
  app.logger.debug("INTRADAY refresh failed for %s: %s", tk, exc)
3906
  app.logger.info("INTRADAY cache refreshed for %d tickers", len(tickers))
database.py CHANGED
@@ -1159,6 +1159,9 @@ def get_validation_summary() -> dict:
1159
  )
1160
  directional_where = base_where + " AND UPPER(direction) IN ('BULLISH', 'BEARISH', 'SLIGHTLY BULLISH', 'SLIGHTLY BEARISH')"
1161
  high_conf_where = directional_where + " AND UPPER(COALESCE(confidence, '')) = 'HIGH'"
 
 
 
1162
 
1163
  with _conn() as conn:
1164
  def _query(where: str):
@@ -1178,10 +1181,37 @@ def get_validation_summary() -> dict:
1178
  ).fetchall()
1179
  return {row["timeframe"]: dict(row) for row in rows}
1180
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1181
  return {
1182
  "all": _query(base_where),
1183
  "directional": _query(directional_where),
1184
  "high_conf": _query(high_conf_where),
 
 
1185
  }
1186
 
1187
 
 
1159
  )
1160
  directional_where = base_where + " AND UPPER(direction) IN ('BULLISH', 'BEARISH', 'SLIGHTLY BULLISH', 'SLIGHTLY BEARISH')"
1161
  high_conf_where = directional_where + " AND UPPER(COALESCE(confidence, '')) = 'HIGH'"
1162
+ # Source split: 'ml' = the standalone quantile model; anything else = the AI/LLM path.
1163
+ ml_where = directional_where + " AND LOWER(COALESCE(snapshot_source, '')) = 'ml'"
1164
+ ai_where = directional_where + " AND LOWER(COALESCE(snapshot_source, '')) <> 'ml'"
1165
 
1166
  with _conn() as conn:
1167
  def _query(where: str):
 
1181
  ).fetchall()
1182
  return {row["timeframe"]: dict(row) for row in rows}
1183
 
1184
+ # Agreement bucket: ML and AI made the SAME directional call on the same
1185
+ # ticker/timeframe/target_date, and BOTH were validated. hit_rate_pct = how
1186
+ # often both hit β€” the highest-quality consensus signal.
1187
+ agree_rows = conn.execute(
1188
+ """
1189
+ SELECT m.timeframe AS timeframe,
1190
+ COUNT(*) AS total,
1191
+ SUM(CASE WHEN m.validation_result = 'HIT' AND a.validation_result = 'HIT' THEN 1 ELSE 0 END) AS hits,
1192
+ ROUND(AVG(CASE WHEN m.validation_result = 'HIT' AND a.validation_result = 'HIT' THEN 100.0 ELSE 0 END), 1) AS hit_rate_pct
1193
+ FROM prediction_snapshots m
1194
+ JOIN prediction_snapshots a
1195
+ ON m.ticker = a.ticker AND m.timeframe = a.timeframe
1196
+ AND m.validation_target_date = a.validation_target_date
1197
+ AND UPPER(m.direction) = UPPER(a.direction)
1198
+ WHERE LOWER(COALESCE(m.snapshot_source, '')) = 'ml'
1199
+ AND LOWER(COALESCE(a.snapshot_source, '')) <> 'ml'
1200
+ AND m.validation_status = 'VALIDATED' AND a.validation_status = 'VALIDATED'
1201
+ AND m.validation_result IN ('HIT', 'MISS') AND a.validation_result IN ('HIT', 'MISS')
1202
+ AND UPPER(m.direction) IN ('BULLISH', 'BEARISH', 'SLIGHTLY BULLISH', 'SLIGHTLY BEARISH')
1203
+ GROUP BY m.timeframe
1204
+ ORDER BY m.timeframe
1205
+ """
1206
+ ).fetchall()
1207
+ agreement = {r["timeframe"]: dict(r) for r in agree_rows}
1208
+
1209
  return {
1210
  "all": _query(base_where),
1211
  "directional": _query(directional_where),
1212
  "high_conf": _query(high_conf_where),
1213
+ "by_source": {"ml": _query(ml_where), "ai": _query(ai_where)},
1214
+ "agreement": agreement,
1215
  }
1216
 
1217
 
llm_client.py CHANGED
@@ -150,6 +150,34 @@ def _all_cloud_daily_exhausted() -> bool:
150
  return all(_PROVIDER_STATUS[n]["daily_exhausted"] for n in _CLOUD_PROVIDERS)
151
 
152
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
153
  def _mark_ok(name: str) -> None:
154
  with _LLM_LOCK:
155
  s = _PROVIDER_STATUS[name]
 
150
  return all(_PROVIDER_STATUS[n]["daily_exhausted"] for n in _CLOUD_PROVIDERS)
151
 
152
 
153
+ def unavailability_is_recoverable() -> bool:
154
+ """After make_chat_call raised, classify the outage as TEMPORARY vs HARD.
155
+
156
+ TEMPORARY (returns True): at least one keyed cloud provider is only cooling down /
157
+ burst-rate-limited (NOT daily-exhausted) and will recover once its short per-minute
158
+ window lapses, OR Ollama is configured and not in a hard backoff. In this case the
159
+ caller should mark the failure as a retryable 'timeout' β€” the frontend keeps refetching
160
+ and the forecast fills in a moment later when a provider resets.
161
+
162
+ HARD (returns False): every keyed cloud provider is daily-exhausted (real quota gone
163
+ until midnight IST) AND Ollama is unconfigured / in backoff β€” nothing will work soon,
164
+ so 'ai_unavailable' is the honest reason.
165
+
166
+ Note: a provider with no API key can never recover on its own, so it doesn't count as
167
+ a recoverable source (this is checked via provider_key_status()).
168
+ """
169
+ _maybe_daily_reset()
170
+ keys = provider_key_status()
171
+ # A keyed cloud provider that hit only a transient (per-minute) limit will reset soon.
172
+ for name in _CLOUD_PROVIDERS:
173
+ if keys.get(name) and not _PROVIDER_STATUS[name]["daily_exhausted"]:
174
+ return True
175
+ # Ollama has no rate limits β€” recoverable if configured and not in a hard backoff window.
176
+ if keys.get("ollama") and time.time() >= _OLLAMA_INFER_BACKOFF_UNTIL:
177
+ return True
178
+ return False
179
+
180
+
181
  def _mark_ok(name: str) -> None:
182
  with _LLM_LOCK:
183
  s = _PROVIDER_STATUS[name]
ml_predictor/infer.py CHANGED
@@ -49,14 +49,31 @@ _SESSION_OPEN_MIN = 9 * 60 + 15 # 09:15 IST
49
  _SESSION_CLOSE_MIN = 15 * 60 # 15:00 IST (same validation cutoff as the intraday backtest)
50
  _SESSION_TOTAL = _SESSION_CLOSE_MIN - _SESSION_OPEN_MIN # 345 min
51
 
52
- # INTRADAY reachable-edge calibration. The model predicts a FULL-DAY excursion, but at
53
- # deployment the features are as-of the PREVIOUS daily close, so the near (q10) edge is
54
- # systematically too ambitious for the session that actually remains. On top of the √time
55
- # scaling above, shrink ONLY the *reachable* edge of the reported range toward 0 by this
56
- # factor so the range's near bound is genuinely touched β‰₯75% of the time (calibrated on
57
- # research/ml_intraday_backtest.py β€” 0.40 β†’ ~78/75/77% coverage at 09:15/12:00/14:00). The
58
- # optimistic edge (q90) and the median target are left informative. Env-overridable for A/B.
59
- _INTRADAY_REACH_MULT = float(os.environ.get("ML_INTRADAY_REACH_MULT", "0.40"))
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
60
 
61
 
62
  def intraday_session_scale(now_minutes: float) -> float:
@@ -202,8 +219,9 @@ class MLPredictor:
202
  # Pure derivation of the output schema from raw model outputs (no model calls).
203
  # Shared by _predict_tf (live) and research/ml_backtest.py (batch) β€” one source of truth.
204
  # INTRADAY time-of-day scaling: the model predicts a FULL-DAY excursion, but a mid-session
205
- # entry only has part of the day left. Scale the band by √(remaining session fraction)
206
- # (volatility ~ √time) so 12:00/14:00 targets are reachable in the hours that remain.
 
207
  if tf == "INTRADAY" and intraday_scale != 1.0:
208
  q = {k: v * intraday_scale for k, v in q.items()}
209
  up10, up50, up90 = q["up10"], q["up50"], q["up90"]
@@ -244,17 +262,21 @@ class MLPredictor:
244
  elif confidence == "MEDIUM":
245
  confidence = "LOW"
246
 
247
- # ── Return band = a prediction INTERVAL (q10 easily-reached bound … q90 optimistic) ──
248
  # so the reported range is honestly hit most of the time, not a coin-flip median band.
249
- # INTRADAY: the *reachable* edge is additionally shrunk toward 0 (deployment-calibrated,
250
- # see _INTRADAY_REACH_MULT) so the range's near bound is touched β‰₯75% of the session.
251
- reach_m = _INTRADAY_REACH_MULT if tf == "INTRADAY" else 1.0
 
 
 
 
252
  if direction == "BULLISH":
253
- ret_lo, ret_hi = round(up10 * reach_m, 2), round(up90, 2) # 0 < lo < hi
254
- expected_pct = up50 # median expected high
255
  elif direction == "BEARISH":
256
- ret_lo, ret_hi = round(dn10, 2), round(dn90 * reach_m, 2) # lo < hi < 0 (deep … shallow)
257
- expected_pct = dn50 # median expected dip
258
  else:
259
  from research.range_model import calibrated_range
260
  n_lo, n_hi = calibrated_range("NEUTRAL", tf)
@@ -266,8 +288,8 @@ class MLPredictor:
266
  midpoint = round((ret_lo + ret_hi) / 2.0, 2)
267
  # Expected (most-likely) target = the median quantile β€” the headline price estimate.
268
  expected_target_price = round(price * (1 + expected_pct / 100.0), 2)
269
- # "Estimated high the stock can reach" = optimistic up-quantile.
270
- estimated_high = round(price * (1 + up90 / 100.0), 2)
271
 
272
  # ── Buy-price suggestion: the modeled median dip (buy on the pullback) ─
273
  dip_entry = round(price * (1 + dn50 / 100.0), 2)
@@ -312,7 +334,7 @@ class MLPredictor:
312
  # "reached". up90 was trained on the entry day's High vs its close (daily proxy).
313
  if tf == "INTRADAY":
314
  anchor = anchor_close if (anchor_close and anchor_close > 0) else price
315
- intraday_est_high = round(anchor * (1 + up90 / 100.0), 2)
316
  ref = live_price if (live_price and live_price > 0) else None
317
  hi_today = today_high if (today_high and today_high > 0) else None
318
  already_gone = False
 
49
  _SESSION_CLOSE_MIN = 15 * 60 # 15:00 IST (same validation cutoff as the intraday backtest)
50
  _SESSION_TOTAL = _SESSION_CLOSE_MIN - _SESSION_OPEN_MIN # 345 min
51
 
52
+ # INTRADAY magnitude calibration. The model predicts a FULL-DAY excursion (its labels are
53
+ # the entry day's own High/Low vs close), but at deployment the features are as-of the
54
+ # PREVIOUS daily close and the entry is mid-session, so the raw quantiles are miscalibrated
55
+ # for the session that actually remains β€” AND not by a single factor: measured on the true
56
+ # 15-min backtest (research/ml_intraday_backtest.py, 30 tickers Γ— 57 days), the model's q90
57
+ # is about right once √time-scaled (a genuine ~90% ceiling), but its q50 systematically
58
+ # OVERSHOOTS the realized median move and its q10 is too ambitious for the reachable floor.
59
+ # So we calibrate the three roles of the reported band INDEPENDENTLY, each on top of the
60
+ # √time session scaling above, to the realized excursion distribution:
61
+ # β€’ _INTRADAY_FAR_MULT (β‰ˆ1.0) β€” far/optimistic edge = true q90 ceiling (~90% not exceeded;
62
+ # the old uniform-shrink left this at a q65, understating the achievable high).
63
+ # β€’ _INTRADAY_MED_MULT (β‰ˆ0.42) β€” the EXPECTED/headline target = realized MEDIAN move (reached
64
+ # ~50% of the time). This is the HONEST, tradeable setting. WARNING: "expected-target hit %"
65
+ # is monotonic in the target level, so you can push it to ~85% by dropping this to β‰ˆ0.08 β€”
66
+ # BUT that makes the target ~0.15%, which is SMALLER than the ~0.30% round-trip cost, so the
67
+ # backtest win-rate collapses to ~5% (the target is "hit" but you still lose to fees). 85%
68
+ # expected-target accuracy and profitability are mutually exclusive here. Set
69
+ # ML_INTRADAY_MED_MULT=0.08 only if you explicitly want the high-hit-rate display target.
70
+ # β€’ _INTRADAY_NEAR_MULT (β‰ˆ0.12) β€” reachable near edge, so the range's near bound (RANGE_HIT)
71
+ # is genuinely touched β‰₯85% of the session.
72
+ # Result (default): graded (range) hit β‰ˆ88%, expected-target hit β‰ˆ51%, far-bound coverage β‰ˆ90%.
73
+ # All three are env-overridable for A/B.
74
+ _INTRADAY_FAR_MULT = float(os.environ.get("ML_INTRADAY_FAR_MULT", "1.0"))
75
+ _INTRADAY_MED_MULT = float(os.environ.get("ML_INTRADAY_MED_MULT", "0.42"))
76
+ _INTRADAY_NEAR_MULT = float(os.environ.get("ML_INTRADAY_NEAR_MULT", "0.12"))
77
 
78
 
79
  def intraday_session_scale(now_minutes: float) -> float:
 
219
  # Pure derivation of the output schema from raw model outputs (no model calls).
220
  # Shared by _predict_tf (live) and research/ml_backtest.py (batch) β€” one source of truth.
221
  # INTRADAY time-of-day scaling: the model predicts a FULL-DAY excursion, but a mid-session
222
+ # entry only has part of the day left. Scale all quantiles by √(remaining session fraction)
223
+ # (volatility ~ √time) so 12:00/14:00 targets are reachable in the hours that remain. The
224
+ # per-role recalibration (near/median/far, see the *_MULT constants) is applied below.
225
  if tf == "INTRADAY" and intraday_scale != 1.0:
226
  q = {k: v * intraday_scale for k, v in q.items()}
227
  up10, up50, up90 = q["up10"], q["up50"], q["up90"]
 
262
  elif confidence == "MEDIUM":
263
  confidence = "LOW"
264
 
265
+ # ── Return band = a prediction INTERVAL (near easily-reached bound … far optimistic) ──
266
  # so the reported range is honestly hit most of the time, not a coin-flip median band.
267
+ # INTRADAY: the near/median/far levels are calibrated INDEPENDENTLY to the realized
268
+ # 15-min excursion distribution (see the _INTRADAY_*_MULT constants) β€” near edge is a
269
+ # reachable floor (~85% touched), far edge is a true q90 ceiling, and the expected
270
+ # target is pulled to the realized median (~50% touched). Other TFs use the raw quantiles.
271
+ near_m = _INTRADAY_NEAR_MULT if tf == "INTRADAY" else 1.0
272
+ far_m = _INTRADAY_FAR_MULT if tf == "INTRADAY" else 1.0
273
+ med_m = _INTRADAY_MED_MULT if tf == "INTRADAY" else 1.0
274
  if direction == "BULLISH":
275
+ ret_lo, ret_hi = round(up10 * near_m, 2), round(up90 * far_m, 2) # 0 < lo < hi
276
+ expected_pct = up50 * med_m # median expected high
277
  elif direction == "BEARISH":
278
+ ret_lo, ret_hi = round(dn10 * far_m, 2), round(dn90 * near_m, 2) # lo < hi < 0 (deep … shallow)
279
+ expected_pct = dn50 * med_m # median expected dip
280
  else:
281
  from research.range_model import calibrated_range
282
  n_lo, n_hi = calibrated_range("NEUTRAL", tf)
 
288
  midpoint = round((ret_lo + ret_hi) / 2.0, 2)
289
  # Expected (most-likely) target = the median quantile β€” the headline price estimate.
290
  expected_target_price = round(price * (1 + expected_pct / 100.0), 2)
291
+ # "Estimated high the stock can reach" = optimistic up-quantile (INTRADAY: far-calibrated).
292
+ estimated_high = round(price * (1 + up90 * far_m / 100.0), 2)
293
 
294
  # ── Buy-price suggestion: the modeled median dip (buy on the pullback) ─
295
  dip_entry = round(price * (1 + dn50 / 100.0), 2)
 
334
  # "reached". up90 was trained on the entry day's High vs its close (daily proxy).
335
  if tf == "INTRADAY":
336
  anchor = anchor_close if (anchor_close and anchor_close > 0) else price
337
+ intraday_est_high = round(anchor * (1 + up90 * far_m / 100.0), 2)
338
  ref = live_price if (live_price and live_price > 0) else None
339
  hi_today = today_high if (today_high and today_high > 0) else None
340
  already_gone = False
news_sentiment.py CHANGED
@@ -56,26 +56,38 @@ def analyze_news(
56
  headlines: list[str],
57
  ticker: str,
58
  company: str = "",
 
59
  ) -> dict:
60
  """
61
  Analyze news headlines using OpenRouter β†’ Groq β†’ HuggingFace.
62
  Returns { label, score, summary, key_headline, source }.
63
  Falls back to keyword scoring if no API key is set.
 
 
 
64
  """
65
  if not headlines:
66
  return {"label": "NEUTRAL", "score": 0, "summary": "No recent news found.",
67
  "key_headline": "", "source": "none"}
68
 
69
- result = _llm_analyze(headlines, ticker, company or ticker)
70
  if result:
71
  return result
72
 
73
  return _keyword_fallback(headlines)
74
 
75
 
76
- def _llm_analyze(headlines: list[str], ticker: str, company: str) -> dict | None:
 
77
  """Call shared LLM provider chain for news sentiment. Falls back to None on failure."""
78
- numbered = "\n".join(f"{i+1}. {h}" for i, h in enumerate(headlines[:8]))
 
 
 
 
 
 
 
79
  prompt = f"""You are a financial news analyst specializing in Indian equity markets.
80
 
81
  Analyze these news headlines for {company} ({ticker}, NSE-listed stock):
@@ -91,6 +103,7 @@ Respond with ONLY a valid JSON object β€” no markdown, no explanation:
91
  }}
92
 
93
  Rules:
 
94
  - BULLISH: positive earnings, contracts, upgrades, sector tailwinds, management guidance up
95
  - BEARISH: misses, downgrades, regulatory issues, macro headwinds, management exits
96
  - NEUTRAL: routine news, sector-level stories without stock-specific impact
@@ -154,10 +167,13 @@ def _keyword_fallback(headlines: list[str]) -> dict:
154
 
155
 
156
  # ── GOOGLE NEWS RSS FETCH ─────────────────────────────────────────────────────
157
- def _fetch_google_news(query: str, max_items: int = 8) -> list[str]:
158
  """
159
  Fetch headlines from Google News RSS for the given search query.
160
  Uses company name search (e.g. 'HDFC Bank stock NSE') for accurate results.
 
 
 
161
  """
162
  url = (
163
  f"https://news.google.com/rss/search"
@@ -180,19 +196,25 @@ def _fetch_google_news(query: str, max_items: int = 8) -> list[str]:
180
  if not title:
181
  continue
182
  pub_ts = 0
 
183
  pd = re.search(r"<pubDate>(.*?)</pubDate>", item)
184
  if pd:
185
  try:
186
- pub_ts = parsedate_to_datetime(pd.group(1).strip()).timestamp()
 
 
187
  except Exception:
188
  pass
189
- parsed.append((pub_ts, title))
190
  parsed.sort(key=lambda x: x[0], reverse=True) # newest first
191
- return [title for _, title in parsed[:max_items]]
 
 
192
  except Exception:
193
  return []
194
 
195
 
 
196
  def _fetch_yfinance_news(ticker: str, max_items: int = 8) -> list[str]:
197
  """Secondary: yfinance .news β€” often empty/wrong for NSE tickers, used as fallback."""
198
  try:
@@ -256,15 +278,20 @@ def fetch_and_analyze(ticker: str, company: str = "", max_items: int = 8) -> dic
256
  search_name = company.strip() if company.strip() else bare
257
  google_query = f"{search_name} stock NSE"
258
 
259
- # 1. Google News RSS (primary β€” searches by company name)
260
- headlines = _fetch_google_news(google_query, max_items)
 
261
 
262
  # 2. yfinance fallback if Google returned nothing
263
  if not headlines:
264
  headlines = _fetch_yfinance_news(ticker, max_items)
 
265
 
266
- sentiment = analyze_news(headlines, ticker, company or bare)
267
  sentiment["headlines"] = headlines[:5]
 
 
 
268
  _NEWS_CACHE[key] = {"ts": time.time(), "data": sentiment}
269
  return sentiment
270
 
 
56
  headlines: list[str],
57
  ticker: str,
58
  company: str = "",
59
+ dated: list | None = None,
60
  ) -> dict:
61
  """
62
  Analyze news headlines using OpenRouter β†’ Groq β†’ HuggingFace.
63
  Returns { label, score, summary, key_headline, source }.
64
  Falls back to keyword scoring if no API key is set.
65
+
66
+ `dated` (optional) is a list of (date 'YYYY-MM-DD', title) newest-first; when
67
+ supplied the LLM is shown the publish dates so it can weight recent news higher.
68
  """
69
  if not headlines:
70
  return {"label": "NEUTRAL", "score": 0, "summary": "No recent news found.",
71
  "key_headline": "", "source": "none"}
72
 
73
+ result = _llm_analyze(headlines, ticker, company or ticker, dated=dated)
74
  if result:
75
  return result
76
 
77
  return _keyword_fallback(headlines)
78
 
79
 
80
+ def _llm_analyze(headlines: list[str], ticker: str, company: str,
81
+ dated: list | None = None) -> dict | None:
82
  """Call shared LLM provider chain for news sentiment. Falls back to None on failure."""
83
+ # Prefix each headline with its publish date (when known) so the model weights
84
+ # today's news above week-old stories. Falls back to plain numbering.
85
+ if dated:
86
+ numbered = "\n".join(
87
+ f"{i+1}. [{(d or 'undated')}] {t}" for i, (d, t) in enumerate(dated[:8])
88
+ )
89
+ else:
90
+ numbered = "\n".join(f"{i+1}. {h}" for i, h in enumerate(headlines[:8]))
91
  prompt = f"""You are a financial news analyst specializing in Indian equity markets.
92
 
93
  Analyze these news headlines for {company} ({ticker}, NSE-listed stock):
 
103
  }}
104
 
105
  Rules:
106
+ - Weight RECENT headlines (bracketed dates) more heavily β€” today's news outweighs week-old news.
107
  - BULLISH: positive earnings, contracts, upgrades, sector tailwinds, management guidance up
108
  - BEARISH: misses, downgrades, regulatory issues, macro headwinds, management exits
109
  - NEUTRAL: routine news, sector-level stories without stock-specific impact
 
167
 
168
 
169
  # ── GOOGLE NEWS RSS FETCH ─────────────────────────────────────────────────────
170
+ def _fetch_google_news(query: str, max_items: int = 8, with_dates: bool = False):
171
  """
172
  Fetch headlines from Google News RSS for the given search query.
173
  Uses company name search (e.g. 'HDFC Bank stock NSE') for accurate results.
174
+
175
+ Returns newest-first. By default a list[str] of titles; with_dates=True returns
176
+ list[tuple[str, str]] of (pubDate 'YYYY-MM-DD', title) so callers can surface recency.
177
  """
178
  url = (
179
  f"https://news.google.com/rss/search"
 
196
  if not title:
197
  continue
198
  pub_ts = 0
199
+ pub_date = ""
200
  pd = re.search(r"<pubDate>(.*?)</pubDate>", item)
201
  if pd:
202
  try:
203
+ _dt = parsedate_to_datetime(pd.group(1).strip())
204
+ pub_ts = _dt.timestamp()
205
+ pub_date = _dt.strftime("%Y-%m-%d")
206
  except Exception:
207
  pass
208
+ parsed.append((pub_ts, pub_date, title))
209
  parsed.sort(key=lambda x: x[0], reverse=True) # newest first
210
+ if with_dates:
211
+ return [(d, t) for _ts, d, t in parsed[:max_items]]
212
+ return [t for _ts, _d, t in parsed[:max_items]]
213
  except Exception:
214
  return []
215
 
216
 
217
+
218
  def _fetch_yfinance_news(ticker: str, max_items: int = 8) -> list[str]:
219
  """Secondary: yfinance .news β€” often empty/wrong for NSE tickers, used as fallback."""
220
  try:
 
278
  search_name = company.strip() if company.strip() else bare
279
  google_query = f"{search_name} stock NSE"
280
 
281
+ # 1. Google News RSS (primary β€” searches by company name), newest-first with dates
282
+ dated = _fetch_google_news(google_query, max_items, with_dates=True)
283
+ headlines = [t for _d, t in dated]
284
 
285
  # 2. yfinance fallback if Google returned nothing
286
  if not headlines:
287
  headlines = _fetch_yfinance_news(ticker, max_items)
288
+ dated = [("", h) for h in headlines]
289
 
290
+ sentiment = analyze_news(headlines, ticker, company or bare, dated=dated)
291
  sentiment["headlines"] = headlines[:5]
292
+ sentiment["headlines_dated"] = [{"date": d, "title": t} for d, t in dated[:5]]
293
+ # Newest publish date across the fetched window (surfaced in the UI as "as of").
294
+ sentiment["latest_date"] = next((d for d, _t in dated if d), "")
295
  _NEWS_CACHE[key] = {"ts": time.time(), "data": sentiment}
296
  return sentiment
297
 
predictor_core.py CHANGED
@@ -1094,6 +1094,10 @@ def predict_stock_v2(ticker: str, start_date: str, end_date: str,
1094
  headlines = news_obj.get("headlines")
1095
  if not isinstance(headlines, list):
1096
  headlines = []
 
 
 
 
1097
  source = str(news_obj.get("source") or "none")
1098
 
1099
  return {
@@ -1102,6 +1106,8 @@ def predict_stock_v2(ticker: str, start_date: str, end_date: str,
1102
  "summary": summary,
1103
  "key_headline": key_headline,
1104
  "headlines": headlines,
 
 
1105
  "source": source,
1106
  }
1107
 
@@ -1347,12 +1353,40 @@ def predict_stock_v2(ticker: str, start_date: str, end_date: str,
1347
  # AI directional forecast β€” runs for all watchlist predictions when _run_ai_forecast=True
1348
  ai_forecast: dict | None = None
1349
  _af_err_msg: str | None = None
 
1350
  if _run_ai_forecast:
1351
  try:
1352
  # Build indicator snapshot in β‚Ή for Claude context
1353
  _c = sc[ticker].dropna()
1354
  _h = sh[ticker].dropna()
1355
  _lo = sl[ticker].dropna()
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1356
  _indicators = {}
1357
  _ohlcv_df = None
1358
  try:
@@ -1467,6 +1501,13 @@ def predict_stock_v2(ticker: str, start_date: str, end_date: str,
1467
  except Exception as _af_err:
1468
  _af_err_msg = str(_af_err)
1469
  logging.warning("ai_forecast skipped for %s: %s", ticker, _af_err)
 
 
 
 
 
 
 
1470
 
1471
  # AI forecast supersedes the ML directional forecast when it ran successfully.
1472
  # Skip ai_unavailable results β€” they are not real predictions.
@@ -1642,8 +1683,14 @@ def predict_stock_v2(ticker: str, start_date: str, end_date: str,
1642
  # from AI and do not suppress with strategy horizon gates.
1643
  no_trade_reason = None
1644
  elif _run_ai_forecast and not _ai_real:
1645
- # AI was unavailable β€” treat as no signal so UI shows the warning
1646
- no_trade_reason = "ai_unavailable"
 
 
 
 
 
 
1647
 
1648
  # NEUTRAL calls have no directional edge β€” midpoint = 0 β†’ target = entry = current price,
1649
  # making the risk block misleading. Suppress as no-trade regardless of AI availability.
@@ -1666,7 +1713,31 @@ def predict_stock_v2(ticker: str, start_date: str, end_date: str,
1666
 
1667
  _is_actionable_buy = direction in ("BULLISH", "SLIGHTLY BULLISH") and no_trade_reason is None
1668
  _is_actionable_sell = direction in ("SELL", "BEARISH") and no_trade_reason is None
1669
- if _is_actionable_buy:
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1670
  entry_price = round(price * (1 + _entry_buffer), 2)
1671
  entry_basis = "est_open_conservative" if _ml_score < 50 else "est_open"
1672
  elif _is_actionable_sell:
@@ -1676,14 +1747,13 @@ def predict_stock_v2(ticker: str, start_date: str, end_date: str,
1676
  entry_price = round(price, 2)
1677
  entry_basis = "last_close"
1678
 
1679
- # Recompute targets from entry_price so price-range, SL and R:R are
1680
- # all internally consistent with the achievable entry.
1681
- # Targets stay anchored to close (price) β€” the AI's forecast of where the
1682
- # stock goes from current market price. entry_price (with open buffer) is
1683
- # used only for R:R and stop-loss sizing, not for the price forecast itself.
1684
- target_price_lo = round(price * (1 + ret_lo / 100), 2)
1685
- target_price_hi = round(price * (1 + ret_hi / 100), 2)
1686
- expected_target_price = round(price * (1 + midpoint / 100), 2)
1687
 
1688
  # Recalculate stop-loss from entry_price so risk % and R:R reflect actual cost.
1689
  # SL ALWAYS below entry (max loss level). Direction affects target/gain only.
@@ -1764,6 +1834,7 @@ def predict_stock_v2(ticker: str, start_date: str, end_date: str,
1764
  "entry_basis": entry_basis,
1765
  "entry_buffer_pct": round(_entry_buffer * 100, 2),
1766
  "max_chase_pct": round(_entry_buffer * 100, 2),
 
1767
  "predicted_direction": price_forecast["predicted_direction"],
1768
  "predicted_return_lo": price_forecast["predicted_return_lo"],
1769
  "predicted_return_hi": price_forecast["predicted_return_hi"],
@@ -1783,6 +1854,8 @@ def predict_stock_v2(ticker: str, start_date: str, end_date: str,
1783
  "summary": news["summary"],
1784
  "key_headline": news.get("key_headline", ""),
1785
  "headlines": news.get("headlines", []),
 
 
1786
  "source": news.get("source", "keywords"),
1787
  },
1788
  "earnings": earnings,
@@ -1799,6 +1872,7 @@ def predict_stock_v2(ticker: str, start_date: str, end_date: str,
1799
  "entry_basis": entry_basis,
1800
  "entry_buffer_pct": round(_entry_buffer * 100, 2),
1801
  "max_chase_pct": round(_entry_buffer * 100, 2),
 
1802
  "expected_target_price": expected_target_price,
1803
  "target_price_lo": target_price_lo,
1804
  "target_price_hi": target_price_hi,
 
1094
  headlines = news_obj.get("headlines")
1095
  if not isinstance(headlines, list):
1096
  headlines = []
1097
+ headlines_dated = news_obj.get("headlines_dated")
1098
+ if not isinstance(headlines_dated, list):
1099
+ headlines_dated = []
1100
+ latest_date = str(news_obj.get("latest_date") or "")
1101
  source = str(news_obj.get("source") or "none")
1102
 
1103
  return {
 
1106
  "summary": summary,
1107
  "key_headline": key_headline,
1108
  "headlines": headlines,
1109
+ "headlines_dated": headlines_dated,
1110
+ "latest_date": latest_date,
1111
  "source": source,
1112
  }
1113
 
 
1353
  # AI directional forecast β€” runs for all watchlist predictions when _run_ai_forecast=True
1354
  ai_forecast: dict | None = None
1355
  _af_err_msg: str | None = None
1356
+ _ai_soft_fail = False # True when the AI outage is transient (provider will reset soon / Ollama up)
1357
  if _run_ai_forecast:
1358
  try:
1359
  # Build indicator snapshot in β‚Ή for Claude context
1360
  _c = sc[ticker].dropna()
1361
  _h = sh[ticker].dropna()
1362
  _lo = sl[ticker].dropna()
1363
+ # INTRADAY: the daily OHLCV series ends at yesterday's close, so RSI / Bollinger /
1364
+ # momentum computed off it would describe YESTERDAY β€” not today's intraday move.
1365
+ # Append the live price as today's provisional bar so the indicators the AI reasons
1366
+ # about reflect the current session (e.g. a stock that has already dropped intraday
1367
+ # shows a lower RSI / BB position). INTRADAY-only and only when the live price differs
1368
+ # from the last close; backtest (no live price) and 1D/3D are unaffected.
1369
+ if _tf_label == "INTRADAY" and _live_price and len(_c) >= 1:
1370
+ try:
1371
+ _last_close = float(_c.iloc[-1])
1372
+ if _last_close > 0 and abs(_live_price - _last_close) / _last_close > 0.001:
1373
+ _today_ts = pd.Timestamp.now().normalize()
1374
+ if len(_c.index) == 0 or _c.index[-1] != _today_ts:
1375
+ # Use today's intraday high/low when available, else the live price.
1376
+ _t_hi = _live_price
1377
+ _t_lo = _live_price
1378
+ if isinstance(intraday_dict, dict) and intraday_dict.get("data_available"):
1379
+ _oh = intraday_dict.get("orb_high")
1380
+ _ol = intraday_dict.get("orb_low")
1381
+ if _oh:
1382
+ _t_hi = max(_live_price, float(_oh))
1383
+ if _ol:
1384
+ _t_lo = min(_live_price, float(_ol))
1385
+ _c = pd.concat([_c, pd.Series([_live_price], index=[_today_ts])])
1386
+ _h = pd.concat([_h, pd.Series([_t_hi], index=[_today_ts])]) if len(_h) else _h
1387
+ _lo = pd.concat([_lo, pd.Series([_t_lo], index=[_today_ts])]) if len(_lo) else _lo
1388
+ except Exception as _iv_err:
1389
+ logging.debug("intraday live-bar append failed for %s: %s", ticker, _iv_err)
1390
  _indicators = {}
1391
  _ohlcv_df = None
1392
  try:
 
1501
  except Exception as _af_err:
1502
  _af_err_msg = str(_af_err)
1503
  logging.warning("ai_forecast skipped for %s: %s", ticker, _af_err)
1504
+ # Classify the outage: a provider that is only per-minute rate-limited (or Ollama)
1505
+ # will recover shortly, so mark it retryable rather than a hard failure.
1506
+ try:
1507
+ from llm_client import unavailability_is_recoverable
1508
+ _ai_soft_fail = unavailability_is_recoverable()
1509
+ except Exception:
1510
+ _ai_soft_fail = False
1511
 
1512
  # AI forecast supersedes the ML directional forecast when it ran successfully.
1513
  # Skip ai_unavailable results β€” they are not real predictions.
 
1683
  # from AI and do not suppress with strategy horizon gates.
1684
  no_trade_reason = None
1685
  elif _run_ai_forecast and not _ai_real:
1686
+ # AI was unavailable this pass. The ML forecast already renders instantly beside the
1687
+ # AI slot (ML-vs-AI), so the card is never empty β€” therefore we NEVER emit a terminal
1688
+ # 'ai_unavailable'. The AI cell always stays in the retryable 'timeout' state so the
1689
+ # frontend keeps refetching and the forecast fills in the moment a provider (or Ollama)
1690
+ # frees up. No ML value is substituted into the AI slot; the two stay independent.
1691
+ # (_ai_soft_fail is still computed above for logging/diagnostics but no longer gates
1692
+ # the reason β€” even a hard outage is treated as retryable, since providers reset.)
1693
+ no_trade_reason = "timeout"
1694
 
1695
  # NEUTRAL calls have no directional edge β€” midpoint = 0 β†’ target = entry = current price,
1696
  # making the risk block misleading. Suppress as no-trade regardless of AI availability.
 
1713
 
1714
  _is_actionable_buy = direction in ("BULLISH", "SLIGHTLY BULLISH") and no_trade_reason is None
1715
  _is_actionable_sell = direction in ("SELL", "BEARISH") and no_trade_reason is None
1716
+ # When a live price is available (market open / intraday view), 1D/3D now anchor to it just
1717
+ # like INTRADAY: the realistic entry is the CURRENT live price and targets/SL are measured
1718
+ # from NOW, not from yesterday's close + an open-gap buffer. This keeps a BULLISH target ABOVE
1719
+ # the live price on a gap-up day (previously the close-anchored target could render BELOW the
1720
+ # shown live price) and matches the AI-forecast targets, which already anchor to the live price.
1721
+ # Backtest has no live price (_live_price is None) β†’ falls back to the prior close, so
1722
+ # historical behaviour is unchanged.
1723
+ _has_live = _live_price is not None and _live_price > 0
1724
+ _use_live = _has_live and _tf_label in ("INTRADAY", "1D", "3D")
1725
+
1726
+ # Gap detection: has today's live price ALREADY run past the move as originally forecast from
1727
+ # the prior close? If so the predicted edge is largely spent β€” flag it for a card note.
1728
+ gapped_past_target = False
1729
+ if _has_live and _tf_label in ("1D", "3D") and no_trade_reason is None:
1730
+ _close_tgt_hi = price * (1 + ret_hi / 100)
1731
+ _close_tgt_lo = price * (1 + ret_lo / 100)
1732
+ if direction in ("BULLISH", "SLIGHTLY BULLISH") and _live_price >= _close_tgt_hi:
1733
+ gapped_past_target = True
1734
+ elif direction in ("SELL", "BEARISH") and _live_price <= _close_tgt_lo:
1735
+ gapped_past_target = True
1736
+
1737
+ if _use_live:
1738
+ entry_price = round(_live_price, 2)
1739
+ entry_basis = "live"
1740
+ elif _is_actionable_buy:
1741
  entry_price = round(price * (1 + _entry_buffer), 2)
1742
  entry_basis = "est_open_conservative" if _ml_score < 50 else "est_open"
1743
  elif _is_actionable_sell:
 
1747
  entry_price = round(price, 2)
1748
  entry_basis = "last_close"
1749
 
1750
+ # Recompute targets from the anchor so price-range, SL and R:R are all internally consistent
1751
+ # with the achievable entry. Anchor = live price when available (INTRADAY/1D/3D), else the
1752
+ # prior close (backtest / market closed).
1753
+ _target_anchor = _live_price if _use_live else price
1754
+ target_price_lo = round(_target_anchor * (1 + ret_lo / 100), 2)
1755
+ target_price_hi = round(_target_anchor * (1 + ret_hi / 100), 2)
1756
+ expected_target_price = round(_target_anchor * (1 + midpoint / 100), 2)
 
1757
 
1758
  # Recalculate stop-loss from entry_price so risk % and R:R reflect actual cost.
1759
  # SL ALWAYS below entry (max loss level). Direction affects target/gain only.
 
1834
  "entry_basis": entry_basis,
1835
  "entry_buffer_pct": round(_entry_buffer * 100, 2),
1836
  "max_chase_pct": round(_entry_buffer * 100, 2),
1837
+ "gapped_past_target": gapped_past_target,
1838
  "predicted_direction": price_forecast["predicted_direction"],
1839
  "predicted_return_lo": price_forecast["predicted_return_lo"],
1840
  "predicted_return_hi": price_forecast["predicted_return_hi"],
 
1854
  "summary": news["summary"],
1855
  "key_headline": news.get("key_headline", ""),
1856
  "headlines": news.get("headlines", []),
1857
+ "headlines_dated": news.get("headlines_dated", []),
1858
+ "latest_date": news.get("latest_date", ""),
1859
  "source": news.get("source", "keywords"),
1860
  },
1861
  "earnings": earnings,
 
1872
  "entry_basis": entry_basis,
1873
  "entry_buffer_pct": round(_entry_buffer * 100, 2),
1874
  "max_chase_pct": round(_entry_buffer * 100, 2),
1875
+ "gapped_past_target": gapped_past_target,
1876
  "expected_target_price": expected_target_price,
1877
  "target_price_lo": target_price_lo,
1878
  "target_price_hi": target_price_hi,
research/ml_backtest.py CHANGED
@@ -101,7 +101,7 @@ def _pinball(y, q_pred, tau):
101
  return float(np.mean(np.maximum(tau * d, (tau - 1) * d)))
102
 
103
 
104
- def run(csv_path: str = DEFAULT_CSV) -> pd.DataFrame:
105
  predictor = MLPredictor()
106
  if not predictor.available:
107
  raise SystemExit("ml_predictor model not loaded β€” run `python ml_predictor/train.py` first.")
@@ -161,6 +161,9 @@ def run(csv_path: str = DEFAULT_CSV) -> pd.DataFrame:
161
  res.to_csv(OUT_CSV, index=False)
162
  _summary(res)
163
  _pnl_simulation(res)
 
 
 
164
  print(f"\n βœ“ Wrote per-row results β†’ {OUT_CSV}")
165
  return res
166
 
@@ -169,16 +172,31 @@ def run(csv_path: str = DEFAULT_CSV) -> pd.DataFrame:
169
  ROUND_TRIP_COST_PCT = 0.30 # 0.10% fees + 0.05% slippage per side Γ— 2 (matches research/db_backtest.py)
170
 
171
 
172
- def _simulate_trade(tp_pct, stop_pct, up_real, dn_real, ret_real):
173
  """Long trade, market entry (price=100). Exit at take-profit, stop, or window close.
174
- Excursion-only data β†’ assume the STOP fills first when both would trigger (risk-first,
175
- same limitation as research/db_backtest.py). Returns net-of-cost P&L in %."""
176
- if stop_pct and dn_real <= -stop_pct:
177
- gross = -stop_pct
178
- elif tp_pct and tp_pct > 0 and up_real >= tp_pct:
179
- gross = tp_pct
180
- else:
181
- gross = ret_real # exit at window close (INTRADAY retβ‰ˆ0 β†’ β‰ˆflat)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
182
  return gross - ROUND_TRIP_COST_PCT
183
 
184
 
@@ -198,34 +216,149 @@ def _equity_metrics(daily_rets_pct):
198
 
199
 
200
  def _pnl_simulation(res: pd.DataFrame):
201
- """Simulate taking the model's LONG (BULLISH / should_buy) calls, net of fees."""
 
 
 
 
 
202
  print("\n" + "=" * 78)
203
  print(" P&L TRADE SIMULATION β€” long-only BULLISH signals, market entry")
204
  print(f" Take-profit = expected(median) target Β· stop = model stop Β· cost = {ROUND_TRIP_COST_PCT}% round-trip")
205
- print(" (Educational backtest β€” excursion-based, stop assumed to fill before target.)")
206
  print("=" * 78)
207
- hdr = f" {'TF':<9}{'#Trades':>8}{'WinRate':>9}{'Expect':>9}{'AvgWin':>9}{'AvgLoss':>9}"
208
- hdr += f"{'PF':>7}{'DayRet':>9}{'MaxDD':>9}{'#Days':>7}"
209
  print(hdr)
210
- print(" " + "-" * 82)
211
  for tf in TIMEFRAMES:
212
  d = res[(res["tf"] == tf) & (res["should_buy"] == 1)].copy()
213
  if d.empty:
214
  print(f" {tf:<9}{'0':>8} (no BULLISH signals)")
215
  continue
216
- d["pnl"] = [_simulate_trade(r.expected_ret_pct, r.stop_loss_pct, r.up_real, r.dn_real, r.ret_real)
217
- for r in d.itertuples()]
218
- pnls = d["pnl"].to_numpy()
219
- wins, losses = pnls[pnls > 0], pnls[pnls < 0]
 
 
220
  pf = (wins.sum() / abs(losses.sum())) if losses.sum() < 0 else 99.0
221
  # Equal-weighted daily equity curve (mean P&L per date, compounded across dates).
222
  daily = d.groupby("date")["pnl"].mean().sort_index()
223
  total_ret, max_dd = _equity_metrics(daily.tolist())
224
- print(f" {tf:<9}{len(pnls):>8}{np.mean(pnls > 0):>9.0%}{np.mean(pnls):>+9.2f}"
225
  f"{(np.mean(wins) if len(wins) else 0):>+9.2f}{(np.mean(losses) if len(losses) else 0):>+9.2f}"
226
- f"{min(pf, 99.0):>7.2f}{total_ret:>+9.1f}{max_dd:>9.1f}{len(daily):>7}")
227
- print("\n Expect = mean net P&L per trade (expectancy, the headline signal-quality metric).")
228
- print(" DayRet = total return of an equal-weight, daily-rebalanced book over the holdout window.")
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
229
 
230
 
231
  def _summary(res: pd.DataFrame):
@@ -286,8 +419,10 @@ def _summary(res: pd.DataFrame):
286
  def main():
287
  ap = argparse.ArgumentParser()
288
  ap.add_argument("--csv", default=DEFAULT_CSV)
 
 
289
  args = ap.parse_args()
290
- run(args.csv)
291
 
292
 
293
  if __name__ == "__main__":
 
101
  return float(np.mean(np.maximum(tau * d, (tau - 1) * d)))
102
 
103
 
104
+ def run(csv_path: str = DEFAULT_CSV, sweep: bool = False, target_winrate: float = 0.85) -> pd.DataFrame:
105
  predictor = MLPredictor()
106
  if not predictor.available:
107
  raise SystemExit("ml_predictor model not loaded β€” run `python ml_predictor/train.py` first.")
 
161
  res.to_csv(OUT_CSV, index=False)
162
  _summary(res)
163
  _pnl_simulation(res)
164
+ if sweep:
165
+ _pnl_sweep(res, target_winrate=target_winrate)
166
+ _dip_entry_compare(res)
167
  print(f"\n βœ“ Wrote per-row results β†’ {OUT_CSV}")
168
  return res
169
 
 
172
  ROUND_TRIP_COST_PCT = 0.30 # 0.10% fees + 0.05% slippage per side Γ— 2 (matches research/db_backtest.py)
173
 
174
 
175
+ def _simulate_trade(tp_pct, stop_pct, up_real, dn_real, ret_real, order: str = "stop_first"):
176
  """Long trade, market entry (price=100). Exit at take-profit, stop, or window close.
177
+
178
+ Excursion-only data (daily bars) cannot tell us whether the target or the stop was
179
+ touched FIRST when both lie inside the horizon's range. So we bracket the truth:
180
+ β€’ order="stop_first" β†’ pessimistic: assume the stop fills first (lower bound)
181
+ β€’ order="target_first"β†’ optimistic: assume the target fills first (upper bound)
182
+ The real P&L is guaranteed to sit between the two. Returns net-of-cost P&L in %.
183
+ """
184
+ hit_stop = bool(stop_pct and dn_real <= -stop_pct)
185
+ hit_tp = bool(tp_pct and tp_pct > 0 and up_real >= tp_pct)
186
+ if order == "target_first":
187
+ if hit_tp:
188
+ gross = tp_pct
189
+ elif hit_stop:
190
+ gross = -stop_pct
191
+ else:
192
+ gross = ret_real
193
+ else: # stop_first (default, pessimistic)
194
+ if hit_stop:
195
+ gross = -stop_pct
196
+ elif hit_tp:
197
+ gross = tp_pct
198
+ else:
199
+ gross = ret_real # exit at window close (INTRADAY retβ‰ˆ0 β†’ β‰ˆflat)
200
  return gross - ROUND_TRIP_COST_PCT
201
 
202
 
 
216
 
217
 
218
  def _pnl_simulation(res: pd.DataFrame):
219
+ """Simulate taking the model's LONG (BULLISH / should_buy) calls, net of fees.
220
+
221
+ Reports a PESSIMISTIC↔OPTIMISTIC bracket: since daily-bar excursions can't tell us
222
+ whether the stop or the target was touched first, we show both orderings. The real
223
+ P&L sits between them. WinRate/Expect columns are the pessimistic (honest lower) bound.
224
+ """
225
  print("\n" + "=" * 78)
226
  print(" P&L TRADE SIMULATION β€” long-only BULLISH signals, market entry")
227
  print(f" Take-profit = expected(median) target Β· stop = model stop Β· cost = {ROUND_TRIP_COST_PCT}% round-trip")
228
+ print(" Bracket = [stop-first pessimistic … target-first optimistic]; truth sits between.")
229
  print("=" * 78)
230
+ hdr = f" {'TF':<9}{'#Trades':>8}{'WinRate':>9}{'Expect↓':>9}{'Expect↑':>9}{'AvgWin':>9}{'AvgLoss':>9}"
231
+ hdr += f"{'PF':>7}{'DayRet':>9}{'MaxDD':>9}"
232
  print(hdr)
233
+ print(" " + "-" * 84)
234
  for tf in TIMEFRAMES:
235
  d = res[(res["tf"] == tf) & (res["should_buy"] == 1)].copy()
236
  if d.empty:
237
  print(f" {tf:<9}{'0':>8} (no BULLISH signals)")
238
  continue
239
+ pess = np.array([_simulate_trade(r.expected_ret_pct, r.stop_loss_pct, r.up_real, r.dn_real, r.ret_real, "stop_first")
240
+ for r in d.itertuples()])
241
+ opt = np.array([_simulate_trade(r.expected_ret_pct, r.stop_loss_pct, r.up_real, r.dn_real, r.ret_real, "target_first")
242
+ for r in d.itertuples()])
243
+ d["pnl"] = pess
244
+ wins, losses = pess[pess > 0], pess[pess < 0]
245
  pf = (wins.sum() / abs(losses.sum())) if losses.sum() < 0 else 99.0
246
  # Equal-weighted daily equity curve (mean P&L per date, compounded across dates).
247
  daily = d.groupby("date")["pnl"].mean().sort_index()
248
  total_ret, max_dd = _equity_metrics(daily.tolist())
249
+ print(f" {tf:<9}{len(pess):>8}{np.mean(pess > 0):>9.0%}{np.mean(pess):>+9.2f}{np.mean(opt):>+9.2f}"
250
  f"{(np.mean(wins) if len(wins) else 0):>+9.2f}{(np.mean(losses) if len(losses) else 0):>+9.2f}"
251
+ f"{min(pf, 99.0):>7.2f}{total_ret:>+9.1f}{max_dd:>9.1f}")
252
+ print("\n Expect↓ = pessimistic (stop-first) mean net P&L/trade β€” the honest headline.")
253
+ print(" Expect↑ = optimistic (target-first) upper bound. DayRet uses Expect↓.")
254
+
255
+
256
+ # ── Stop Γ— take-profit sweep β€” find the profit-maximizing exit at each accuracy level ──
257
+ # TP candidates are the model's own up-move quantiles (how ambitious the target is); a
258
+ # LOWER quantile is reached more often (higher win rate) but banks a smaller gain.
259
+ _TP_LEVELS = [("q10", "up_q10"), ("q50", "up_q50"), ("q90", "up_q90")]
260
+ _STOP_MULTS = [0.5, 0.7, 1.0, 1.3] # Γ—model stop; <1 = "bring the stop down" (tighter)
261
+
262
+
263
+ def _pnl_sweep(res: pd.DataFrame, target_winrate: float = 0.85):
264
+ """Grid-search take-profit level Γ— stop multiplier per TF to maximize profit.
265
+
266
+ For each config, WinRate + Expect↓ (pessimistic) and Expect↑ (optimistic) are shown.
267
+ Then per TF we highlight (a) the max-expectancy config and (b) the best config whose
268
+ win rate β‰₯ target_winrate β€” so the profit↔accuracy trade-off is explicit.
269
+ """
270
+ print("\n" + "=" * 90)
271
+ print(f" STOP Γ— TAKE-PROFIT SWEEP β€” long BULLISH, net {ROUND_TRIP_COST_PCT}% cost Β· "
272
+ f"target win rate β‰₯ {target_winrate:.0%}")
273
+ print(" TP = model up-move quantile (lower = hit more often, banks less). StopΓ— scales the model stop.")
274
+ print("=" * 90)
275
+ for tf in TIMEFRAMES:
276
+ d = res[(res["tf"] == tf) & (res["should_buy"] == 1)].copy()
277
+ if d.empty:
278
+ print(f"\n {tf}: (no BULLISH signals)")
279
+ continue
280
+ print(f"\n {tf} (n={len(d)})")
281
+ print(f" {'TP':>5}{'StopΓ—':>7}{'WinRate':>9}{'Expect↓':>9}{'Expect↑':>9}{'AvgWin':>8}{'AvgLoss':>9}{'PF':>7}")
282
+ print(" " + "-" * 62)
283
+ rows = []
284
+ for tp_name, tp_col in _TP_LEVELS:
285
+ for sm in _STOP_MULTS:
286
+ tp = d[tp_col].to_numpy(float)
287
+ stop = d["stop_loss_pct"].to_numpy(float) * sm
288
+ pess = np.array([_simulate_trade(tp[i], stop[i], d.iloc[i].up_real, d.iloc[i].dn_real,
289
+ d.iloc[i].ret_real, "stop_first") for i in range(len(d))])
290
+ opt = np.array([_simulate_trade(tp[i], stop[i], d.iloc[i].up_real, d.iloc[i].dn_real,
291
+ d.iloc[i].ret_real, "target_first") for i in range(len(d))])
292
+ wins, losses = pess[pess > 0], pess[pess < 0]
293
+ pf = (wins.sum() / abs(losses.sum())) if losses.sum() < 0 else 99.0
294
+ wr = float(np.mean(pess > 0))
295
+ rows.append({"tp": tp_name, "sm": sm, "wr": wr, "exp_lo": float(np.mean(pess)),
296
+ "exp_hi": float(np.mean(opt)), "avg_win": float(np.mean(wins)) if len(wins) else 0.0,
297
+ "avg_loss": float(np.mean(losses)) if len(losses) else 0.0, "pf": min(pf, 99.0)})
298
+ print(f" {tp_name:>5}{sm:>7.1f}{wr:>9.0%}{np.mean(pess):>+9.2f}{np.mean(opt):>+9.2f}"
299
+ f"{(np.mean(wins) if len(wins) else 0):>+8.2f}{(np.mean(losses) if len(losses) else 0):>+9.2f}{min(pf,99.0):>7.2f}")
300
+ best = max(rows, key=lambda r: r["exp_lo"])
301
+ constrained = [r for r in rows if r["wr"] >= target_winrate]
302
+ best_c = max(constrained, key=lambda r: r["exp_lo"]) if constrained else None
303
+ print(f" β†’ MAX PROFIT: TP={best['tp']} StopΓ—{best['sm']} β†’ Expect↓ {best['exp_lo']:+.2f}% "
304
+ f"(win {best['wr']:.0%}, PF {best['pf']:.2f})")
305
+ if best_c:
306
+ print(f" β†’ BEST @β‰₯{target_winrate:.0%} win: TP={best_c['tp']} StopΓ—{best_c['sm']} β†’ "
307
+ f"Expect↓ {best_c['exp_lo']:+.2f}% (win {best_c['wr']:.0%}, PF {best_c['pf']:.2f})")
308
+ else:
309
+ print(f" β†’ No config reaches {target_winrate:.0%} win rate at any stop/TP "
310
+ f"(max win {max(r['wr'] for r in rows):.0%}).")
311
+
312
+
313
+ # ── Market-entry vs DIP-entry (limit buy at the modeled pullback) ─────────────
314
+ # The model already outputs buy_price_suggestion = price*(1+down_q50/100) β€” i.e. buy on the
315
+ # modeled median dip instead of at market. Entering lower gives a cushion above the stop AND
316
+ # puts the target closer, so filled trades should win more often. The cost: you only get
317
+ # filled when the price actually dips (fill-rate < 100%), and you miss runaway winners that
318
+ # never pulled back. This measures the trade-off with the same excursion data.
319
+ def _dip_entry_compare(res: pd.DataFrame):
320
+ print("\n" + "=" * 90)
321
+ print(" MARKET-ENTRY vs DIP-ENTRY (limit buy at model's suggested dip = down_q50)")
322
+ print(" DIP fills only if price reached the dip; win/expectancy shown for FILLED trades,")
323
+ print(" plus expectancy PER SIGNAL (unfilled = 0, since you couldn't deploy capital).")
324
+ print("=" * 90)
325
+ for tf in TIMEFRAMES:
326
+ d = res[(res["tf"] == tf) & (res["should_buy"] == 1)].copy()
327
+ if d.empty:
328
+ print(f"\n {tf}: (no BULLISH signals)")
329
+ continue
330
+ up_real = d["up_real"].to_numpy(float)
331
+ dn_real = d["dn_real"].to_numpy(float)
332
+ ret_real = d["ret_real"].to_numpy(float)
333
+ dip = np.minimum(d["down_q50"].to_numpy(float), 0.0) # modeled dip, % (<0)
334
+ print(f"\n {tf} (n={len(d)}) β€” dip median {np.median(dip):+.2f}%")
335
+ print(f" {'TP':>5}{'StopΓ—':>7}{'Entry':>8}{'Fill%':>7}{'Win%':>7}{'Exp/fill':>9}{'Exp/sig':>9}{'PF':>7}")
336
+ print(" " + "-" * 60)
337
+ for tp_name, tp_col in _TP_LEVELS:
338
+ for sm in (1.0, 1.3):
339
+ tp = d[tp_col].to_numpy(float)
340
+ stop = d["stop_loss_pct"].to_numpy(float) * sm
341
+ # MARKET entry: entry=close(0), excursions as-is, all rows filled.
342
+ mkt = np.array([_simulate_trade(tp[i], stop[i], up_real[i], dn_real[i], ret_real[i], "stop_first")
343
+ for i in range(len(d))])
344
+ # DIP entry: fill only if dn_real <= dip; shift excursions by -dip (cushion).
345
+ filled = dn_real <= dip
346
+ u = up_real - dip # larger upside from lower entry
347
+ dd = dn_real - dip # smaller (<=0) downside from entry
348
+ rc = ret_real - dip
349
+ dip_pnl = np.array([_simulate_trade(tp[i], stop[i], u[i], dd[i], rc[i], "stop_first")
350
+ for i in range(len(d))])
351
+ for label, pnl, fillmask in (("mkt", mkt, np.ones(len(d), bool)), ("dip", dip_pnl, filled)):
352
+ sub = pnl[fillmask]
353
+ if not len(sub):
354
+ continue
355
+ wins, losses = sub[sub > 0], sub[sub < 0]
356
+ pf = (wins.sum() / abs(losses.sum())) if losses.sum() < 0 else 99.0
357
+ fill_rate = float(fillmask.mean())
358
+ exp_fill = float(np.mean(sub))
359
+ exp_sig = float(np.sum(sub) / len(d)) # per signal (unfilled=0)
360
+ print(f" {tp_name:>5}{sm:>7.1f}{label:>8}{fill_rate:>7.0%}{np.mean(sub > 0):>7.0%}"
361
+ f"{exp_fill:>+9.2f}{exp_sig:>+9.2f}{min(pf, 99.0):>7.2f}")
362
 
363
 
364
  def _summary(res: pd.DataFrame):
 
419
  def main():
420
  ap = argparse.ArgumentParser()
421
  ap.add_argument("--csv", default=DEFAULT_CSV)
422
+ ap.add_argument("--sweep", action="store_true", help="run the stopΓ—take-profit profit-maximization grid")
423
+ ap.add_argument("--target-winrate", type=float, default=0.85, help="win-rate floor for the sweep's constrained best")
424
  args = ap.parse_args()
425
+ run(args.csv, sweep=args.sweep, target_winrate=args.target_winrate)
426
 
427
 
428
  if __name__ == "__main__":
research/ml_intraday_backtest.py CHANGED
@@ -40,6 +40,12 @@ PRED_TIMES = ["09:15", "12:00", "14:00"] # IST decision points
40
  CLOSE_TIME = "15:00" # validate touches up to this bar (15:00 IST)
41
  OUT_CSV = os.path.join(os.path.dirname(os.path.abspath(__file__)), "ml_intraday_results.csv")
42
  _NEWS_CACHE_DB = os.path.join(os.path.dirname(os.path.abspath(__file__)), "cache", "news_asof.sqlite")
 
 
 
 
 
 
43
 
44
 
45
  def _watchlist() -> list[str]:
@@ -60,7 +66,14 @@ def _sample_universe(n: int) -> list[str]:
60
  return []
61
 
62
 
63
- def _fetch_15m(ticker: str) -> pd.DataFrame | None:
 
 
 
 
 
 
 
64
  try:
65
  import yfinance as yf
66
  df = yf.download(ticker, period="60d", interval="15m", auto_adjust=True, progress=False)
@@ -70,16 +83,55 @@ def _fetch_15m(ticker: str) -> pd.DataFrame | None:
70
  df.columns = df.columns.get_level_values(0)
71
  idx = df.index
72
  df.index = idx.tz_convert("Asia/Kolkata") if idx.tz else idx.tz_localize("UTC").tz_convert("Asia/Kolkata")
73
- return df[["Open", "High", "Low", "Close"]].dropna()
 
 
 
 
 
 
74
  except Exception:
75
  return None
76
 
77
 
78
- def run(tickers: list[str], nifty_c, vix_c, use_scale: bool = True):
79
- predictor = MLPredictor()
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
80
  def run(tickers: list[str], nifty_c, vix_c, use_scale: bool = True,
81
  news: bool = False, news_llm: bool = False, news_lookback: int = 7,
82
- names: dict | None = None):
83
  predictor = MLPredictor()
84
  if not predictor.available:
85
  raise SystemExit("ml_predictor model not loaded β€” run ml_predictor/train.py first.")
@@ -92,7 +144,7 @@ def run(tickers: list[str], nifty_c, vix_c, use_scale: bool = True,
92
 
93
  rows = []
94
  for tk in tickers:
95
- intr = _fetch_15m(tk)
96
  if intr is None or intr.empty:
97
  continue
98
  try:
@@ -154,8 +206,29 @@ def run(tickers: list[str], nifty_c, vix_c, use_scale: bool = True,
154
  else:
155
  dir_hit = abs(close_ret) <= 0.9
156
  exp_ret = (pred["expected_target_price"] / entry - 1) * 100
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
157
  pnl = (_simulate_trade(exp_ret, pred["stop_loss_pct"], max_up, min_down, close_ret)
158
  if pred["should_buy"] else None)
 
 
 
 
 
159
  row = {
160
  "ticker": tk, "date": str(day), "pred_time": T,
161
  "direction": pred["direction"], "confidence": pred["confidence"],
@@ -166,8 +239,13 @@ def run(tickers: list[str], nifty_c, vix_c, use_scale: bool = True,
166
  "dir_hit": int(bool(dir_hit)),
167
  "graded_hit": int(grade in ("MIDPOINT_HIT", "RANGE_HIT")),
168
  "midpoint_hit": int(grade == "MIDPOINT_HIT"),
 
 
169
  "should_buy": int(pred["should_buy"]),
170
  "pnl": round(pnl, 3) if pnl is not None else None,
 
 
 
171
  }
172
  if news:
173
  # Re-derive WITH the news score β†’ A/B the news-adjusted direction/confidence.
@@ -206,8 +284,16 @@ def _report(df: pd.DataFrame, use_scale: bool = True):
206
  print(f" {df['ticker'].nunique()} tickers Β· {df['date'].nunique()} days Β· {len(df):,} predictions Β· "
207
  f"net {ROUND_TRIP_COST_PCT}% cost")
208
  print("=" * 84)
209
- print(f" {'pred_time':<11}{'N':>6}{'DirHit':>9}{'Graded':>9}{'MidHit':>9}{'#Buys':>7}{'BuyP&L':>9}{'BuyWin%':>9}")
210
- print(" " + "-" * 76)
 
 
 
 
 
 
 
 
211
  for T in PRED_TIMES:
212
  t = df[df["pred_time"] == T]
213
  if t.empty:
@@ -215,22 +301,39 @@ def _report(df: pd.DataFrame, use_scale: bool = True):
215
  buys = t[t["pnl"].notna()]
216
  avg = buys["pnl"].mean() if len(buys) else float("nan")
217
  win = (buys["pnl"] > 0).mean() if len(buys) else float("nan")
218
- print(f" {T:<11}{len(t):>6}{t['dir_hit'].mean():>9.0%}{t['graded_hit'].mean():>9.0%}"
219
- f"{t['midpoint_hit'].mean():>9.0%}{len(buys):>7}{avg:>+9.2f}{win:>9.0%}")
220
  allbuys = df[df["pnl"].notna()]
221
  print("\n Direction mix:", dict(df["direction"].value_counts()))
222
  if len(allbuys):
223
  print(f" Overall BUY (BULLISH) intraday trades: {len(allbuys)} Β· avg net P&L {allbuys['pnl'].mean():+.2f}% "
224
  f"Β· win {(allbuys['pnl'] > 0).mean():.0%}")
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
225
  if "graded_hit_news" in df.columns:
226
  nz = df[df["news_n"] > 0]
227
  print("\n " + "-" * 76)
228
  print(f" NEWS A/B (rows WITH β‰₯1 as-of headline: {len(nz):,} of {len(df):,}):")
229
- print(f" base : DirHit {df['dir_hit'].mean():.0%} Graded {df['graded_hit'].mean():.0%}")
230
- print(f" +news: DirHit {df['dir_hit_news'].mean():.0%} Graded {df['graded_hit_news'].mean():.0%} "
231
  f"(Ξ” {df['graded_hit_news'].mean()-df['graded_hit'].mean():+.1%})")
232
  if len(nz):
233
- print(f" on news-bearing rows only β€” base Graded {nz['graded_hit'].mean():.0%} β†’ "
234
  f"+news {nz['graded_hit_news'].mean():.0%} (Ξ” {nz['graded_hit_news'].mean()-nz['graded_hit'].mean():+.1%}); "
235
  f"flips to NEUTRAL: {(nz['direction_news']!=nz['direction']).sum()}")
236
  print(" NOTE: features are as-of the PREVIOUS daily close (the current model is trained on")
@@ -253,6 +356,7 @@ def main():
253
  ap.add_argument("--news", action="store_true", help="A/B as-of company news adjustment")
254
  ap.add_argument("--news-llm", action="store_true", help="use the LLM news analyst (else keyword scorer)")
255
  ap.add_argument("--news-lookback", type=int, default=7, help="news window in days before each trading day")
 
256
  args = ap.parse_args()
257
  if args.tickers:
258
  tickers = [t.strip() for t in args.tickers.split(",")]
@@ -267,7 +371,8 @@ def main():
267
  nifty_c = vix_c = None
268
  names = _name_map() if args.news else {}
269
  run(tickers, nifty_c, vix_c, use_scale=not args.no_scale,
270
- news=args.news, news_llm=args.news_llm, news_lookback=args.news_lookback, names=names)
 
271
 
272
 
273
  if __name__ == "__main__":
 
40
  CLOSE_TIME = "15:00" # validate touches up to this bar (15:00 IST)
41
  OUT_CSV = os.path.join(os.path.dirname(os.path.abspath(__file__)), "ml_intraday_results.csv")
42
  _NEWS_CACHE_DB = os.path.join(os.path.dirname(os.path.abspath(__file__)), "cache", "news_asof.sqlite")
43
+ # 15-min bars come from yfinance which only serves ~60 days of rolling history, and the same
44
+ # ~60-day window is identical for the rest of the calendar day β€” so we cache one pickle per
45
+ # ticker per fetch-date under research/cache/intraday_15m/. Re-runs on the same day skip the
46
+ # (slow, ~2-3 min for 30 tickers) re-download entirely. Pass --refresh to force a fresh pull.
47
+ # (pickle, not parquet, so no pyarrow/fastparquet dependency is needed.)
48
+ _BAR_CACHE_DIR = os.path.join(os.path.dirname(os.path.abspath(__file__)), "cache", "intraday_15m")
49
 
50
 
51
  def _watchlist() -> list[str]:
 
66
  return []
67
 
68
 
69
+ def _fetch_15m(ticker: str, refresh: bool = False) -> pd.DataFrame | None:
70
+ from datetime import date
71
+ cache_path = os.path.join(_BAR_CACHE_DIR, f"{ticker}_{date.today().isoformat()}.pkl")
72
+ if not refresh and os.path.exists(cache_path):
73
+ try:
74
+ return pd.read_pickle(cache_path)
75
+ except Exception:
76
+ pass # corrupt/unreadable cache β†’ fall through to re-download
77
  try:
78
  import yfinance as yf
79
  df = yf.download(ticker, period="60d", interval="15m", auto_adjust=True, progress=False)
 
83
  df.columns = df.columns.get_level_values(0)
84
  idx = df.index
85
  df.index = idx.tz_convert("Asia/Kolkata") if idx.tz else idx.tz_localize("UTC").tz_convert("Asia/Kolkata")
86
+ out = df[["Open", "High", "Low", "Close"]].dropna()
87
+ try:
88
+ os.makedirs(_BAR_CACHE_DIR, exist_ok=True)
89
+ out.to_pickle(cache_path)
90
+ except Exception:
91
+ pass # caching is best-effort; never fail the run over it
92
+ return out
93
  except Exception:
94
  return None
95
 
96
 
97
+ def _dip_path_pnl(win: pd.DataFrame, entry: float, dip_pct: float, tp_pct: float,
98
+ stop_pct: float) -> tuple[float | None, bool]:
99
+ """TRUE intraday dip-entry sim by walking 15-min bars in time order.
100
+
101
+ Place a limit buy at the modeled dip (entry*(1+dip_pct/100)); it fills only if a bar's
102
+ Low actually reaches it. After fill, the FIRST subsequent bar whose High hits the target
103
+ (fill*(1+tp_pct/100)) is a win; whose Low hits the stop (fill*(1-stop_pct/100)) is a loss;
104
+ otherwise exit at the 15:00 close. Returns (net_pnl_pct or None if never filled, filled).
105
+ """
106
+ dip_price = entry * (1 + dip_pct / 100.0)
107
+ filled = False
108
+ tgt = stop = fill_price = None
109
+ for _, bar in win.iterrows():
110
+ lo, hi = float(bar["Low"]), float(bar["High"])
111
+ if not filled:
112
+ if lo <= dip_price: # limit touched β†’ fill at the limit price
113
+ filled = True
114
+ fill_price = dip_price
115
+ tgt = fill_price * (1 + tp_pct / 100.0)
116
+ stop = fill_price * (1 - stop_pct / 100.0)
117
+ if lo <= stop: # same bar can resolve; stop-first (pessimistic)
118
+ return -stop_pct - ROUND_TRIP_COST_PCT, True
119
+ if hi >= tgt:
120
+ return tp_pct - ROUND_TRIP_COST_PCT, True
121
+ continue
122
+ if lo <= stop:
123
+ return -stop_pct - ROUND_TRIP_COST_PCT, True
124
+ if hi >= tgt:
125
+ return tp_pct - ROUND_TRIP_COST_PCT, True
126
+ if filled:
127
+ exit_ret = (float(win["Close"].iloc[-1]) / fill_price - 1) * 100.0
128
+ return exit_ret - ROUND_TRIP_COST_PCT, True
129
+ return None, False
130
+
131
+
132
  def run(tickers: list[str], nifty_c, vix_c, use_scale: bool = True,
133
  news: bool = False, news_llm: bool = False, news_lookback: int = 7,
134
+ names: dict | None = None, refresh: bool = False):
135
  predictor = MLPredictor()
136
  if not predictor.available:
137
  raise SystemExit("ml_predictor model not loaded β€” run ml_predictor/train.py first.")
 
144
 
145
  rows = []
146
  for tk in tickers:
147
+ intr = _fetch_15m(tk, refresh=refresh)
148
  if intr is None or intr.empty:
149
  continue
150
  try:
 
206
  else:
207
  dir_hit = abs(close_ret) <= 0.9
208
  exp_ret = (pred["expected_target_price"] / entry - 1) * 100
209
+ # Expected-target hit = the HEADLINE estimate (median q50) actually touched.
210
+ # This is the honest central metric β€” unlike the mechanical band-midpoint, whose
211
+ # touch-rate is misleading for a right-skewed [q10,q90] interval.
212
+ if pred["direction"] == "BULLISH":
213
+ exp_hit = max_up >= exp_ret
214
+ elif pred["direction"] == "BEARISH":
215
+ exp_hit = min_down <= exp_ret
216
+ else:
217
+ exp_hit = abs(close_ret) <= 0.9
218
+ # Far-bound coverage = the reported ceiling is a genuine ~q90 (rarely exceeded).
219
+ if pred["direction"] == "BULLISH":
220
+ far_cov = max_up <= pred["predicted_return_hi"]
221
+ elif pred["direction"] == "BEARISH":
222
+ far_cov = min_down >= pred["predicted_return_lo"]
223
+ else:
224
+ far_cov = True
225
  pnl = (_simulate_trade(exp_ret, pred["stop_loss_pct"], max_up, min_down, close_ret)
226
  if pred["should_buy"] else None)
227
+ # DIP-ENTRY: limit buy at the model's suggested dip (down_q50), true bar-walk fill.
228
+ dip_pct = float(pred.get("quantiles", {}).get("down_q50", 0.0))
229
+ dip_pnl, dip_filled = (
230
+ _dip_path_pnl(win, entry, dip_pct, exp_ret, pred["stop_loss_pct"])
231
+ if pred["should_buy"] else (None, False))
232
  row = {
233
  "ticker": tk, "date": str(day), "pred_time": T,
234
  "direction": pred["direction"], "confidence": pred["confidence"],
 
239
  "dir_hit": int(bool(dir_hit)),
240
  "graded_hit": int(grade in ("MIDPOINT_HIT", "RANGE_HIT")),
241
  "midpoint_hit": int(grade == "MIDPOINT_HIT"),
242
+ "exp_hit": int(bool(exp_hit)),
243
+ "far_cov": int(bool(far_cov)),
244
  "should_buy": int(pred["should_buy"]),
245
  "pnl": round(pnl, 3) if pnl is not None else None,
246
+ "dip_pnl": round(dip_pnl, 3) if dip_pnl is not None else None,
247
+ "dip_filled": int(dip_filled),
248
+ "dip_pct": round(dip_pct, 3),
249
  }
250
  if news:
251
  # Re-derive WITH the news score β†’ A/B the news-adjusted direction/confidence.
 
284
  print(f" {df['ticker'].nunique()} tickers Β· {df['date'].nunique()} days Β· {len(df):,} predictions Β· "
285
  f"net {ROUND_TRIP_COST_PCT}% cost")
286
  print("=" * 84)
287
+ print(" Column meaning (plain English):")
288
+ print(" RightDir% = we called up/down correctly")
289
+ print(" ReachFloor% = stock reached our SAFE low target (very likely level)")
290
+ print(" ReachMain% = stock reached our MAIN 'best-guess' target")
291
+ print(" UnderCeil% = stock stayed BELOW our best-case top (rarely blown past)")
292
+ print(" Win% = of the buys taken, how many actually made money after fees")
293
+ print(" " + "-" * 82)
294
+ print(f" {'time':<9}{'N':>6}{'RightDir%':>11}{'ReachFloor%':>13}{'ReachMain%':>12}"
295
+ f"{'UnderCeil%':>12}{'#Buys':>7}{'BuyP&L':>9}{'Win%':>7}")
296
+ print(" " + "-" * 82)
297
  for T in PRED_TIMES:
298
  t = df[df["pred_time"] == T]
299
  if t.empty:
 
301
  buys = t[t["pnl"].notna()]
302
  avg = buys["pnl"].mean() if len(buys) else float("nan")
303
  win = (buys["pnl"] > 0).mean() if len(buys) else float("nan")
304
+ print(f" {T:<9}{len(t):>6}{t['dir_hit'].mean():>11.0%}{t['graded_hit'].mean():>13.0%}"
305
+ f"{t['exp_hit'].mean():>12.0%}{t['far_cov'].mean():>12.0%}{len(buys):>7}{avg:>+9.2f}{win:>7.0%}")
306
  allbuys = df[df["pnl"].notna()]
307
  print("\n Direction mix:", dict(df["direction"].value_counts()))
308
  if len(allbuys):
309
  print(f" Overall BUY (BULLISH) intraday trades: {len(allbuys)} Β· avg net P&L {allbuys['pnl'].mean():+.2f}% "
310
  f"Β· win {(allbuys['pnl'] > 0).mean():.0%}")
311
+ # ── MARKET vs DIP entry (true 15-min bar-walk) ──────────────────────────
312
+ if "dip_pnl" in df.columns and len(allbuys):
313
+ dip = df[df["dip_filled"] == 1]
314
+ n_sig = len(allbuys)
315
+ print("\n " + "-" * 76)
316
+ print(" MARKET-ENTRY vs DIP-ENTRY (limit buy at model dip = down_q50; true bar-walk fill):")
317
+ print(f" MARKET: buys {n_sig} win {(allbuys['pnl']>0).mean():.0%} "
318
+ f"avg/trade {allbuys['pnl'].mean():+.2f}% avg/signal {allbuys['pnl'].mean():+.2f}%")
319
+ if len(dip):
320
+ fill_rate = len(dip) / n_sig
321
+ exp_sig = dip["dip_pnl"].sum() / n_sig # unfilled = 0 opportunity
322
+ print(f" DIP : fills {len(dip)} ({fill_rate:.0%}) win {(dip['dip_pnl']>0).mean():.0%} "
323
+ f"avg/fill {dip['dip_pnl'].mean():+.2f}% avg/signal {exp_sig:+.2f}%")
324
+ print(" β†’ DIP raises win-rate on the trades it takes, but only fills a fraction;")
325
+ print(" avg/signal is the honest deploy-all-capital number (misses count as 0).")
326
+ else:
327
+ print(" DIP : never filled (model predicted no meaningful dip).")
328
  if "graded_hit_news" in df.columns:
329
  nz = df[df["news_n"] > 0]
330
  print("\n " + "-" * 76)
331
  print(f" NEWS A/B (rows WITH β‰₯1 as-of headline: {len(nz):,} of {len(df):,}):")
332
+ print(f" base : RightDir {df['dir_hit'].mean():.0%} ReachFloor {df['graded_hit'].mean():.0%}")
333
+ print(f" +news: RightDir {df['dir_hit_news'].mean():.0%} ReachFloor {df['graded_hit_news'].mean():.0%} "
334
  f"(Ξ” {df['graded_hit_news'].mean()-df['graded_hit'].mean():+.1%})")
335
  if len(nz):
336
+ print(f" on news-bearing rows only β€” base ReachFloor {nz['graded_hit'].mean():.0%} β†’ "
337
  f"+news {nz['graded_hit_news'].mean():.0%} (Ξ” {nz['graded_hit_news'].mean()-nz['graded_hit'].mean():+.1%}); "
338
  f"flips to NEUTRAL: {(nz['direction_news']!=nz['direction']).sum()}")
339
  print(" NOTE: features are as-of the PREVIOUS daily close (the current model is trained on")
 
356
  ap.add_argument("--news", action="store_true", help="A/B as-of company news adjustment")
357
  ap.add_argument("--news-llm", action="store_true", help="use the LLM news analyst (else keyword scorer)")
358
  ap.add_argument("--news-lookback", type=int, default=7, help="news window in days before each trading day")
359
+ ap.add_argument("--refresh", action="store_true", help="ignore cached 15-min bars and re-download")
360
  args = ap.parse_args()
361
  if args.tickers:
362
  tickers = [t.strip() for t in args.tickers.split(",")]
 
371
  nifty_c = vix_c = None
372
  names = _name_map() if args.news else {}
373
  run(tickers, nifty_c, vix_c, use_scale=not args.no_scale,
374
+ news=args.news, news_llm=args.news_llm, news_lookback=args.news_lookback,
375
+ names=names, refresh=args.refresh)
376
 
377
 
378
  if __name__ == "__main__":
research/ml_intraday_results.csv CHANGED
The diff for this file is too large to render. See raw diff
 
static/app.js CHANGED
@@ -571,10 +571,23 @@ function renderPredCard(pred, showChart = true) {
571
  // ── News modal cache & renderer ───────────────────────────────────────────────
572
  const _newsDataCache = {};
573
 
 
 
 
 
 
 
 
 
 
 
 
 
574
  function showNewsModal(ticker) {
575
  const d = _newsDataCache[ticker] || {};
576
  const label = d.label || 'NEUTRAL';
577
  const summary = d.summary || '';
 
578
  const headlines = d.headlines || (d.key_headline ? [d.key_headline] : []);
579
  const sentimentColor = label === 'BULLISH' ? 'var(--green)' : label === 'BEARISH' ? 'var(--red)' : 'var(--yellow)';
580
  const sentimentText = label === 'BULLISH' ? 'POSITIVE' : label === 'BEARISH' ? 'NEGATIVE' : label || 'NEUTRAL';
@@ -585,13 +598,25 @@ function showNewsModal(ticker) {
585
 
586
  titleEl.textContent = `Latest News β€” ${ticker.replace(/\.(NS|BO)$/i, '')}`;
587
 
588
- const headlinesHtml = headlines.length
589
- ? headlines.map((h, i) => `<div class="news-modal-item"><span class="news-modal-num">${i + 1}</span><span class="news-modal-text">${h}</span></div>`).join('')
 
 
 
 
 
 
590
  : '<div style="color:var(--text-muted);font-size:13px">No headlines available.</div>';
591
 
 
 
 
 
 
592
  bodyEl.innerHTML = `
593
- <div style="margin-bottom:12px;display:flex;align-items:center;gap:8px">
594
  <span style="font-size:13px;font-weight:600;color:${sentimentColor}">Sentiment: ${sentimentText}</span>
 
595
  </div>
596
  ${summary ? `<div style="font-size:12px;color:var(--text-muted);margin-bottom:14px;font-style:italic">${summary}</div>` : ''}
597
  <div class="news-modal-list">${headlinesHtml}</div>`;
@@ -614,19 +639,22 @@ const _NO_TRADE_LABELS = {
614
  'neutral_signal': 'β€” Neutral (no edge)',
615
  'vix_block': '⚠ BLOCKED (VIX > 25)',
616
  'data_error': 'β€” Data unavailable',
617
- 'ai_unavailable': '⚠ AI unavailable',
618
  'market_closed': 'πŸ• Market closed',
619
- 'timeout': '⏱ Timed out',
620
  };
 
 
 
621
  const _NO_TRADE_REASONS = {
622
  'no_signal': 'No strategy signal is active for this timeframe right now.',
623
  'wrong_timeframe': 'A signal may exist, but it is not validated for this timeframe.',
624
  'neutral_signal': 'Strategy signals are firing, but the AI forecast is NEUTRAL β€” no directional edge, so there is no trade to take.',
625
  'vix_block': 'Market risk gate is active (India VIX above threshold).',
626
  'data_error': 'Required market data is incomplete, so the setup is skipped.',
627
- 'ai_unavailable': 'AI models are rate-limited or no API key is configured. No directional forecast can be made.',
628
  'market_closed': 'NSE is currently closed. INTRADAY prediction unavailable until market opens.',
629
- 'timeout': 'Prediction took too long (AI providers busy). Tap the cell to retry.',
630
  };
631
 
632
  // Render one TF cell β€” used by renderPickCard and _fetchAndUpdateTfCell for live updates.
@@ -640,10 +668,12 @@ function _renderOneTfCell(tf, d, pick) {
640
  // background (streaming top-picks). Show a spinner instead of a "no trade" label.
641
  if (d.no_trade_reason === 'pending') {
642
  const isBestTfP = bestTf !== null && (tf === bestTf);
643
- return `<div class="tf-cell tf-cell--loading${isBestTfP ? ' tf-cell--best' : ''}" id="tf-${safeId}-${tf}">
644
  <div class="tf-label">${tf === 'INTRADAY' ? 'Today' : tf}</div>
 
 
645
  <div class="tf-cell-spinner">⟳</div>
646
- <div style="font-size:11px;color:var(--text-muted);margin-top:4px">Analysing…</div>
647
  </div>`;
648
  }
649
 
@@ -664,6 +694,11 @@ function _renderOneTfCell(tf, d, pick) {
664
  const targetMid = (!isNoTrade && tfExpectedTarget !== null)
665
  ? `<div class="tf-mid-target">Target β‚Ή${num(tfExpectedTarget, 0)}</div>`
666
  : '';
 
 
 
 
 
667
  const retLabel = isNoTrade
668
  ? `<span class="no-trade-label">${_NO_TRADE_LABELS[noTradeReason] || 'β€” No trade'}</span>`
669
  : (d.ret_lo != null && d.ret_hi != null
@@ -696,18 +731,16 @@ function _renderOneTfCell(tf, d, pick) {
696
  const pd = d.predicted_direction;
697
  const pdLo = d.predicted_return_lo;
698
  const pdHi = d.predicted_return_hi;
699
- const pdColor = pd === 'BULLISH' ? 'var(--green)' : pd === 'BEARISH' ? 'var(--red)' : 'var(--text-muted)';
700
- const pdArrow = pd === 'BULLISH' ? 'β–²' : pd === 'BEARISH' ? 'β–Ό' : 'β—†';
701
- const pdRangeStr = (pdLo != null && pdHi != null) ? ` ${formatReturnRange(pdLo, pdHi, 1)}` : '';
702
  const af = d.ai_forecast;
703
- const aiUnavailable = af && af.source === 'ai_unavailable';
 
 
 
 
704
 
705
- const forecastHtml = (pd && !af)
706
- ? `<div class="tf-forecast" style="color:${pdColor}" title="ML price forecast (independent of buy signal)">${pdArrow} ${pd}${pdRangeStr}</div>`
707
- : '';
708
  let aiForecastHtml = '';
709
- if (aiUnavailable) {
710
- aiForecastHtml = `<div class="tf-ai-note" style="color:var(--text-muted)">⚠ AI unavailable β€” ${af.reasoning || 'models rate-limited'}<br>No directional forecast for this timeframe.</div>`;
711
  } else if (af && af.direction) {
712
  const afColor = af.direction === 'BULLISH' ? 'var(--green)' : af.direction === 'BEARISH' ? 'var(--red)' : 'var(--text-muted)';
713
  const afArrow = af.direction === 'BULLISH' ? 'β–²' : af.direction === 'BEARISH' ? 'β–Ό' : 'β—†';
@@ -736,39 +769,54 @@ function _renderOneTfCell(tf, d, pick) {
736
  ? Math.min(100, Math.max(2, (pickPrice - d.stop_loss) / (tfTarget - d.stop_loss) * 100)).toFixed(0)
737
  : 50;
738
  const entryLbl = d.entry_basis === 'est_open' ? 'Est. Open' : 'Entry';
 
 
 
 
739
  // No-trade cells (no signal, neutral, blocked, etc.) have no actionable entry/SL/target,
740
  // so the risk block is misleading β€” suppress it entirely.
741
  const riskLine = isNoTrade ? '' : `<div class="tf-risk ${hasSl ? (tgMet ? 'rr-ok' : 'rr-miss') : ''}">
742
- <div class="tf-risk-row"><span class="tf-entry-lbl" title="Based on previous close β‚Ή${num(pickPrice)} β€” actual fill at next-day open">${entryLbl}</span><span class="tf-entry-val">β‚Ή${num(tfEntry)}</span></div>
743
  ${hasSl ? `<div class="tf-risk-row"><span class="tf-sl-lbl">SL</span><span class="tf-sl-val">β‚Ή${num(d.stop_loss)}</span></div>` : ''}
744
  ${hasSl ? `<div class="tf-risk-row"><span class="tf-tgt-lbl">Tgt ${tgMet ? 'βœ“' : '⚠'}${d.actual_rr ? ` ${d.actual_rr}R` : ''}</span><span class="tf-tgt-val">β‚Ή${num(tfTarget)}</span></div>` : ''}
745
  ${hasSl ? `<div class="rr-bar"><div class="rr-bar-fill" style="width:${rrPct}%"></div></div>` : ''}
746
  </div>`;
747
 
748
  const isBestTf = bestTf !== null && (tf === bestTf);
749
- return `<div class="tf-cell${isBestTf ? ' tf-cell--best' : ''}" id="tf-${safeId}-${tf}">
 
 
 
 
 
750
  ${isBestTf ? '<span class="best-tf-badge">Best Bet</span>' : ''}
751
  <div class="tf-label">${tf === 'INTRADAY' ? 'Today' : tf}</div>
752
  <div class="tf-return" style="color:${isNoTrade ? 'var(--text-muted)' : retColor(d.midpoint||0)}">${retLabel}</div>
753
  ${noTradeDetail}
754
  ${priceRange}
755
  ${targetMid}
 
756
  ${dirHtml}
757
- ${forecastHtml}
758
- ${aiForecastHtml}
 
759
  ${riskLine}
760
  </div>`;
761
  }
762
 
763
  // Fetch one TF for a watchlist card and update its cell in place (no full-card reload).
764
- async function _fetchAndUpdateTfCell(ticker, tf, pick) {
 
 
 
 
765
  const safeId = ticker.replace(/[^a-zA-Z0-9]/g, '_');
766
  const cell = document.getElementById('tf-' + safeId + '-' + tf);
767
  if (!cell) return;
768
 
769
  const tfLabel = tf === 'INTRADAY' ? 'Today' : tf;
770
  cell.className = 'tf-cell tf-cell--loading';
771
- cell.innerHTML = `<div class="tf-label">${tfLabel}</div><div class="tf-cell-spinner">⟳</div><div style="font-size:11px;color:var(--text-muted);margin-top:4px">Loading…</div>`;
772
 
773
  try {
774
  const res = await fetch('/api/watchlist-pick/' + encodeURIComponent(ticker) + '/' + tf, {cache: 'no-store'});
@@ -786,12 +834,96 @@ async function _fetchAndUpdateTfCell(ticker, tf, pick) {
786
  tmp.innerHTML = _renderOneTfCell(tf, tfData, updatedPick);
787
  const newCell = tmp.firstElementChild;
788
  if (newCell) cell.replaceWith(newCell);
 
 
 
 
 
 
 
 
 
789
  } catch(e) {
790
- cell.className = 'tf-cell';
791
- cell.innerHTML = `<div class="tf-label">${tfLabel}</div><div class="tf-no-trade-reason" style="color:var(--red);font-size:11px">Retry failed β€” tap β†Ί to try again</div>`;
 
 
 
 
 
 
 
 
792
  }
793
  }
794
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
795
  // ── Render: Pick Card (Top 5) ─────────────────────────────────────────────────
796
  function renderPickCard(pick, idx, idPrefix = 'pick', mode = 'top5') {
797
  const dir = pick.direction || 'NEUTRAL';
@@ -832,6 +964,16 @@ function renderPickCard(pick, idx, idPrefix = 'pick', mode = 'top5') {
832
  const retryBtn = _hasRetryable
833
  ? `<button class="card-retry-btn" onclick="retryWatchlistCard('${pick.ticker}',this)">β†Ί Retry</button>`
834
  : '';
 
 
 
 
 
 
 
 
 
 
835
  const tfHtml = ['INTRADAY','1D','3D'].map(tf => _renderOneTfCell(tf, tfs[tf] || {}, pick)).join('');
836
 
837
  const safeCompany = (pick.company || '').replace(/'/g, "\\'");
@@ -932,6 +1074,7 @@ function renderPickCard(pick, idx, idPrefix = 'pick', mode = 'top5') {
932
  <div class="pick-body">
933
  <div class="pick-signals">
934
  ${convictionBadge}
 
935
  ${wlSummaryHtml}
936
  <div class="tf-grid">${tfHtml}</div>
937
  ${retryBtn}
@@ -941,7 +1084,7 @@ function renderPickCard(pick, idx, idPrefix = 'pick', mode = 'top5') {
941
  <span class="conf-pill ${confClass(pick.confidence)}">${pick.confidence}</span>
942
  </div>
943
  ${(news.key_headline || news.summary) ? `<div class="news-block" style="margin-top:12px;cursor:pointer" onclick="showNewsModal('${pick.ticker}')" title="Click to see latest headlines">
944
- ${news.key_headline ? `<div class="news-headline" style="font-size:11px;color:var(--text-muted);margin-bottom:4px;font-style:italic">πŸ“° ${news.key_headline}</div>` : ''}
945
  ${news.summary ? `<div class="news-sum">${news.summary}</div>` : ''}
946
  <div style="font-size:10px;color:var(--text-dim);margin-top:4px">Tap for full news β†’</div>
947
  </div>` : ''}
@@ -1116,13 +1259,62 @@ let _top5PollStart = 0; // epoch ms of the first poll β€” used for the el
1116
  // Render top-pick cards into a container and mount their mini charts.
1117
  // Shared by the final render and the streaming (partial) render.
1118
  function _renderTop5CardsInto(cardsEl, idPrefix, picks, bannerHtml = '') {
1119
- cardsEl.innerHTML = bannerHtml + picks.map((p, i) => renderPickCard(p, i, idPrefix)).join('');
1120
- picks.forEach(p => {
 
 
 
 
 
 
 
 
1121
  const tvId = 'tv-' + idPrefix + '-' + p.ticker.replace(/[^a-zA-Z0-9]/g, '_');
1122
  observeTvChart(tvId, p.ticker);
 
1123
  });
1124
  }
1125
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1126
  async function loadTop5Cards(cardsId, loadingId, limit = 20, forceRefresh = false) {
1127
  _clearAiRetry();
1128
  const cardsEl = document.getElementById(cardsId);
@@ -1310,10 +1502,13 @@ async function loadWatchlist(forceRefresh = false) {
1310
  if (!cardEl) return;
1311
  cardEl.outerHTML = renderPickCard(pick, 0, 'wl', 'watchlist');
1312
  applyWatchlistConvictionFilter(); // keep filter honored as cards resolve
 
1313
 
1314
- // Auto-fetch any TF cells that timed out β€” updates them in place as each resolves.
 
1315
  ['INTRADAY','1D','3D'].forEach(tf => {
1316
- if ((pick.timeframes || {})[tf]?.no_trade_reason === 'timeout') {
 
1317
  _fetchAndUpdateTfCell(ticker, tf, pick);
1318
  }
1319
  });
@@ -2397,6 +2592,80 @@ function renderValidationHistoryCard(h) {
2397
  `;
2398
  }
2399
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
2400
  async function loadValidation() {
2401
  // Pre-populate the AI-learn panel from the last saved learnings.json β€” no button click needed.
2402
  fetch('/api/learnings').then(r => r.json()).then(data => {
@@ -2461,44 +2730,9 @@ async function loadValidation() {
2461
 
2462
  // Update summary stats β€” show directional hit rate (BULLISH+BEARISH) as headline,
2463
  // all-predictions as a footnote so NEUTRAL misses don't bury the signal quality.
2464
- const summaryRaw = summData.summary || {};
2465
- const directional = summaryRaw.directional || summaryRaw; // fallback for old API shape
2466
- const allPreds = summaryRaw.all || summaryRaw;
2467
- const highConf = summaryRaw.high_conf || {};
2468
- ['INTRADAY', '1D', '3D'].forEach(tf => {
2469
- const dStat = directional[tf];
2470
- const aStat = allPreds[tf];
2471
- const el = document.getElementById(`vstat-${tf.toLowerCase()}`);
2472
- if (el && dStat) {
2473
- el.textContent = `${dStat.hit_rate_pct || 0}%`;
2474
- const subEl = document.getElementById(`vstat-${tf.toLowerCase()}-sub`);
2475
- if (subEl) {
2476
- const allNote = aStat ? ` (all: ${aStat.hit_rate_pct || 0}%)` : '';
2477
- subEl.textContent = `${dStat.hits}/${dStat.total} directional${allNote}`;
2478
- }
2479
- } else if (el && aStat) {
2480
- el.textContent = `${aStat.hit_rate_pct || 0}%`;
2481
- const subEl = document.getElementById(`vstat-${tf.toLowerCase()}-sub`);
2482
- if (subEl) subEl.textContent = `${aStat.hits}/${aStat.total} hits`;
2483
- }
2484
- });
2485
-
2486
- // HIGH-confidence card β€” aggregate the high_conf bucket across all timeframes.
2487
- // This is the profit bucket (backtest: 95-97% price-hit, +0.8-1.0%/trade).
2488
- const hcEl = document.getElementById('vstat-highconf');
2489
- if (hcEl) {
2490
- let hcHits = 0, hcTotal = 0;
2491
- Object.entries(highConf).forEach(([tf, s]) => {
2492
- if (tf === '5D') return; // 5D retired β€” exclude legacy rows from the headline number
2493
- hcHits += (s.hits || 0); hcTotal += (s.total || 0);
2494
- });
2495
- const hcPct = hcTotal > 0 ? Math.round(hcHits / hcTotal * 1000) / 10 : 0;
2496
- hcEl.textContent = hcTotal > 0 ? `${hcPct}%` : 'β€”';
2497
- const hcSub = document.getElementById('vstat-highconf-sub');
2498
- if (hcSub) hcSub.textContent = hcTotal > 0 ? `${hcHits}/${hcTotal} HIGH-conf` : 'no HIGH-conf yet';
2499
- }
2500
-
2501
- // Pending stat card β€” after auto-validation, reflect the refreshed count
2502
  const pendingEl = document.getElementById('vstat-pending');
2503
  const pendingSubEl = document.getElementById('vstat-pending-sub');
2504
  if (pendingEl) pendingEl.textContent = pendingList.length;
 
571
  // ── News modal cache & renderer ───────────────────────────────────────────────
572
  const _newsDataCache = {};
573
 
574
+ // Format an ISO 'YYYY-MM-DD' date as "21 Jul" plus a relative age ("today" / "3d ago").
575
+ function _fmtNewsDate(iso) {
576
+ if (!iso) return '';
577
+ const d = new Date(iso + 'T00:00:00');
578
+ if (isNaN(d)) return '';
579
+ const label = d.toLocaleDateString('en-IN', { day: '2-digit', month: 'short' });
580
+ const today = new Date(); today.setHours(0, 0, 0, 0);
581
+ const days = Math.round((today - d) / 86400000);
582
+ const rel = days <= 0 ? 'today' : days === 1 ? 'yesterday' : `${days}d ago`;
583
+ return `${label} Β· ${rel}`;
584
+ }
585
+
586
  function showNewsModal(ticker) {
587
  const d = _newsDataCache[ticker] || {};
588
  const label = d.label || 'NEUTRAL';
589
  const summary = d.summary || '';
590
+ const dated = Array.isArray(d.headlines_dated) ? d.headlines_dated : [];
591
  const headlines = d.headlines || (d.key_headline ? [d.key_headline] : []);
592
  const sentimentColor = label === 'BULLISH' ? 'var(--green)' : label === 'BEARISH' ? 'var(--red)' : 'var(--yellow)';
593
  const sentimentText = label === 'BULLISH' ? 'POSITIVE' : label === 'BEARISH' ? 'NEGATIVE' : label || 'NEUTRAL';
 
598
 
599
  titleEl.textContent = `Latest News β€” ${ticker.replace(/\.(NS|BO)$/i, '')}`;
600
 
601
+ // Prefer dated headlines (newest-first with publish date) when available.
602
+ const items = dated.length ? dated : headlines.map(h => ({ title: h, date: '' }));
603
+ const headlinesHtml = items.length
604
+ ? items.map((it, i) => {
605
+ const ds = _fmtNewsDate(it.date);
606
+ const dateHtml = ds ? `<span class="news-modal-date" style="display:block;font-size:11px;color:var(--text-muted);margin-top:2px">${ds}</span>` : '';
607
+ return `<div class="news-modal-item"><span class="news-modal-num">${i + 1}</span><span class="news-modal-text">${it.title}${dateHtml}</span></div>`;
608
+ }).join('')
609
  : '<div style="color:var(--text-muted);font-size:13px">No headlines available.</div>';
610
 
611
+ const asOf = _fmtNewsDate(d.latest_date);
612
+ const asOfHtml = asOf
613
+ ? `<span style="font-size:11px;color:var(--text-muted)">Latest: ${asOf}</span>`
614
+ : '';
615
+
616
  bodyEl.innerHTML = `
617
+ <div style="margin-bottom:12px;display:flex;align-items:center;gap:8px;flex-wrap:wrap">
618
  <span style="font-size:13px;font-weight:600;color:${sentimentColor}">Sentiment: ${sentimentText}</span>
619
+ ${asOfHtml}
620
  </div>
621
  ${summary ? `<div style="font-size:12px;color:var(--text-muted);margin-bottom:14px;font-style:italic">${summary}</div>` : ''}
622
  <div class="news-modal-list">${headlinesHtml}</div>`;
 
639
  'neutral_signal': 'β€” Neutral (no edge)',
640
  'vix_block': '⚠ BLOCKED (VIX > 25)',
641
  'data_error': 'β€” Data unavailable',
642
+ 'ai_unavailable': 'πŸ€– AI loading…',
643
  'market_closed': 'πŸ• Market closed',
644
+ 'timeout': 'πŸ€– AI loading…',
645
  };
646
+ // Max background auto-retries per AI cell (~1/min). Covers per-minute rate-limit
647
+ // resets and Ollama cold starts so the AI forecast fills in once a provider frees up.
648
+ const _AI_RETRY_MAX = 30;
649
  const _NO_TRADE_REASONS = {
650
  'no_signal': 'No strategy signal is active for this timeframe right now.',
651
  'wrong_timeframe': 'A signal may exist, but it is not validated for this timeframe.',
652
  'neutral_signal': 'Strategy signals are firing, but the AI forecast is NEUTRAL β€” no directional edge, so there is no trade to take.',
653
  'vix_block': 'Market risk gate is active (India VIX above threshold).',
654
  'data_error': 'Required market data is incomplete, so the setup is skipped.',
655
+ 'ai_unavailable': 'AI forecast is loading β€” retrying automatically as providers free up. The ML estimate is shown meanwhile.',
656
  'market_closed': 'NSE is currently closed. INTRADAY prediction unavailable until market opens.',
657
+ 'timeout': 'AI forecast is loading β€” retrying automatically as providers free up. The ML estimate is shown meanwhile.',
658
  };
659
 
660
  // Render one TF cell β€” used by renderPickCard and _fetchAndUpdateTfCell for live updates.
 
668
  // background (streaming top-picks). Show a spinner instead of a "no trade" label.
669
  if (d.no_trade_reason === 'pending') {
670
  const isBestTfP = bestTf !== null && (tf === bestTf);
671
+ return `<div class="tf-cell tf-cell--loading${isBestTfP ? ' tf-cell--best' : ''}" id="tf-${safeId}-${tf}" data-ai-dir="">
672
  <div class="tf-label">${tf === 'INTRADAY' ? 'Today' : tf}</div>
673
+ <div class="tf-fc-block tf-ml-block"><div class="tf-ml-slot" id="ml-${safeId}-${tf}"><div class="tf-ml-mini-loader">πŸ€– ML…</div></div></div>
674
+ <div class="tf-agree-slot" id="agree-${safeId}-${tf}"></div>
675
  <div class="tf-cell-spinner">⟳</div>
676
+ <div style="font-size:11px;color:var(--text-muted);margin-top:4px">AI analysing…</div>
677
  </div>`;
678
  }
679
 
 
694
  const targetMid = (!isNoTrade && tfExpectedTarget !== null)
695
  ? `<div class="tf-mid-target">Target β‚Ή${num(tfExpectedTarget, 0)}</div>`
696
  : '';
697
+ // Gap note: the live price has already run past the level this forecast projected from
698
+ // yesterday's close, so the predicted move may already be spent.
699
+ const gappedNote = (!isNoTrade && d.gapped_past_target)
700
+ ? `<div class="tf-gapped-note" title="The live price has already moved past the level this forecast projected from yesterday's close β€” the predicted edge may be largely spent.">⚑ Stock has gapped past target β€” move may already be done</div>`
701
+ : '';
702
  const retLabel = isNoTrade
703
  ? `<span class="no-trade-label">${_NO_TRADE_LABELS[noTradeReason] || 'β€” No trade'}</span>`
704
  : (d.ret_lo != null && d.ret_hi != null
 
731
  const pd = d.predicted_direction;
732
  const pdLo = d.predicted_return_lo;
733
  const pdHi = d.predicted_return_hi;
 
 
 
734
  const af = d.ai_forecast;
735
+ // AI is loading whenever this TF is in a retryable state (timeout/ai_unavailable) β€” the
736
+ // frontend keeps refetching in the background, so show a soft "loading" note, never a
737
+ // terminal error. The ML forecast renders independently in its own slot meanwhile.
738
+ const aiLoading = noTradeReason === 'timeout' || noTradeReason === 'ai_unavailable'
739
+ || (af && af.source === 'ai_unavailable');
740
 
 
 
 
741
  let aiForecastHtml = '';
742
+ if (aiLoading) {
743
+ aiForecastHtml = `<div class="tf-ai-note" style="color:var(--text-muted)">πŸ€– AI forecast loading β€” retrying automatically.<br>ML estimate shown meanwhile.</div>`;
744
  } else if (af && af.direction) {
745
  const afColor = af.direction === 'BULLISH' ? 'var(--green)' : af.direction === 'BEARISH' ? 'var(--red)' : 'var(--text-muted)';
746
  const afArrow = af.direction === 'BULLISH' ? 'β–²' : af.direction === 'BEARISH' ? 'β–Ό' : 'β—†';
 
769
  ? Math.min(100, Math.max(2, (pickPrice - d.stop_loss) / (tfTarget - d.stop_loss) * 100)).toFixed(0)
770
  : 50;
771
  const entryLbl = d.entry_basis === 'est_open' ? 'Est. Open' : 'Entry';
772
+ const isLiveEntry = d.entry_basis === 'live';
773
+ const entryTitle = isLiveEntry
774
+ ? 'Live intraday price β€” entry for a same-session trade'
775
+ : `Based on previous close β‚Ή${num(pickPrice)} β€” actual fill at next-day open`;
776
  // No-trade cells (no signal, neutral, blocked, etc.) have no actionable entry/SL/target,
777
  // so the risk block is misleading β€” suppress it entirely.
778
  const riskLine = isNoTrade ? '' : `<div class="tf-risk ${hasSl ? (tgMet ? 'rr-ok' : 'rr-miss') : ''}">
779
+ <div class="tf-risk-row"><span class="tf-entry-lbl" title="${entryTitle}">${entryLbl}${isLiveEntry ? ' <span style="opacity:.7">(live)</span>' : ''}</span><span class="tf-entry-val">β‚Ή${num(tfEntry)}</span></div>
780
  ${hasSl ? `<div class="tf-risk-row"><span class="tf-sl-lbl">SL</span><span class="tf-sl-val">β‚Ή${num(d.stop_loss)}</span></div>` : ''}
781
  ${hasSl ? `<div class="tf-risk-row"><span class="tf-tgt-lbl">Tgt ${tgMet ? 'βœ“' : '⚠'}${d.actual_rr ? ` ${d.actual_rr}R` : ''}</span><span class="tf-tgt-val">β‚Ή${num(tfTarget)}</span></div>` : ''}
782
  ${hasSl ? `<div class="rr-bar"><div class="rr-bar-fill" style="width:${rrPct}%"></div></div>` : ''}
783
  </div>`;
784
 
785
  const isBestTf = bestTf !== null && (tf === bestTf);
786
+ // ML mini-row: prefer inline d.ml, else the per-ticker ML cache (filled by _fetchAndFillMl).
787
+ const _mlData = d.ml || (_mlCache.get(pick.ticker || '') || {}).tfs?.[tf] || null;
788
+ const _mlSlotInner = _mlData ? _renderMlRow(tf, _mlData) : '<div class="tf-ml-mini-loader">πŸ€– ML…</div>';
789
+ const _aiDirAttr = (af && af.direction) ? af.direction : '';
790
+ const _agreeInner = _agreeHtml(_mlData && _mlData.direction, _aiDirAttr);
791
+ return `<div class="tf-cell${isBestTf ? ' tf-cell--best' : ''}" id="tf-${safeId}-${tf}" data-ai-dir="${_aiDirAttr}">
792
  ${isBestTf ? '<span class="best-tf-badge">Best Bet</span>' : ''}
793
  <div class="tf-label">${tf === 'INTRADAY' ? 'Today' : tf}</div>
794
  <div class="tf-return" style="color:${isNoTrade ? 'var(--text-muted)' : retColor(d.midpoint||0)}">${retLabel}</div>
795
  ${noTradeDetail}
796
  ${priceRange}
797
  ${targetMid}
798
+ ${gappedNote}
799
  ${dirHtml}
800
+ <div class="tf-fc-block tf-ml-block"><div class="tf-ml-slot" id="ml-${safeId}-${tf}">${_mlSlotInner}</div></div>
801
+ <div class="tf-agree-slot" id="agree-${safeId}-${tf}">${_agreeInner}</div>
802
+ <div class="tf-fc-block tf-ai-block">${aiForecastHtml}</div>
803
  ${riskLine}
804
  </div>`;
805
  }
806
 
807
  // Fetch one TF for a watchlist card and update its cell in place (no full-card reload).
808
+ // Fetch one TF for a watchlist card and update its cell in place (no full-card reload).
809
+ // attempt: self-retry counter. A transient 'timeout' (a provider that is only per-minute
810
+ // rate-limited) is re-fetched after a short delay β€” single TF only, so it catches the
811
+ // provider reset WITHOUT re-bursting the whole watchlist the way a full reload would.
812
+ async function _fetchAndUpdateTfCell(ticker, tf, pick, attempt = 0) {
813
  const safeId = ticker.replace(/[^a-zA-Z0-9]/g, '_');
814
  const cell = document.getElementById('tf-' + safeId + '-' + tf);
815
  if (!cell) return;
816
 
817
  const tfLabel = tf === 'INTRADAY' ? 'Today' : tf;
818
  cell.className = 'tf-cell tf-cell--loading';
819
+ cell.innerHTML = `<div class="tf-label">${tfLabel}</div><div class="tf-cell-spinner">⟳</div><div style="font-size:11px;color:var(--text-muted);margin-top:4px">πŸ€– AI loading…</div>`;
820
 
821
  try {
822
  const res = await fetch('/api/watchlist-pick/' + encodeURIComponent(ticker) + '/' + tf, {cache: 'no-store'});
 
834
  tmp.innerHTML = _renderOneTfCell(tf, tfData, updatedPick);
835
  const newCell = tmp.firstElementChild;
836
  if (newCell) cell.replaceWith(newCell);
837
+ _fetchAndFillMl(ticker); // refill ML row on the replaced cell (cached β†’ instant)
838
+ // AI still loading (rate-limited / provider busy)? Keep retrying this single cell every
839
+ // ~60s until a provider frees up β€” no terminal "AI unavailable". The ML forecast is
840
+ // already shown beside it, so the card is never blocked. Targeted per-cell retry does
841
+ // not touch the other cards/providers.
842
+ const _r = tfData.no_trade_reason;
843
+ if ((_r === 'timeout' || _r === 'ai_unavailable') && attempt < _AI_RETRY_MAX) {
844
+ setTimeout(() => _fetchAndUpdateTfCell(ticker, tf, pick, attempt + 1), 60000);
845
+ }
846
  } catch(e) {
847
+ // Network / server hiccup while fetching the AI forecast β€” keep retrying quietly
848
+ // (the ML estimate is already shown), don't surface a terminal error.
849
+ if (attempt < _AI_RETRY_MAX) {
850
+ cell.className = 'tf-cell tf-cell--loading';
851
+ cell.innerHTML = `<div class="tf-label">${tfLabel}</div><div class="tf-cell-spinner">⟳</div><div style="font-size:11px;color:var(--text-muted);margin-top:4px">πŸ€– AI loading…</div>`;
852
+ setTimeout(() => _fetchAndUpdateTfCell(ticker, tf, pick, attempt + 1), 60000);
853
+ } else {
854
+ cell.className = 'tf-cell';
855
+ cell.innerHTML = `<div class="tf-label">${tfLabel}</div><div class="tf-no-trade-reason" style="color:var(--text-muted);font-size:11px">πŸ€– AI still loading β€” tap β†Ί to retry</div>`;
856
+ }
857
  }
858
  }
859
 
860
+ // ── ML forecast (standalone quantile model) β€” instant, local, no rate limits ──
861
+ // Each TF cell reserves a "ml-<safeId>-<tf>" slot; ML fills it as soon as one fast
862
+ // /api/ml-predict call resolves, while the AI row keeps its own (slower) loader.
863
+ const _mlCache = new Map(); // ticker -> /api/ml-predict result (all 3 TFs)
864
+
865
+ // Render the ML mini-row for one timeframe from an ml_predictor TF object.
866
+ function _renderMlRow(tf, ml) {
867
+ if (!ml || !ml.direction) {
868
+ return '<div class="tf-ml-mini-loader" style="color:var(--text-muted)">πŸ€– ML n/a</div>';
869
+ }
870
+ const dir = ml.direction;
871
+ const color = dir === 'BULLISH' ? 'var(--green)' : dir === 'BEARISH' ? 'var(--red)' : 'var(--text-muted)';
872
+ const arrow = dir === 'BULLISH' ? 'β–²' : dir === 'BEARISH' ? 'β–Ό' : 'β—†';
873
+ const conf = ml.confidence ? ` Β· ${ml.confidence}` : '';
874
+ const range = (ml.predicted_return_lo != null && ml.predicted_return_hi != null)
875
+ ? ` ${formatReturnRange(ml.predicted_return_lo, ml.predicted_return_hi, 1)}` : '';
876
+ const hasTgt = ml.target_price_lo && ml.target_price_hi && ml.target_price_lo > 0 && ml.target_price_hi > 0;
877
+ const tgt = hasTgt
878
+ ? `<div class="tf-ml-target" style="color:${color}">β‚Ή${num(Math.min(ml.target_price_lo, ml.target_price_hi), 0)} – β‚Ή${num(Math.max(ml.target_price_lo, ml.target_price_hi), 0)}</div>`
879
+ : '';
880
+ // INTRADAY is a direction/range signal, not a tradeable long (per P&L analysis) β€” label it.
881
+ const note = (tf === 'INTRADAY' && dir === 'BULLISH')
882
+ ? '<span class="tf-ml-note" title="INTRADAY ML is a direction/range signal, not a standalone long">signal</span>' : '';
883
+ return `${tgt}<div class="tf-ml-forecast" style="color:${color}" title="ML quantile model β€” local, instant, no rate limits">πŸ€– ML: ${arrow} ${dir}${range}${conf}${note}</div>`;
884
+ }
885
+
886
+ // Agreement badge between the ML and AI directional calls.
887
+ function _agreeHtml(mlDir, aiDir) {
888
+ if (!mlDir || !aiDir) return '';
889
+ const m = String(mlDir).toUpperCase(), a = String(aiDir).toUpperCase();
890
+ if (m === 'NEUTRAL' || a === 'NEUTRAL' || m === 'N/A' || a === 'N/A') return '';
891
+ if (m === a) return `<div class="tf-agree tf-agree-yes" title="ML and AI agree on direction β€” strongest signal">βœ“ ML + AI agree</div>`;
892
+ if ((m === 'BULLISH' && a === 'BEARISH') || (m === 'BEARISH' && a === 'BULLISH'))
893
+ return `<div class="tf-agree tf-agree-no" title="ML and AI disagree on direction">⚠ ML / AI split</div>`;
894
+ return '';
895
+ }
896
+
897
+ // Fetch ML predictions for a ticker (one call = all 3 TFs) and fill each cell's ML slot.
898
+ // Cached per ticker so re-renders (top5 polling) refill instantly without a network hit.
899
+ async function _fetchAndFillMl(ticker) {
900
+ if (!ticker) return;
901
+ const safeId = ticker.replace(/[^a-zA-Z0-9]/g, '_');
902
+ try {
903
+ let ml = _mlCache.get(ticker);
904
+ if (!ml) {
905
+ const res = await fetch('/api/ml-predict/' + encodeURIComponent(ticker) + '?archive=1', { cache: 'no-store' });
906
+ ml = await res.json();
907
+ _mlCache.set(ticker, ml);
908
+ }
909
+ ['INTRADAY', '1D', '3D'].forEach(tf => _fillMlSlot(safeId, tf, ml));
910
+ } catch (e) {
911
+ ['INTRADAY', '1D', '3D'].forEach(tf => {
912
+ const slot = document.getElementById('ml-' + safeId + '-' + tf);
913
+ if (slot) slot.innerHTML = '<div class="tf-ml-mini-loader" style="color:var(--text-muted)">πŸ€– ML n/a</div>';
914
+ });
915
+ }
916
+ }
917
+
918
+ function _fillMlSlot(safeId, tf, ml) {
919
+ const slot = document.getElementById('ml-' + safeId + '-' + tf);
920
+ const mlTf = (ml && ml.available && ml.tfs) ? ml.tfs[tf] : null;
921
+ if (slot) slot.innerHTML = _renderMlRow(tf, mlTf);
922
+ const cell = document.getElementById('tf-' + safeId + '-' + tf);
923
+ const agree = document.getElementById('agree-' + safeId + '-' + tf);
924
+ if (agree) agree.innerHTML = _agreeHtml(mlTf && mlTf.direction, cell ? cell.dataset.aiDir : '');
925
+ }
926
+
927
  // ── Render: Pick Card (Top 5) ─────────────────────────────────────────────────
928
  function renderPickCard(pick, idx, idPrefix = 'pick', mode = 'top5') {
929
  const dir = pick.direction || 'NEUTRAL';
 
964
  const retryBtn = _hasRetryable
965
  ? `<button class="card-retry-btn" onclick="retryWatchlistCard('${pick.ticker}',this)">β†Ί Retry</button>`
966
  : '';
967
+ // ML-selection verdict: was this stock chosen by the ML selector, and did AI confirm?
968
+ let mlVerdictBadge = '';
969
+ if (pick.ml_selected) {
970
+ if (pick.ml_ai_verdict === 'confirmed')
971
+ mlVerdictBadge = `<span class="ml-verdict ml-verdict-ok" title="ML selected this stock and AI confirmed the direction">⭐ ML pick · AI confirmed</span>`;
972
+ else if (pick.ml_ai_verdict === 'disagree')
973
+ mlVerdictBadge = `<span class="ml-verdict ml-verdict-bad" title="ML selected this stock but AI disagrees on direction β€” trade with caution">⚠ ML pick Β· AI disagrees</span>`;
974
+ else
975
+ mlVerdictBadge = `<span class="ml-verdict ml-verdict-neutral" title="Surfaced by the ML selector">πŸ€– ML pick</span>`;
976
+ }
977
  const tfHtml = ['INTRADAY','1D','3D'].map(tf => _renderOneTfCell(tf, tfs[tf] || {}, pick)).join('');
978
 
979
  const safeCompany = (pick.company || '').replace(/'/g, "\\'");
 
1074
  <div class="pick-body">
1075
  <div class="pick-signals">
1076
  ${convictionBadge}
1077
+ ${mlVerdictBadge}
1078
  ${wlSummaryHtml}
1079
  <div class="tf-grid">${tfHtml}</div>
1080
  ${retryBtn}
 
1084
  <span class="conf-pill ${confClass(pick.confidence)}">${pick.confidence}</span>
1085
  </div>
1086
  ${(news.key_headline || news.summary) ? `<div class="news-block" style="margin-top:12px;cursor:pointer" onclick="showNewsModal('${pick.ticker}')" title="Click to see latest headlines">
1087
+ ${news.key_headline ? `<div class="news-headline" style="font-size:11px;color:var(--text-muted);margin-bottom:4px;font-style:italic">πŸ“° ${news.key_headline}${_fmtNewsDate(news.latest_date) ? ` <span style="font-style:normal;opacity:.75">Β· ${_fmtNewsDate(news.latest_date)}</span>` : ''}</div>` : ''}
1088
  ${news.summary ? `<div class="news-sum">${news.summary}</div>` : ''}
1089
  <div style="font-size:10px;color:var(--text-dim);margin-top:4px">Tap for full news β†’</div>
1090
  </div>` : ''}
 
1259
  // Render top-pick cards into a container and mount their mini charts.
1260
  // Shared by the final render and the streaming (partial) render.
1261
  function _renderTop5CardsInto(cardsEl, idPrefix, picks, bannerHtml = '') {
1262
+ _lastTop5 = { cardsEl, idPrefix, picks, banner: bannerHtml };
1263
+ const ordered = _applyTop5Sort(picks);
1264
+ const sortBar = `<div class="top5-sort-bar">
1265
+ <span class="top5-sort-lbl">Rank by</span>
1266
+ ${[['ai','AI'],['blend','Blend'],['ml','πŸ€– ML']].map(([m,l]) =>
1267
+ `<button class="top5-sort-btn${_top5Sort===m?' active':''}" onclick="_setTop5Sort('${m}')">${l}</button>`).join('')}
1268
+ <span class="top5-sort-hint">ML ranks on 1D/3D conviction</span>
1269
+ </div>`;
1270
+ cardsEl.innerHTML = sortBar + bannerHtml + ordered.map((p, i) => renderPickCard(p, i, idPrefix)).join('');
1271
+ ordered.forEach(p => {
1272
  const tvId = 'tv-' + idPrefix + '-' + p.ticker.replace(/[^a-zA-Z0-9]/g, '_');
1273
  observeTvChart(tvId, p.ticker);
1274
+ _fetchAndFillMl(p.ticker); // instant ML row; AI row keeps its own loader
1275
  });
1276
  }
1277
 
1278
+ // ── Top-pick ranking: AI (server order) / ML (quantile conviction) / Blend ─────
1279
+ let _top5Sort = 'ai';
1280
+ let _lastTop5 = { cardsEl: null, idPrefix: '', picks: [], banner: '' };
1281
+
1282
+ // ML conviction score for a ticker from its cached prediction (1D/3D horizons only β€”
1283
+ // the profit horizons; INTRADAY is a signal, not a tradeable long).
1284
+ function _mlPickScore(ticker) {
1285
+ const ml = _mlCache.get(ticker);
1286
+ if (!ml || !ml.available || !ml.tfs) return 0;
1287
+ let best = 0;
1288
+ ['1D', '3D'].forEach(tf => {
1289
+ const d = ml.tfs[tf];
1290
+ if (!d) return;
1291
+ const prob = d.confidence_prob || 0.5;
1292
+ let exp = 0;
1293
+ if (d.current_price && d.expected_target_price) exp = (d.expected_target_price / d.current_price - 1) * 100;
1294
+ else if (d.predicted_return_hi != null) exp = d.predicted_return_hi;
1295
+ const dirMult = d.direction === 'BULLISH' ? 1 : d.direction === 'BEARISH' ? 0.2 : 0.4;
1296
+ const s = prob * Math.abs(exp) * dirMult;
1297
+ if (s > best) best = s;
1298
+ });
1299
+ return best;
1300
+ }
1301
+
1302
+ function _applyTop5Sort(picks) {
1303
+ if (_top5Sort === 'ai') return picks;
1304
+ const arr = picks.map((p, i) => ({ p, ai: i, ml: _mlPickScore(p.ticker) }));
1305
+ if (_top5Sort === 'ml') { arr.sort((a, b) => b.ml - a.ml || a.ai - b.ai); return arr.map(x => x.p); }
1306
+ // Blend: average the AI position and the ML position (lower = better).
1307
+ const byMl = arr.slice().sort((a, b) => b.ml - a.ml);
1308
+ byMl.forEach((x, idx) => { x.mlRank = idx; });
1309
+ arr.sort((a, b) => (a.ai + a.mlRank) - (b.ai + b.mlRank));
1310
+ return arr.map(x => x.p);
1311
+ }
1312
+
1313
+ function _setTop5Sort(mode) {
1314
+ _top5Sort = mode;
1315
+ if (_lastTop5.cardsEl) _renderTop5CardsInto(_lastTop5.cardsEl, _lastTop5.idPrefix, _lastTop5.picks, _lastTop5.banner);
1316
+ }
1317
+
1318
  async function loadTop5Cards(cardsId, loadingId, limit = 20, forceRefresh = false) {
1319
  _clearAiRetry();
1320
  const cardsEl = document.getElementById(cardsId);
 
1502
  if (!cardEl) return;
1503
  cardEl.outerHTML = renderPickCard(pick, 0, 'wl', 'watchlist');
1504
  applyWatchlistConvictionFilter(); // keep filter honored as cards resolve
1505
+ _fetchAndFillMl(ticker); // instant ML row alongside the AI forecast
1506
 
1507
+ // Auto-fetch any TF cells whose AI is still loading β€” updates them in place as
1508
+ // each resolves, and keeps retrying in the background until a provider frees up.
1509
  ['INTRADAY','1D','3D'].forEach(tf => {
1510
+ const r = (pick.timeframes || {})[tf]?.no_trade_reason;
1511
+ if (r === 'timeout' || r === 'ai_unavailable') {
1512
  _fetchAndUpdateTfCell(ticker, tf, pick);
1513
  }
1514
  });
 
2592
  `;
2593
  }
2594
 
2595
+ // ── Validation model source (AI / ML / Both) ─────────────────────────────────
2596
+ let _valSource = 'ai';
2597
+ let _lastValSumm = null;
2598
+
2599
+ function setValSource(src) {
2600
+ _valSource = src;
2601
+ document.querySelectorAll('.val-source-btn').forEach(b =>
2602
+ b.classList.toggle('active', b.dataset.vsource === src));
2603
+ if (_lastValSumm) _applyValStats();
2604
+ }
2605
+
2606
+ // Render the validation stat cards for the currently-selected model source.
2607
+ // AI-only and ML-only read summary.by_source; Both reads the combined directional bucket.
2608
+ function _applyValStats() {
2609
+ const summData = _lastValSumm;
2610
+ if (!summData) return;
2611
+ const summaryRaw = summData.summary || {};
2612
+ const bySrc = summaryRaw.by_source || {};
2613
+ const directional = _valSource === 'ml' ? (bySrc.ml || {})
2614
+ : _valSource === 'ai' ? (bySrc.ai || {})
2615
+ : (summaryRaw.directional || {});
2616
+ const allPreds = summaryRaw.all || {};
2617
+ const highConf = summaryRaw.high_conf || {};
2618
+ const srcLabel = _valSource === 'ml' ? 'ML' : _valSource === 'ai' ? 'AI' : 'directional';
2619
+
2620
+ ['INTRADAY', '1D', '3D'].forEach(tf => {
2621
+ const dStat = directional[tf];
2622
+ const aStat = allPreds[tf];
2623
+ const el = document.getElementById(`vstat-${tf.toLowerCase()}`);
2624
+ const subEl = document.getElementById(`vstat-${tf.toLowerCase()}-sub`);
2625
+ if (el && dStat) {
2626
+ el.textContent = `${dStat.hit_rate_pct || 0}%`;
2627
+ if (subEl) {
2628
+ const allNote = (_valSource === 'both' && aStat) ? ` (all: ${aStat.hit_rate_pct || 0}%)` : '';
2629
+ subEl.textContent = `${dStat.hits}/${dStat.total} ${srcLabel}${allNote}`;
2630
+ }
2631
+ } else if (el) {
2632
+ el.textContent = 'β€”';
2633
+ if (subEl) subEl.textContent = `no ${srcLabel} data yet`;
2634
+ }
2635
+ });
2636
+
2637
+ // HIGH-confidence card is AI's profit bucket; only meaningful for AI/Both.
2638
+ const hcEl = document.getElementById('vstat-highconf');
2639
+ if (hcEl) {
2640
+ if (_valSource === 'ml') {
2641
+ hcEl.textContent = 'n/a';
2642
+ const hcSub = document.getElementById('vstat-highconf-sub');
2643
+ if (hcSub) hcSub.textContent = 'AI-only metric';
2644
+ } else {
2645
+ let hcHits = 0, hcTotal = 0;
2646
+ Object.entries(highConf).forEach(([tf, s]) => {
2647
+ if (tf === '5D') return;
2648
+ hcHits += (s.hits || 0); hcTotal += (s.total || 0);
2649
+ });
2650
+ const hcPct = hcTotal > 0 ? Math.round(hcHits / hcTotal * 1000) / 10 : 0;
2651
+ hcEl.textContent = hcTotal > 0 ? `${hcPct}%` : 'β€”';
2652
+ const hcSub = document.getElementById('vstat-highconf-sub');
2653
+ if (hcSub) hcSub.textContent = hcTotal > 0 ? `${hcHits}/${hcTotal} HIGH-conf` : 'no HIGH-conf yet';
2654
+ }
2655
+ }
2656
+
2657
+ // Agreement hint: when ML & AI agreed on direction, how often both hit.
2658
+ const hintEl = document.getElementById('val-agree-hint');
2659
+ if (hintEl) {
2660
+ const agree = summaryRaw.agreement || {};
2661
+ let aHits = 0, aTotal = 0;
2662
+ Object.values(agree).forEach(s => { aHits += (s.hits || 0); aTotal += (s.total || 0); });
2663
+ hintEl.textContent = aTotal > 0
2664
+ ? `🀝 When ML + AI agree: ${Math.round(aHits / aTotal * 1000) / 10}% both hit (${aHits}/${aTotal})`
2665
+ : '';
2666
+ }
2667
+ }
2668
+
2669
  async function loadValidation() {
2670
  // Pre-populate the AI-learn panel from the last saved learnings.json β€” no button click needed.
2671
  fetch('/api/learnings').then(r => r.json()).then(data => {
 
2730
 
2731
  // Update summary stats β€” show directional hit rate (BULLISH+BEARISH) as headline,
2732
  // all-predictions as a footnote so NEUTRAL misses don't bury the signal quality.
2733
+ // Source-aware: AI-only / ML-only / Both, driven by the model toggle.
2734
+ _lastValSumm = summData;
2735
+ _applyValStats();
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
2736
  const pendingEl = document.getElementById('vstat-pending');
2737
  const pendingSubEl = document.getElementById('vstat-pending-sub');
2738
  if (pendingEl) pendingEl.textContent = pendingList.length;
static/style.css CHANGED
@@ -458,9 +458,50 @@ input::placeholder { color: var(--text-dim); }
458
  .ai-buy-chip { display: inline-block; font-size: 9px; font-weight: 700; letter-spacing: .4px; padding: 1px 5px; border-radius: 3px; margin-right: 3px; vertical-align: middle; }
459
  .ai-buy-yes { background: rgba(34,197,94,.18); color: #22c55e; }
460
  .ai-buy-no { background: rgba(107,114,128,.18); color: var(--text-muted); }
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
461
  .news-ai-divergence { margin-top: 8px; font-size: 11px; color: var(--text-muted); line-height: 1.35; }
462
  .tf-prices { font-size: 12px; font-family: monospace; font-weight: 600; font-variant-numeric: tabular-nums; color: var(--text-muted); }
463
  .tf-mid-target { font-size: 10px; color: var(--text-muted); margin-top: 1px; }
 
 
 
 
 
 
 
 
 
 
 
 
464
  .tf-dir { font-size: 11px; color: var(--text-muted); }
465
  .tf-dir-row { display: flex; align-items: center; gap: 4px; justify-content: center; }
466
  .tf-chips { display: flex; gap: 4px; justify-content: center; flex-wrap: wrap; }
@@ -940,6 +981,15 @@ input::placeholder { color: var(--text-dim); }
940
  background: linear-gradient(90deg, rgba(34,197,94,0.22), rgba(16,185,129,0.14));
941
  color: var(--green); border: 1px solid rgba(34,197,94,0.35);
942
  }
 
 
 
 
 
 
 
 
 
943
  .vstat-card--highconf {
944
  border: 1px solid rgba(34,197,94,0.35);
945
  background: rgba(34,197,94,0.06);
 
458
  .ai-buy-chip { display: inline-block; font-size: 9px; font-weight: 700; letter-spacing: .4px; padding: 1px 5px; border-radius: 3px; margin-right: 3px; vertical-align: middle; }
459
  .ai-buy-yes { background: rgba(34,197,94,.18); color: #22c55e; }
460
  .ai-buy-no { background: rgba(107,114,128,.18); color: var(--text-muted); }
461
+
462
+ /* ── ML vs AI two-row forecast block ─────────────────────────────────────── */
463
+ .tf-fc-block { margin-top: 3px; padding-top: 3px; border-top: 1px solid var(--border); }
464
+ .tf-ml-block { position: relative; }
465
+ .tf-ml-slot { min-height: 15px; }
466
+ .tf-ml-forecast { font-size: 11px; font-weight: 600; letter-spacing: .3px; }
467
+ .tf-ml-target { font-size: 12px; font-weight: 700; letter-spacing: .2px; font-variant-numeric: tabular-nums; }
468
+ .tf-ml-mini-loader { font-size: 10px; color: var(--text-muted); opacity: .8; }
469
+ .tf-ml-note { font-size: 8px; font-weight: 700; letter-spacing: .3px; margin-left: 4px; padding: 0 4px; border-radius: 3px; background: var(--bg3); color: var(--text-muted); vertical-align: middle; }
470
+ .tf-agree-slot { min-height: 0; }
471
+ .tf-agree { font-size: 9px; font-weight: 700; letter-spacing: .3px; margin-top: 2px; padding: 1px 5px; border-radius: 3px; display: inline-block; }
472
+ .tf-agree-yes { background: rgba(34,197,94,.15); color: #22c55e; }
473
+ .tf-agree-no { background: rgba(234,179,8,.15); color: var(--yellow, #eab308); }
474
+
475
+ /* ── Top-pick ranking toggle (AI / Blend / ML) ───────────────────────────── */
476
+ .top5-sort-bar { display: flex; align-items: center; gap: 6px; flex-wrap: wrap; margin-bottom: 12px; grid-column: 1 / -1; }
477
+ .top5-sort-lbl { font-size: 11px; color: var(--text-muted); font-weight: 600; letter-spacing: .3px; }
478
+ .top5-sort-btn { font-size: 11px; font-weight: 600; padding: 4px 11px; border-radius: 6px; cursor: pointer; background: var(--bg3); border: 1px solid var(--border); color: var(--text-dim); }
479
+ .top5-sort-btn:hover { border-color: var(--border2); }
480
+ .top5-sort-btn.active { background: var(--accent, #6366f1); border-color: var(--accent, #6366f1); color: #fff; }
481
+ .top5-sort-hint { font-size: 10px; color: var(--text-dim); font-style: italic; margin-left: auto; }
482
+
483
+ /* ── Validation model source toggle (AI / ML / Both) ─────────────────────── */
484
+ .val-source-bar { display: flex; align-items: center; gap: 6px; flex-wrap: wrap; margin-bottom: 12px; }
485
+ .val-source-lbl { font-size: 11px; color: var(--text-muted); font-weight: 600; letter-spacing: .3px; }
486
+ .val-source-btn { font-size: 11px; font-weight: 600; padding: 4px 11px; border-radius: 6px; cursor: pointer; background: var(--bg3); border: 1px solid var(--border); color: var(--text-dim); }
487
+ .val-source-btn:hover { border-color: var(--border2); }
488
+ .val-source-btn.active { background: var(--accent, #6366f1); border-color: var(--accent, #6366f1); color: #fff; }
489
+ .val-source-hint { font-size: 11px; color: var(--text-muted); margin-left: auto; font-weight: 600; }
490
  .news-ai-divergence { margin-top: 8px; font-size: 11px; color: var(--text-muted); line-height: 1.35; }
491
  .tf-prices { font-size: 12px; font-family: monospace; font-weight: 600; font-variant-numeric: tabular-nums; color: var(--text-muted); }
492
  .tf-mid-target { font-size: 10px; color: var(--text-muted); margin-top: 1px; }
493
+ .tf-gapped-note {
494
+ font-size: 10px;
495
+ font-weight: 600;
496
+ line-height: 1.3;
497
+ margin-top: 3px;
498
+ padding: 2px 6px;
499
+ border-radius: 4px;
500
+ background: var(--yellow-dim);
501
+ color: var(--yellow);
502
+ border: 1px solid rgba(245,158,11,.3);
503
+ max-width: 160px;
504
+ }
505
  .tf-dir { font-size: 11px; color: var(--text-muted); }
506
  .tf-dir-row { display: flex; align-items: center; gap: 4px; justify-content: center; }
507
  .tf-chips { display: flex; gap: 4px; justify-content: center; flex-wrap: wrap; }
 
981
  background: linear-gradient(90deg, rgba(34,197,94,0.22), rgba(16,185,129,0.14));
982
  color: var(--green); border: 1px solid rgba(34,197,94,0.35);
983
  }
984
+ /* ML-selection verdict badge (ML pick Β· AI confirmed / disagrees) */
985
+ .ml-verdict {
986
+ display: inline-block; margin-bottom: 10px; margin-left: 6px;
987
+ font-size: 11px; font-weight: 700; letter-spacing: .3px;
988
+ padding: 4px 10px; border-radius: 6px; border: 1px solid transparent;
989
+ }
990
+ .ml-verdict-ok { background: rgba(99,102,241,0.16); color: #818cf8; border-color: rgba(99,102,241,0.35); }
991
+ .ml-verdict-bad { background: rgba(234,179,8,0.14); color: var(--yellow, #eab308); border-color: rgba(234,179,8,0.32); }
992
+ .ml-verdict-neutral { background: var(--bg3); color: var(--text-muted); border-color: var(--border); }
993
  .vstat-card--highconf {
994
  border: 1px solid rgba(34,197,94,0.35);
995
  background: rgba(34,197,94,0.06);
templates/index.html CHANGED
@@ -33,7 +33,7 @@
33
  @keyframes apl-spin { to { transform: rotate(360deg); } }
34
  .apl-hint { font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', sans-serif; font-size: 11px; color: #5a6278; }
35
  </style>
36
- <link rel="stylesheet" href="/static/style.css?v=20260721a">
37
  <script src="https://unpkg.com/lightweight-charts@4.2.0/dist/lightweight-charts.standalone.production.js"></script>
38
  </head>
39
  <body>
@@ -268,6 +268,14 @@
268
  <p>Running validation checks...</p>
269
  </div>
270
 
 
 
 
 
 
 
 
 
271
  <div class="validation-stats" id="validation-stats">
272
  <div class="vstat-card">
273
  <span class="vstat-label">Today Hit Rate</span>
@@ -436,6 +444,6 @@
436
  </a>
437
  </nav>
438
 
439
- <script src="/static/app.js?v=20260721a"></script>
440
  </body>
441
  </html>
 
33
  @keyframes apl-spin { to { transform: rotate(360deg); } }
34
  .apl-hint { font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', sans-serif; font-size: 11px; color: #5a6278; }
35
  </style>
36
+ <link rel="stylesheet" href="/static/style.css?v=20260721f">
37
  <script src="https://unpkg.com/lightweight-charts@4.2.0/dist/lightweight-charts.standalone.production.js"></script>
38
  </head>
39
  <body>
 
268
  <p>Running validation checks...</p>
269
  </div>
270
 
271
+ <div class="val-source-bar">
272
+ <span class="val-source-lbl">Model</span>
273
+ <button class="val-source-btn active" data-vsource="ai" onclick="setValSource('ai')">✨ AI</button>
274
+ <button class="val-source-btn" data-vsource="ml" onclick="setValSource('ml')">πŸ€– ML</button>
275
+ <button class="val-source-btn" data-vsource="both" onclick="setValSource('both')">Both</button>
276
+ <span class="val-source-hint" id="val-agree-hint"></span>
277
+ </div>
278
+
279
  <div class="validation-stats" id="validation-stats">
280
  <div class="vstat-card">
281
  <span class="vstat-label">Today Hit Rate</span>
 
444
  </a>
445
  </nav>
446
 
447
+ <script src="/static/app.js?v=20260721f"></script>
448
  </body>
449
  </html>
top5_picker.py CHANGED
@@ -20,6 +20,47 @@ from predictor_core import predict_stock_v2, DEFAULT_UNIVERSE, timeframe_to_date
20
 
21
  TIMEFRAMES = ["INTRADAY", "1D", "3D"] # 5D removed β€” 1D/3D are the profit horizons
22
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
23
  # Universe for top picks β€” the WHOLE NSE market (all cap tiers), sourced via
24
  # universe.get_universe() (NSE full equity list β†’ Nifty-500 CSV β†’ static fallback),
25
  # so mid/small-caps are included, not just the top 500 by market cap. Never empty even
@@ -60,8 +101,12 @@ def _order_and_cap_scan(universe: list[str], cap: int) -> list[str]:
60
  if cap <= 0 or len(universe) <= cap:
61
  return universe
62
  try:
 
 
 
 
63
  from data_sources import cached_tickers
64
- warm = cached_tickers("1y")
65
  except Exception:
66
  warm = set()
67
 
@@ -357,9 +402,80 @@ def get_top5_picks(
357
 
358
  valid_scan = [p for p in scan_preds.values() if p and not p.get("error")]
359
  valid_scan.sort(key=_score_scan, reverse=True)
360
- # Pass all valid candidates to Phase 2 β€” no artificial pool cap.
361
- # Phase 2 trims to top_n after AI scoring.
362
- candidates = valid_scan
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
363
 
364
  market_from_scan = next((p.get("market", {}) for p in scan_preds.values() if p and p.get("market")), {})
365
  shared_ctx = {
@@ -477,6 +593,8 @@ def get_top5_picks(
477
  price = stock.get("price") or 0
478
  anchor_atr14 = (ai_preds.get((ticker, "3D"), {}).get("risk") or {}).get("atr14")
479
  timeframe_data: dict[str, dict] = {}
 
 
480
 
481
  for tf in TIMEFRAMES:
482
  base_stock = ai_preds.get((ticker, tf), {})
@@ -503,6 +621,7 @@ def get_top5_picks(
503
  "target_price_hi": base_stock.get("target_price_hi"),
504
  "expected_target_price": base_stock.get("expected_target_price"),
505
  "expected_entry_price": base_stock.get("expected_entry_price", price),
 
506
  "direction": base_stock.get("direction", "NO TRADE"),
507
  "confidence": base_stock.get("confidence", "LOW"),
508
  "no_trade_reason": base_stock.get("no_trade_reason"),
@@ -511,6 +630,7 @@ def get_top5_picks(
511
  "predicted_return_lo": base_stock.get("predicted_return_lo"),
512
  "predicted_return_hi": base_stock.get("predicted_return_hi"),
513
  "ai_forecast": base_stock.get("ai_forecast"),
 
514
  "stop_loss": sl,
515
  "stop_loss_pct": sl_pct,
516
  "min_target": tgt,
@@ -529,6 +649,25 @@ def get_top5_picks(
529
  pick["signals"] = {}
530
  pick["signal_count"] = 0
531
  pick["timeframes"] = timeframe_data
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
532
  pick["_score_best"] = best_score
533
  assembled.append(pick)
534
 
 
20
 
21
  TIMEFRAMES = ["INTRADAY", "1D", "3D"] # 5D removed β€” 1D/3D are the profit horizons
22
 
23
+
24
+ def _slim_ml_tf(m: Optional[dict]) -> Optional[dict]:
25
+ """Extract the frontend-facing subset of an ml_predictor TF object (predict_all_tf['tfs'][tf])."""
26
+ if not m:
27
+ return None
28
+ return {
29
+ "direction": m.get("direction"),
30
+ "confidence": m.get("confidence"),
31
+ "confidence_prob": m.get("confidence_prob"),
32
+ "predicted_return_lo": m.get("predicted_return_lo"),
33
+ "predicted_return_hi": m.get("predicted_return_hi"),
34
+ "target_price_lo": m.get("target_price_lo"),
35
+ "target_price_hi": m.get("target_price_hi"),
36
+ "expected_target_price": m.get("expected_target_price"),
37
+ "current_price": m.get("current_price"),
38
+ }
39
+
40
+
41
+ def _ml_conviction_score(ml_res: Optional[dict]) -> float:
42
+ """ML selection score for a stock β€” 1D/3D only (the profit horizons; INTRADAY is a
43
+ signal, not a tradeable long). confidence_prob Γ— |expected return| Γ— direction multiplier."""
44
+ if not ml_res or not ml_res.get("available"):
45
+ return 0.0
46
+ tfs = ml_res.get("tfs", {}) or {}
47
+ best = 0.0
48
+ for tf in ("1D", "3D"):
49
+ d = tfs.get(tf) or {}
50
+ prob = d.get("confidence_prob") or 0.5
51
+ cur = d.get("current_price") or 0
52
+ exp = 0.0
53
+ if cur and d.get("expected_target_price"):
54
+ exp = (d["expected_target_price"] / cur - 1) * 100
55
+ elif d.get("predicted_return_hi") is not None:
56
+ exp = d["predicted_return_hi"]
57
+ direction = d.get("direction")
58
+ dir_mult = 1.0 if direction == "BULLISH" else 0.2 if direction == "BEARISH" else 0.4
59
+ s = prob * abs(exp) * dir_mult
60
+ if s > best:
61
+ best = s
62
+ return best
63
+
64
  # Universe for top picks β€” the WHOLE NSE market (all cap tiers), sourced via
65
  # universe.get_universe() (NSE full equity list β†’ Nifty-500 CSV β†’ static fallback),
66
  # so mid/small-caps are included, not just the top 500 by market cap. Never empty even
 
101
  if cap <= 0 or len(universe) <= cap:
102
  return universe
103
  try:
104
+ # Match the period the scan (predict_stock_v2 β†’ _load_ticker_data) actually
105
+ # caches: "2y". Checking "1y" here (the old value) meant the warm set was almost
106
+ # always empty, so cache-first ordering silently no-op'd. Phase 1b's ML pass also
107
+ # reads the same "2y" row, so warm stocks skip the OHLCV re-fetch entirely.
108
  from data_sources import cached_tickers
109
+ warm = cached_tickers("2y")
110
  except Exception:
111
  warm = set()
112
 
 
402
 
403
  valid_scan = [p for p in scan_preds.values() if p and not p.get("error")]
404
  valid_scan.sort(key=_score_scan, reverse=True)
405
+
406
+ # ── Phase 1b: ML conviction pass (standalone quantile model, no LLM) ──────
407
+ # The ml_predictor is local + instant + rate-limit-free, so it can score the
408
+ # market as a genuine SELECTOR (not just a display layer). We score the top
409
+ # signal-ranked candidates, then BLEND: the candidate order fed to Phase 2 is
410
+ # the interleaved union of the signal-top and the ML-top, so AI confirms BOTH
411
+ # sets. ML predictions are stashed per ticker (closure) so _assemble can attach
412
+ # them + compute an ML/AI agreement verdict. Bounded to _ML_SCAN_N + a deadline.
413
+ _ML_SCAN_N = 300
414
+ ml_preds_by_ticker: dict[str, dict] = {}
415
+ try:
416
+ from ml_predictor.infer import get_ml_predictor
417
+ _mlp = get_ml_predictor()
418
+ except Exception:
419
+ _mlp = None
420
+
421
+ if _mlp is not None and getattr(_mlp, "available", False) and valid_scan:
422
+ ml_pool = valid_scan[:_ML_SCAN_N]
423
+ _publish({
424
+ "computing": True, "phase": "scanning",
425
+ "scanned": _uni_n, "scan_total": _uni_n, "picks": [], "generated_at": None,
426
+ "message": f"ML scoring {len(ml_pool)} shortlisted candidates…",
427
+ })
428
+
429
+ def _ml_one(p: dict):
430
+ tk = p.get("ticker")
431
+ try:
432
+ return tk, _mlp.predict_all_tf(tk, live_price=p.get("price"))
433
+ except Exception:
434
+ return tk, None
435
+
436
+ ml_start = time.time()
437
+ _ml_deadline = 120
438
+ _ml_ex = ThreadPoolExecutor(max_workers=min(8, len(ml_pool)))
439
+ _ml_futs = {_ml_ex.submit(_ml_one, p): p for p in ml_pool}
440
+ try:
441
+ for fut in _cf.as_completed(_ml_futs, timeout=_ml_deadline):
442
+ tk, res = fut.result()
443
+ if res and res.get("available"):
444
+ ml_preds_by_ticker[tk] = res
445
+ except _cf.TimeoutError:
446
+ logger.info("[TOP5] PHASE 1b ML deadline (%ds) reached", _ml_deadline)
447
+ for fut in _ml_futs:
448
+ if not fut.done():
449
+ fut.cancel()
450
+ _ml_ex.shutdown(wait=False)
451
+ logger.info("[TOP5] PHASE 1b (ML conviction): scored %d/%d in %.1fs",
452
+ len(ml_preds_by_ticker), len(ml_pool), time.time() - ml_start)
453
+
454
+ # BLEND the candidate order: interleave signal-ranked and ML-ranked so both
455
+ # tops reach Phase 2 first (Phase 2 processes in submission order under a deadline).
456
+ if ml_preds_by_ticker:
457
+ ml_ranked = sorted(ml_preds_by_ticker.keys(),
458
+ key=lambda tk: _ml_conviction_score(ml_preds_by_ticker.get(tk)),
459
+ reverse=True)
460
+ signal_order = [p.get("ticker") for p in valid_scan]
461
+ by_ticker = {p.get("ticker"): p for p in valid_scan}
462
+ merged: list[str] = []
463
+ seen: set[str] = set()
464
+ si = mi = 0
465
+ while si < len(signal_order) or mi < len(ml_ranked):
466
+ if si < len(signal_order):
467
+ t = signal_order[si]; si += 1
468
+ if t not in seen:
469
+ seen.add(t); merged.append(t)
470
+ if mi < len(ml_ranked):
471
+ t = ml_ranked[mi]; mi += 1
472
+ if t not in seen:
473
+ seen.add(t); merged.append(t)
474
+ candidates = [by_ticker[t] for t in merged if t in by_ticker]
475
+ else:
476
+ # Pass all valid candidates to Phase 2 β€” no artificial pool cap.
477
+ # Phase 2 trims to top_n after AI scoring.
478
+ candidates = valid_scan
479
 
480
  market_from_scan = next((p.get("market", {}) for p in scan_preds.values() if p and p.get("market")), {})
481
  shared_ctx = {
 
593
  price = stock.get("price") or 0
594
  anchor_atr14 = (ai_preds.get((ticker, "3D"), {}).get("risk") or {}).get("atr14")
595
  timeframe_data: dict[str, dict] = {}
596
+ ml_res = ml_preds_by_ticker.get(ticker)
597
+ ml_tfs = (ml_res.get("tfs", {}) if (ml_res and ml_res.get("available")) else {}) or {}
598
 
599
  for tf in TIMEFRAMES:
600
  base_stock = ai_preds.get((ticker, tf), {})
 
621
  "target_price_hi": base_stock.get("target_price_hi"),
622
  "expected_target_price": base_stock.get("expected_target_price"),
623
  "expected_entry_price": base_stock.get("expected_entry_price", price),
624
+ "gapped_past_target": base_stock.get("gapped_past_target", False),
625
  "direction": base_stock.get("direction", "NO TRADE"),
626
  "confidence": base_stock.get("confidence", "LOW"),
627
  "no_trade_reason": base_stock.get("no_trade_reason"),
 
630
  "predicted_return_lo": base_stock.get("predicted_return_lo"),
631
  "predicted_return_hi": base_stock.get("predicted_return_hi"),
632
  "ai_forecast": base_stock.get("ai_forecast"),
633
+ "ml": _slim_ml_tf(ml_tfs.get(tf)),
634
  "stop_loss": sl,
635
  "stop_loss_pct": sl_pct,
636
  "min_target": tgt,
 
649
  pick["signals"] = {}
650
  pick["signal_count"] = 0
651
  pick["timeframes"] = timeframe_data
652
+
653
+ # ── ML/AI agreement verdict (AI confirms the ML selection, or not) ──
654
+ # ml_selected = this stock was scored by the ML selector this run.
655
+ # Verdict on the best timeframe: confirmed (same dir) β†’ boost so it
656
+ # surfaces; disagree (opposite dir) β†’ kept but flagged; mixed β†’ neutral.
657
+ pick["ml_selected"] = ticker in ml_preds_by_ticker
658
+ ml_best = _slim_ml_tf(ml_tfs.get(best_tf))
659
+ ai_best_dir = (ai_preds.get((ticker, best_tf), {}) or {}).get("direction")
660
+ pick["ml_ai_verdict"] = None
661
+ if ml_best and ml_best.get("direction") and ai_best_dir:
662
+ m = str(ml_best["direction"]).upper()
663
+ a = str(ai_best_dir).upper()
664
+ if m == a and m in ("BULLISH", "BEARISH"):
665
+ pick["ml_ai_verdict"] = "confirmed"
666
+ best_score *= 1.10 # reward ML+AI consensus so it ranks higher
667
+ elif (m == "BULLISH" and a == "BEARISH") or (m == "BEARISH" and a == "BULLISH"):
668
+ pick["ml_ai_verdict"] = "disagree"
669
+ elif m in ("BULLISH", "BEARISH") and a in ("BULLISH", "BEARISH", "NEUTRAL"):
670
+ pick["ml_ai_verdict"] = "mixed"
671
  pick["_score_best"] = best_score
672
  assembled.append(pick)
673