Khanna, Videh Rakesh Rakesh Claude Sonnet 5.5 commited on
Commit
953b4c2
Β·
1 Parent(s): 3b2af33

Add 1M (1-month hold) timeframe to watchlist and dashboard

Browse files

AI-forecast-only third horizon (~21 sessions, buy-now entry, 2.5x ATR stop)
with a sqrt-time ATR band, dedicated 1M direction guardrails, a separate
"1 Month picks" dashboard ranking from a no-LLM shortlist, lazy 1M cells on
other picks, and a Validation tab 1M card. Fixes silent unknown-timeframe
fallbacks (date window, 1W label, 3D prompt, validation deadlines, price
window, self-learning token leakage). No ML 1M model; F&O and portfolio
insight unchanged.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>

CLAUDE.md CHANGED
@@ -37,6 +37,19 @@ This section supersedes older notes below where their timeout, chart, learning,
37
  - Trade modal "Live Quote" entry stays disabled unless a live provider is configured (`DHAN_ENABLED=1`, credentials, `DHAN_ALLOW_BROWSER_DATA=1`) and a reference contract is chosen; the option label now says which condition is missing. NSE snapshots are display-only and never fill a paper trade automatically. Without a live provider, the modal's "Use NSE Price" button (`/api/fo/quote?snapshot=1`, `executable:false`) pre-fills the entry premium on an explicit click; the trade is still recorded as a Manual entry.
38
  - Manual F&O positions that carry a stop and/or target are auto-closed by the `fo-monitor` thread (every 15s, plus `/api/trades/check-stops`) using `fo.snapshot_exit_price`: NSE last-traded price, market OPEN only, snapshot ≀5 min old, exact-contract match, tick-aligned. Exit is recorded with `close_price_source="nse_snapshot"`. Fills and pre-expiry exits still require a live provider. Because it is a ~1-minute last-trade snapshot, a spike between polls can be missed and the exit price can overshoot the level.
39
 
 
 
 
 
 
 
 
 
 
 
 
 
 
40
  ## Deployment β€” HF Spaces (primary) and local
41
 
42
  **This is a deployed web application hosted on Hugging Face Spaces. Always think about HF Spaces first when reasoning about storage, paths, and environment.**
@@ -674,8 +687,8 @@ Trades used to develop and validate the trigger rules:
674
 
675
  - **Cache buster**: `?v=20260804a` on `style.css` and `app.js` in `templates/index.html`. Bump the suffix letter (aβ†’bβ†’c…) whenever JS/CSS changes need to bypass browser cache.
676
  - **Catch-up refresh on tab focus (2026-08-04)**: browsers throttle `setInterval`/`setTimeout` heavily in background tabs (Chrome caps background timers to ~once/hour after ~5 min hidden), so the 3-min watchlist/top-pick and 5-min ML INTRADAY auto-refresh loops in `static/app.js` effectively stopped firing while a tab wasn't focused β€” looking like data "stopped auto-updating after 5 minutes". Fixed with a `visibilitychange` listener that fires an immediate refresh (watchlist INTRADAY warm, top-pick INTRADAY cells, ML INTRADAY) the moment the tab becomes visible again, debounced to 15s.
677
- - **Timeframes shown: INTRADAY / 1D only (2 cards).** 3D **and** 5D are retired from the entire live view + API (2026-07-28). Frontend TF arrays are `['INTRADAY','1D']`; backend `TIMEFRAMES = ["INTRADAY","1D"]` (both `app.py._build_watchlist_pick` and `top5_picker`); `all_tfs`/`tfs_to_run` = INTRADAY/1D. 3D/5D remain ONLY in: historical validation grading (old snapshots), `get_weekly_picks` (no route β€” dead on API), the ML model's internal `predict_all_tf` (stripped to INTRADAY/1D at the `/api/ml-predict` boundary), and the MCP server (caller-supplied explicit dates). No prod API path calls a 3D/5D prediction β€” see "No 3D/5D on prod API" below.
678
- - **CSS grid for 2 cards**: `.tf-grid` = `repeat(2,1fr)` (was 3); `.wl-summary-grid` = `repeat(4,…)` (Current Price / AI Today / AI 1D / News β€” the "AI (3D)" cell was removed); `.port-insight-timeframes` = `repeat(2,…)`. Portfolio-insight primary label is "Primary (1D)".
679
  - **INTRADAY 1% minimum move = a FLOOR, not a skip (2026-07-28).** Intraday moves clear β‰₯1% on ~89% of NSE days (verified on 3.05M day-rows), so a directional intraday best-case below 1% is FLOORED up to 1% (`INTRADAY_MIN_MOVE_PCT`, env-overridable) rather than skipped. Enforced in three places kept in sync: `ai_forecast._atr_clamp_range` (floors the far bound within the 2% INTRADAY cap), `predictor_core` (floors `ret_hi`/`ret_lo` + recomputes midpoint), and `ml_predictor/infer.py` (floors the far bound before target/midpoint; raw quantiles untouched for backtests). `no_trade_reason="below_min_move"` is NO LONGER emitted anywhere.
680
  - **INTRADAY momentum override**: when the LLM reads NEUTRAL but the live session move vs prior close is clearly directional (β‰₯ `AI_INTRADAY_MOMENTUM_PCT`, default 0.6%), `ai_forecast._apply_trigger_guardrails` surfaces BULLISH/BEARISH (INTRADAY only, symmetric; the BULLISH-into-crash guard still wins). Env `AI_INTRADAY_MOMENTUM_OVERRIDE=0` disables.
681
  - **Pre-market intraday preview**: during `PRE_MARKET` (<09:15 IST) the watchlist runs a labeled INTRADAY preview (πŸŒ… Pre-market badge) instead of the "market closed" stub, so a directional lean is ready at the bell. The refresh scheduler starts at 09:00 and runs on OPEN+PRE_MARKET. `pred["intraday_premarket"]` flag; not stored as the session final call.
 
37
  - Trade modal "Live Quote" entry stays disabled unless a live provider is configured (`DHAN_ENABLED=1`, credentials, `DHAN_ALLOW_BROWSER_DATA=1`) and a reference contract is chosen; the option label now says which condition is missing. NSE snapshots are display-only and never fill a paper trade automatically. Without a live provider, the modal's "Use NSE Price" button (`/api/fo/quote?snapshot=1`, `executable:false`) pre-fills the entry premium on an explicit click; the trade is still recorded as a Manual entry.
38
  - Manual F&O positions that carry a stop and/or target are auto-closed by the `fo-monitor` thread (every 15s, plus `/api/trades/check-stops`) using `fo.snapshot_exit_price`: NSE last-traded price, market OPEN only, snapshot ≀5 min old, exact-contract match, tick-aligned. Exit is recorded with `close_price_source="nse_snapshot"`. Fills and pre-expiry exits still require a live provider. Because it is a ~1-minute last-trade snapshot, a spike between polls can be missed and the exit price can overshoot the level.
39
 
40
+ ## 1M (1-month hold) timeframe β€” 2026-11-12
41
+
42
+ A third live horizon, `1M` (~21 trading sessions / 30 calendar days), shown on the equity watchlist and the dashboard. **AI forecast only β€” there is no ML 1M model** (the local model covers INTRADAY/1D/3D; its 3D artifacts cannot honestly stand in for 21 days), so 1M cells never render the ML block. F&O cards, portfolio insight, `/api/ml-predict`, "Best Bet" and the recommended-action logic stay INTRADAY/1D.
43
+
44
+ - **Dates/label:** `predictor_core.TIMEFRAME_DAYS["1M"]=28` (+2-day buffer = 30 days). `predict_stock_v2` labels a window with >=15 trading days `1M` (7-14 is `1W`). 1M entry = the live price (`entry_basis="live"`, "buy now"); stop = 2.5Γ—ATR14; strategies = `STRATEGY_TIMEFRAME_MAP["1M"]` (S6V2, S_SEASONAL, S19).
45
+ - **Band (`ai_forecast._atr_clamp_range`)** is a sqrt-time ATR band, NOT the day-length power law (that only holds to ~4 days): near = 0.20Γ—ATR%Γ—βˆš21, far = 0.80Γ—ATR%Γ—βˆš21, hard cap 25%, min spread 2%. NEUTRAL = Β±clamp(1.2Γ—ATR%Γ—βˆš21, 5%, 12%) (the flat Β±1.5% of 1D can never contain a month). Calibrated 2026-11-12 on 16,601 21-session windows (Nifty 50, 5y; touch = window high): near touched 79%, far 30%, midpoint ~51%; NEUTRAL contained 73%. Env: `ONE_M_BAND_NEAR_K/FAR_K`, `ONE_M_NEUT_ATR_K/MIN_PCT/MAX_PCT`. Re-run the calibration if the grading metric or universe changes.
46
+ - **Direction (`ai_forecast._guardrails_1m`)** replaces the 10D-based T/B triggers for 1M: bullish `M1` (above EMA50, 20D>0, 3M RS vs Nifty >= 0, RSI<=72), `M2` (shallow pullback in an uptrend); bearish `MB1` (below EMA50, 20D<-4%, MACD<0, RS<0), `MB2` (crash + MACD<0); structural laggard (RS<-8%) and crashes can never be BULLISH; conflicting or no trigger β†’ NEUTRAL (no keep-the-LLM-call mode). `predictor_core` supplies `rs_3m_pct` to the indicators for 1M ONLY β€” production has never passed it for 1D/3D, so the documented structural-laggard guard is effectively dormant there (not changed here).
47
+ - **API:** `app.LIVE_TIMEFRAMES = [INTRADAY, 1D, 1M]` drives `VALID_TFS`, the per-ticker/bulk watchlist routes, `_resolve_dates` and the archive loop. 1M is excluded from WhatsApp alerts. `/api/watchlist-pick(s)` therefore runs 3 AI TFs per ticker (~+50% LLM calls; cached until IST midnight).
48
+ - **Dashboard (`top5_picker`):** 1M is NOT in `TIMEFRAMES`. After Phase 1, a no-LLM shortlist (`_ONE_M_SHORTLIST_N`=20, env `TOP5_1M_SHORTLIST`) ranks on trend/RS quality from `ml.features` (EMA stack, `rs_3m_pct`, MACD, ADX) and drops stocks with RS < `TOP5_1M_MIN_RS_PCT` (-4). Each shortlisted stock gets ONE fast-mode 1M AI call in the same Phase 2 pool (1M jobs queued first, +3 workers, +30s deadline). Result gets `picks_1m` (top `TOP5_1M_TOP_N`=10, BULLISH/SLIGHTLY BULLISH + MEDIUM+ confidence, score = confidence Γ— trend quality Γ— sector Γ— R:R Γ— √(midpoint%), sector-diversified) and `picks_1m_note` (why it is empty). Streaming snapshots carry `picks_1m`. Picks outside the shortlist show a pending 1M cell that the frontend lazy-loads via `/api/pick-tf/<t>/1M` (`_lazyLoadOneM`). Degraded mode (all cloud providers exhausted) reports 1M as `ai_unavailable` and never fabricates 1M picks.
49
+ - **Validation:** `database.TF_CALENDAR_OFFSET` (1M = 30 calendar days, rolled to a trading day) is shared by snapshots, trade deadlines and `/api/prediction-validation` (now reads 45 days so 1M snapshots survive until maturity). `_fetch_price_window` sizes its download from the window START. `market_calendar` warns once and treats a year with no loaded holidays as weekdays-only β€” **add 2027 NSE holidays when NSE publishes them**. `self_learning._TF_TOKENS` includes 1M, so 1M lessons never leak into other timeframes. 1M accuracy is unmeasured until ~30 days of snapshots mature β€” the UI labels it "New Β· unvalidated" and the Validation tab has a separate 1 Month card/filter.
50
+ - **Frontend:** `LIVE_TFS`/`ONE_M_TF`/`tfLabel()` in `static/app.js`; 5-item watchlist summary row (`.wl-summary-grid--5`); auto-fit `.tf-grid`; Top Picks view toggle (`_setTop5View`: "Today / 1D picks" | "1 Month picks").
51
+ - **Tests:** `tests/test_one_month_timeframe.py` (window/label, band, guardrails, snapshots, price window, top picks with fakes) and the 1M cases in `tests/test_watchlist_frontend.cjs`. Run `tests/test_api_contract.py` BEFORE any module that imports `app` with a different DB patch (pytest collects alphabetically; reversing the order breaks `FoApiTests`).
52
+
53
  ## Deployment β€” HF Spaces (primary) and local
54
 
55
  **This is a deployed web application hosted on Hugging Face Spaces. Always think about HF Spaces first when reasoning about storage, paths, and environment.**
 
687
 
688
  - **Cache buster**: `?v=20260804a` on `style.css` and `app.js` in `templates/index.html`. Bump the suffix letter (aβ†’bβ†’c…) whenever JS/CSS changes need to bypass browser cache.
689
  - **Catch-up refresh on tab focus (2026-08-04)**: browsers throttle `setInterval`/`setTimeout` heavily in background tabs (Chrome caps background timers to ~once/hour after ~5 min hidden), so the 3-min watchlist/top-pick and 5-min ML INTRADAY auto-refresh loops in `static/app.js` effectively stopped firing while a tab wasn't focused β€” looking like data "stopped auto-updating after 5 minutes". Fixed with a `visibilitychange` listener that fires an immediate refresh (watchlist INTRADAY warm, top-pick INTRADAY cells, ML INTRADAY) the moment the tab becomes visible again, debounced to 15s.
690
+ - **Timeframes shown: INTRADAY / 1D (+ 1M since 2026-11-12, see the "1M (1-month hold) timeframe" section).** 3D **and** 5D are retired from the entire live view + API (2026-07-28). Frontend TF arrays are `['INTRADAY','1D']`; backend `TIMEFRAMES = ["INTRADAY","1D"]` (both `app.py._build_watchlist_pick` and `top5_picker`); `all_tfs`/`tfs_to_run` = INTRADAY/1D. 3D/5D remain ONLY in: historical validation grading (old snapshots), `get_weekly_picks` (no route β€” dead on API), the ML model's internal `predict_all_tf` (stripped to INTRADAY/1D at the `/api/ml-predict` boundary), and the MCP server (caller-supplied explicit dates). No prod API path calls a 3D/5D prediction β€” see "No 3D/5D on prod API" below.
691
+ - **CSS grid** (superseded for equities by the 1M change: `.tf-grid` is now `repeat(auto-fit,minmax(170px,1fr))` and the equity summary row is `.wl-summary-grid--5`): `.tf-grid` was `repeat(2,1fr)`; `.wl-summary-grid` = `repeat(4,…)` (Current Price / AI Today / AI 1D / News β€” the "AI (3D)" cell was removed); `.port-insight-timeframes` = `repeat(2,…)`. Portfolio-insight primary label is "Primary (1D)".
692
  - **INTRADAY 1% minimum move = a FLOOR, not a skip (2026-07-28).** Intraday moves clear β‰₯1% on ~89% of NSE days (verified on 3.05M day-rows), so a directional intraday best-case below 1% is FLOORED up to 1% (`INTRADAY_MIN_MOVE_PCT`, env-overridable) rather than skipped. Enforced in three places kept in sync: `ai_forecast._atr_clamp_range` (floors the far bound within the 2% INTRADAY cap), `predictor_core` (floors `ret_hi`/`ret_lo` + recomputes midpoint), and `ml_predictor/infer.py` (floors the far bound before target/midpoint; raw quantiles untouched for backtests). `no_trade_reason="below_min_move"` is NO LONGER emitted anywhere.
693
  - **INTRADAY momentum override**: when the LLM reads NEUTRAL but the live session move vs prior close is clearly directional (β‰₯ `AI_INTRADAY_MOMENTUM_PCT`, default 0.6%), `ai_forecast._apply_trigger_guardrails` surfaces BULLISH/BEARISH (INTRADAY only, symmetric; the BULLISH-into-crash guard still wins). Env `AI_INTRADAY_MOMENTUM_OVERRIDE=0` disables.
694
  - **Pre-market intraday preview**: during `PRE_MARKET` (<09:15 IST) the watchlist runs a labeled INTRADAY preview (πŸŒ… Pre-market badge) instead of the "market closed" stub, so a directional lean is ready at the bell. The refresh scheduler starts at 09:00 and runs on OPEN+PRE_MARKET. `pred["intraday_premarket"]` flag; not stored as the session final call.
ai_forecast.py CHANGED
@@ -19,6 +19,7 @@ This version generates intelligent ranges from any LLM response:
19
 
20
  import json
21
  import logging
 
22
  import os
23
  import re
24
  import threading
@@ -70,7 +71,7 @@ def _volatility_percentile(ohlcv_df: Optional[pd.DataFrame], tf_label: str) -> f
70
  """Return realized volatility percentile [0,1] for timeframe using close-to-close moves."""
71
  if ohlcv_df is None or not isinstance(ohlcv_df, pd.DataFrame) or "Close" not in ohlcv_df.columns:
72
  return 0.50
73
- tf_days = {"INTRADAY": 1, "1D": 1, "3D": 3, "5D": 5}.get(tf_label, 3)
74
  close = pd.to_numeric(ohlcv_df["Close"], errors="coerce").dropna()
75
  if len(close) < max(30, tf_days + 10):
76
  return 0.50
@@ -87,14 +88,14 @@ def _volatility_percentile(ohlcv_df: Optional[pd.DataFrame], tf_label: str) -> f
87
  def _realized_move_anchor(ohlcv_df: Optional[pd.DataFrame], tf_label: str, vol_pctile: float) -> float:
88
  """Estimate achievable move (%) from historical realized moves for this timeframe."""
89
  if ohlcv_df is None or not isinstance(ohlcv_df, pd.DataFrame) or "Close" not in ohlcv_df.columns:
90
- return {"INTRADAY": 0.5, "1D": 0.8, "3D": 1.6, "5D": 2.2}.get(tf_label, 1.5)
91
- tf_days = {"INTRADAY": 1, "1D": 1, "3D": 3, "5D": 5}.get(tf_label, 3)
92
  close = pd.to_numeric(ohlcv_df["Close"], errors="coerce").dropna()
93
  if len(close) < max(40, tf_days + 15):
94
- return {"INTRADAY": 0.5, "1D": 0.8, "3D": 1.6, "5D": 2.2}.get(tf_label, 1.5)
95
  moves = close.pct_change(tf_days).abs().dropna() * 100.0
96
  if len(moves) < 25:
97
- return {"INTRADAY": 0.5, "1D": 0.8, "3D": 1.6, "5D": 2.2}.get(tf_label, 1.5)
98
 
99
  # In quieter regimes use lower quantiles; in volatile regimes allow wider targets.
100
  q = 0.45 + 0.35 * max(0.0, min(1.0, float(vol_pctile)))
@@ -155,7 +156,8 @@ def _generate_range_from_point(
155
  "INTRADAY": 2.0,
156
  "1D": 4.0,
157
  "3D": 7.0,
158
- "5D": 12.0
 
159
  }.get(tf_label, 10.0)
160
 
161
  # Generate range based on direction
@@ -382,6 +384,10 @@ _TRIGGER_DESC: dict[str, str] = {
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
  # When no same-side trigger fires on 1D/3D/5D, keep the LLM's directional call at reduced
@@ -699,6 +705,15 @@ def _apply_trigger_guardrails(
699
  )
700
  return direction, confidence, None
701
 
 
 
 
 
 
 
 
 
 
702
  # ── Evaluate bullish triggers ─────────────────────────────────────────────
703
  # All bull triggers are skipped entirely when structural_laggard (see above) β€” an absolute
704
  # oversold/breakout setup is much weaker evidence on a stock that's been underperforming the
@@ -931,6 +946,63 @@ def _apply_trigger_guardrails(
931
  return direction, confidence, None
932
 
933
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
934
  def _reconcile_override(
935
  note: str | None, direction: str, confidence: str,
936
  reasoning: str, should_buy: bool,
@@ -1013,7 +1085,7 @@ def _apply_calibrated_range(direction: str, tf_label: str) -> tuple[float, float
1013
  return _NEUT_RANGE.get(tf_label, (-0.15, 0.15))
1014
 
1015
 
1016
- _TF_HARD_CAP_PCT: dict[str, float] = {"INTRADAY": 2.0, "1D": 4.0, "3D": 7.0}
1017
 
1018
  # INTRADAY realistic-move floor for a DIRECTIONAL best-case target. Intraday moves clear ~1% on
1019
  # ~89% of NSE days (3.05M day-rows), so an ATR-derived far bound below 1% under-predicts the
@@ -1040,7 +1112,7 @@ _INTRADAY_MIN_MOVE_PCT = float(os.getenv("INTRADAY_MIN_MOVE_PCT", "1.0"))
1040
  # ratio) / covering realized moves for NEUTRAL calls (half-width). Fitting BASE/EXPONENT to those
1041
  # grid-searched points (1D, 3D) reproduces them almost exactly (near: 0.12Γ—1^0.83=0.12,
1042
  # 0.12Γ—3^0.83β‰ˆ0.30) and extrapolates smoothly to untested horizons like 5D instead of guessing.
1043
- _TF_WINDOW_DAYS: dict[str, float] = {"1D": 1.0, "3D": 3.0, "5D": 5.0, "1W": 7.0}
1044
  # INTRADAY has no calendar-day length (same-day) so each formula gets its own fitted "equivalent
1045
  # day count" for INTRADAY β€” these two differ because they fit different physical quantities (a
1046
  # directional bounce-target vs. a two-sided flat-range containment), not because of inconsistency.
@@ -1074,7 +1146,26 @@ _FAR_BOUND_EXP = 0.6354
1074
  # Minimum spread between near and far bounds per timeframe. The power-law exponents cause k_far
1075
  # to converge with k_near around day 3.7 and cross below it at 5D β€” leaving bands as narrow as
1076
  # 0.01% wide. These floors guarantee a meaningful band regardless of ATR level.
1077
- _MIN_SPREAD_PCT: dict[str, float] = {"INTRADAY": 0.15, "1D": 0.20, "3D": 0.80, "5D": 1.20}
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1078
 
1079
  # ── TIGHT DIRECTIONAL BAND for INTRADAY + 1D (user request 2026-07-30) ──────────────────────────
1080
  # The wide volatility-scaled bands ([1.0, 2.0] intraday, flat Β±1% for 1D) hid the expected move β€”
@@ -1195,6 +1286,25 @@ def _atr_clamp_range(
1195
  cap = _TF_HARD_CAP_PCT.get(tf_label, 7.0)
1196
  _dir = (direction or "").upper()
1197
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1198
  # NEUTRAL: FLAT, falsifiable band by policy β€” NOT an ATR/volatility magnitude. A NEUTRAL call
1199
  # must give the user an actionable "stays within X%" claim they can bet on; an ATR-scaled band
1200
  # ballooned to Β±5%+ on volatile stocks, which tells the user nothing ("no idea what to bet on").
@@ -1643,7 +1753,7 @@ def _build_context_block(
1643
 
1644
 
1645
  def _build_bull_prompt(ctx: str, social: str, tf_label: str, current_price: float = 0.0, ticker: str = "", company: str = "") -> str:
1646
- holding = {"INTRADAY": "the rest of today's session (until ~3pm)", "1D": "1 trading day", "3D": "3 trading days", "5D": "5 trading days"}.get(tf_label, "3 trading days")
1647
  stock_id = f"{company} ({ticker})" if company and ticker else (ticker or company or "this stock")
1648
  price_anchor = (
1649
  f"IMPORTANT: You are analyzing {stock_id}. "
@@ -1662,7 +1772,7 @@ def _build_bull_prompt(ctx: str, social: str, tf_label: str, current_price: floa
1662
 
1663
 
1664
  def _build_bear_prompt(ctx: str, social: str, tf_label: str, current_price: float = 0.0, ticker: str = "", company: str = "") -> str:
1665
- holding = {"INTRADAY": "the rest of today's session (until ~3pm)", "1D": "1 trading day", "3D": "3 trading days", "5D": "5 trading days"}.get(tf_label, "3 trading days")
1666
  stock_id = f"{company} ({ticker})" if company and ticker else (ticker or company or "this stock")
1667
  price_anchor = (
1668
  f"IMPORTANT: You are analyzing {stock_id}. "
@@ -1700,9 +1810,10 @@ def _build_synthesis_prompt(
1700
  atr14: float,
1701
  nifty_ok: bool = True,
1702
  ) -> str:
1703
- _cap_pct = {"INTRADAY": 2.0, "1D": 4.0, "3D": 7.0, "5D": 12.0}.get(tf_label, 7.0)
1704
  holding = {"INTRADAY": "the rest of today's session (target must be touched by ~3pm)",
1705
- "1D": "1 trading day", "3D": "3 trading days", "5D": "5 trading days"}.get(tf_label, "3 trading days")
 
1706
 
1707
  # Direction rules β€” decisive momentum-based framework.
1708
  # KEY PRINCIPLES:
@@ -1867,6 +1978,27 @@ def _build_synthesis_prompt(
1867
  "Nifty below EMA200 β†’ cap at MEDIUM. "
1868
  "LOW = weak/conflicting signals.\n"
1869
  ),
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1870
  }.get(tf_label, "")
1871
 
1872
  signal_rules = (
@@ -1930,6 +2062,8 @@ def _build_synthesis_prompt(
1930
  "INTRADAY": (0.20, 0.45),
1931
  "1D": (0.25, 0.60),
1932
  "3D": (0.45, 0.95),
 
 
1933
  }.get(tf_label, (0.25, 0.60))
1934
  _atr_for_tgt = atr14 if atr14 and atr14 > 0 else max(0.01, current_price * 0.015)
1935
  _bull_lo = current_price + _lo_mult * _atr_for_tgt
@@ -2014,7 +2148,7 @@ def get_ai_forecast(
2014
  Source label: "{provider}:{model}+debate+fund" | "+debate" | "" | "heuristic".
2015
  """
2016
  # ── Parse arguments ────────────────────────────────────────────────────────
2017
- _TF_LABELS = ("INTRADAY", "1D", "3D", "5D")
2018
  company = args[0] if len(args) >= 1 and isinstance(args[0], str) and args[0] not in _TF_LABELS else kwargs.get("company", ticker)
2019
  tf_label = next((a for a in args if a in _TF_LABELS), None) or kwargs.get("tf_label", "3D")
2020
  ml = args[2] if len(args) >= 3 and isinstance(args[2], dict) else kwargs.get("ml", {})
 
19
 
20
  import json
21
  import logging
22
+ import math
23
  import os
24
  import re
25
  import threading
 
71
  """Return realized volatility percentile [0,1] for timeframe using close-to-close moves."""
72
  if ohlcv_df is None or not isinstance(ohlcv_df, pd.DataFrame) or "Close" not in ohlcv_df.columns:
73
  return 0.50
74
+ tf_days = {"INTRADAY": 1, "1D": 1, "3D": 3, "5D": 5, "1M": 21}.get(tf_label, 3)
75
  close = pd.to_numeric(ohlcv_df["Close"], errors="coerce").dropna()
76
  if len(close) < max(30, tf_days + 10):
77
  return 0.50
 
88
  def _realized_move_anchor(ohlcv_df: Optional[pd.DataFrame], tf_label: str, vol_pctile: float) -> float:
89
  """Estimate achievable move (%) from historical realized moves for this timeframe."""
90
  if ohlcv_df is None or not isinstance(ohlcv_df, pd.DataFrame) or "Close" not in ohlcv_df.columns:
91
+ return {"INTRADAY": 0.5, "1D": 0.8, "3D": 1.6, "5D": 2.2, "1M": 6.0}.get(tf_label, 1.5)
92
+ tf_days = {"INTRADAY": 1, "1D": 1, "3D": 3, "5D": 5, "1M": 21}.get(tf_label, 3)
93
  close = pd.to_numeric(ohlcv_df["Close"], errors="coerce").dropna()
94
  if len(close) < max(40, tf_days + 15):
95
+ return {"INTRADAY": 0.5, "1D": 0.8, "3D": 1.6, "5D": 2.2, "1M": 6.0}.get(tf_label, 1.5)
96
  moves = close.pct_change(tf_days).abs().dropna() * 100.0
97
  if len(moves) < 25:
98
+ return {"INTRADAY": 0.5, "1D": 0.8, "3D": 1.6, "5D": 2.2, "1M": 6.0}.get(tf_label, 1.5)
99
 
100
  # In quieter regimes use lower quantiles; in volatile regimes allow wider targets.
101
  q = 0.45 + 0.35 * max(0.0, min(1.0, float(vol_pctile)))
 
156
  "INTRADAY": 2.0,
157
  "1D": 4.0,
158
  "3D": 7.0,
159
+ "5D": 12.0,
160
+ "1M": 25.0,
161
  }.get(tf_label, 10.0)
162
 
163
  # Generate range based on direction
 
384
  "B1": "an overbought extreme with stretched momentum β€” reversal risk",
385
  "B2": "a confirmed downtrend below EMA50 with negative MACD and momentum",
386
  "B3": "a sustained multi-day decline confirmed by negative MACD (falling-knife risk)",
387
+ "M1": "price is above EMA50 with positive 20-day momentum and non-negative strength vs Nifty over 3 months (1-month trend intact)",
388
+ "M2": "a shallow pullback within an intact uptrend (above EMA50, RSI below 50, no relative-strength deficit)",
389
+ "MB1": "price is below EMA50 with falling 20-day momentum, negative MACD and underperformance vs Nifty (1-month downtrend)",
390
+ "MB2": "a sustained multi-week decline confirmed by negative MACD (falling-knife risk)",
391
  }
392
 
393
  # When no same-side trigger fires on 1D/3D/5D, keep the LLM's directional call at reduced
 
705
  )
706
  return direction, confidence, None
707
 
708
+ # ── 1M: trend / relative-strength framework (the 10D-based triggers below are tuned on 1D) ──
709
+ if tf_label == "1M":
710
+ return _guardrails_1m(
711
+ direction, confidence, rsi=rsi, macd=macd, ret20=ret20,
712
+ above_ema50=above_ema50,
713
+ above_ema200=((current_price > _v("ema200")) if (_v("ema200") is not None and current_price > 0) else None),
714
+ rs_3m=rs_3m, crash_exhausted=crash_exhausted, structural_laggard=structural_laggard,
715
+ )
716
+
717
  # ── Evaluate bullish triggers ─────────────────────────────────────────────
718
  # All bull triggers are skipped entirely when structural_laggard (see above) β€” an absolute
719
  # oversold/breakout setup is much weaker evidence on a stock that's been underperforming the
 
946
  return direction, confidence, None
947
 
948
 
949
+ def _guardrails_1m(
950
+ direction: str, confidence: str, *, rsi: float, macd: "float | None",
951
+ ret20: "float | None", above_ema50: "bool | None", above_ema200: "bool | None",
952
+ rs_3m: "float | None", crash_exhausted: bool, structural_laggard: bool,
953
+ ) -> tuple[str, str, str | None]:
954
+ """1-month direction triggers: EMA50/EMA200 trend + 20D momentum + 3M relative strength.
955
+
956
+ BULLISH M1: above EMA50, 20D>0, RS vs Nifty not negative, RSI<=72 (not above a failed EMA200)
957
+ M2: shallow pullback in an uptrend (above EMA50, -3%<=20D<=0, RSI<50, RS not negative)
958
+ BEARISH MB1: below EMA50, 20D<-4%, MACD<0, RS negative
959
+ MB2: crash-exhausted (10D<-6% or 20D<-8%) with MACD<0
960
+ Bullish triggers are skipped for a structural laggard (RS < -8%) or a crash. Conflicting or no
961
+ trigger -> NEUTRAL (a month-long hold needs trend evidence; there is no keep-the-LLM-call mode).
962
+ """
963
+ rs_ok = rs_3m is None or rs_3m >= 0
964
+ bull = None
965
+ if not structural_laggard and not crash_exhausted and above_ema200 is not False:
966
+ if above_ema50 is True and ret20 is not None and ret20 > 0 and rs_ok and rsi <= 72:
967
+ bull = "M1"
968
+ elif above_ema50 is True and ret20 is not None and -3.0 <= ret20 <= 0 and rsi < 50 and rs_ok:
969
+ bull = "M2"
970
+ bear = None
971
+ if (above_ema50 is False and ret20 is not None and ret20 < -4.0
972
+ and macd is not None and macd < 0 and (rs_3m is None or rs_3m < 0)):
973
+ bear = "MB1"
974
+ elif crash_exhausted and macd is not None and macd < 0:
975
+ bear = "MB2"
976
+
977
+ if bear and not bull:
978
+ note = None
979
+ if direction != "BEARISH":
980
+ note = f"Direction set BEARISH by 1-month trigger {bear}: {_TRIGGER_DESC[bear]}."
981
+ logger.info("GUARDRAIL 1M %s: overriding %s→BEARISH (20D=%s RS3M=%s)", bear, direction, ret20, rs_3m)
982
+ return "BEARISH", confidence, note
983
+ if bull and not bear:
984
+ note = None
985
+ if direction != "BULLISH":
986
+ note = f"Direction set BULLISH by 1-month trigger {bull}: {_TRIGGER_DESC[bull]}."
987
+ logger.info("GUARDRAIL 1M %s: overriding %s→BULLISH (20D=%s RS3M=%s)", bull, direction, ret20, rs_3m)
988
+ return "BULLISH", confidence, note
989
+
990
+ levels = ["LOW", "MEDIUM", "HIGH"]
991
+ idx = levels.index(confidence) if confidence in levels else 1
992
+ downgraded = levels[max(0, idx - 1)]
993
+ if bull and bear:
994
+ note = (f"Conflicting 1-month triggers ({bull} vs {bear}) β€” no clear edge, treated as NEUTRAL."
995
+ if direction != "NEUTRAL" else None)
996
+ return "NEUTRAL", downgraded, note
997
+ if direction == "NEUTRAL":
998
+ return direction, confidence, None
999
+ logger.info("GUARDRAIL 1M NO_TRIGGER: %s→NEUTRAL (20D=%s RS3M=%s)", direction, ret20, rs_3m)
1000
+ return "NEUTRAL", downgraded, (
1001
+ "No 1-month trend trigger fired (needs trend + relative-strength confirmation) β€” "
1002
+ "treated as NEUTRAL for a month-long hold."
1003
+ )
1004
+
1005
+
1006
  def _reconcile_override(
1007
  note: str | None, direction: str, confidence: str,
1008
  reasoning: str, should_buy: bool,
 
1085
  return _NEUT_RANGE.get(tf_label, (-0.15, 0.15))
1086
 
1087
 
1088
+ _TF_HARD_CAP_PCT: dict[str, float] = {"INTRADAY": 2.0, "1D": 4.0, "3D": 7.0, "1M": 25.0}
1089
 
1090
  # INTRADAY realistic-move floor for a DIRECTIONAL best-case target. Intraday moves clear ~1% on
1091
  # ~89% of NSE days (3.05M day-rows), so an ATR-derived far bound below 1% under-predicts the
 
1112
  # ratio) / covering realized moves for NEUTRAL calls (half-width). Fitting BASE/EXPONENT to those
1113
  # grid-searched points (1D, 3D) reproduces them almost exactly (near: 0.12Γ—1^0.83=0.12,
1114
  # 0.12Γ—3^0.83β‰ˆ0.30) and extrapolates smoothly to untested horizons like 5D instead of guessing.
1115
+ _TF_WINDOW_DAYS: dict[str, float] = {"1D": 1.0, "3D": 3.0, "5D": 5.0, "1W": 7.0, "1M": 30.0}
1116
  # INTRADAY has no calendar-day length (same-day) so each formula gets its own fitted "equivalent
1117
  # day count" for INTRADAY β€” these two differ because they fit different physical quantities (a
1118
  # directional bounce-target vs. a two-sided flat-range containment), not because of inconsistency.
 
1146
  # Minimum spread between near and far bounds per timeframe. The power-law exponents cause k_far
1147
  # to converge with k_near around day 3.7 and cross below it at 5D β€” leaving bands as narrow as
1148
  # 0.01% wide. These floors guarantee a meaningful band regardless of ATR level.
1149
+ _MIN_SPREAD_PCT: dict[str, float] = {"INTRADAY": 0.15, "1D": 0.20, "3D": 0.80, "5D": 1.20, "1M": 2.0}
1150
+
1151
+ # ── 1-MONTH (1M) BAND ───────────────────────────────────────────────────────────────────────────
1152
+ # The day-length power law above is only valid out to ~4 days (its near and far curves cross near
1153
+ # d=3.85), so 1M cannot use it. A ~21-session move scales with sqrt(time), so the 1M band is a pair
1154
+ # of multiples of the stock's one-month volatility proxy ATR% x sqrt(21): the NEAR bound is the
1155
+ # easily-reached edge, the FAR bound the optimistic edge, the headline target their midpoint.
1156
+ # Calibrated 2026-11-12 on 16,601 historical 21-session windows (Nifty 50, 5y, entry=close, touch =
1157
+ # window HIGH): near K=0.20 is touched 79%, far K=0.80 is touched 30%, so the midpoint (K=0.50) is
1158
+ # touched ~51% (higher when the direction call is right). K=0.40 near would be touched only 60%.
1159
+ # NEUTRAL cannot be the flat +/-1% used for 1D (a 21-day window never stays that tight), so it is a
1160
+ # wide band clamped to [NEUT_MIN, NEUT_MAX] percent: K=1.2 keeps the whole window inside ~73% of
1161
+ # the time. Re-run the calibration if the grading metric or universe changes (see CLAUDE.md).
1162
+ _ONE_M_SESSIONS = 21
1163
+ _ONE_M_NEAR_K = float(os.getenv("ONE_M_BAND_NEAR_K", "0.20"))
1164
+ _ONE_M_FAR_K = float(os.getenv("ONE_M_BAND_FAR_K", "0.80"))
1165
+ _ONE_M_NEUT_K = float(os.getenv("ONE_M_NEUT_ATR_K", "1.20"))
1166
+ _ONE_M_NEUT_MIN_PCT = float(os.getenv("ONE_M_NEUT_MIN_PCT", "5.0"))
1167
+ _ONE_M_NEUT_MAX_PCT = float(os.getenv("ONE_M_NEUT_MAX_PCT", "12.0"))
1168
+ _ONE_M_MIN_NEAR_PCT = 0.5
1169
 
1170
  # ── TIGHT DIRECTIONAL BAND for INTRADAY + 1D (user request 2026-07-30) ──────────────────────────
1171
  # The wide volatility-scaled bands ([1.0, 2.0] intraday, flat Β±1% for 1D) hid the expected move β€”
 
1286
  cap = _TF_HARD_CAP_PCT.get(tf_label, 7.0)
1287
  _dir = (direction or "").upper()
1288
 
1289
+ # 1M: sqrt-time volatility band (the 1D flat +/-1% NEUTRAL and the day-length power law both
1290
+ # break down over ~21 sessions β€” see the _ONE_M_* constants).
1291
+ if tf_label == "1M" and _dir in ("NEUTRAL", "BULLISH", "BEARISH"):
1292
+ span = math.sqrt(_ONE_M_SESSIONS) * atr_pct
1293
+ if _dir == "NEUTRAL":
1294
+ half = min(cap, _ONE_M_NEUT_MAX_PCT, max(_ONE_M_NEUT_MIN_PCT, _ONE_M_NEUT_K * span))
1295
+ lo, hi = -half, half
1296
+ else:
1297
+ near = max(_ONE_M_MIN_NEAR_PCT, _ONE_M_NEAR_K * span)
1298
+ far = min(cap, max(_ONE_M_FAR_K * span, near + _MIN_SPREAD_PCT["1M"]))
1299
+ near = min(near, far - _ONE_M_MIN_NEAR_PCT)
1300
+ lo, hi = (near, far) if _dir == "BULLISH" else (-far, -near)
1301
+ return {
1302
+ "predicted_return_lo": round(lo, 2),
1303
+ "predicted_return_hi": round(hi, 2),
1304
+ "target_price_lo": round(current_price * (1 + lo / 100), 2),
1305
+ "target_price_hi": round(current_price * (1 + hi / 100), 2),
1306
+ }
1307
+
1308
  # NEUTRAL: FLAT, falsifiable band by policy β€” NOT an ATR/volatility magnitude. A NEUTRAL call
1309
  # must give the user an actionable "stays within X%" claim they can bet on; an ATR-scaled band
1310
  # ballooned to Β±5%+ on volatile stocks, which tells the user nothing ("no idea what to bet on").
 
1753
 
1754
 
1755
  def _build_bull_prompt(ctx: str, social: str, tf_label: str, current_price: float = 0.0, ticker: str = "", company: str = "") -> str:
1756
+ holding = {"INTRADAY": "the rest of today's session (until ~3pm)", "1D": "1 trading day", "3D": "3 trading days", "5D": "5 trading days", "1M": "~1 month (about 21 trading days)"}.get(tf_label, "3 trading days")
1757
  stock_id = f"{company} ({ticker})" if company and ticker else (ticker or company or "this stock")
1758
  price_anchor = (
1759
  f"IMPORTANT: You are analyzing {stock_id}. "
 
1772
 
1773
 
1774
  def _build_bear_prompt(ctx: str, social: str, tf_label: str, current_price: float = 0.0, ticker: str = "", company: str = "") -> str:
1775
+ holding = {"INTRADAY": "the rest of today's session (until ~3pm)", "1D": "1 trading day", "3D": "3 trading days", "5D": "5 trading days", "1M": "~1 month (about 21 trading days)"}.get(tf_label, "3 trading days")
1776
  stock_id = f"{company} ({ticker})" if company and ticker else (ticker or company or "this stock")
1777
  price_anchor = (
1778
  f"IMPORTANT: You are analyzing {stock_id}. "
 
1810
  atr14: float,
1811
  nifty_ok: bool = True,
1812
  ) -> str:
1813
+ _cap_pct = {"INTRADAY": 2.0, "1D": 4.0, "3D": 7.0, "5D": 12.0, "1M": 25.0}.get(tf_label, 7.0)
1814
  holding = {"INTRADAY": "the rest of today's session (target must be touched by ~3pm)",
1815
+ "1D": "1 trading day", "3D": "3 trading days", "5D": "5 trading days",
1816
+ "1M": "~1 month (about 21 trading days)"}.get(tf_label, "3 trading days")
1817
 
1818
  # Direction rules β€” decisive momentum-based framework.
1819
  # KEY PRINCIPLES:
 
1978
  "Nifty below EMA200 β†’ cap at MEDIUM. "
1979
  "LOW = weak/conflicting signals.\n"
1980
  ),
1981
+ "1M": (
1982
+ "DIRECTION GUIDE for 1M (a ~1-month, ~21-trading-day hold; buy now, target at the end of the month) β€” "
1983
+ "daily noise is irrelevant; trend and relative strength vs Nifty dominate. Ignore 1D mean-reversion "
1984
+ "and next-day overbought rules.\n\n"
1985
+ "BULLISH triggers (ANY one is sufficient):\n"
1986
+ " [M1] Price above EMA50 AND 20D momentum > 0% AND 3M relative strength vs Nifty >= 0 AND RSI <= 72\n"
1987
+ " (and not below a falling EMA200) [1-month trend intact and outperforming the market]\n"
1988
+ " [M2] Price above EMA50 AND 20D momentum between -3% and 0% AND RSI < 50 AND relative strength >= 0\n"
1989
+ " [a shallow pullback within an uptrend β€” a better entry for a month-long hold]\n"
1990
+ "BEARISH triggers (ANY one is sufficient):\n"
1991
+ " [MB1] Below EMA50 AND 20D momentum < -4% AND MACD < 0 AND 3M relative strength < 0\n"
1992
+ " [MB2] 10D momentum < -6% OR 20D momentum < -8% (sustained decline) AND MACD < 0 [falling knife]\n"
1993
+ "STRUCTURAL LAGGARD GUARD: if 3M relative strength vs Nifty < -8% β†’ do NOT call BULLISH, however\n"
1994
+ " oversold the stock looks (a month is too short for a chronic underperformer to turn).\n"
1995
+ "CRASH GUARD: if 10D momentum < -6% OR 20D momentum < -8% β†’ no BULLISH bounce call.\n"
1996
+ "NEUTRAL: no trigger fires, or bullish and bearish triggers conflict. A month-long position needs\n"
1997
+ " trend evidence β€” do not force a direction on a stock with no trend and no relative strength.\n"
1998
+ "Confidence: HIGH = trend (EMA50 and EMA200) + relative strength + sector all aligned AND Nifty above\n"
1999
+ "EMA200. MEDIUM = one clear trigger. Nifty below EMA200 β†’ cap at MEDIUM. LOW = weak/conflicting β†’ NEUTRAL.\n"
2000
+ "Targets are the realistic best/worst the stock can reach over the month β€” scaled to ITS OWN volatility.\n"
2001
+ ),
2002
  }.get(tf_label, "")
2003
 
2004
  signal_rules = (
 
2062
  "INTRADAY": (0.20, 0.45),
2063
  "1D": (0.25, 0.60),
2064
  "3D": (0.45, 0.95),
2065
+ # 1M: same sqrt-time multiples as the production band (_atr_clamp_range) in ATR units.
2066
+ "1M": (_ONE_M_NEAR_K * math.sqrt(_ONE_M_SESSIONS), _ONE_M_FAR_K * math.sqrt(_ONE_M_SESSIONS)),
2067
  }.get(tf_label, (0.25, 0.60))
2068
  _atr_for_tgt = atr14 if atr14 and atr14 > 0 else max(0.01, current_price * 0.015)
2069
  _bull_lo = current_price + _lo_mult * _atr_for_tgt
 
2148
  Source label: "{provider}:{model}+debate+fund" | "+debate" | "" | "heuristic".
2149
  """
2150
  # ── Parse arguments ────────────────────────────────────────────────────────
2151
+ _TF_LABELS = ("INTRADAY", "1D", "3D", "5D", "1M")
2152
  company = args[0] if len(args) >= 1 and isinstance(args[0], str) and args[0] not in _TF_LABELS else kwargs.get("company", ticker)
2153
  tf_label = next((a for a in args if a in _TF_LABELS), None) or kwargs.get("tf_label", "3D")
2154
  ml = args[2] if len(args) >= 3 and isinstance(args[2], dict) else kwargs.get("ml", {})
app.py CHANGED
@@ -119,6 +119,9 @@ _TOP5_PROGRESS_LOCK = __import__("threading").Lock()
119
  # TTL: 1D/3D/5D cached until IST midnight (re-run not needed same trading day).
120
  # INTRADAY: 15-min TTL, auto-refreshed by _start_intraday_refresh_scheduler().
121
  _WATCHLIST_PICK_CACHE: dict = {}
 
 
 
122
  _WATCHLIST_PICK_AI_UNAVAILABLE_TTL = 125 # short TTL when AI was unavailable (>120s Ollama backoff so retry fires after cooldown clears)
123
  _WATCHLIST_MARKET_CTX_CACHE: dict = {"ts": 0.0, "data": None}
124
  _WATCHLIST_MARKET_CTX_LOCK = threading.Lock()
@@ -484,12 +487,12 @@ def _classify_watchlist_warning(err: object) -> str:
484
  def _resolve_dates(data: dict) -> tuple[str, str]:
485
  """Return (start, end) from either timeframe or explicit dates.
486
 
487
- Only INTRADAY/1D are accepted as timeframe shortcuts β€” 3D/5D are retired from the live
488
  API. A 3D/5D timeframe falls through to explicit start/end dates (usually absent), so the
489
  caller gets the "timeframe required" error instead of a 3D/5D prediction.
490
  """
491
  tf = data.get("timeframe", "").upper()
492
- if tf in ("INTRADAY", "1D"):
493
  return timeframe_to_dates(tf)
494
  start = data.get("start_date", "")
495
  end = data.get("end_date", "")
@@ -836,9 +839,13 @@ def _with_live_prices(payload: dict) -> dict:
836
  picks = payload.get("picks") if isinstance(payload, dict) else None
837
  if not isinstance(picks, list):
838
  return payload
 
 
 
839
 
840
  out = dict(payload)
841
- tickers = [p["ticker"] for p in picks if isinstance(p, dict) and p.get("ticker")]
 
842
 
843
  price_map: dict = {}
844
  if tickers:
@@ -869,29 +876,34 @@ def _with_live_prices(payload: dict) -> dict:
869
  finally:
870
  ex.shutdown(wait=False)
871
 
872
- out_picks = []
873
- for p in picks:
874
- if not isinstance(p, dict):
875
- out_picks.append(p)
876
- continue
877
- cloned = dict(p)
878
- ticker = p.get("ticker")
879
- if ticker and ticker in price_map:
880
- _live = price_map[ticker]
881
- cloned["price"] = _live
882
- cloned["current_price"] = _live
883
- # Re-anchor each timeframe's targets to the fresh live price so the shown target
884
- # range stays ahead of the current price (pre-market/gap moves otherwise leave the
885
- # cached target already surpassed). Clone the timeframes dict to avoid mutating the
886
- # shared cached pick.
887
- _tfs = cloned.get("timeframes")
888
- if isinstance(_tfs, dict):
889
- _tfs = {k: (dict(v) if isinstance(v, dict) else v) for k, v in _tfs.items()}
890
- for _tf_v in _tfs.values():
891
- _reanchor_targets_to_live(_tf_v, _live)
892
- cloned["timeframes"] = _tfs
893
- out_picks.append(cloned)
894
- out["picks"] = out_picks
 
 
 
 
 
895
  return out
896
 
897
 
@@ -978,14 +990,14 @@ def _read_iteration_metrics(path: str) -> dict | None:
978
 
979
 
980
  def _archive_top5_predictions(result: dict, source: str = "top5") -> None:
981
- """Persist predictions for validation tracking."""
982
- for pick in result.get("picks", []):
983
  ticker = pick.get("ticker")
984
  if not ticker:
985
  continue
986
  price = pick.get("price", 0)
987
  timeframes = pick.get("timeframes", {})
988
- for tf in ["INTRADAY", "1D"]:
989
  tf_data = timeframes.get(tf, {})
990
  direction = tf_data.get("direction", "NEUTRAL")
991
  # Skip NO TRADE / data-error entries β€” they have no meaningful range to validate
@@ -1314,7 +1326,7 @@ def predict():
1314
  if not stocks:
1315
  return jsonify({"error": "Provide at least one ticker"}), 400
1316
  if not start or not end:
1317
- return jsonify({"error": "timeframe (INTRADAY/1D) or start_date + end_date required"}), 400
1318
  if len(stocks) > 20:
1319
  return jsonify({"error": "Max 20 stocks per request"}), 400
1320
 
@@ -1348,7 +1360,7 @@ def rank():
1348
  universe = data.get("universe")
1349
 
1350
  if not start or not end:
1351
- return jsonify({"error": "timeframe (INTRADAY/1D) or start_date + end_date required"}), 400
1352
 
1353
  if capital:
1354
  try:
@@ -2098,6 +2110,10 @@ def top5():
2098
  result["picks"] = [dict(pick) for pick in payload.get("picks", []) if pick.get("ticker") in members]
2099
  for rank, pick in enumerate(result["picks"], 1):
2100
  pick["rank"] = rank
 
 
 
 
2101
  result["universe"] = "NIFTY50"
2102
  result["universe_size"] = len(members)
2103
  return _json_no_store(result)
@@ -2305,7 +2321,7 @@ def watchlist_remove(ticker: str):
2305
  t = _normalise(ticker)
2306
  removed = db.remove_from_watchlist(t)
2307
  if removed:
2308
- for _tf in ("INTRADAY", "1D", "3D"):
2309
  _WATCHLIST_PICK_CACHE.pop((t, _tf), None)
2310
  return jsonify({"removed": t})
2311
  return jsonify({"error": "Not found"}), 404
@@ -2360,7 +2376,7 @@ def _watchlist_market_ctx(force_refresh: bool = False) -> dict:
2360
 
2361
  def _build_watchlist_pick(item: dict, preds: dict) -> tuple[dict, dict]:
2362
  """Build one watchlist pick payload from timeframe predictions."""
2363
- TIMEFRAMES = ["INTRADAY", "1D"] # 3D + 5D removed β€” INTRADAY/1D are the shown horizons
2364
 
2365
  anchor_tf = next(
2366
  (tf for tf in ["1D", "INTRADAY"] if preds.get(tf) and not preds[tf].get("error")),
@@ -2508,7 +2524,7 @@ def _build_watchlist_pick(item: dict, preds: dict) -> tuple[dict, dict]:
2508
 
2509
  # Refresh entry prices from the current live price so cached predictions don't show
2510
  # stale β‚Ή anchors. Buffers match ENTRY_BUFFER_BY_TIMEFRAME in predictor_core.
2511
- _entry_buffers = {"INTRADAY": 0.001, "1D": 0.002}
2512
  if live:
2513
  for _tf, _buf in _entry_buffers.items():
2514
  _tf_d = timeframes.get(_tf, {})
@@ -2609,7 +2625,7 @@ def watchlist_pick_single(ticker: str):
2609
  _now_ist_dt = _now_ist()
2610
  _intraday_too_late = market_is_open and (_now_ist_dt.hour, _now_ist_dt.minute) >= (14, 15)
2611
 
2612
- all_tfs = ["INTRADAY", "1D"] # 3D + 5D removed from live predictions
2613
  preds: dict = {}
2614
 
2615
  if not _intraday_live:
@@ -2745,7 +2761,7 @@ def watchlist_pick_single_tf(ticker: str, tf: str):
2745
  Used by the frontend for progressive per-TF card loading and INTRADAY auto-refresh β€”
2746
  for BOTH watchlist cards and top-pick cards, so it accepts any ticker (not only watchlist
2747
  members). The /api/pick-tf/ alias is the explicit non-watchlist entry point."""
2748
- VALID_TFS = {"INTRADAY", "1D"} # 3D/5D retired from the live API
2749
  tf = tf.upper()
2750
  if tf not in VALID_TFS:
2751
  return jsonify({"error": f"Invalid timeframe: {tf}"}), 400
@@ -2883,7 +2899,7 @@ def watchlist_picks():
2883
  picks.append(_watchlist_contract_pick(item))
2884
  continue
2885
  preds: dict = {}
2886
- for tf in ("INTRADAY", "1D"):
2887
  pred, stale, _saved_at = _watchlist_prediction_cache_get(
2888
  item["ticker"], tf, allow_stale=True
2889
  )
@@ -2929,8 +2945,8 @@ def watchlist_picks():
2929
  _now_ist_dt = _now_ist()
2930
  _intraday_too_late = market_is_open and (_now_ist_dt.hour, _now_ist_dt.minute) >= (14, 15)
2931
 
2932
- tfs_to_run = (["INTRADAY", "1D"] if (_intraday_live and not _intraday_too_late)
2933
- else ["1D"])
2934
 
2935
  def _predict(ticker, tf):
2936
  start, end = timeframe_to_dates(tf)
@@ -3030,7 +3046,7 @@ def watchlist_picks():
3030
  if alerts_enabled:
3031
  try:
3032
  from whatsapp_alerts import send_bulk_alerts
3033
- all_tf_preds = [tf_pred for pick in picks for tf_pred in pick.get("timeframes", {}).values() if isinstance(tf_pred, dict)]
3034
  send_bulk_alerts(all_tf_preds)
3035
  except Exception:
3036
  pass
@@ -3837,8 +3853,8 @@ def prediction_validation():
3837
  """
3838
  from datetime import datetime, timedelta, timezone
3839
 
3840
- # Get all predictions from last 7 days
3841
- snapshots = db.get_prediction_snapshots(ticker=None, days=7, limit=500)
3842
 
3843
  if not snapshots:
3844
  return _json_no_store({"validation": [], "summary": {}})
@@ -3846,7 +3862,7 @@ def prediction_validation():
3846
  validation_results = []
3847
 
3848
  # Timeframe expiry offsets (days to wait before checking). INTRADAY = same-day.
3849
- tf_offset = {"INTRADAY": 0, "1D": 1, "3D": 3, "5D": 5}
3850
 
3851
  now_utc = datetime.now(timezone.utc)
3852
  now_ist = now_utc.astimezone(timezone(timedelta(hours=5, minutes=30)))
@@ -3963,7 +3979,7 @@ def prediction_validation():
3963
 
3964
  # Compute summary statistics by timeframe
3965
  summary = {}
3966
- for tf in ["INTRADAY", "1D", "3D", "5D"]:
3967
  validated = [v for v in validation_results if v["timeframe"] == tf and v["status"] == "VALIDATED"]
3968
  if validated:
3969
  hits = sum(1 for v in validated if v["target_hit"])
@@ -4027,8 +4043,10 @@ def _fetch_price_window(ticker: str, start_date_str: str, end_date_str: str):
4027
  return None, None, None
4028
  try:
4029
  today = datetime.now(timezone(timedelta(hours=5, minutes=30))).date()
4030
- end = datetime.strptime(end_date_str, "%Y-%m-%d").date()
4031
- days_back = max((today - end).days + 15, 15)
 
 
4032
  if days_back <= 30:
4033
  period = "1mo"
4034
  elif days_back <= 90:
 
119
  # TTL: 1D/3D/5D cached until IST midnight (re-run not needed same trading day).
120
  # INTRADAY: 15-min TTL, auto-refreshed by _start_intraday_refresh_scheduler().
121
  _WATCHLIST_PICK_CACHE: dict = {}
122
+ # Horizons predicted for equities in the live app. 1M is a ~21-session hold: AI forecast only
123
+ # (no ML model), never the "Best Bet" timeframe. 3D/5D stay retired from the live API.
124
+ LIVE_TIMEFRAMES = ["INTRADAY", "1D", "1M"]
125
  _WATCHLIST_PICK_AI_UNAVAILABLE_TTL = 125 # short TTL when AI was unavailable (>120s Ollama backoff so retry fires after cooldown clears)
126
  _WATCHLIST_MARKET_CTX_CACHE: dict = {"ts": 0.0, "data": None}
127
  _WATCHLIST_MARKET_CTX_LOCK = threading.Lock()
 
487
  def _resolve_dates(data: dict) -> tuple[str, str]:
488
  """Return (start, end) from either timeframe or explicit dates.
489
 
490
+ Only LIVE_TIMEFRAMES (INTRADAY/1D/1M) are accepted as timeframe shortcuts β€” 3D/5D are retired from the live
491
  API. A 3D/5D timeframe falls through to explicit start/end dates (usually absent), so the
492
  caller gets the "timeframe required" error instead of a 3D/5D prediction.
493
  """
494
  tf = data.get("timeframe", "").upper()
495
+ if tf in LIVE_TIMEFRAMES:
496
  return timeframe_to_dates(tf)
497
  start = data.get("start_date", "")
498
  end = data.get("end_date", "")
 
839
  picks = payload.get("picks") if isinstance(payload, dict) else None
840
  if not isinstance(picks, list):
841
  return payload
842
+ picks_1m = payload.get("picks_1m")
843
+ if not isinstance(picks_1m, list):
844
+ picks_1m = None
845
 
846
  out = dict(payload)
847
+ tickers = list(dict.fromkeys(
848
+ p["ticker"] for p in [*picks, *(picks_1m or [])] if isinstance(p, dict) and p.get("ticker")))
849
 
850
  price_map: dict = {}
851
  if tickers:
 
876
  finally:
877
  ex.shutdown(wait=False)
878
 
879
+ def _apply_live(pick_list: list) -> list:
880
+ out_picks = []
881
+ for p in pick_list:
882
+ if not isinstance(p, dict):
883
+ out_picks.append(p)
884
+ continue
885
+ cloned = dict(p)
886
+ ticker = p.get("ticker")
887
+ if ticker and ticker in price_map:
888
+ _live = price_map[ticker]
889
+ cloned["price"] = _live
890
+ cloned["current_price"] = _live
891
+ # Re-anchor each timeframe's targets to the fresh live price so the shown target
892
+ # range stays ahead of the current price (pre-market/gap moves otherwise leave the
893
+ # cached target already surpassed). Clone the timeframes dict to avoid mutating the
894
+ # shared cached pick.
895
+ _tfs = cloned.get("timeframes")
896
+ if isinstance(_tfs, dict):
897
+ _tfs = {k: (dict(v) if isinstance(v, dict) else v) for k, v in _tfs.items()}
898
+ for _tf_v in _tfs.values():
899
+ _reanchor_targets_to_live(_tf_v, _live)
900
+ cloned["timeframes"] = _tfs
901
+ out_picks.append(cloned)
902
+ return out_picks
903
+
904
+ out["picks"] = _apply_live(picks)
905
+ if picks_1m is not None:
906
+ out["picks_1m"] = _apply_live(picks_1m)
907
  return out
908
 
909
 
 
990
 
991
 
992
  def _archive_top5_predictions(result: dict, source: str = "top5") -> None:
993
+ """Persist predictions for validation tracking (picks plus the separate 1M ranking)."""
994
+ for pick in [*result.get("picks", []), *(result.get("picks_1m") or [])]:
995
  ticker = pick.get("ticker")
996
  if not ticker:
997
  continue
998
  price = pick.get("price", 0)
999
  timeframes = pick.get("timeframes", {})
1000
+ for tf in LIVE_TIMEFRAMES:
1001
  tf_data = timeframes.get(tf, {})
1002
  direction = tf_data.get("direction", "NEUTRAL")
1003
  # Skip NO TRADE / data-error entries β€” they have no meaningful range to validate
 
1326
  if not stocks:
1327
  return jsonify({"error": "Provide at least one ticker"}), 400
1328
  if not start or not end:
1329
+ return jsonify({"error": "timeframe (INTRADAY/1D/1M) or start_date + end_date required"}), 400
1330
  if len(stocks) > 20:
1331
  return jsonify({"error": "Max 20 stocks per request"}), 400
1332
 
 
1360
  universe = data.get("universe")
1361
 
1362
  if not start or not end:
1363
+ return jsonify({"error": "timeframe (INTRADAY/1D/1M) or start_date + end_date required"}), 400
1364
 
1365
  if capital:
1366
  try:
 
2110
  result["picks"] = [dict(pick) for pick in payload.get("picks", []) if pick.get("ticker") in members]
2111
  for rank, pick in enumerate(result["picks"], 1):
2112
  pick["rank"] = rank
2113
+ if isinstance(payload.get("picks_1m"), list):
2114
+ result["picks_1m"] = [dict(pick) for pick in payload["picks_1m"] if pick.get("ticker") in members]
2115
+ for rank, pick in enumerate(result["picks_1m"], 1):
2116
+ pick["rank"] = rank
2117
  result["universe"] = "NIFTY50"
2118
  result["universe_size"] = len(members)
2119
  return _json_no_store(result)
 
2321
  t = _normalise(ticker)
2322
  removed = db.remove_from_watchlist(t)
2323
  if removed:
2324
+ for _tf in (*LIVE_TIMEFRAMES, "3D"):
2325
  _WATCHLIST_PICK_CACHE.pop((t, _tf), None)
2326
  return jsonify({"removed": t})
2327
  return jsonify({"error": "Not found"}), 404
 
2376
 
2377
  def _build_watchlist_pick(item: dict, preds: dict) -> tuple[dict, dict]:
2378
  """Build one watchlist pick payload from timeframe predictions."""
2379
+ TIMEFRAMES = LIVE_TIMEFRAMES # 3D + 5D removed β€” INTRADAY/1D/1M are the shown horizons
2380
 
2381
  anchor_tf = next(
2382
  (tf for tf in ["1D", "INTRADAY"] if preds.get(tf) and not preds[tf].get("error")),
 
2524
 
2525
  # Refresh entry prices from the current live price so cached predictions don't show
2526
  # stale β‚Ή anchors. Buffers match ENTRY_BUFFER_BY_TIMEFRAME in predictor_core.
2527
+ _entry_buffers = {"INTRADAY": 0.001, "1D": 0.002, "1M": 0.0} # 1M entry = the live price ("buy now")
2528
  if live:
2529
  for _tf, _buf in _entry_buffers.items():
2530
  _tf_d = timeframes.get(_tf, {})
 
2625
  _now_ist_dt = _now_ist()
2626
  _intraday_too_late = market_is_open and (_now_ist_dt.hour, _now_ist_dt.minute) >= (14, 15)
2627
 
2628
+ all_tfs = LIVE_TIMEFRAMES # 3D + 5D removed from live predictions
2629
  preds: dict = {}
2630
 
2631
  if not _intraday_live:
 
2761
  Used by the frontend for progressive per-TF card loading and INTRADAY auto-refresh β€”
2762
  for BOTH watchlist cards and top-pick cards, so it accepts any ticker (not only watchlist
2763
  members). The /api/pick-tf/ alias is the explicit non-watchlist entry point."""
2764
+ VALID_TFS = set(LIVE_TIMEFRAMES) # 3D/5D retired from the live API
2765
  tf = tf.upper()
2766
  if tf not in VALID_TFS:
2767
  return jsonify({"error": f"Invalid timeframe: {tf}"}), 400
 
2899
  picks.append(_watchlist_contract_pick(item))
2900
  continue
2901
  preds: dict = {}
2902
+ for tf in LIVE_TIMEFRAMES:
2903
  pred, stale, _saved_at = _watchlist_prediction_cache_get(
2904
  item["ticker"], tf, allow_stale=True
2905
  )
 
2945
  _now_ist_dt = _now_ist()
2946
  _intraday_too_late = market_is_open and (_now_ist_dt.hour, _now_ist_dt.minute) >= (14, 15)
2947
 
2948
+ tfs_to_run = (list(LIVE_TIMEFRAMES) if (_intraday_live and not _intraday_too_late)
2949
+ else [_tf for _tf in LIVE_TIMEFRAMES if _tf != "INTRADAY"])
2950
 
2951
  def _predict(ticker, tf):
2952
  start, end = timeframe_to_dates(tf)
 
3046
  if alerts_enabled:
3047
  try:
3048
  from whatsapp_alerts import send_bulk_alerts
3049
+ all_tf_preds = [tf_pred for pick in picks for _tfk, tf_pred in pick.get("timeframes", {}).items() if _tfk != "1M" and isinstance(tf_pred, dict)] # 1M is unvalidated β€” no alerts
3050
  send_bulk_alerts(all_tf_preds)
3051
  except Exception:
3052
  pass
 
3853
  """
3854
  from datetime import datetime, timedelta, timezone
3855
 
3856
+ # Last 45 days: a 1M snapshot must stay readable until its ~30-day window matures.
3857
+ snapshots = db.get_prediction_snapshots(ticker=None, days=45, limit=500)
3858
 
3859
  if not snapshots:
3860
  return _json_no_store({"validation": [], "summary": {}})
 
3862
  validation_results = []
3863
 
3864
  # Timeframe expiry offsets (days to wait before checking). INTRADAY = same-day.
3865
+ tf_offset = db.TF_CALENDAR_OFFSET
3866
 
3867
  now_utc = datetime.now(timezone.utc)
3868
  now_ist = now_utc.astimezone(timezone(timedelta(hours=5, minutes=30)))
 
3979
 
3980
  # Compute summary statistics by timeframe
3981
  summary = {}
3982
+ for tf in ["INTRADAY", "1D", "3D", "5D", "1M"]:
3983
  validated = [v for v in validation_results if v["timeframe"] == tf and v["status"] == "VALIDATED"]
3984
  if validated:
3985
  hits = sum(1 for v in validated if v["target_hit"])
 
4043
  return None, None, None
4044
  try:
4045
  today = datetime.now(timezone(timedelta(hours=5, minutes=30))).date()
4046
+ # Size the download from the window START so a long window (1M ~30 days) is never
4047
+ # truncated at its beginning (that would undercount the window high/low).
4048
+ start = datetime.strptime(start_date_str, "%Y-%m-%d").date()
4049
+ days_back = max((today - start).days + 15, 15)
4050
  if days_back <= 30:
4051
  period = "1mo"
4052
  elif days_back <= 90:
database.py CHANGED
@@ -367,6 +367,8 @@ def _migrate() -> None:
367
  WHEN '1D' THEN DATE(created_at, '+1 day')
368
  WHEN '3D' THEN DATE(created_at, '+3 day')
369
  WHEN '5D' THEN DATE(created_at, '+5 day')
 
 
370
  ELSE DATE(created_at, '+1 day')
371
  END
372
  WHERE validation_target_date IS NULL OR TRIM(validation_target_date) = ''
@@ -1155,12 +1157,16 @@ def get_postmortems() -> list[dict]:
1155
 
1156
  # ── PREDICTION SNAPSHOTS (audit trail) ───────────────────────────────────────
1157
 
 
 
 
 
 
1158
  def _trading_deadline(timeframe: str) -> str:
1159
  """Return the ISO date string when a prediction for the given timeframe expires (weekends + NSE holidays skipped)."""
1160
  from datetime import datetime, timedelta, timezone
1161
  from market_calendar import next_trading_day
1162
- tf_offset = {"INTRADAY": 0, "1D": 1, "3D": 3, "5D": 5, "1W": 7}
1163
- days_offset = tf_offset.get(timeframe, 1)
1164
  now_ist = datetime.now(timezone.utc).astimezone(timezone(timedelta(hours=5, minutes=30)))
1165
  target_dt = now_ist + timedelta(days=days_offset)
1166
  return next_trading_day(target_dt.date()).isoformat()
@@ -1191,8 +1197,7 @@ def save_prediction_snapshot(
1191
  # Calculate validation target date based on timeframe, skipping weekends and NSE holidays.
1192
  # INTRADAY (offset 0) validates same-day β€” target_date == today (a trading day).
1193
  from market_calendar import next_trading_day
1194
- tf_offset = {"INTRADAY": 0, "1D": 1, "3D": 3, "5D": 5, "1W": 7}
1195
- days_offset = tf_offset.get(timeframe, 1)
1196
  now_utc = datetime.now(timezone.utc)
1197
  now_ist = now_utc.astimezone(timezone(timedelta(hours=5, minutes=30)))
1198
  # INTRADAY predictions made at/after the 15:00 IST grading cutoff (matches
 
367
  WHEN '1D' THEN DATE(created_at, '+1 day')
368
  WHEN '3D' THEN DATE(created_at, '+3 day')
369
  WHEN '5D' THEN DATE(created_at, '+5 day')
370
+ WHEN '1W' THEN DATE(created_at, '+7 day')
371
+ WHEN '1M' THEN DATE(created_at, '+30 day')
372
  ELSE DATE(created_at, '+1 day')
373
  END
374
  WHERE validation_target_date IS NULL OR TRIM(validation_target_date) = ''
 
1157
 
1158
  # ── PREDICTION SNAPSHOTS (audit trail) ───────────────────────────────────────
1159
 
1160
+ # Calendar-day offset from prediction time to its validation/expiry date (rolled forward to the next
1161
+ # trading day). 1M = 30 calendar days (~21 sessions). An unknown timeframe falls back to +1 day.
1162
+ TF_CALENDAR_OFFSET = {"INTRADAY": 0, "1D": 1, "3D": 3, "5D": 5, "1W": 7, "1M": 30}
1163
+
1164
+
1165
  def _trading_deadline(timeframe: str) -> str:
1166
  """Return the ISO date string when a prediction for the given timeframe expires (weekends + NSE holidays skipped)."""
1167
  from datetime import datetime, timedelta, timezone
1168
  from market_calendar import next_trading_day
1169
+ days_offset = TF_CALENDAR_OFFSET.get(timeframe, 1)
 
1170
  now_ist = datetime.now(timezone.utc).astimezone(timezone(timedelta(hours=5, minutes=30)))
1171
  target_dt = now_ist + timedelta(days=days_offset)
1172
  return next_trading_day(target_dt.date()).isoformat()
 
1197
  # Calculate validation target date based on timeframe, skipping weekends and NSE holidays.
1198
  # INTRADAY (offset 0) validates same-day β€” target_date == today (a trading day).
1199
  from market_calendar import next_trading_day
1200
+ days_offset = TF_CALENDAR_OFFSET.get(timeframe, 1)
 
1201
  now_utc = datetime.now(timezone.utc)
1202
  now_ist = now_utc.astimezone(timezone(timedelta(hours=5, minutes=30)))
1203
  # INTRADAY predictions made at/after the 15:00 IST grading cutoff (matches
market_calendar.py CHANGED
@@ -73,8 +73,19 @@ _MARKET_CLOSE_IST = (15, 30) # 15:30
73
  _IST_OFFSET = timedelta(hours=5, minutes=30)
74
 
75
 
 
 
 
76
  def is_nse_holiday(d: date) -> bool:
77
- """Return True if `d` is an NSE-declared holiday (not a weekend)."""
 
 
 
 
 
 
 
 
78
  return d.isoformat() in _NSE_HOLIDAYS
79
 
80
 
 
73
  _IST_OFFSET = timedelta(hours=5, minutes=30)
74
 
75
 
76
+ _WARNED_YEARS: set[int] = set()
77
+
78
+
79
  def is_nse_holiday(d: date) -> bool:
80
+ """Return True if `d` is an NSE-declared holiday (not a weekend).
81
+
82
+ A year with no holidays loaded is treated as weekdays-only (long horizons such as the 1M
83
+ forecast can land in next year before NSE publishes its list); a warning is logged once.
84
+ """
85
+ if d.year not in _WARNED_YEARS and not any(h.startswith(f"{d.year}-") for h in _NSE_HOLIDAYS):
86
+ _WARNED_YEARS.add(d.year)
87
+ logger.warning("market_calendar: no NSE holidays loaded for %s β€” treating all weekdays as "
88
+ "trading days. Add the year's list to _NSE_HOLIDAYS.", d.year)
89
  return d.isoformat() in _NSE_HOLIDAYS
90
 
91
 
predictor_core.py CHANGED
@@ -95,11 +95,12 @@ except ImportError:
95
  _HAS_FUNDAMENTALS = False
96
 
97
  # ── TIMEFRAME HELPER ─────────────────────────────────────────────────────────
98
- TIMEFRAME_DAYS: dict[str, int] = {"INTRADAY": 0, "1D": 1, "3D": 3, "5D": 5, "1W": 7}
 
99
 
100
 
101
  def timeframe_to_dates(tf: str) -> tuple[str, str]:
102
- """Convert 'INTRADAY'/'1D'/'3D'/'5D' to (start_date, end_date) strings.
103
 
104
  On weekdays start_date = today (unchanged).
105
  On weekends/holidays start_date advances to the next trading day so
@@ -273,6 +274,7 @@ ENTRY_BUFFER_BY_TIMEFRAME: dict[str, float] = {
273
  "3D": 0.003, # 0.30%
274
  "5D": 0.005, # 0.50%
275
  "1W": 0.007, # 0.70% β€” wider buffer for longer hold
 
276
  }
277
 
278
  # INTRADAY minimum favorable move: a same-session trade must be able to clear ~1% to be worth
@@ -886,7 +888,7 @@ def _directional_forecast(
886
 
887
  Returns a dict with predicted_direction, predicted_return_lo, predicted_return_hi.
888
  """
889
- tf_scale = {"INTRADAY": 0.20, "1D": 0.35, "3D": 0.65, "5D": 1.0, "1W": 1.3}.get(tf_label, 1.0)
890
  regime_mult = 0.7 if not nifty_ok else 1.0
891
  vix_mult = 0.8 if vix_level > 20 else 1.0
892
 
@@ -1390,7 +1392,7 @@ def predict_stock_v2(ticker: str, start_date: str, end_date: str,
1390
  if start_date == end_date:
1391
  _tf_label = "INTRADAY"
1392
  else:
1393
- _tf_label = "1D" if n_trading <= 2 else ("3D" if n_trading <= 4 else ("5D" if n_trading <= 6 else "1W"))
1394
  _relevant = STRATEGY_TIMEFRAME_MAP.get(_tf_label, sig_result["active"])
1395
  _active_for_ev = [s for s in sig_result["active"] if s in _relevant]
1396
 
@@ -1525,6 +1527,11 @@ def predict_stock_v2(ticker: str, start_date: str, end_date: str,
1525
  _indicators["return_20d"] = round((_price_now / float(_c.iloc[-20]) - 1) * 100, 1)
1526
  if len(_c) >= 63:
1527
  _indicators["return_90d"] = round((_price_now / float(_c.iloc[-63]) - 1) * 100, 1)
 
 
 
 
 
1528
  if len(_c) >= 252:
1529
  _hi52 = float(_c.iloc[-252:].max())
1530
  _indicators["Dist_from_52W_High_%"] = round((_price_now / _hi52 - 1) * 100, 1)
@@ -1738,12 +1745,16 @@ def predict_stock_v2(ticker: str, start_date: str, end_date: str,
1738
 
1739
  # Global directional preference: if AI still lands NEUTRAL on a mature ticker,
1740
  # resolve to up/down from ML probability so the card is actionable.
 
 
 
1741
  _hist_len = len(sc[ticker].dropna()) if ticker in sc.columns else 0
1742
  if (
1743
  AI_ALWAYS_DIRECTIONAL_CALL
1744
  and _run_ai_forecast
1745
  and _ai_real
1746
  and direction == "NEUTRAL"
 
1747
  and _hist_len >= 200
1748
  ):
1749
  _ml_prob = float(ml.get("probability", 0.5) or 0.5)
@@ -1789,7 +1800,7 @@ def predict_stock_v2(ticker: str, start_date: str, end_date: str,
1789
  atr14_val = float(atr14_series.iloc[-1])
1790
  # ATR multiplier and R:R target keyed to _tf_label (not raw n_trading)
1791
  # so the 1D weekend-buffer inflation (n_trading=2) doesn't bleed into 3D sizing.
1792
- atr_mult = {"INTRADAY": 0.4, "1D": 0.7, "3D": 1.1, "5D": 1.5, "1W": 1.8}.get(_tf_label, 1.5)
1793
  sl_risk = atr_mult * atr14_val
1794
  # Final SL/target/R:R are computed later after entry_price is finalized
1795
  # and with direction-aware logic (LONG vs SHORT).
@@ -1890,7 +1901,7 @@ def predict_stock_v2(ticker: str, start_date: str, end_date: str,
1890
  # Backtest has no live price (_live_price is None) β†’ falls back to the prior close, so
1891
  # historical behaviour is unchanged.
1892
  _has_live = _live_price is not None and _live_price > 0
1893
- _use_live = _has_live and _tf_label in ("INTRADAY", "1D", "3D")
1894
 
1895
  # NOTE: a "gapped past target" flag used to be computed here by comparing the live price to a
1896
  # target derived from the PRIOR CLOSE. It was removed because 1D/3D targets are now re-anchored
 
95
  _HAS_FUNDAMENTALS = False
96
 
97
  # ── TIMEFRAME HELPER ─────────────────────────────────────────────────────────
98
+ # 1M = 28 days + the 2-day buffer in timeframe_to_dates = 30 calendar days (~21 trading sessions).
99
+ TIMEFRAME_DAYS: dict[str, int] = {"INTRADAY": 0, "1D": 1, "3D": 3, "5D": 5, "1W": 7, "1M": 28}
100
 
101
 
102
  def timeframe_to_dates(tf: str) -> tuple[str, str]:
103
+ """Convert 'INTRADAY'/'1D'/'3D'/'5D'/'1M' to (start_date, end_date) strings.
104
 
105
  On weekdays start_date = today (unchanged).
106
  On weekends/holidays start_date advances to the next trading day so
 
274
  "3D": 0.003, # 0.30%
275
  "5D": 0.005, # 0.50%
276
  "1W": 0.007, # 0.70% β€” wider buffer for longer hold
277
+ "1M": 0.008, # 0.80% β€” only used when no live price is available
278
  }
279
 
280
  # INTRADAY minimum favorable move: a same-session trade must be able to clear ~1% to be worth
 
888
 
889
  Returns a dict with predicted_direction, predicted_return_lo, predicted_return_hi.
890
  """
891
+ tf_scale = {"INTRADAY": 0.20, "1D": 0.35, "3D": 0.65, "5D": 1.0, "1W": 1.3, "1M": 2.0}.get(tf_label, 1.0)
892
  regime_mult = 0.7 if not nifty_ok else 1.0
893
  vix_mult = 0.8 if vix_level > 20 else 1.0
894
 
 
1392
  if start_date == end_date:
1393
  _tf_label = "INTRADAY"
1394
  else:
1395
+ _tf_label = "1D" if n_trading <= 2 else ("3D" if n_trading <= 4 else ("5D" if n_trading <= 6 else ("1W" if n_trading < 15 else "1M")))
1396
  _relevant = STRATEGY_TIMEFRAME_MAP.get(_tf_label, sig_result["active"])
1397
  _active_for_ev = [s for s in sig_result["active"] if s in _relevant]
1398
 
 
1527
  _indicators["return_20d"] = round((_price_now / float(_c.iloc[-20]) - 1) * 100, 1)
1528
  if len(_c) >= 63:
1529
  _indicators["return_90d"] = round((_price_now / float(_c.iloc[-63]) - 1) * 100, 1)
1530
+ # Relative strength vs Nifty is a core 1M trigger input (ai_forecast._guardrails_1m).
1531
+ # Scoped to 1M so the structural-laggard guard is not newly activated for 1D/3D,
1532
+ # which have never received this value in production.
1533
+ if _tf_label == "1M" and (ml.get("features") or {}).get("rs_3m_pct") is not None:
1534
+ _indicators["rs_3m_pct"] = ml["features"]["rs_3m_pct"]
1535
  if len(_c) >= 252:
1536
  _hi52 = float(_c.iloc[-252:].max())
1537
  _indicators["Dist_from_52W_High_%"] = round((_price_now / _hi52 - 1) * 100, 1)
 
1745
 
1746
  # Global directional preference: if AI still lands NEUTRAL on a mature ticker,
1747
  # resolve to up/down from ML probability so the card is actionable.
1748
+ # Not applied to 1M: a month-long hold needs trend evidence (ai_forecast._guardrails_1m), so a
1749
+ # NEUTRAL 1M call stays NEUTRAL β€” and this fallback would rebuild the wide symmetric NEUTRAL
1750
+ # band into a zero-width "x%..x%" directional band.
1751
  _hist_len = len(sc[ticker].dropna()) if ticker in sc.columns else 0
1752
  if (
1753
  AI_ALWAYS_DIRECTIONAL_CALL
1754
  and _run_ai_forecast
1755
  and _ai_real
1756
  and direction == "NEUTRAL"
1757
+ and _tf_label != "1M"
1758
  and _hist_len >= 200
1759
  ):
1760
  _ml_prob = float(ml.get("probability", 0.5) or 0.5)
 
1800
  atr14_val = float(atr14_series.iloc[-1])
1801
  # ATR multiplier and R:R target keyed to _tf_label (not raw n_trading)
1802
  # so the 1D weekend-buffer inflation (n_trading=2) doesn't bleed into 3D sizing.
1803
+ atr_mult = {"INTRADAY": 0.4, "1D": 0.7, "3D": 1.1, "5D": 1.5, "1W": 1.8, "1M": 2.5}.get(_tf_label, 1.5)
1804
  sl_risk = atr_mult * atr14_val
1805
  # Final SL/target/R:R are computed later after entry_price is finalized
1806
  # and with direction-aware logic (LONG vs SHORT).
 
1901
  # Backtest has no live price (_live_price is None) β†’ falls back to the prior close, so
1902
  # historical behaviour is unchanged.
1903
  _has_live = _live_price is not None and _live_price > 0
1904
+ _use_live = _has_live and _tf_label in ("INTRADAY", "1D", "3D", "1M")
1905
 
1906
  # NOTE: a "gapped past target" flag used to be computed here by comparing the live price to a
1907
  # target derived from the PRIOR CLOSE. It was removed because 1D/3D targets are now re-anchored
self_learning.py CHANGED
@@ -304,7 +304,7 @@ def _analyze_and_update(days: Optional[int] = None, force_llm: bool = False) ->
304
  return result
305
 
306
 
307
- _TF_TOKENS = ("INTRADAY", "1D", "3D", "5D")
308
 
309
 
310
  def _note_matches_tf(note: str, tf_label: str) -> bool:
 
304
  return result
305
 
306
 
307
+ _TF_TOKENS = ("INTRADAY", "1D", "3D", "5D", "1M")
308
 
309
 
310
  def _note_matches_tf(note: str, tf_label: str) -> bool:
static/app.js CHANGED
@@ -1057,7 +1057,13 @@ function showNewsModal(ticker) {
1057
  }
1058
 
1059
  // ── TF cell constants & renderer (module-level so _fetchAndUpdateTfCell can use them) ──
 
 
 
 
 
1060
  const _TF_SIGNALS = {
 
1061
  'INTRADAY': ['S1', 'S4', 'S4V2', 'S8', 'S16', 'S_CTRIO'],
1062
  '1D': ['S1', 'S4', 'S4V2', 'S7', 'S8', 'S11', 'PED', 'S_CAPFLOW', 'S_CTRIO', 'S15', 'S16', 'S20'],
1063
  '3D': ['S1', 'S4', 'S4V2', 'S5', 'S5V2', 'S6', 'S6V2', 'S7', 'S8', 'S9', 'S11', 'SUPER', 'PED',
@@ -1121,13 +1127,14 @@ function _renderOneTfCell(tf, d, pick) {
1121
  if (d.no_trade_reason === 'pending') {
1122
  const isBestTfP = bestTf !== null && (tf === bestTf);
1123
  const _mlSlotPending = _mlData ? _renderMlRow(tf, _mlData) : '<div class="tf-ml-mini-loader">πŸ€– ML…</div>';
1124
- return `<div class="tf-cell tf-cell--loading${isBestTfP ? ' tf-cell--best' : ''}" id="tf-${safeId}-${tf}" data-ai-dir="">
1125
- <div class="tf-label">${tf === 'INTRADAY' ? 'Today' : tf}</div>
1126
- <div class="tf-cell-spinner">⟳</div>
1127
- <div style="font-size:11px;color:var(--text-muted);margin-top:4px">AI analysing…</div>
1128
  <div class="tf-ai-ml-sep"><span class="tf-ai-ml-sep-lbl">πŸ€– ML MODEL</span></div>
1129
  <div class="tf-ml-block"><div class="tf-ml-slot" id="ml-${safeId}-${tf}">${_mlSlotPending}</div></div>
1130
- <div class="tf-agree-slot" id="agree-${safeId}-${tf}"></div>
 
 
 
 
1131
  </div>`;
1132
  }
1133
 
@@ -1151,7 +1158,7 @@ function _renderOneTfCell(tf, d, pick) {
1151
  const targetMid = isRangeBound
1152
  ? `<div class="tf-mid-target tf-range-bound" title="1D next-day direction has a ~74% accuracy ceiling β€” shown as an honest reachable range instead of a directional target that misses ~1-in-4 times">Range-bound Β· no directional target</div>`
1153
  : ((!isNoTrade && tfExpectedTarget !== null)
1154
- ? `<div class="tf-mid-target">Target β‚Ή${num(tfExpectedTarget, 0)}</div>`
1155
  : '');
1156
  const gappedNote = '';
1157
  const retLabel = isNoTrade
@@ -1162,7 +1169,7 @@ function _renderOneTfCell(tf, d, pick) {
1162
  let noTradeDetailText = _NO_TRADE_REASONS[noTradeReason] || 'No actionable setup for this timeframe.';
1163
  if (noTradeReason === 'wrong_timeframe') {
1164
  const activeSigNames = Object.keys(signals).filter(s => signals[s]);
1165
- const validTfs = ['INTRADAY', '1D'].filter(t => t !== tf && activeSigNames.some(s => (_TF_SIGNALS[t] || []).includes(s)));
1166
  const sigList = activeSigNames.length ? ` Active: ${activeSigNames.join(', ')}.` : '';
1167
  const hintTfs = validTfs.length ? ` Check ${validTfs.join(' or ')}.` : '';
1168
  noTradeDetailText += sigList + hintTfs;
@@ -1235,11 +1242,18 @@ function _renderOneTfCell(tf, d, pick) {
1235
  const rrPct = hasSl && pickPrice > d.stop_loss
1236
  ? Math.min(100, Math.max(2, (pickPrice - d.stop_loss) / (tfTarget - d.stop_loss) * 100)).toFixed(0)
1237
  : 50;
1238
- const entryLbl = d.entry_basis === 'est_open' ? 'Est. Open' : 'Entry';
 
 
 
1239
  const isLiveEntry = d.entry_basis === 'live';
1240
- const entryTitle = isLiveEntry
1241
- ? 'Live intraday price β€” entry for a same-session trade'
1242
- : `Based on previous close β‚Ή${num(pickPrice)} β€” actual fill at next-day open`;
 
 
 
 
1243
  // ML risk data for this TF. The ML model may have its own directional call even when the
1244
  // AI side is a no-trade, so this block can render independently (keeps e.g. 3D from blanking).
1245
  // (_mlData is computed near the top of this function so the AI banner can also use it.)
@@ -1268,16 +1282,28 @@ function _renderOneTfCell(tf, d, pick) {
1268
  // actionable AI entry/SL/target, so suppress the AI risk block β€” but still show the ML block
1269
  // beneath when ML has its own call.
1270
  const aiRiskBlock = (isNoTrade || isRangeBound) ? '' : `<div class="tf-risk ${hasSl ? (tgMet ? 'rr-ok' : 'rr-miss') : ''}">
1271
- <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>
1272
  ${hasSl ? `<div class="tf-risk-row"><span class="tf-sl-lbl">SL</span><span class="tf-sl-val">β‚Ή${num(d.stop_loss)}</span></div>` : ''}
1273
- ${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>` : ''}
1274
  ${hasSl ? `<div class="rr-bar"><div class="rr-bar-fill" style="width:${rrPct}%"></div></div>` : ''}
1275
  </div>`;
1276
 
1277
  const isBestTf = bestTf !== null && (tf === bestTf);
1278
  const _mlSlotInner = _mlData ? _renderMlRow(tf, _mlData) : '<div class="tf-ml-mini-loader">πŸ€– ML…</div>';
 
 
 
 
 
 
1279
  const _aiDirAttr = (af && af.direction) ? af.direction : '';
1280
  const _agreeInner = _agreeHtml(_mlData && _mlData.direction, _aiDirAttr, _mlData && _mlData.dir_basis);
 
 
 
 
 
 
1281
  // Session's final INTRADAY call, shown after the market closes instead of a "market closed"
1282
  // stub β€” it's the last real call made during the session, not a live prediction.
1283
  const finalCallBadge = d.intraday_final_call
@@ -1304,7 +1330,8 @@ function _renderOneTfCell(tf, d, pick) {
1304
  : '';
1305
  return `<div class="tf-cell${isBestTf ? ' tf-cell--best' : ''}${d.intraday_final_call ? ' tf-cell--final' : ''}" id="tf-${safeId}-${tf}" data-ai-dir="${_aiDirAttr}">
1306
  ${isBestTf ? '<span class="best-tf-badge">Best Bet</span>' : ''}
1307
- <div class="tf-label">${tf === 'INTRADAY' ? 'Today' : tf}</div>
 
1308
  ${refreshMetaHtml}
1309
  ${finalCallBadge}
1310
  ${premarketBadge}
@@ -1319,11 +1346,8 @@ function _renderOneTfCell(tf, d, pick) {
1319
  ${dirHtml}
1320
  ${mainConfBar}
1321
  ${aiForecastHtml ? `<div class="tf-fc-block tf-ai-block">${aiForecastHtml}</div>` : ''}
1322
- ${aiRiskBlock}
1323
- <div class="tf-ai-ml-sep"><span class="tf-ai-ml-sep-lbl">πŸ€– ML MODEL</span></div>
1324
- <div class="tf-ml-block"><div class="tf-ml-slot" id="ml-${safeId}-${tf}">${_mlSlotInner}</div></div>
1325
- <div class="tf-agree-slot" id="agree-${safeId}-${tf}">${_agreeInner}</div>
1326
- ${mlRiskBlock}
1327
  </div>`;
1328
  }
1329
 
@@ -1357,13 +1381,14 @@ async function _runTfCellRequest(ticker, tf, pick, attempt = 0, opts = {}) {
1357
  }, delay);
1358
  };
1359
 
1360
- const tfLabel = tf === 'INTRADAY' ? 'Today' : tf;
1361
  // Keep the ML block in the loading cell (with its slot id) so the independent ML forecast
1362
  // stays visible while the slow AI call is in flight β€” ML must never disappear behind AI.
1363
- const _loadingCellHtml = `<div class="tf-label">${tfLabel}</div><div class="tf-cell-spinner">⟳</div>`
 
1364
  + `<div style="font-size:11px;color:var(--text-muted);margin-top:4px">πŸ€– AI loading…</div>`
1365
- + `<div class="tf-ai-ml-sep"><span class="tf-ai-ml-sep-lbl">πŸ€– ML MODEL</span></div>`
1366
- + `<div class="tf-ml-block"><div class="tf-ml-slot" id="ml-${safeId}-${tf}"><div class="tf-ml-mini-loader">πŸ€– ML…</div></div></div>`;
1367
  // Silent mode (periodic INTRADAY auto-refresh of an already-populated cell): DON'T paint the
1368
  // loader β€” keep the current cell visible and swap it only once the fresh forecast arrives, so
1369
  // the auto-refresh doesn't flash a spinner every few minutes.
@@ -1452,7 +1477,7 @@ async function _runTfCellRequest(ticker, tf, pick, attempt = 0, opts = {}) {
1452
  retry(10000);
1453
  } else {
1454
  cell.className = 'tf-cell';
1455
- 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>`;
1456
  }
1457
  }
1458
  }
@@ -1658,6 +1683,9 @@ function _agreeHtml(mlDir, aiDir, mlBasis) {
1658
  // only the intraday slot repaints (1D stays put; no full-card flicker).
1659
  async function _fetchAndFillMl(ticker, force = false, tfs = ['INTRADAY', '1D']) {
1660
  if (!ticker) return;
 
 
 
1661
  const safeId = ticker.replace(/[^a-zA-Z0-9]/g, '_');
1662
  try {
1663
  let ml = _mlCache.get(ticker);
@@ -1752,22 +1780,22 @@ function _recommendedTradeMeta(bestTf, recSource, planData, targetPrice) {
1752
  };
1753
  }
1754
 
1755
- const tfLabel = bestTf === 'INTRADAY' ? 'Today' : bestTf;
1756
  const dir = _inferTradeDirection(planData || {});
1757
  const target = Number(targetPrice || 0);
1758
  const hasTarget = Number.isFinite(target) && target > 0;
1759
 
1760
- let label = `Recommended: ${tfLabel}`;
1761
  if (dir === 'SHORT') {
1762
- label = hasTarget ? `Short ${tfLabel} β†’ β‚Ή${num(target)}` : `Short ${tfLabel}`;
1763
  }
1764
  if (recSource === 'ml') label += ' Β· πŸ€– ML';
1765
 
1766
  const srcLabel = recSource === 'ml' ? 'ML' : 'AI';
1767
  const dirLabel = dir || 'LONG';
1768
  const title = hasTarget
1769
- ? `${srcLabel} setup: ${dirLabel} on ${tfLabel}, target β‚Ή${num(target)}`
1770
- : `${srcLabel} setup: ${dirLabel} on ${tfLabel}`;
1771
 
1772
  return { label, title };
1773
  }
@@ -1777,7 +1805,7 @@ function _tradeActionMeta(bestTf, recSource, planData, targetPrice) {
1777
  const direction = _inferTradeDirection(planData || {});
1778
  if (!bestTf || !direction) return { label: 'Open Trade', title: recommendation.title, isShort: false };
1779
  return {
1780
- label: `Open ${direction} Β· ${bestTf === 'INTRADAY' ? 'Today' : bestTf}`,
1781
  title: recommendation.title,
1782
  isShort: direction === 'SHORT',
1783
  };
@@ -1802,9 +1830,15 @@ function _refreshWatchlistSummaryBadges(ticker) {
1802
  const safeId = (ticker || '').replace(/[^a-zA-Z0-9]/g, '_');
1803
  const todayDir = _summaryAiDirection(tfs.INTRADAY || {});
1804
  const oneDayDir = _summaryAiDirection(tfs['1D'] || {});
 
1805
 
1806
  const todayEl = document.getElementById(`wl-${safeId}-ai-intraday`);
1807
  const oneDayEl = document.getElementById(`wl-${safeId}-ai-1d`);
 
 
 
 
 
1808
  if (todayEl) {
1809
  todayEl.textContent = todayDir;
1810
  todayEl.style.color = _aiTfColor(todayDir);
@@ -1885,7 +1919,7 @@ function _refreshWatchlistRecommendedAction(ticker) {
1885
  );
1886
  }
1887
 
1888
- function renderPickCard(pick, idx, idPrefix = 'pick', mode = 'top5') {
1889
  const dir = pick.direction || 'NEUTRAL';
1890
  const isUp = dir.includes('BULLISH');
1891
  const cls = isUp ? 'bullish' : dir.includes('BEARISH') ? 'bearish' : '';
@@ -1946,7 +1980,7 @@ function renderPickCard(pick, idx, idPrefix = 'pick', mode = 'top5') {
1946
 
1947
  // Retry button: shown when any TF timed out or AI was unavailable (watchlist only)
1948
  const _retryReasons = new Set(['timeout', 'ai_unavailable']);
1949
- const _hasRetryable = mode === 'watchlist' && ['INTRADAY','1D'].some(tf => {
1950
  const r = (tfs[tf] || {}).no_trade_reason;
1951
  return _retryReasons.has(r);
1952
  });
@@ -1963,7 +1997,13 @@ function renderPickCard(pick, idx, idPrefix = 'pick', mode = 'top5') {
1963
  else
1964
  mlVerdictBadge = `<span class="ml-verdict ml-verdict-neutral" title="Surfaced by the ML selector">πŸ€– ML pick</span>`;
1965
  }
1966
- const tfHtml = ['INTRADAY','1D'].map(tf => _renderOneTfCell(tf, tfs[tf] || {}, pick)).join('');
 
 
 
 
 
 
1967
 
1968
  const safeCompany = (pick.company || '').replace(/'/g, "\\'");
1969
  const headerLeft = mode === 'watchlist'
@@ -1989,7 +2029,10 @@ function renderPickCard(pick, idx, idPrefix = 'pick', mode = 'top5') {
1989
  const bareSym = pick.ticker.replace(/\.(NS|BO)$/i, '');
1990
  const exchange = pick.ticker.endsWith('.BO') ? 'BSE' : 'NSE';
1991
 
1992
- const aiDirs = ['INTRADAY', '1D']
 
 
 
1993
  .map(tf => ((tfs[tf] || {}).ai_forecast || {}).direction)
1994
  .filter(d => d === 'BULLISH' || d === 'BEARISH');
1995
  const aiConsensus = aiDirs[0] || null;
@@ -2013,8 +2056,9 @@ function renderPickCard(pick, idx, idPrefix = 'pick', mode = 'top5') {
2013
 
2014
  const aiToday = _summaryAiDirection(tfs.INTRADAY || {});
2015
  const ai1d = _summaryAiDirection(tfs['1D'] || {});
 
2016
  const wlSummaryHtml = mode === 'watchlist'
2017
- ? `<div class="wl-summary-grid">
2018
  <div class="wl-summary-item">
2019
  <div class="wl-summary-label">Current Price</div>
2020
  <div class="wl-summary-value" id="wl-${safeId}-price" data-live-ticker="${pick.ticker}">β‚Ή${num(pickPrice)}</div>
@@ -2027,6 +2071,10 @@ function renderPickCard(pick, idx, idPrefix = 'pick', mode = 'top5') {
2027
  <div class="wl-summary-label">AI (1D)</div>
2028
  <div class="wl-summary-value" id="wl-${safeId}-ai-1d" style="color:${_aiTfColor(ai1d)}">${ai1d}</div>
2029
  </div>
 
 
 
 
2030
  <div class="wl-summary-item" style="cursor:pointer" onclick="showNewsModal('${pick.ticker}')" title="Click to see latest headlines">
2031
  <div class="wl-summary-label">πŸ“° News</div>
2032
  <div class="wl-summary-value" style="color:${news.label === 'BULLISH' ? 'var(--green)' : news.label === 'BEARISH' ? 'var(--red)' : 'var(--text-muted)'}">${newsSentiment}</div>
@@ -2415,11 +2463,11 @@ function renderWatchlistShellCard(item) {
2415
  const shortPlan = JSON.stringify({ direction: 'SHORT' }).replace(/'/g, "&#39;");
2416
  // Shell TF grid: ML slots are painted immediately so the instant, local ML forecast
2417
  // can fill in without waiting for the slow per-card AI (/api/watchlist-pick) call.
2418
- const shellTfHtml = ['INTRADAY', '1D'].map(tf => `
2419
  <div class="tf-cell tf-cell--loading" id="tf-${safeId}-${tf}" data-ai-dir="">
2420
- <div class="tf-label">${tf === 'INTRADAY' ? 'Today' : tf}</div>
2421
  <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>
2422
- <div class="tf-agree-slot" id="agree-${safeId}-${tf}"></div>
2423
  <div class="tf-fc-block tf-ai-block"><div class="tf-ai-note" style="color:var(--text-muted)">πŸ€– AI forecast loading…</div></div>
2424
  </div>`).join('');
2425
  return `<div class="pick-card pick-card--loading" id="${cardId}" data-ticker="${ticker}">
@@ -2591,9 +2639,11 @@ const _top5AiRetried = new Set(); // 'ticker|tf' cells that already have a back
2591
 
2592
  // Render top-pick cards into a container and mount their mini charts.
2593
  // Shared by the final render and the streaming (partial) render.
2594
- function _renderTop5CardsInto(cardsEl, idPrefix, picks, bannerHtml = '') {
2595
- _lastTop5 = { cardsEl, idPrefix, picks, banner: bannerHtml };
2596
- const ordered = _applyTop5Sort(picks);
 
 
2597
  // Preserve already-mounted chart nodes across re-renders. Streaming polls this every ~4s and
2598
  // the sort toggle re-renders too; a naive innerHTML rebuild tore down + remounted every live
2599
  // chart each time, causing visible blinking. Stash each mounted chart's wrapper by ticker id
@@ -2606,13 +2656,29 @@ function _renderTop5CardsInto(cardsEl, idPrefix, picks, bannerHtml = '') {
2606
  chartStash[tvId] = existing.closest('.chart-wrap') || existing;
2607
  }
2608
  });
 
 
 
 
2609
  const sortBar = `<div class="top5-sort-bar">
2610
  <span class="top5-sort-lbl">Rank by</span>
2611
  ${[['ai','AI'],['ml','πŸ€– ML'],['blend','Blend']].map(([m,l]) =>
2612
  `<button class="top5-sort-btn${_top5Sort===m?' active':''}" onclick="_setTop5Sort('${m}')">${l}</button>`).join('')}
2613
  <span class="top5-sort-hint">ML ranks on INTRADAY/1D conviction</span>
2614
  </div>`;
2615
- cardsEl.innerHTML = sortBar + bannerHtml + ordered.map((p, i) => renderPickCard(p, i, idPrefix)).join('');
 
 
 
 
 
 
 
 
 
 
 
 
2616
  ordered.forEach(p => {
2617
  const tvId = 'tv-' + idPrefix + '-' + p.ticker.replace(/[^a-zA-Z0-9]/g, '_');
2618
  const stashed = chartStash[tvId];
@@ -2622,12 +2688,12 @@ function _renderTop5CardsInto(cardsEl, idPrefix, picks, bannerHtml = '') {
2622
  } else {
2623
  observeTvChart(tvId, p.ticker);
2624
  }
2625
- _fetchAndFillMl(p.ticker); // instant ML row; AI row keeps its own loader
2626
  // Top picks have no per-card β†Ί Retry button, so without this any TF that came back
2627
  // 'ai_unavailable'/'timeout' would sit on "AI loading… retrying automatically" forever.
2628
  // Kick off the same per-cell background retry the watchlist uses (single-ticker/TF
2629
  // endpoint), guarded so each cell only spawns one retry chain across re-renders/sorts.
2630
- ['INTRADAY', '1D'].forEach(tf => {
2631
  const r = (p.timeframes || {})[tf]?.no_trade_reason;
2632
  if (r !== 'timeout' && r !== 'ai_unavailable') return;
2633
  const key = p.ticker + '|' + tf;
@@ -2635,10 +2701,45 @@ function _renderTop5CardsInto(cardsEl, idPrefix, picks, bannerHtml = '') {
2635
  _top5AiRetried.add(key);
2636
  _fetchAndUpdateTfCell(p.ticker, tf, p);
2637
  });
 
 
 
2638
  });
2639
  // Top picks are cached for the day (same stocks), but INTRADAY moves all session β€” freshen
2640
  // each pick's INTRADAY cell in place right after render (silent, deduped to ≀1/60s per ticker).
2641
- _refreshTop5Intraday(ordered);
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
2642
  }
2643
 
2644
  // Silent INTRADAY auto-refresh for the currently-rendered top picks. Keeps the SAME day-cached
@@ -2658,7 +2759,8 @@ function _refreshTop5Intraday(picks, minGapMs = 60000, force = false) {
2658
 
2659
  // ── Top-pick ranking: AI (server order) / ML (quantile conviction) / Blend ─────
2660
  let _top5Sort = 'ai';
2661
- let _lastTop5 = { cardsEl: null, idPrefix: '', picks: [], banner: '' };
 
2662
 
2663
  // ML conviction score for a ticker from its cached prediction β€” INTRADAY/1D
2664
  // (matches the AI ranking horizons).
@@ -2693,7 +2795,12 @@ function _applyTop5Sort(picks) {
2693
 
2694
  function _setTop5Sort(mode) {
2695
  _top5Sort = mode;
2696
- if (_lastTop5.cardsEl) _renderTop5CardsInto(_lastTop5.cardsEl, _lastTop5.idPrefix, _lastTop5.picks, _lastTop5.banner);
 
 
 
 
 
2697
  }
2698
 
2699
  async function loadTop5Cards(cardsId, loadingId, limit = 20, forceRefresh = false) {
@@ -2705,7 +2812,7 @@ async function loadTop5Cards(cardsId, loadingId, limit = 20, forceRefresh = fals
2705
  // Retries update the existing "Analysing…" message in place so the UI doesn't flicker.
2706
  const isRetry = !forceRefresh && _top5PollCount > 0;
2707
  if (!isRetry) { showEl(loadingId); cardsEl.innerHTML = ''; _top5PollStart = Date.now(); _top5AiRetried.clear(); }
2708
- if (forceRefresh) { _top5PollCount = 0; _top5AutoRetried = false; _top5PollStart = Date.now(); _top5AiRetried.clear(); if (_top5PollTimer) { clearTimeout(_top5PollTimer); _top5PollTimer = null; } }
2709
 
2710
  // Abort the fetch after 5 min β€” allows the server time to finish computing on a cold start.
2711
  const ctrl = new AbortController();
@@ -2774,7 +2881,8 @@ async function loadTop5Cards(cardsId, loadingId, limit = 20, forceRefresh = fals
2774
  <span class="tf-cell-spinner" style="font-size:15px">⟳</span>
2775
  <span>${phaseMsg} β€” showing ${partial.length} ready pick${partial.length > 1 ? 's' : ''}, more loading…</span>
2776
  </div>`;
2777
- _renderTop5CardsInto(cardsEl, idPrefix, partial, banner);
 
2778
  cardsEl.setAttribute('data-loaded', '1');
2779
  _top5PollTimer = setTimeout(() => loadTop5Cards(cardsId, loadingId, limit, false), 4000);
2780
  return;
@@ -2828,7 +2936,8 @@ async function loadTop5Cards(cardsId, loadingId, limit = 20, forceRefresh = fals
2828
  generatedEl.textContent = prefix + (data.generated_at || '');
2829
  }
2830
  const idPrefix = cardsId.replace(/[^a-zA-Z0-9]/g, '_');
2831
- _renderTop5CardsInto(cardsEl, idPrefix, picks);
 
2832
  if (data.has_ai_unavailable) {
2833
  _showAiRetryBanner(cardsEl, () => loadTop5Cards(cardsId, loadingId, limit, true));
2834
  }
@@ -2923,7 +3032,7 @@ async function loadWatchlist(forceRefresh = false) {
2923
  _fetchAndFillMl(ticker);
2924
 
2925
  // Auto-fetch only unresolved TF cells in the background.
2926
- ['INTRADAY','1D'].forEach(tf => {
2927
  const tfData = (pick.timeframes || {})[tf] || {};
2928
  const r = tfData.no_trade_reason;
2929
  if (forceRefresh || !Object.keys(tfData).length || tfData.cache_stale || r === 'pending' || r === 'timeout' || r === 'ai_unavailable') {
@@ -4754,7 +4863,7 @@ function renderValidationHistoryCard(h) {
4754
  <div class="validation-history-card ${hitClass}" data-tf="${tf}">
4755
  <div class="vh-header">
4756
  <span class="vh-ticker">${h.ticker}</span>
4757
- <span class="vh-tf">${tf}</span>
4758
  <span class="dir-badge dir-${dirCssKey}" title="${h.direction || 'NEUTRAL'}">${dirLabel(h.direction || 'NEUTRAL')}</span>
4759
  ${_srcTag(h.snapshot_source)}
4760
  <span class="vh-result vh-${hitClass}">${h.validation_result}</span>
@@ -4833,7 +4942,7 @@ function _applyValStats() {
4833
  const allPreds = summaryRaw.all || {};
4834
  const highConf = summaryRaw.high_conf || {};
4835
 
4836
- ['INTRADAY', '1D'].forEach(tf => {
4837
  const dStat = directional[tf]; // directional-only (NEUTRAL excluded)
4838
  const aStat = allPreds[tf]; // all predictions (the honest headline)
4839
  const el = document.getElementById(`vstat-${tf.toLowerCase()}`);
@@ -4918,7 +5027,7 @@ function _renderValidationLists() {
4918
  <div class="validation-card${isOverdue ? ' val-overdue' : ''}" data-tf="${p.timeframe}">
4919
  <div class="val-header">
4920
  <span class="val-ticker">${p.ticker}</span>
4921
- <span class="val-tf">${p.timeframe}</span>
4922
  <span class="dir-badge dir-${dirCssKey}" title="${p.direction || 'NEUTRAL'}">${dirLabel(p.direction || 'NEUTRAL')}</span>
4923
  ${_srcTag(p.snapshot_source)}
4924
  <span class="val-conf conf-${p.confidence}">${p.confidence}</span>
 
1057
  }
1058
 
1059
  // ── TF cell constants & renderer (module-level so _fetchAndUpdateTfCell can use them) ──
1060
+ // Horizons shown for equities. 1M is a ~21-session hold: AI forecast only (no ML model), so its
1061
+ // cells never render the ML slot. F&O cards stay INTRADAY/1D and do not use LIVE_TFS.
1062
+ const LIVE_TFS = ['INTRADAY', '1D', '1M'];
1063
+ const ONE_M_TF = '1M';
1064
+ function tfLabel(tf) { return tf === 'INTRADAY' ? 'Today' : (tf === ONE_M_TF ? '1 Month' : tf); }
1065
  const _TF_SIGNALS = {
1066
+ '1M': ['S6V2', 'S_SEASONAL', 'S19'],
1067
  'INTRADAY': ['S1', 'S4', 'S4V2', 'S8', 'S16', 'S_CTRIO'],
1068
  '1D': ['S1', 'S4', 'S4V2', 'S7', 'S8', 'S11', 'PED', 'S_CAPFLOW', 'S_CTRIO', 'S15', 'S16', 'S20'],
1069
  '3D': ['S1', 'S4', 'S4V2', 'S5', 'S5V2', 'S6', 'S6V2', 'S7', 'S8', 'S9', 'S11', 'SUPER', 'PED',
 
1127
  if (d.no_trade_reason === 'pending') {
1128
  const isBestTfP = bestTf !== null && (tf === bestTf);
1129
  const _mlSlotPending = _mlData ? _renderMlRow(tf, _mlData) : '<div class="tf-ml-mini-loader">πŸ€– ML…</div>';
1130
+ const _mlPendingHtml = tf === ONE_M_TF ? '' : `
 
 
 
1131
  <div class="tf-ai-ml-sep"><span class="tf-ai-ml-sep-lbl">πŸ€– ML MODEL</span></div>
1132
  <div class="tf-ml-block"><div class="tf-ml-slot" id="ml-${safeId}-${tf}">${_mlSlotPending}</div></div>
1133
+ <div class="tf-agree-slot" id="agree-${safeId}-${tf}"></div>`;
1134
+ return `<div class="tf-cell tf-cell--loading${isBestTfP ? ' tf-cell--best' : ''}" id="tf-${safeId}-${tf}" data-ai-dir="">
1135
+ <div class="tf-label">${tfLabel(tf)}</div>
1136
+ <div class="tf-cell-spinner">⟳</div>
1137
+ <div style="font-size:11px;color:var(--text-muted);margin-top:4px">AI analysing…</div>${_mlPendingHtml}
1138
  </div>`;
1139
  }
1140
 
 
1158
  const targetMid = isRangeBound
1159
  ? `<div class="tf-mid-target tf-range-bound" title="1D next-day direction has a ~74% accuracy ceiling β€” shown as an honest reachable range instead of a directional target that misses ~1-in-4 times">Range-bound Β· no directional target</div>`
1160
  : ((!isNoTrade && tfExpectedTarget !== null)
1161
+ ? `<div class="tf-mid-target">${tf === ONE_M_TF ? '1M target' : 'Target'} β‚Ή${num(tfExpectedTarget, 0)}</div>`
1162
  : '');
1163
  const gappedNote = '';
1164
  const retLabel = isNoTrade
 
1169
  let noTradeDetailText = _NO_TRADE_REASONS[noTradeReason] || 'No actionable setup for this timeframe.';
1170
  if (noTradeReason === 'wrong_timeframe') {
1171
  const activeSigNames = Object.keys(signals).filter(s => signals[s]);
1172
+ const validTfs = LIVE_TFS.filter(t => t !== tf && activeSigNames.some(s => (_TF_SIGNALS[t] || []).includes(s)));
1173
  const sigList = activeSigNames.length ? ` Active: ${activeSigNames.join(', ')}.` : '';
1174
  const hintTfs = validTfs.length ? ` Check ${validTfs.join(' or ')}.` : '';
1175
  noTradeDetailText += sigList + hintTfs;
 
1242
  const rrPct = hasSl && pickPrice > d.stop_loss
1243
  ? Math.min(100, Math.max(2, (pickPrice - d.stop_loss) / (tfTarget - d.stop_loss) * 100)).toFixed(0)
1244
  : 50;
1245
+ const isOneM = tf === ONE_M_TF;
1246
+ const entryLbl = isOneM
1247
+ ? (d.entry_basis === 'live' ? 'Buy now' : 'Buy (next open)')
1248
+ : (d.entry_basis === 'est_open' ? 'Est. Open' : 'Entry');
1249
  const isLiveEntry = d.entry_basis === 'live';
1250
+ const entryTitle = isOneM
1251
+ ? (isLiveEntry
1252
+ ? 'Current price β€” buy now and hold for about one month (~21 trading days)'
1253
+ : `Based on previous close β‚Ή${num(pickPrice)} β€” estimated fill at the next open (market closed)`)
1254
+ : (isLiveEntry
1255
+ ? 'Live intraday price β€” entry for a same-session trade'
1256
+ : `Based on previous close β‚Ή${num(pickPrice)} β€” actual fill at next-day open`);
1257
  // ML risk data for this TF. The ML model may have its own directional call even when the
1258
  // AI side is a no-trade, so this block can render independently (keeps e.g. 3D from blanking).
1259
  // (_mlData is computed near the top of this function so the AI banner can also use it.)
 
1282
  // actionable AI entry/SL/target, so suppress the AI risk block β€” but still show the ML block
1283
  // beneath when ML has its own call.
1284
  const aiRiskBlock = (isNoTrade || isRangeBound) ? '' : `<div class="tf-risk ${hasSl ? (tgMet ? 'rr-ok' : 'rr-miss') : ''}">
1285
+ <div class="tf-risk-row"><span class="tf-entry-lbl" title="${entryTitle}">${entryLbl}${isLiveEntry && !isOneM ? ' <span style="opacity:.7">(live)</span>' : ''}</span><span class="tf-entry-val">β‚Ή${num(tfEntry)}</span></div>
1286
  ${hasSl ? `<div class="tf-risk-row"><span class="tf-sl-lbl">SL</span><span class="tf-sl-val">β‚Ή${num(d.stop_loss)}</span></div>` : ''}
1287
+ ${hasSl ? `<div class="tf-risk-row"><span class="tf-tgt-lbl">${isOneM ? '1M Tgt' : 'Tgt'} ${tgMet ? 'βœ“' : '⚠'}${d.actual_rr ? ` ${d.actual_rr}R` : ''}</span><span class="tf-tgt-val">β‚Ή${num(tfTarget)}</span></div>` : ''}
1288
  ${hasSl ? `<div class="rr-bar"><div class="rr-bar-fill" style="width:${rrPct}%"></div></div>` : ''}
1289
  </div>`;
1290
 
1291
  const isBestTf = bestTf !== null && (tf === bestTf);
1292
  const _mlSlotInner = _mlData ? _renderMlRow(tf, _mlData) : '<div class="tf-ml-mini-loader">πŸ€– ML…</div>';
1293
+ const oneMChip = isOneM
1294
+ ? `<div class="tf-new-chip" title="1-month forecasts are new and have not been graded yet. Accuracy appears on the Validation tab once enough 1M calls have matured (~30 days each).">New Β· unvalidated</div>`
1295
+ : '';
1296
+ const holdNote = (isOneM && !isNoTrade && !isRangeBound)
1297
+ ? `<div class="tf-hold-note">Buy now Β· hold ~1 month (β‰ˆ21 trading days)</div>`
1298
+ : '';
1299
  const _aiDirAttr = (af && af.direction) ? af.direction : '';
1300
  const _agreeInner = _agreeHtml(_mlData && _mlData.direction, _aiDirAttr, _mlData && _mlData.dir_basis);
1301
+ // 1M has no ML model (the local model covers INTRADAY/1D only) β€” omit the whole ML section.
1302
+ const _mlSectionHtml = isOneM ? '' : `
1303
+ <div class="tf-ai-ml-sep"><span class="tf-ai-ml-sep-lbl">πŸ€– ML MODEL</span></div>
1304
+ <div class="tf-ml-block"><div class="tf-ml-slot" id="ml-${safeId}-${tf}">${_mlSlotInner}</div></div>
1305
+ <div class="tf-agree-slot" id="agree-${safeId}-${tf}">${_agreeInner}</div>
1306
+ ${mlRiskBlock}`;
1307
  // Session's final INTRADAY call, shown after the market closes instead of a "market closed"
1308
  // stub β€” it's the last real call made during the session, not a live prediction.
1309
  const finalCallBadge = d.intraday_final_call
 
1330
  : '';
1331
  return `<div class="tf-cell${isBestTf ? ' tf-cell--best' : ''}${d.intraday_final_call ? ' tf-cell--final' : ''}" id="tf-${safeId}-${tf}" data-ai-dir="${_aiDirAttr}">
1332
  ${isBestTf ? '<span class="best-tf-badge">Best Bet</span>' : ''}
1333
+ <div class="tf-label">${tfLabel(tf)}</div>
1334
+ ${oneMChip}
1335
  ${refreshMetaHtml}
1336
  ${finalCallBadge}
1337
  ${premarketBadge}
 
1346
  ${dirHtml}
1347
  ${mainConfBar}
1348
  ${aiForecastHtml ? `<div class="tf-fc-block tf-ai-block">${aiForecastHtml}</div>` : ''}
1349
+ ${holdNote}
1350
+ ${aiRiskBlock}${_mlSectionHtml}
 
 
 
1351
  </div>`;
1352
  }
1353
 
 
1381
  }, delay);
1382
  };
1383
 
1384
+ const tfLabelText = tfLabel(tf);
1385
  // Keep the ML block in the loading cell (with its slot id) so the independent ML forecast
1386
  // stays visible while the slow AI call is in flight β€” ML must never disappear behind AI.
1387
+ // (1M has no ML model, so its loading cell has no ML block.)
1388
+ const _loadingCellHtml = `<div class="tf-label">${tfLabelText}</div><div class="tf-cell-spinner">⟳</div>`
1389
  + `<div style="font-size:11px;color:var(--text-muted);margin-top:4px">πŸ€– AI loading…</div>`
1390
+ + (tf === ONE_M_TF ? '' : `<div class="tf-ai-ml-sep"><span class="tf-ai-ml-sep-lbl">πŸ€– ML MODEL</span></div>`
1391
+ + `<div class="tf-ml-block"><div class="tf-ml-slot" id="ml-${safeId}-${tf}"><div class="tf-ml-mini-loader">πŸ€– ML…</div></div></div>`);
1392
  // Silent mode (periodic INTRADAY auto-refresh of an already-populated cell): DON'T paint the
1393
  // loader β€” keep the current cell visible and swap it only once the fresh forecast arrives, so
1394
  // the auto-refresh doesn't flash a spinner every few minutes.
 
1477
  retry(10000);
1478
  } else {
1479
  cell.className = 'tf-cell';
1480
+ cell.innerHTML = `<div class="tf-label">${tfLabelText}</div><div class="tf-no-trade-reason" style="color:var(--text-muted);font-size:11px">πŸ€– AI still loading β€” tap β†Ί to retry</div>`;
1481
  }
1482
  }
1483
  }
 
1683
  // only the intraday slot repaints (1D stays put; no full-card flicker).
1684
  async function _fetchAndFillMl(ticker, force = false, tfs = ['INTRADAY', '1D']) {
1685
  if (!ticker) return;
1686
+ // 1M has no ML model β€” never request or fill an ML slot for it.
1687
+ tfs = tfs.filter(t => t !== ONE_M_TF);
1688
+ if (!tfs.length) return;
1689
  const safeId = ticker.replace(/[^a-zA-Z0-9]/g, '_');
1690
  try {
1691
  let ml = _mlCache.get(ticker);
 
1780
  };
1781
  }
1782
 
1783
+ const tfText = tfLabel(bestTf);
1784
  const dir = _inferTradeDirection(planData || {});
1785
  const target = Number(targetPrice || 0);
1786
  const hasTarget = Number.isFinite(target) && target > 0;
1787
 
1788
+ let label = `Recommended: ${tfText}`;
1789
  if (dir === 'SHORT') {
1790
+ label = hasTarget ? `Short ${tfText} β†’ β‚Ή${num(target)}` : `Short ${tfText}`;
1791
  }
1792
  if (recSource === 'ml') label += ' Β· πŸ€– ML';
1793
 
1794
  const srcLabel = recSource === 'ml' ? 'ML' : 'AI';
1795
  const dirLabel = dir || 'LONG';
1796
  const title = hasTarget
1797
+ ? `${srcLabel} setup: ${dirLabel} on ${tfText}, target β‚Ή${num(target)}`
1798
+ : `${srcLabel} setup: ${dirLabel} on ${tfText}`;
1799
 
1800
  return { label, title };
1801
  }
 
1805
  const direction = _inferTradeDirection(planData || {});
1806
  if (!bestTf || !direction) return { label: 'Open Trade', title: recommendation.title, isShort: false };
1807
  return {
1808
+ label: `Open ${direction} Β· ${tfLabel(bestTf)}`,
1809
  title: recommendation.title,
1810
  isShort: direction === 'SHORT',
1811
  };
 
1830
  const safeId = (ticker || '').replace(/[^a-zA-Z0-9]/g, '_');
1831
  const todayDir = _summaryAiDirection(tfs.INTRADAY || {});
1832
  const oneDayDir = _summaryAiDirection(tfs['1D'] || {});
1833
+ const oneMonthDir = _summaryAiDirection(tfs[ONE_M_TF] || {});
1834
 
1835
  const todayEl = document.getElementById(`wl-${safeId}-ai-intraday`);
1836
  const oneDayEl = document.getElementById(`wl-${safeId}-ai-1d`);
1837
+ const oneMonthEl = document.getElementById(`wl-${safeId}-ai-1m`);
1838
+ if (oneMonthEl) {
1839
+ oneMonthEl.textContent = oneMonthDir;
1840
+ oneMonthEl.style.color = _aiTfColor(oneMonthDir);
1841
+ }
1842
  if (todayEl) {
1843
  todayEl.textContent = todayDir;
1844
  todayEl.style.color = _aiTfColor(todayDir);
 
1919
  );
1920
  }
1921
 
1922
+ function renderPickCard(pick, idx, idPrefix = 'pick', mode = 'top5', opts = {}) {
1923
  const dir = pick.direction || 'NEUTRAL';
1924
  const isUp = dir.includes('BULLISH');
1925
  const cls = isUp ? 'bullish' : dir.includes('BEARISH') ? 'bearish' : '';
 
1980
 
1981
  // Retry button: shown when any TF timed out or AI was unavailable (watchlist only)
1982
  const _retryReasons = new Set(['timeout', 'ai_unavailable']);
1983
+ const _hasRetryable = mode === 'watchlist' && LIVE_TFS.some(tf => {
1984
  const r = (tfs[tf] || {}).no_trade_reason;
1985
  return _retryReasons.has(r);
1986
  });
 
1997
  else
1998
  mlVerdictBadge = `<span class="ml-verdict ml-verdict-neutral" title="Surfaced by the ML selector">πŸ€– ML pick</span>`;
1999
  }
2000
+ // opts.tfs restricts the cells (the dashboard's 1 Month view shows only 1M). On the Top Picks
2001
+ // dashboard a missing 1M cell renders as a pending spinner and is lazy-loaded after render.
2002
+ const cellTfs = Array.isArray(opts.tfs) && opts.tfs.length ? opts.tfs : LIVE_TFS;
2003
+ const tfHtml = cellTfs.map(tf => {
2004
+ const fallback = (tf === ONE_M_TF && mode !== 'watchlist') ? { no_trade_reason: 'pending' } : {};
2005
+ return _renderOneTfCell(tf, tfs[tf] || fallback, pick);
2006
+ }).join('');
2007
 
2008
  const safeCompany = (pick.company || '').replace(/'/g, "\\'");
2009
  const headerLeft = mode === 'watchlist'
 
2029
  const bareSym = pick.ticker.replace(/\.(NS|BO)$/i, '');
2030
  const exchange = pick.ticker.endsWith('.BO') ? 'BSE' : 'NSE';
2031
 
2032
+ // News-vs-AI divergence uses the horizons this card shows: INTRADAY/1D normally, only 1M in the
2033
+ // dashboard's 1 Month view (those picks carry no INTRADAY/1D forecast).
2034
+ const consensusTfs = Array.isArray(opts.tfs) && opts.tfs.length ? opts.tfs : ['INTRADAY', '1D'];
2035
+ const aiDirs = consensusTfs
2036
  .map(tf => ((tfs[tf] || {}).ai_forecast || {}).direction)
2037
  .filter(d => d === 'BULLISH' || d === 'BEARISH');
2038
  const aiConsensus = aiDirs[0] || null;
 
2056
 
2057
  const aiToday = _summaryAiDirection(tfs.INTRADAY || {});
2058
  const ai1d = _summaryAiDirection(tfs['1D'] || {});
2059
+ const ai1m = _summaryAiDirection(tfs[ONE_M_TF] || {});
2060
  const wlSummaryHtml = mode === 'watchlist'
2061
+ ? `<div class="wl-summary-grid wl-summary-grid--5">
2062
  <div class="wl-summary-item">
2063
  <div class="wl-summary-label">Current Price</div>
2064
  <div class="wl-summary-value" id="wl-${safeId}-price" data-live-ticker="${pick.ticker}">β‚Ή${num(pickPrice)}</div>
 
2071
  <div class="wl-summary-label">AI (1D)</div>
2072
  <div class="wl-summary-value" id="wl-${safeId}-ai-1d" style="color:${_aiTfColor(ai1d)}">${ai1d}</div>
2073
  </div>
2074
+ <div class="wl-summary-item">
2075
+ <div class="wl-summary-label">AI (1M)</div>
2076
+ <div class="wl-summary-value" id="wl-${safeId}-ai-1m" style="color:${_aiTfColor(ai1m)}">${ai1m}</div>
2077
+ </div>
2078
  <div class="wl-summary-item" style="cursor:pointer" onclick="showNewsModal('${pick.ticker}')" title="Click to see latest headlines">
2079
  <div class="wl-summary-label">πŸ“° News</div>
2080
  <div class="wl-summary-value" style="color:${news.label === 'BULLISH' ? 'var(--green)' : news.label === 'BEARISH' ? 'var(--red)' : 'var(--text-muted)'}">${newsSentiment}</div>
 
2463
  const shortPlan = JSON.stringify({ direction: 'SHORT' }).replace(/'/g, "&#39;");
2464
  // Shell TF grid: ML slots are painted immediately so the instant, local ML forecast
2465
  // can fill in without waiting for the slow per-card AI (/api/watchlist-pick) call.
2466
+ const shellTfHtml = LIVE_TFS.map(tf => `
2467
  <div class="tf-cell tf-cell--loading" id="tf-${safeId}-${tf}" data-ai-dir="">
2468
+ <div class="tf-label">${tfLabel(tf)}</div>${tf === ONE_M_TF ? '' : `
2469
  <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>
2470
+ <div class="tf-agree-slot" id="agree-${safeId}-${tf}"></div>`}
2471
  <div class="tf-fc-block tf-ai-block"><div class="tf-ai-note" style="color:var(--text-muted)">πŸ€– AI forecast loading…</div></div>
2472
  </div>`).join('');
2473
  return `<div class="pick-card pick-card--loading" id="${cardId}" data-ticker="${ticker}">
 
2639
 
2640
  // Render top-pick cards into a container and mount their mini charts.
2641
  // Shared by the final render and the streaming (partial) render.
2642
+ function _renderTop5CardsInto(cardsEl, idPrefix, picks, bannerHtml = '', oneM = null) {
2643
+ _lastTop5 = { cardsEl, idPrefix, picks, banner: bannerHtml, oneM };
2644
+ const is1m = _top5View === '1m';
2645
+ const oneMPicks = (oneM && Array.isArray(oneM.picks)) ? oneM.picks : [];
2646
+ const ordered = is1m ? oneMPicks : _applyTop5Sort(picks);
2647
  // Preserve already-mounted chart nodes across re-renders. Streaming polls this every ~4s and
2648
  // the sort toggle re-renders too; a naive innerHTML rebuild tore down + remounted every live
2649
  // chart each time, causing visible blinking. Stash each mounted chart's wrapper by ticker id
 
2656
  chartStash[tvId] = existing.closest('.chart-wrap') || existing;
2657
  }
2658
  });
2659
+ const viewBar = `<div class="top5-view-bar">
2660
+ <button class="top5-view-btn${is1m ? '' : ' active'}" onclick="_setTop5View('short')">Today / 1D picks</button>
2661
+ <button class="top5-view-btn${is1m ? ' active' : ''}" onclick="_setTop5View('1m')" title="Stocks ranked for buying now and holding about one month">1 Month picks${oneMPicks.length ? ` <span class="top5-view-count">${oneMPicks.length}</span>` : ''}</button>
2662
+ </div>`;
2663
  const sortBar = `<div class="top5-sort-bar">
2664
  <span class="top5-sort-lbl">Rank by</span>
2665
  ${[['ai','AI'],['ml','πŸ€– ML'],['blend','Blend']].map(([m,l]) =>
2666
  `<button class="top5-sort-btn${_top5Sort===m?' active':''}" onclick="_setTop5Sort('${m}')">${l}</button>`).join('')}
2667
  <span class="top5-sort-hint">ML ranks on INTRADAY/1D conviction</span>
2668
  </div>`;
2669
+ let body;
2670
+ if (is1m) {
2671
+ const oneMNote = `<div class="top5-1m-note">Ranked for a <strong>~1-month hold</strong>: trend and relative strength vs Nifty first, then AI confidence and target. Buy now, target at about one month. New Β· unvalidated.</div>`;
2672
+ const emptyMsg = bannerHtml
2673
+ ? 'Still analysing β€” 1 Month picks appear as the AI finishes.'
2674
+ : ((oneM && oneM.note) || 'No 1 Month picks yet.');
2675
+ body = bannerHtml + (oneMPicks.length
2676
+ ? oneMNote + ordered.map((p, i) => renderPickCard(p, i, idPrefix, 'top5', { tfs: [ONE_M_TF] })).join('')
2677
+ : `<div class="empty-state"><div class="empty-icon">πŸ“…</div><div>${emptyMsg}</div></div>`);
2678
+ } else {
2679
+ body = sortBar + bannerHtml + ordered.map((p, i) => renderPickCard(p, i, idPrefix)).join('');
2680
+ }
2681
+ cardsEl.innerHTML = viewBar + body;
2682
  ordered.forEach(p => {
2683
  const tvId = 'tv-' + idPrefix + '-' + p.ticker.replace(/[^a-zA-Z0-9]/g, '_');
2684
  const stashed = chartStash[tvId];
 
2688
  } else {
2689
  observeTvChart(tvId, p.ticker);
2690
  }
2691
+ if (!is1m) _fetchAndFillMl(p.ticker); // instant ML row; AI row keeps its own loader
2692
  // Top picks have no per-card β†Ί Retry button, so without this any TF that came back
2693
  // 'ai_unavailable'/'timeout' would sit on "AI loading… retrying automatically" forever.
2694
  // Kick off the same per-cell background retry the watchlist uses (single-ticker/TF
2695
  // endpoint), guarded so each cell only spawns one retry chain across re-renders/sorts.
2696
+ (is1m ? [ONE_M_TF] : LIVE_TFS).forEach(tf => {
2697
  const r = (p.timeframes || {})[tf]?.no_trade_reason;
2698
  if (r !== 'timeout' && r !== 'ai_unavailable') return;
2699
  const key = p.ticker + '|' + tf;
 
2701
  _top5AiRetried.add(key);
2702
  _fetchAndUpdateTfCell(p.ticker, tf, p);
2703
  });
2704
+ // Picks outside the server's 1M shortlist have no 1M cell yet β€” load it once the scan is
2705
+ // final (not while streaming, when cards are rebuilt every few seconds).
2706
+ if (!is1m && !bannerHtml && !(p.timeframes || {})[ONE_M_TF]) _lazyLoadOneM(p);
2707
  });
2708
  // Top picks are cached for the day (same stocks), but INTRADAY moves all session β€” freshen
2709
  // each pick's INTRADAY cell in place right after render (silent, deduped to ≀1/60s per ticker).
2710
+ if (!is1m) _refreshTop5Intraday(ordered);
2711
+ }
2712
+
2713
+ // Load the 1M forecast for a top pick that was not in the server's 1M shortlist. Independent of
2714
+ // the DOM cell (cards are rebuilt on sort/view toggles): the result is stored on the pick object,
2715
+ // and the cell is repainted in place only if it is still mounted.
2716
+ const _top5OneMLoading = new Set();
2717
+ async function _lazyLoadOneM(pick, attempt = 0) {
2718
+ const ticker = pick && pick.ticker;
2719
+ if (!ticker || _top5OneMLoading.has(ticker)) return;
2720
+ _top5OneMLoading.add(ticker);
2721
+ let retryMs = 0;
2722
+ try {
2723
+ const { res, data } = await _fetchBackgroundJson(
2724
+ '/api/pick-tf/' + encodeURIComponent(ticker) + '/' + ONE_M_TF, { cache: 'no-store' }, 1);
2725
+ if (!res.ok || !data || data.error || !data.data) throw new Error((data && data.error) || `Server error ${res.status}`);
2726
+ const tfData = data.data;
2727
+ pick.timeframes = Object.assign({}, pick.timeframes, { [ONE_M_TF]: tfData });
2728
+ const safeId = ticker.replace(/[^a-zA-Z0-9]/g, '_');
2729
+ const cell = document.getElementById('tf-' + safeId + '-' + ONE_M_TF);
2730
+ if (cell) {
2731
+ const tmp = document.createElement('div');
2732
+ tmp.innerHTML = _renderOneTfCell(ONE_M_TF, tfData, pick);
2733
+ if (tmp.firstElementChild) cell.replaceWith(tmp.firstElementChild);
2734
+ }
2735
+ const r = tfData.no_trade_reason;
2736
+ if (r === 'timeout' || r === 'ai_unavailable') retryMs = r === 'timeout' ? 5000 : 60000;
2737
+ } catch (e) {
2738
+ retryMs = 20000;
2739
+ } finally {
2740
+ _top5OneMLoading.delete(ticker);
2741
+ }
2742
+ if (retryMs && attempt < 8) setTimeout(() => _lazyLoadOneM(pick, attempt + 1), retryMs);
2743
  }
2744
 
2745
  // Silent INTRADAY auto-refresh for the currently-rendered top picks. Keeps the SAME day-cached
 
2759
 
2760
  // ── Top-pick ranking: AI (server order) / ML (quantile conviction) / Blend ─────
2761
  let _top5Sort = 'ai';
2762
+ let _top5View = 'short'; // 'short' = Today/1D picks, '1m' = 1 Month picks
2763
+ let _lastTop5 = { cardsEl: null, idPrefix: '', picks: [], banner: '', oneM: null };
2764
 
2765
  // ML conviction score for a ticker from its cached prediction β€” INTRADAY/1D
2766
  // (matches the AI ranking horizons).
 
2795
 
2796
  function _setTop5Sort(mode) {
2797
  _top5Sort = mode;
2798
+ if (_lastTop5.cardsEl) _renderTop5CardsInto(_lastTop5.cardsEl, _lastTop5.idPrefix, _lastTop5.picks, _lastTop5.banner, _lastTop5.oneM);
2799
+ }
2800
+
2801
+ function _setTop5View(view) {
2802
+ _top5View = view === '1m' ? '1m' : 'short';
2803
+ if (_lastTop5.cardsEl) _renderTop5CardsInto(_lastTop5.cardsEl, _lastTop5.idPrefix, _lastTop5.picks, _lastTop5.banner, _lastTop5.oneM);
2804
  }
2805
 
2806
  async function loadTop5Cards(cardsId, loadingId, limit = 20, forceRefresh = false) {
 
2812
  // Retries update the existing "Analysing…" message in place so the UI doesn't flicker.
2813
  const isRetry = !forceRefresh && _top5PollCount > 0;
2814
  if (!isRetry) { showEl(loadingId); cardsEl.innerHTML = ''; _top5PollStart = Date.now(); _top5AiRetried.clear(); }
2815
+ if (forceRefresh) { _top5PollCount = 0; _top5AutoRetried = false; _top5PollStart = Date.now(); _top5AiRetried.clear(); _top5OneMLoading.clear(); if (_top5PollTimer) { clearTimeout(_top5PollTimer); _top5PollTimer = null; } }
2816
 
2817
  // Abort the fetch after 5 min β€” allows the server time to finish computing on a cold start.
2818
  const ctrl = new AbortController();
 
2881
  <span class="tf-cell-spinner" style="font-size:15px">⟳</span>
2882
  <span>${phaseMsg} β€” showing ${partial.length} ready pick${partial.length > 1 ? 's' : ''}, more loading…</span>
2883
  </div>`;
2884
+ _renderTop5CardsInto(cardsEl, idPrefix, partial, banner,
2885
+ { picks: data.picks_1m || [], note: data.picks_1m_note || '' });
2886
  cardsEl.setAttribute('data-loaded', '1');
2887
  _top5PollTimer = setTimeout(() => loadTop5Cards(cardsId, loadingId, limit, false), 4000);
2888
  return;
 
2936
  generatedEl.textContent = prefix + (data.generated_at || '');
2937
  }
2938
  const idPrefix = cardsId.replace(/[^a-zA-Z0-9]/g, '_');
2939
+ _renderTop5CardsInto(cardsEl, idPrefix, picks, '',
2940
+ { picks: data.picks_1m || [], note: data.picks_1m_note || '' });
2941
  if (data.has_ai_unavailable) {
2942
  _showAiRetryBanner(cardsEl, () => loadTop5Cards(cardsId, loadingId, limit, true));
2943
  }
 
3032
  _fetchAndFillMl(ticker);
3033
 
3034
  // Auto-fetch only unresolved TF cells in the background.
3035
+ LIVE_TFS.forEach(tf => {
3036
  const tfData = (pick.timeframes || {})[tf] || {};
3037
  const r = tfData.no_trade_reason;
3038
  if (forceRefresh || !Object.keys(tfData).length || tfData.cache_stale || r === 'pending' || r === 'timeout' || r === 'ai_unavailable') {
 
4863
  <div class="validation-history-card ${hitClass}" data-tf="${tf}">
4864
  <div class="vh-header">
4865
  <span class="vh-ticker">${h.ticker}</span>
4866
+ <span class="vh-tf">${tf === ONE_M_TF ? '1 Month' : tf}</span>
4867
  <span class="dir-badge dir-${dirCssKey}" title="${h.direction || 'NEUTRAL'}">${dirLabel(h.direction || 'NEUTRAL')}</span>
4868
  ${_srcTag(h.snapshot_source)}
4869
  <span class="vh-result vh-${hitClass}">${h.validation_result}</span>
 
4942
  const allPreds = summaryRaw.all || {};
4943
  const highConf = summaryRaw.high_conf || {};
4944
 
4945
+ ['INTRADAY', '1D', ONE_M_TF].forEach(tf => {
4946
  const dStat = directional[tf]; // directional-only (NEUTRAL excluded)
4947
  const aStat = allPreds[tf]; // all predictions (the honest headline)
4948
  const el = document.getElementById(`vstat-${tf.toLowerCase()}`);
 
5027
  <div class="validation-card${isOverdue ? ' val-overdue' : ''}" data-tf="${p.timeframe}">
5028
  <div class="val-header">
5029
  <span class="val-ticker">${p.ticker}</span>
5030
+ <span class="val-tf">${p.timeframe === ONE_M_TF ? '1 Month' : p.timeframe}</span>
5031
  <span class="dir-badge dir-${dirCssKey}" title="${p.direction || 'NEUTRAL'}">${dirLabel(p.direction || 'NEUTRAL')}</span>
5032
  ${_srcTag(p.snapshot_source)}
5033
  <span class="val-conf conf-${p.confidence}">${p.confidence}</span>
static/style.css CHANGED
@@ -422,6 +422,9 @@ input::placeholder { color: var(--text-dim); }
422
  gap: 6px;
423
  margin-bottom: 10px;
424
  }
 
 
 
425
 
426
  .wl-summary-item {
427
  background: var(--bg3);
@@ -448,7 +451,7 @@ input::placeholder { color: var(--text-dim); }
448
  }
449
 
450
  .tf-grid {
451
- display: grid; grid-template-columns: repeat(2, 1fr);
452
  gap: 6px; margin-bottom: 12px;
453
  }
454
  .tf-cell {
@@ -978,7 +981,7 @@ input::placeholder { color: var(--text-dim); }
978
 
979
  /* ── Validation view ────────────────────────────────────────────────────────── */
980
  .validation-stats {
981
- display: grid; grid-template-columns: repeat(4, 1fr); gap: 12px;
982
  margin-bottom: 24px;
983
  }
984
  .vstat-card {
@@ -1762,3 +1765,31 @@ input::placeholder { color: var(--text-dim); }
1762
  /* Portfolio card on very small phones */
1763
  .portfolio-stats { grid-template-columns: repeat(2, 1fr); }
1764
  }
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
422
  gap: 6px;
423
  margin-bottom: 10px;
424
  }
425
+ /* Equity watchlist summary: Price / AI Today / AI 1D / AI 1M / News. Must stay BEFORE the
426
+ responsive .wl-summary-grid overrides below so those win at narrow widths. */
427
+ .wl-summary-grid--5 { grid-template-columns: repeat(5, minmax(0, 1fr)); }
428
 
429
  .wl-summary-item {
430
  background: var(--bg3);
 
451
  }
452
 
453
  .tf-grid {
454
+ display: grid; grid-template-columns: repeat(auto-fit, minmax(170px, 1fr));
455
  gap: 6px; margin-bottom: 12px;
456
  }
457
  .tf-cell {
 
981
 
982
  /* ── Validation view ────────────────────────────────────────────────────────── */
983
  .validation-stats {
984
+ display: grid; grid-template-columns: repeat(auto-fit, minmax(140px, 1fr)); gap: 12px;
985
  margin-bottom: 24px;
986
  }
987
  .vstat-card {
 
1765
  /* Portfolio card on very small phones */
1766
  .portfolio-stats { grid-template-columns: repeat(2, 1fr); }
1767
  }
1768
+
1769
+
1770
+ /* ── 1 Month (1M) timeframe ─────────────────────────────────────────────────── */
1771
+ .tf-new-chip {
1772
+ display: inline-block; margin: 2px 0 4px; padding: 1px 7px; border-radius: 999px;
1773
+ font-size: 9px; font-weight: 700; letter-spacing: .3px; text-transform: uppercase;
1774
+ color: var(--text-muted); background: var(--bg2, var(--bg3)); border: 1px dashed var(--border2, var(--border));
1775
+ }
1776
+ .tf-hold-note { font-size: 10px; color: var(--text-muted); margin: 2px 0 4px; }
1777
+ .top5-view-bar { display: flex; gap: 6px; flex-wrap: wrap; margin-bottom: 10px; grid-column: 1 / -1; }
1778
+ .top5-view-btn {
1779
+ font-size: 12px; font-weight: 600; padding: 6px 14px; border-radius: 8px; cursor: pointer;
1780
+ background: var(--bg3); border: 1px solid var(--border); color: var(--text-dim);
1781
+ }
1782
+ .top5-view-btn:hover { border-color: var(--border2); }
1783
+ .top5-view-btn.active { background: var(--accent, #6366f1); border-color: var(--accent, #6366f1); color: #fff; }
1784
+ .top5-view-count {
1785
+ display: inline-block; min-width: 16px; margin-left: 4px; padding: 0 5px; border-radius: 999px;
1786
+ font-size: 10px; text-align: center; background: rgba(255,255,255,.22);
1787
+ }
1788
+ .top5-1m-note {
1789
+ grid-column: 1 / -1; font-size: 12px; color: var(--text-muted); margin-bottom: 10px;
1790
+ padding: 8px 12px; border-radius: 8px; background: var(--bg3); border: 1px solid var(--border);
1791
+ }
1792
+ @media (max-width: 900px) {
1793
+ /* 5 summary items on a 2-column grid: let the last (News) fill the row instead of orphaning. */
1794
+ .wl-summary-grid--5 > .wl-summary-item:last-child { grid-column: 1 / -1; }
1795
+ }
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=20261103fo-refresh-btn">
37
  <script src="/static/vendor/lightweight-charts-4.2.0.js"></script>
38
  </head>
39
  <body>
@@ -169,7 +169,7 @@
169
  <div class="view-header view-header--row">
170
  <div>
171
  <h1 class="view-title">Watchlist</h1>
172
- <p class="view-subtitle">Stocks you're monitoring β€” Today / 1D predictions with entry, stop-loss, and target.</p>
173
  </div>
174
  <div class="view-header-actions">
175
  <button class="btn-ghost" id="wl-refresh-fo-btn" title="Re-quote and re-forecast only the F&amp;O contracts">Refresh F&amp;O</button>
@@ -321,6 +321,11 @@
321
  <span class="vstat-val" id="vstat-1d">β€”</span>
322
  <span class="vstat-sub" id="vstat-1d-sub"></span>
323
  </div>
 
 
 
 
 
324
  <div class="vstat-card vstat-card--highconf">
325
  <span class="vstat-label">HIGH-Conf Hit Rate</span>
326
  <span class="vstat-val" id="vstat-highconf">β€”</span>
@@ -344,6 +349,7 @@
344
  <button class="tf-pill active" data-tf="ALL">All</button>
345
  <button class="tf-pill" data-tf="INTRADAY">Today</button>
346
  <button class="tf-pill" data-tf="1D">1D</button>
 
347
  </div>
348
  <div id="pending-validation-list"></div>
349
  </div>
@@ -353,6 +359,7 @@
353
  <button class="tf-pill active" data-tf="ALL">All</button>
354
  <button class="tf-pill" data-tf="INTRADAY">Today</button>
355
  <button class="tf-pill" data-tf="1D">1D</button>
 
356
  </div>
357
  <div id="validation-history-list"></div>
358
  </div>
@@ -544,6 +551,6 @@
544
  </a>
545
  </nav>
546
 
547
- <script src="/static/app.js?v=20261103fo-refresh-btn"></script>
548
  </body>
549
  </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=20261112a-1m">
37
  <script src="/static/vendor/lightweight-charts-4.2.0.js"></script>
38
  </head>
39
  <body>
 
169
  <div class="view-header view-header--row">
170
  <div>
171
  <h1 class="view-title">Watchlist</h1>
172
+ <p class="view-subtitle">Stocks you're monitoring β€” Today / 1D / 1 Month predictions with entry, stop-loss, and target.</p>
173
  </div>
174
  <div class="view-header-actions">
175
  <button class="btn-ghost" id="wl-refresh-fo-btn" title="Re-quote and re-forecast only the F&amp;O contracts">Refresh F&amp;O</button>
 
321
  <span class="vstat-val" id="vstat-1d">β€”</span>
322
  <span class="vstat-sub" id="vstat-1d-sub"></span>
323
  </div>
324
+ <div class="vstat-card">
325
+ <span class="vstat-label">1 Month Hit Rate</span>
326
+ <span class="vstat-val" id="vstat-1m">β€”</span>
327
+ <span class="vstat-sub" id="vstat-1m-sub"></span>
328
+ </div>
329
  <div class="vstat-card vstat-card--highconf">
330
  <span class="vstat-label">HIGH-Conf Hit Rate</span>
331
  <span class="vstat-val" id="vstat-highconf">β€”</span>
 
349
  <button class="tf-pill active" data-tf="ALL">All</button>
350
  <button class="tf-pill" data-tf="INTRADAY">Today</button>
351
  <button class="tf-pill" data-tf="1D">1D</button>
352
+ <button class="tf-pill" data-tf="1M">1 Month</button>
353
  </div>
354
  <div id="pending-validation-list"></div>
355
  </div>
 
359
  <button class="tf-pill active" data-tf="ALL">All</button>
360
  <button class="tf-pill" data-tf="INTRADAY">Today</button>
361
  <button class="tf-pill" data-tf="1D">1D</button>
362
+ <button class="tf-pill" data-tf="1M">1 Month</button>
363
  </div>
364
  <div id="validation-history-list"></div>
365
  </div>
 
551
  </a>
552
  </nav>
553
 
554
+ <script src="/static/app.js?v=20261112a-1m"></script>
555
  </body>
556
  </html>
tests/test_one_month_timeframe.py ADDED
@@ -0,0 +1,287 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import atexit
2
+ import inspect
3
+ import logging
4
+ import os
5
+ import tempfile
6
+ import unittest
7
+ from datetime import date, datetime, timedelta, timezone
8
+ from unittest.mock import patch
9
+
10
+ import database as db
11
+
12
+ _TEST_BOOK = tempfile.TemporaryDirectory(prefix="papertrade-1m-tests-")
13
+ atexit.register(_TEST_BOOK.cleanup)
14
+ with patch.object(db, "DB_PATH", os.path.join(_TEST_BOOK.name, "paper_trading.db")), \
15
+ patch.object(db, "setup_hf_persistence"), patch("threading.Thread.start"):
16
+ import app as _app_module
17
+
18
+ import ai_forecast
19
+ import market_calendar
20
+ import self_learning
21
+ import top5_picker
22
+ from predictor_core import TIMEFRAME_DAYS, timeframe_to_dates
23
+
24
+ _IST = timezone(timedelta(hours=5, minutes=30))
25
+
26
+
27
+ def _today_ist() -> date:
28
+ return datetime.now(timezone.utc).astimezone(_IST).date()
29
+
30
+
31
+ class OneMonthWindowTests(unittest.TestCase):
32
+ def test_window_is_about_one_month_and_labelled_1m_not_1w(self):
33
+ start, end = timeframe_to_dates("1M")
34
+ span = (date.fromisoformat(end) - date.fromisoformat(start)).days
35
+ self.assertEqual(span, 30)
36
+ # predict_stock_v2 maps trading-day counts >= 15 to "1M" and 7-14 to "1W".
37
+ self.assertGreaterEqual(int(span * 5 / 7), 15)
38
+ s5, e5 = timeframe_to_dates("5D")
39
+ self.assertLess(int((date.fromisoformat(e5) - date.fromisoformat(s5)).days * 5 / 7), 15)
40
+ self.assertEqual(TIMEFRAME_DAYS["1M"], 28)
41
+
42
+ def test_live_timeframes_accept_1m_and_keep_3d_retired(self):
43
+ self.assertEqual(_app_module.LIVE_TIMEFRAMES, ["INTRADAY", "1D", "1M"])
44
+ start, end = _app_module._resolve_dates({"timeframe": "1m"})
45
+ self.assertEqual((date.fromisoformat(end) - date.fromisoformat(start)).days, 30)
46
+ self.assertEqual(_app_module._resolve_dates({"timeframe": "3D"}), ("", ""))
47
+
48
+
49
+ class OneMonthBandTests(unittest.TestCase):
50
+ def _band(self, direction, tf="1M", atr=40.0, price=2000.0):
51
+ return ai_forecast._atr_clamp_range({}, tf, atr, price, False, direction)
52
+
53
+ def test_directional_band_is_ordered_wide_and_capped(self):
54
+ bull = self._band("BULLISH")
55
+ self.assertGreater(bull["predicted_return_lo"], 0)
56
+ self.assertGreater(bull["predicted_return_hi"] - bull["predicted_return_lo"], 1.99)
57
+ self.assertLessEqual(bull["predicted_return_hi"], 25.0)
58
+ self.assertGreater(bull["target_price_lo"], 2000.0)
59
+ bear = self._band("BEARISH")
60
+ self.assertLess(bear["predicted_return_lo"], bear["predicted_return_hi"])
61
+ self.assertLess(bear["predicted_return_hi"], 0)
62
+ self.assertEqual(bear["predicted_return_lo"], -bull["predicted_return_hi"])
63
+ # A month is far wider than 3 days for the same stock.
64
+ self.assertGreater(bull["predicted_return_hi"], self._band("BULLISH", tf="3D")["predicted_return_hi"])
65
+
66
+ def test_extreme_volatility_stays_inside_the_hard_cap(self):
67
+ wild = self._band("BULLISH", atr=400.0) # ATR = 20% of price
68
+ self.assertLessEqual(wild["predicted_return_hi"], 25.0)
69
+ self.assertLess(wild["predicted_return_lo"], wild["predicted_return_hi"])
70
+
71
+ def test_neutral_band_is_a_wide_symmetric_monthly_range(self):
72
+ for atr in (10.0, 40.0, 400.0):
73
+ band = self._band("NEUTRAL", atr=atr)
74
+ self.assertEqual(band["predicted_return_lo"], -band["predicted_return_hi"])
75
+ self.assertGreaterEqual(band["predicted_return_hi"], 5.0)
76
+ self.assertLessEqual(band["predicted_return_hi"], 12.0)
77
+
78
+ def test_1d_neutral_band_is_unchanged(self):
79
+ band = self._band("NEUTRAL", tf="1D")
80
+ self.assertEqual(band["predicted_return_hi"], ai_forecast._NEUT_RANGE["1D"][1])
81
+
82
+ def test_prompt_is_a_one_month_prompt(self):
83
+ prompt = ai_forecast._build_synthesis_prompt("ctx", "bull", "bear", "", "1M", 2000.0, 40.0)
84
+ self.assertIn("DIRECTION GUIDE for 1M", prompt)
85
+ self.assertIn("~1 month", prompt)
86
+ self.assertIn("25.0%", prompt)
87
+ self.assertNotIn("3 trading days", prompt)
88
+
89
+ def test_get_ai_forecast_recognises_1m_instead_of_defaulting_to_3d(self):
90
+ # The label list is local to get_ai_forecast; an unknown label silently becomes "3D".
91
+ source = inspect.getsource(ai_forecast.get_ai_forecast)
92
+ self.assertRegex(source, r'_TF_LABELS = \([^)]*"1M"[^)]*\)')
93
+
94
+
95
+ class OneMonthGuardrailTests(unittest.TestCase):
96
+ BASE = {"rsi14": 58, "bb_pct": 60, "macd_signal": 1, "return_10d": 2, "return_20d": 4,
97
+ "ema50": 1900, "ema200": 1700, "rs_3m_pct": 3}
98
+
99
+ def _call(self, direction="NEUTRAL", confidence="MEDIUM", **overrides):
100
+ return ai_forecast._apply_trigger_guardrails(
101
+ direction, confidence, {**self.BASE, **overrides}, 2000.0, "1M")
102
+
103
+ def test_trend_with_relative_strength_is_bullish(self):
104
+ direction, confidence, note = self._call("NEUTRAL")
105
+ self.assertEqual((direction, confidence), ("BULLISH", "MEDIUM"))
106
+ self.assertIn("1-month trigger M1", note)
107
+
108
+ def test_structural_laggard_cannot_be_bullish(self):
109
+ direction, _, _ = self._call("BULLISH", rs_3m_pct=-10)
110
+ self.assertEqual(direction, "NEUTRAL")
111
+
112
+ def test_downtrend_below_ema50_is_bearish(self):
113
+ direction, _, note = self._call("BULLISH", ema50=2100, macd_signal=-1,
114
+ return_20d=-6, return_10d=-3, rs_3m_pct=-2)
115
+ self.assertEqual(direction, "BEARISH")
116
+ self.assertIn("MB1", note)
117
+
118
+ def test_crash_is_never_bullish(self):
119
+ direction, _, _ = self._call("BULLISH", return_10d=-8, return_20d=-9, macd_signal=-1)
120
+ self.assertEqual(direction, "BEARISH")
121
+
122
+ def test_no_trigger_downgrades_a_directional_call_to_neutral(self):
123
+ direction, confidence, _ = self._call("BULLISH", "HIGH", ema50=2100, return_20d=1, macd_signal=1)
124
+ self.assertEqual((direction, confidence), ("NEUTRAL", "MEDIUM"))
125
+
126
+ def test_1d_rules_are_untouched(self):
127
+ direction, _, note = ai_forecast._apply_trigger_guardrails(
128
+ "NEUTRAL", "MEDIUM", dict(self.BASE), 2000.0, "1D")
129
+ self.assertEqual(direction, "BULLISH")
130
+ self.assertNotIn("1-month", note or "")
131
+
132
+
133
+ class OneMonthSnapshotTests(unittest.TestCase):
134
+ def test_offsets_and_snapshot_target_date_are_a_month_out(self):
135
+ self.assertEqual(db.TF_CALENDAR_OFFSET["1M"], 30)
136
+ today = _today_ist()
137
+ deadline = date.fromisoformat(db._trading_deadline("1M"))
138
+ self.assertGreaterEqual((deadline - today).days, 30)
139
+ self.assertLessEqual((deadline - today).days, 34)
140
+ with tempfile.TemporaryDirectory() as directory, patch.object(db, "DB_PATH", os.path.join(directory, "book.db")):
141
+ db.init_db()
142
+ snapshot_id = db.save_prediction_snapshot(
143
+ "AAA.NS", "1M", "BULLISH", "MEDIUM", 103.0, 108.0, 3.0, 8.0, 100.0)
144
+ self.assertIsNotNone(snapshot_id)
145
+ with db._conn() as conn:
146
+ target = conn.execute(
147
+ "SELECT validation_target_date FROM prediction_snapshots WHERE id = ?", (snapshot_id,)
148
+ ).fetchone()[0]
149
+ self.assertGreaterEqual((date.fromisoformat(target) - today).days, 30)
150
+
151
+ def test_other_offsets_unchanged(self):
152
+ self.assertEqual({k: v for k, v in db.TF_CALENDAR_OFFSET.items() if k != "1M"},
153
+ {"INTRADAY": 0, "1D": 1, "3D": 3, "5D": 5, "1W": 7})
154
+
155
+ def test_price_window_download_covers_the_whole_one_month_window(self):
156
+ periods = []
157
+
158
+ def _capture(ticker, period="1y"):
159
+ periods.append(period)
160
+ raise RuntimeError("stop after capturing the period")
161
+
162
+ today = _today_ist()
163
+ with patch.object(_app_module, "fetch_ohlcv", _capture):
164
+ _app_module._fetch_price_window("AAA.NS", (today - timedelta(days=30)).isoformat(), today.isoformat())
165
+ _app_module._fetch_price_window("AAA.NS", today.isoformat(), today.isoformat())
166
+ self.assertEqual(periods, ["3mo", "1mo"])
167
+
168
+
169
+ class OneMonthSupportTests(unittest.TestCase):
170
+ def test_learning_notes_for_1m_do_not_leak_into_other_timeframes(self):
171
+ note = "1M calibration: HIGH confidence overshoots targets"
172
+ self.assertTrue(self_learning._note_matches_tf(note, "1M"))
173
+ self.assertFalse(self_learning._note_matches_tf(note, "1D"))
174
+ self.assertTrue(self_learning._note_matches_tf("confidence calibration overall", "1D"))
175
+
176
+ def test_calendar_year_without_holidays_warns_once_and_uses_weekdays(self):
177
+ market_calendar._WARNED_YEARS.discard(2099)
178
+ with self.assertLogs("market_calendar", level="WARNING") as logs:
179
+ self.assertTrue(market_calendar.is_trading_day(date(2099, 1, 5))) # a Monday
180
+ self.assertIn("no NSE holidays loaded for 2099", logs.output[0])
181
+ self.assertFalse(market_calendar.is_trading_day(date(2099, 1, 3))) # a Saturday
182
+ with self.assertRaises(AssertionError): # second lookup is silent
183
+ with self.assertLogs("market_calendar", level="WARNING"):
184
+ market_calendar.is_trading_day(date(2099, 1, 6))
185
+
186
+
187
+ def _scan_pred(ticker, rs_3m):
188
+ return {
189
+ "ticker": ticker, "company": ticker, "price": 1000.0, "direction": "NEUTRAL", "confidence": "LOW",
190
+ "risk": {"atr14": 20.0}, "sector": {}, "news": {},
191
+ "ml": {"probability": 0.6, "signal_count": 1, "features": {
192
+ "ema_stack": 0.8, "rs_3m_pct": rs_3m, "macd_pos": True, "adx": 30.0}},
193
+ "market": {"vix_level": 15.0, "nifty_ok": True, "macro_ok": True, "vix_label": "", "nifty_label": "", "macro_label": ""},
194
+ }
195
+
196
+
197
+ def _ai_pred(ticker, tf):
198
+ ret_hi = {"INTRADAY": 1.0, "1D": 2.0, "1M": 8.0}[tf]
199
+ return {
200
+ "ticker": ticker, "price": 1000.0, "direction": "BULLISH", "confidence": "MEDIUM",
201
+ "ret_lo": ret_hi / 3, "ret_hi": ret_hi, "midpoint": ret_hi * 0.6,
202
+ "expected_entry_price": 1000.0, "entry_basis": "live",
203
+ "target_price_lo": 1000 * (1 + ret_hi / 300), "target_price_hi": 1000 * (1 + ret_hi / 100),
204
+ "expected_target_price": 1000 * (1 + ret_hi * 0.6 / 100), "sector": {}, "news": {},
205
+ "risk": {"atr14": 20.0, "stop_loss": 950.0, "stop_loss_pct": 5.0, "min_target": 1100.0, "actual_rr": 2.0},
206
+ "ai_forecast": {"direction": "BULLISH", "should_buy": True},
207
+ }
208
+
209
+
210
+ class OneMonthTopPicksTests(unittest.TestCase):
211
+ def _run(self, ai_tf_fail=()):
212
+ calls = []
213
+
214
+ def fake_predict(ticker, tf, ctx, run_ai=False, ai_fast_mode=False, skip_news=False):
215
+ calls.append((ticker, tf, run_ai))
216
+ if not run_ai:
217
+ return ticker, tf, _scan_pred(ticker, {"AAA.NS": 6.0, "BBB.NS": 1.0, "LAG.NS": -12.0}[ticker])
218
+ if (ticker, tf) in ai_tf_fail:
219
+ raise RuntimeError("timeout")
220
+ return ticker, tf, _ai_pred(ticker, tf)
221
+
222
+ class _NoMl:
223
+ available = False
224
+
225
+ universe = {"AAA.NS": "A", "BBB.NS": "B", "LAG.NS": "Laggard"}
226
+ snapshots = []
227
+ with patch.object(top5_picker, "_run_predict_with_ctx", fake_predict), \
228
+ patch.object(top5_picker, "_get_specialist_recommendation", lambda t: None), \
229
+ patch("ml_predictor.infer.get_ml_predictor", lambda: _NoMl()), \
230
+ patch("llm_client._all_cloud_daily_exhausted", lambda: False):
231
+ result = top5_picker.get_top5_picks(universe=list(universe), _universe_size=0,
232
+ progress_cb=snapshots.append)
233
+ return result, calls, snapshots
234
+
235
+ def test_one_month_shortlist_excludes_laggards_and_calls_the_ai_once_per_stock(self):
236
+ result, calls, _ = self._run()
237
+ one_m_calls = [c for c in calls if c[1] == "1M"]
238
+ self.assertEqual(sorted(c[0] for c in one_m_calls), ["AAA.NS", "BBB.NS"]) # LAG.NS filtered out
239
+ self.assertTrue(all(run_ai for _, _, run_ai in one_m_calls))
240
+ self.assertEqual(len([c for c in calls if c[1] == "INTRADAY" and c[2]]), 3) # existing TFs unchanged
241
+ self.assertEqual(len([c for c in calls if c[1] == "1D" and c[2]]), 3)
242
+
243
+ def test_picks_carry_a_1m_cell_only_when_shortlisted_and_a_separate_ranking(self):
244
+ result, _, _ = self._run()
245
+ by_ticker = {p["ticker"]: p for p in result["picks"]}
246
+ self.assertIn("1M", by_ticker["AAA.NS"]["timeframes"])
247
+ self.assertNotIn("1M", by_ticker["LAG.NS"]["timeframes"])
248
+ cell = by_ticker["AAA.NS"]["timeframes"]["1M"]
249
+ self.assertEqual(cell["entry_basis"], "live")
250
+ self.assertEqual(cell["ret_hi"], 8.0)
251
+ self.assertNotIn("entry_basis", by_ticker["AAA.NS"]["timeframes"]["1D"])
252
+ self.assertEqual(by_ticker["AAA.NS"]["best_tf"] in ("INTRADAY", "1D"), True)
253
+ ranked = result["picks_1m"]
254
+ self.assertEqual([p["ticker"] for p in ranked], ["AAA.NS", "BBB.NS"]) # stronger trend/RS first
255
+ self.assertEqual([p["rank"] for p in ranked], [1, 2])
256
+ self.assertTrue(all(p["best_tf"] == "1M" and list(p["timeframes"]) == ["1M"] for p in ranked))
257
+ self.assertIsNone(result["picks_1m_note"])
258
+
259
+ def test_failed_1m_calls_are_reported_not_fabricated(self):
260
+ result, _, _ = self._run(ai_tf_fail={("AAA.NS", "1M"), ("BBB.NS", "1M")})
261
+ self.assertEqual(result["picks_1m"], [])
262
+ self.assertIn("No shortlisted stock", result["picks_1m_note"])
263
+ cell = {p["ticker"]: p for p in result["picks"]}["AAA.NS"]["timeframes"]["1M"]
264
+ self.assertEqual(cell["no_trade_reason"], "ai_unavailable")
265
+
266
+ def test_streaming_snapshots_include_the_1m_ranking(self):
267
+ _, _, snapshots = self._run()
268
+ predicting = [s for s in snapshots if s.get("phase") == "predicting"]
269
+ self.assertTrue(predicting)
270
+ self.assertTrue(all("picks_1m" in s for s in predicting))
271
+
272
+ def test_with_live_prices_reanchors_the_1m_ranking(self):
273
+ pick = {"ticker": "AAA.NS", "price": 1000.0, "timeframes": {"1M": {
274
+ "ret_lo": 2.0, "ret_hi": 8.0, "midpoint": 5.0, "target_price_lo": 1020.0,
275
+ "target_price_hi": 1080.0, "expected_target_price": 1050.0}}}
276
+ with patch.object(_app_module, "_current_price", lambda ticker, strict=False: 1100.0):
277
+ out = _app_module._with_live_prices({"picks": [], "picks_1m": [pick]})
278
+ cell = out["picks_1m"][0]["timeframes"]["1M"]
279
+ self.assertEqual(out["picks_1m"][0]["price"], 1100.0)
280
+ self.assertEqual(cell["target_price_lo"], 1122.0)
281
+ self.assertEqual(cell["expected_target_price"], 1155.0)
282
+ self.assertEqual(pick["timeframes"]["1M"]["target_price_lo"], 1020.0) # cached pick not mutated
283
+
284
+
285
+ if __name__ == "__main__":
286
+ logging.basicConfig(level=logging.WARNING)
287
+ unittest.main()
tests/test_watchlist_frontend.cjs CHANGED
@@ -346,6 +346,7 @@ test('watchlist hydrates saved cards before starting slow requests', async () =>
346
  const card = { outerHTML: '', querySelector: () => null };
347
  const context = vm.createContext({
348
  _watchlistLoadSeq: 0,
 
349
  document: { getElementById: id => id === 'wl-list' ? host : card },
350
  _clearAiRetry() {}, _istDateKey: () => '2026-10-12',
351
  _istTimeKeyWithSeconds: () => '10:00:00',
@@ -368,7 +369,8 @@ test('watchlist hydrates saved cards before starting slow requests', async () =>
368
  assert.ok(events.indexOf('ml') > events.findIndex(event => event.startsWith('/api/watchlist-picks')));
369
  assert.ok(events.indexOf('chart') > events.findIndex(event => event.startsWith('/api/watchlist-picks')));
370
  assert.equal(events.filter(event => event === 'ml').length, 1);
371
- assert.equal(events.filter(event => event === 'ai').length, 2);
 
372
  });
373
 
374
  test('an old watchlist response cannot overwrite a newer refresh', async () => {
@@ -929,6 +931,7 @@ test('pending AI retries promptly and preserves manual refresh intent', async ()
929
  createElement: () => ({ firstElementChild: {} }),
930
  },
931
  _AI_RETRY_MAX: 10, _predictionCache: new Map(),
 
932
  _fetchAndFillMl() {}, _istTimeKeyWithSeconds: () => '10:00:00',
933
  _refreshWatchlistSummaryBadges() {}, _refreshWatchlistRecommendedAction() {},
934
  _renderOneTfCell: () => '<cell>',
@@ -952,4 +955,62 @@ test('pending AI retries promptly and preserves manual refresh intent', async ()
952
  retryOptions = null;
953
  timers[0].callback();
954
  assert.equal(retryOptions, null);
955
- });
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
346
  const card = { outerHTML: '', querySelector: () => null };
347
  const context = vm.createContext({
348
  _watchlistLoadSeq: 0,
349
+ LIVE_TFS: ['INTRADAY', '1D', '1M'],
350
  document: { getElementById: id => id === 'wl-list' ? host : card },
351
  _clearAiRetry() {}, _istDateKey: () => '2026-10-12',
352
  _istTimeKeyWithSeconds: () => '10:00:00',
 
369
  assert.ok(events.indexOf('ml') > events.findIndex(event => event.startsWith('/api/watchlist-picks')));
370
  assert.ok(events.indexOf('chart') > events.findIndex(event => event.startsWith('/api/watchlist-picks')));
371
  assert.equal(events.filter(event => event === 'ml').length, 1);
372
+ // INTRADAY (missing) + 1D (timeout) + 1M (missing) each start one background fetch.
373
+ assert.equal(events.filter(event => event === 'ai').length, 3);
374
  });
375
 
376
  test('an old watchlist response cannot overwrite a newer refresh', async () => {
 
931
  createElement: () => ({ firstElementChild: {} }),
932
  },
933
  _AI_RETRY_MAX: 10, _predictionCache: new Map(),
934
+ ONE_M_TF: '1M', tfLabel: tf => tf,
935
  _fetchAndFillMl() {}, _istTimeKeyWithSeconds: () => '10:00:00',
936
  _refreshWatchlistSummaryBadges() {}, _refreshWatchlistRecommendedAction() {},
937
  _renderOneTfCell: () => '<cell>',
 
955
  retryOptions = null;
956
  timers[0].callback();
957
  assert.equal(retryOptions, null);
958
+ });
959
+
960
+ test('1M cell shows a buy-now entry, a 1M target and no ML section', () => {
961
+ const context = vm.createContext({
962
+ _mlCache: new Map(), num: (v, d) => Number(v).toFixed(d ?? 2), retColor: () => 'green',
963
+ formatReturnRange: (lo, hi) => `${lo}% to ${hi}%`, dirLabel: d => d,
964
+ _renderMlRow: () => '<ml-row>', _agreeHtml: () => '<agree>', _isPreMarketIST: () => false,
965
+ });
966
+ vm.runInContext(section('const LIVE_TFS', 'function _renderOneTfCell('), context);
967
+ vm.runInContext(section('function _renderOneTfCell(', '// Fetch one TF for a watchlist card'), context);
968
+ const pick = { ticker: 'TEST.NS', price: 100, signals: {}, timeframes: {} };
969
+ const d = {
970
+ direction: 'BULLISH', confidence: 'MEDIUM', ret_lo: 2, ret_hi: 7, midpoint: 4.5,
971
+ expected_entry_price: 100, entry_basis: 'live', expected_target_price: 104.5,
972
+ target_price_lo: 102, target_price_hi: 107, stop_loss: 92, actual_rr: 1.8,
973
+ ai_forecast: { direction: 'BULLISH', confidence: 'MEDIUM', should_buy: true, entry_price: 100,
974
+ target_price_lo: 102, target_price_hi: 107, predicted_return_lo: 2, predicted_return_hi: 7 },
975
+ };
976
+ const html = context._renderOneTfCell('1M', d, pick);
977
+ assert.match(html, /<div class="tf-label">1 Month<\/div>/);
978
+ assert.match(html, /Buy now/);
979
+ assert.match(html, /1M target β‚Ή10[45]/);
980
+ assert.match(html, /1M Tgt/);
981
+ assert.match(html, /New Β· unvalidated/);
982
+ assert.match(html, /hold ~1 month/);
983
+ assert.doesNotMatch(html, /ML MODEL|tf-ml-slot|<ml-row>/);
984
+ // Other horizons keep their ML section.
985
+ assert.match(context._renderOneTfCell('INTRADAY', d, pick), /ML MODEL/);
986
+ // A pending 1M cell is a spinner with no ML block either.
987
+ const pending = context._renderOneTfCell('1M', { no_trade_reason: 'pending' }, pick);
988
+ assert.match(pending, /AI analysing/);
989
+ assert.doesNotMatch(pending, /ML MODEL/);
990
+ assert.equal(context.tfLabel('INTRADAY'), 'Today');
991
+ assert.equal(context.tfLabel('1D'), '1D');
992
+ assert.equal(context.tfLabel('1M'), '1 Month');
993
+ });
994
+
995
+ test('lazy 1M load stores the forecast on the pick and repaints a mounted cell', async () => {
996
+ const urls = [];
997
+ let painted = null;
998
+ const context = vm.createContext({
999
+ ONE_M_TF: '1M', Set,
1000
+ document: {
1001
+ getElementById: () => ({ replaceWith(replacement) { painted = replacement; } }),
1002
+ createElement: () => ({ set innerHTML(html) { this.firstElementChild = { html }; } }),
1003
+ },
1004
+ _fetchBackgroundJson: async url => { urls.push(url);
1005
+ return { res: { ok: true }, data: { data: { direction: 'BULLISH', no_trade_reason: null } } }; },
1006
+ _renderOneTfCell: (tf, d) => `<cell ${tf} ${d.direction}>`,
1007
+ setTimeout() {},
1008
+ });
1009
+ vm.runInContext(section('const _top5OneMLoading', '// Silent INTRADAY auto-refresh'), context);
1010
+ const pick = { ticker: 'TEST.NS', timeframes: { '1D': {} } };
1011
+ await context._lazyLoadOneM(pick);
1012
+ assert.deepEqual(urls, ['/api/pick-tf/TEST.NS/1M']);
1013
+ assert.equal(pick.timeframes['1M'].direction, 'BULLISH');
1014
+ assert.deepEqual(Object.keys(pick.timeframes).sort(), ['1D', '1M']);
1015
+ assert.equal(painted.html, '<cell 1M BULLISH>');
1016
+ });
top5_picker.py CHANGED
@@ -22,6 +22,14 @@ from predictor_core import predict_stock_v2, DEFAULT_UNIVERSE, timeframe_to_date
22
  TIMEFRAMES = ["INTRADAY", "1D"] # 3D + 5D removed β€” INTRADAY/1D are the shown horizons
23
  _TOP5_DEFAULT_SCAN_SIZE = max(1, int(os.getenv("TOP5_SCAN_SIZE", "200") or "200"))
24
 
 
 
 
 
 
 
 
 
25
 
26
  def _now_ist_str() -> str:
27
  ist = _dt.timezone(_dt.timedelta(hours=5, minutes=30))
@@ -691,8 +699,8 @@ def get_top5_picks(
691
  }
692
 
693
  # ATR multipliers and R:R targets per timeframe (must match predictor_core.py)
694
- _ATR_MULT = {"INTRADAY": 0.4, "1D": 0.7, "3D": 1.1, "5D": 1.5}
695
- _RR_MULT = {"INTRADAY": 1.2, "1D": 1.5, "3D": 1.7, "5D": 2.0}
696
 
697
  def _derive_risk(price, atr14, tf):
698
  """Derive SL/target from ATR when AI response risk fields are missing."""
@@ -707,7 +715,38 @@ def get_top5_picks(
707
  # For shortlisted top picks, compute full-debate AI predictions for all TFs.
708
  # 5D is re-run with full debate (not reused from the fast-mode scan) so all
709
  # three timeframe tabs on the card have consistent, high-quality forecasts.
710
- ai_jobs: list[tuple[str, str]] = []
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
711
  for stock in candidates:
712
  ticker = stock["ticker"]
713
  for tf in TIMEFRAMES:
@@ -779,6 +818,50 @@ def get_top5_picks(
779
  best_score *= 1.0 + min(sv, 5.0) * 0.10
780
  return best, best_score
781
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
782
  def _assemble(partial: bool = False) -> list[dict]:
783
  """Assemble ranked pick cards from candidates + whatever AI predictions exist.
784
 
@@ -794,52 +877,14 @@ def get_top5_picks(
794
  ticker = stock["ticker"]
795
  price = stock.get("price") or 0
796
  anchor_atr14 = ((ai_preds.get((ticker, "1D"), {}).get("risk") or {}).get("atr14")
797
- or (ai_preds.get((ticker, "INTRADAY"), {}).get("risk") or {}).get("atr14"))
 
798
  timeframe_data: dict[str, dict] = {}
799
  ml_res = ml_preds_by_ticker.get(ticker)
800
  ml_tfs = (ml_res.get("tfs", {}) if (ml_res and ml_res.get("available")) else {}) or {}
801
 
802
- for tf in TIMEFRAMES:
803
- base_stock = ai_preds.get((ticker, tf), {})
804
- if not base_stock or base_stock.get("error"):
805
- base_stock = _empty_ai_tf(price, _missing_reason)
806
-
807
- tf_risk = base_stock.get("risk", {}) or {}
808
- sl = tf_risk.get("stop_loss")
809
- tgt = tf_risk.get("min_target")
810
- sl_pct = tf_risk.get("stop_loss_pct")
811
- actual_rr = tf_risk.get("actual_rr")
812
- if sl is None and anchor_atr14:
813
- sl, sl_pct, tgt = _derive_risk(price, anchor_atr14, tf)
814
- pred_ret_hi = base_stock.get("ret_hi")
815
- if pred_ret_hi and pred_ret_hi > 0 and price > 0:
816
- tgt = round(price * (1 + pred_ret_hi / 100), 2)
817
-
818
- timeframe_data[tf] = {
819
- "expected_return_range": base_stock.get("expected_return_range"),
820
- "midpoint": base_stock.get("midpoint", 0),
821
- "ret_lo": base_stock.get("ret_lo"),
822
- "ret_hi": base_stock.get("ret_hi"),
823
- "target_price_lo": base_stock.get("target_price_lo"),
824
- "target_price_hi": base_stock.get("target_price_hi"),
825
- "expected_target_price": base_stock.get("expected_target_price"),
826
- "expected_entry_price": base_stock.get("expected_entry_price", price),
827
- "gapped_past_target": base_stock.get("gapped_past_target", False),
828
- "direction": base_stock.get("direction", "NO TRADE"),
829
- "confidence": base_stock.get("confidence", "LOW"),
830
- "no_trade_reason": base_stock.get("no_trade_reason"),
831
- "range_bound": base_stock.get("range_bound", False),
832
- "signal_count": 0,
833
- "predicted_direction": base_stock.get("predicted_direction"),
834
- "predicted_return_lo": base_stock.get("predicted_return_lo"),
835
- "predicted_return_hi": base_stock.get("predicted_return_hi"),
836
- "ai_forecast": base_stock.get("ai_forecast"),
837
- "ml": _slim_ml_tf(ml_tfs.get(tf)),
838
- "stop_loss": sl,
839
- "stop_loss_pct": sl_pct,
840
- "min_target": tgt,
841
- "actual_rr": actual_rr,
842
- }
843
 
844
  pick = dict(stock)
845
  best_tf, best_score = _pick_best_tf(ticker)
@@ -893,6 +938,58 @@ def get_top5_picks(
893
  p["specialist_recommendation"] = specialist
894
  return result_picks
895
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
896
  # ── Phase 2: AI fast-mode predictions for top candidates (150s cap) ────────
897
 
898
  # Uses fast-mode (1 LLM call per ticker shared across TFs) instead of full
@@ -933,10 +1030,12 @@ def get_top5_picks(
933
  _publish({
934
  "computing": True, "phase": "predicting",
935
  "predicted": 0, "predict_total": len(ai_jobs), "candidates": len(candidates),
936
- "picks": [], "market": market_from_scan, "generated_at": None,
937
  "message": f"Running AI on {len(candidates)} candidates β€” 0/{len(ai_jobs)}",
938
  })
939
- phase2_ex = ThreadPoolExecutor(max_workers=min(len(candidates), 6) * len(TIMEFRAMES))
 
 
940
  p2_futs = {
941
  phase2_ex.submit(_run_predict_with_ctx, ticker, tf, shared_ctx, True, True): (ticker, tf)
942
  for ticker, tf in ai_jobs
@@ -944,7 +1043,7 @@ def get_top5_picks(
944
  p2_done_n = 0
945
  _last_emit = time.time()
946
  try:
947
- for f in _cf.as_completed(p2_futs, timeout=150):
948
  ticker, tf = p2_futs[f]
949
  try:
950
  _ticker, _tf, pred = f.result()
@@ -965,11 +1064,12 @@ def get_top5_picks(
965
  "computing": True, "phase": "predicting",
966
  "predicted": p2_done_n, "predict_total": len(ai_jobs),
967
  "candidates": len(candidates), "picks": _partial,
 
968
  "market": market_from_scan, "generated_at": None,
969
  "message": f"Running AI on candidates β€” {p2_done_n}/{len(ai_jobs)} ({len(_partial)} ready)",
970
  })
971
  except _cf.TimeoutError:
972
- logger.info("[TOP5] PHASE 2 deadline (150s) reached at %d/%d jobs", p2_done_n, len(ai_jobs))
973
  # Cancel and account for any jobs that never completed within the deadline.
974
  for f, key in p2_futs.items():
975
  if not f.done():
@@ -986,6 +1086,15 @@ def get_top5_picks(
986
  # Step 3: Assemble the final ranked picks (partial=False β†’ any still-missing TF
987
  # is marked ai_unavailable, and specialist recommendations are attached).
988
  picks = _assemble(partial=False)
 
 
 
 
 
 
 
 
 
989
 
990
  total_elapsed = time.time() - start_time
991
  msg_final = f"[TOP5] TOTAL time: {total_elapsed:.1f}s | Phase1: {phase1_elapsed:.1f}s | Phase2: {phase2_elapsed:.1f}s | {len(picks)} picks generated"
@@ -994,6 +1103,8 @@ def get_top5_picks(
994
 
995
  return {
996
  "picks": picks,
 
 
997
  "market": market_from_scan,
998
  "generated_at": _now_ist_str(),
999
  "_timing": {
 
22
  TIMEFRAMES = ["INTRADAY", "1D"] # 3D + 5D removed β€” INTRADAY/1D are the shown horizons
23
  _TOP5_DEFAULT_SCAN_SIZE = max(1, int(os.getenv("TOP5_SCAN_SIZE", "200") or "200"))
24
 
25
+ # 1-month (~21 sessions) holding view. It is NOT part of TIMEFRAMES: only a signals-ranked shortlist
26
+ # gets a 1M AI call (one fast-mode LLM call each), so quota rises by ~_ONE_M_SHORTLIST_N calls per
27
+ # scan instead of one per candidate. Picks outside the shortlist lazy-load 1M in the UI.
28
+ ONE_M_TF = "1M"
29
+ _ONE_M_SHORTLIST_N = int(os.getenv("TOP5_1M_SHORTLIST", "20") or "20")
30
+ _ONE_M_TOP_N = int(os.getenv("TOP5_1M_TOP_N", "10") or "10")
31
+ _ONE_M_MIN_RS_PCT = float(os.getenv("TOP5_1M_MIN_RS_PCT", "-4.0")) # 3M RS vs Nifty floor for the shortlist
32
+
33
 
34
  def _now_ist_str() -> str:
35
  ist = _dt.timezone(_dt.timedelta(hours=5, minutes=30))
 
699
  }
700
 
701
  # ATR multipliers and R:R targets per timeframe (must match predictor_core.py)
702
+ _ATR_MULT = {"INTRADAY": 0.4, "1D": 0.7, "3D": 1.1, "5D": 1.5, "1M": 2.5}
703
+ _RR_MULT = {"INTRADAY": 1.2, "1D": 1.5, "3D": 1.7, "5D": 2.0, "1M": 2.0}
704
 
705
  def _derive_risk(price, atr14, tf):
706
  """Derive SL/target from ATR when AI response risk fields are missing."""
 
715
  # For shortlisted top picks, compute full-debate AI predictions for all TFs.
716
  # 5D is re-run with full debate (not reused from the fast-mode scan) so all
717
  # three timeframe tabs on the card have consistent, high-quality forecasts.
718
+ # ── 1M shortlist (no LLM): trend / relative-strength quality from the Phase 1 ML features ──
719
+ # A month-long hold needs trend evidence, so the shortlist ranks on EMA stack, 3M relative
720
+ # strength vs Nifty, MACD and ADX β€” NOT on volatility alone β€” and drops clear laggards (the 1M
721
+ # guardrail can only call those NEUTRAL/BEARISH, so an LLM call would be wasted).
722
+ def _trend_quality_1m(features: dict) -> float:
723
+ ema = float(features.get("ema_stack") if features.get("ema_stack") is not None else 0.5)
724
+ rs = features.get("rs_3m_pct")
725
+ rs_n = 0.5 if rs is None else max(0.0, min(1.0, (float(rs) + 20.0) / 40.0))
726
+ macd_n = 1.0 if features.get("macd_pos") else 0.0
727
+ adx_n = max(0.0, min(1.0, float(features.get("adx") or 20.0) / 40.0))
728
+ return 0.40 * ema + 0.30 * rs_n + 0.15 * macd_n + 0.15 * adx_n
729
+
730
+ m1_trend: dict[str, float] = {}
731
+ _m1_ranked: list[tuple[float, str]] = []
732
+ for stock in candidates:
733
+ _scan = scan_preds.get(stock["ticker"]) or {}
734
+ _feat = (_scan.get("ml") or {}).get("features") or {}
735
+ _rs = _feat.get("rs_3m_pct")
736
+ if _rs is not None and float(_rs) < _ONE_M_MIN_RS_PCT:
737
+ continue
738
+ _q = _trend_quality_1m(_feat)
739
+ _px = float(stock.get("price") or 0.0)
740
+ _atr = float((_scan.get("risk") or {}).get("atr14") or 0.0)
741
+ _atr_pct = (_atr / _px * 100.0) if _px else 0.0
742
+ m1_trend[stock["ticker"]] = _q
743
+ _m1_ranked.append((_q * (1.0 + min(_atr_pct / 6.0, 0.3)), stock["ticker"]))
744
+ _m1_ranked.sort(reverse=True)
745
+ m1_order = [t for _, t in _m1_ranked[:max(0, _ONE_M_SHORTLIST_N)]]
746
+ m1_set = set(m1_order)
747
+
748
+ # 1M jobs go FIRST so the (smaller) 1M batch is never starved by the INTRADAY/1D queue.
749
+ ai_jobs: list[tuple[str, str]] = [(ticker, ONE_M_TF) for ticker in m1_order]
750
  for stock in candidates:
751
  ticker = stock["ticker"]
752
  for tf in TIMEFRAMES:
 
818
  best_score *= 1.0 + min(sv, 5.0) * 0.10
819
  return best, best_score
820
 
821
+ def _tf_cell(ticker: str, price: float, tf: str, anchor_atr14, missing_reason: str, ml_tfs: dict) -> dict:
822
+ """One per-timeframe card cell from the AI prediction (or an unavailable/pending stub)."""
823
+ base_stock = ai_preds.get((ticker, tf), {})
824
+ if not base_stock or base_stock.get("error"):
825
+ base_stock = _empty_ai_tf(price, missing_reason)
826
+
827
+ tf_risk = base_stock.get("risk", {}) or {}
828
+ sl = tf_risk.get("stop_loss")
829
+ tgt = tf_risk.get("min_target")
830
+ sl_pct = tf_risk.get("stop_loss_pct")
831
+ actual_rr = tf_risk.get("actual_rr")
832
+ if sl is None and anchor_atr14:
833
+ sl, sl_pct, tgt = _derive_risk(price, anchor_atr14, tf)
834
+ pred_ret_hi = base_stock.get("ret_hi")
835
+ if pred_ret_hi and pred_ret_hi > 0 and price > 0:
836
+ tgt = round(price * (1 + pred_ret_hi / 100), 2)
837
+
838
+ return {
839
+ "expected_return_range": base_stock.get("expected_return_range"),
840
+ "midpoint": base_stock.get("midpoint", 0),
841
+ "ret_lo": base_stock.get("ret_lo"),
842
+ "ret_hi": base_stock.get("ret_hi"),
843
+ "target_price_lo": base_stock.get("target_price_lo"),
844
+ "target_price_hi": base_stock.get("target_price_hi"),
845
+ "expected_target_price": base_stock.get("expected_target_price"),
846
+ "expected_entry_price": base_stock.get("expected_entry_price", price),
847
+ **({"entry_basis": base_stock.get("entry_basis")} if tf == ONE_M_TF else {}),
848
+ "gapped_past_target": base_stock.get("gapped_past_target", False),
849
+ "direction": base_stock.get("direction", "NO TRADE"),
850
+ "confidence": base_stock.get("confidence", "LOW"),
851
+ "no_trade_reason": base_stock.get("no_trade_reason"),
852
+ "range_bound": base_stock.get("range_bound", False),
853
+ "signal_count": 0,
854
+ "predicted_direction": base_stock.get("predicted_direction"),
855
+ "predicted_return_lo": base_stock.get("predicted_return_lo"),
856
+ "predicted_return_hi": base_stock.get("predicted_return_hi"),
857
+ "ai_forecast": base_stock.get("ai_forecast"),
858
+ "ml": _slim_ml_tf(ml_tfs.get(tf)),
859
+ "stop_loss": sl,
860
+ "stop_loss_pct": sl_pct,
861
+ "min_target": tgt,
862
+ "actual_rr": actual_rr,
863
+ }
864
+
865
  def _assemble(partial: bool = False) -> list[dict]:
866
  """Assemble ranked pick cards from candidates + whatever AI predictions exist.
867
 
 
877
  ticker = stock["ticker"]
878
  price = stock.get("price") or 0
879
  anchor_atr14 = ((ai_preds.get((ticker, "1D"), {}).get("risk") or {}).get("atr14")
880
+ or (ai_preds.get((ticker, "INTRADAY"), {}).get("risk") or {}).get("atr14")
881
+ or (ai_preds.get((ticker, ONE_M_TF), {}).get("risk") or {}).get("atr14"))
882
  timeframe_data: dict[str, dict] = {}
883
  ml_res = ml_preds_by_ticker.get(ticker)
884
  ml_tfs = (ml_res.get("tfs", {}) if (ml_res and ml_res.get("available")) else {}) or {}
885
 
886
+ for tf in (TIMEFRAMES + [ONE_M_TF] if ticker in m1_set else TIMEFRAMES):
887
+ timeframe_data[tf] = _tf_cell(ticker, price, tf, anchor_atr14, _missing_reason, ml_tfs)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
888
 
889
  pick = dict(stock)
890
  best_tf, best_score = _pick_best_tf(ticker)
 
938
  p["specialist_recommendation"] = specialist
939
  return result_picks
940
 
941
+ def _score_1m(pred: dict, trend_q: float) -> float:
942
+ """Ranking score for a 1-month hold (higher is better).
943
+
944
+ Trend / relative-strength quality and AI confidence lead; the expected move is square-rooted
945
+ so volatility alone cannot dominate a month-long ranking (the INTRADAY/1D score is
946
+ volatility-primary, which is the wrong objective for a hold of ~21 sessions)."""
947
+ conf_mult = _CONF_MULT.get(pred.get("confidence", "LOW"), 0.55)
948
+ ret_hi = float(pred.get("ret_hi") or 0.0)
949
+ mid = abs(float(pred.get("midpoint") or 0.0)) or ret_hi * 0.7
950
+ rr = (pred.get("risk") or {}).get("actual_rr")
951
+ rr_term = 1.0 + min(max(float(rr or 0.0), 0.0), 3.0) / 6.0
952
+ sector_data = pred.get("sector") or {}
953
+ sector_factor = 1.12 if sector_data.get("leading") else (0.90 if sector_data.get("lagging") else 1.0)
954
+ score = conf_mult * max(trend_q, 0.05) * sector_factor * rr_term * (mid ** 0.5)
955
+ if pred.get("direction") == "SLIGHTLY BULLISH":
956
+ score *= 0.65
957
+ return score
958
+
959
+ def _assemble_1m() -> list[dict]:
960
+ """Rank the 1M-shortlisted stocks that have a resolved BULLISH 1-month AI call."""
961
+ ranked: list[dict] = []
962
+ for stock in candidates:
963
+ ticker = stock["ticker"]
964
+ if ticker not in m1_set:
965
+ continue
966
+ pred = ai_preds.get((ticker, ONE_M_TF), {})
967
+ if (not pred or pred.get("error") or pred.get("no_trade_reason")
968
+ or pred.get("direction") not in _ACCEPTED_DIRECTIONS
969
+ or pred.get("confidence") not in _CONF_MULT
970
+ or float(pred.get("ret_hi") or 0.0) <= 0):
971
+ continue
972
+ price = stock.get("price") or 0
973
+ pick = dict(stock)
974
+ pick["best_tf"] = ONE_M_TF
975
+ pick["direction"] = pred.get("direction", pick.get("direction"))
976
+ pick["confidence"] = pred.get("confidence", pick.get("confidence"))
977
+ pick["news"] = pred.get("news", pick.get("news", {}))
978
+ pick["risk"] = pred.get("risk", pick.get("risk", {}))
979
+ pick["signals"] = {}
980
+ pick["signal_count"] = 0
981
+ pick["trend_quality_1m"] = round(m1_trend.get(ticker, 0.5), 2)
982
+ pick["timeframes"] = {ONE_M_TF: _tf_cell(
983
+ ticker, price, ONE_M_TF, (pred.get("risk") or {}).get("atr14"), "ai_unavailable", {})}
984
+ pick["_score_1m"] = _score_1m(pred, m1_trend.get(ticker, 0.5))
985
+ ranked.append(pick)
986
+ ranked.sort(key=lambda x: x.get("_score_1m", 0.0), reverse=True)
987
+ out = _diversify_by_sector(ranked, _ONE_M_TOP_N, _MAX_PER_SECTOR)
988
+ for i, p in enumerate(out):
989
+ p["rank"] = i + 1
990
+ p.pop("_score_1m", None)
991
+ return out
992
+
993
  # ── Phase 2: AI fast-mode predictions for top candidates (150s cap) ────────
994
 
995
  # Uses fast-mode (1 LLM call per ticker shared across TFs) instead of full
 
1030
  _publish({
1031
  "computing": True, "phase": "predicting",
1032
  "predicted": 0, "predict_total": len(ai_jobs), "candidates": len(candidates),
1033
+ "picks": [], "picks_1m": [], "market": market_from_scan, "generated_at": None,
1034
  "message": f"Running AI on {len(candidates)} candidates β€” 0/{len(ai_jobs)}",
1035
  })
1036
+ phase2_ex = ThreadPoolExecutor(
1037
+ max_workers=min(len(candidates), 6) * len(TIMEFRAMES) + (3 if m1_order else 0))
1038
+ _p2_deadline = 150 + (30 if m1_order else 0)
1039
  p2_futs = {
1040
  phase2_ex.submit(_run_predict_with_ctx, ticker, tf, shared_ctx, True, True): (ticker, tf)
1041
  for ticker, tf in ai_jobs
 
1043
  p2_done_n = 0
1044
  _last_emit = time.time()
1045
  try:
1046
+ for f in _cf.as_completed(p2_futs, timeout=_p2_deadline):
1047
  ticker, tf = p2_futs[f]
1048
  try:
1049
  _ticker, _tf, pred = f.result()
 
1064
  "computing": True, "phase": "predicting",
1065
  "predicted": p2_done_n, "predict_total": len(ai_jobs),
1066
  "candidates": len(candidates), "picks": _partial,
1067
+ "picks_1m": _assemble_1m(),
1068
  "market": market_from_scan, "generated_at": None,
1069
  "message": f"Running AI on candidates β€” {p2_done_n}/{len(ai_jobs)} ({len(_partial)} ready)",
1070
  })
1071
  except _cf.TimeoutError:
1072
+ logger.info("[TOP5] PHASE 2 deadline (%ds) reached at %d/%d jobs", _p2_deadline, p2_done_n, len(ai_jobs))
1073
  # Cancel and account for any jobs that never completed within the deadline.
1074
  for f, key in p2_futs.items():
1075
  if not f.done():
 
1086
  # Step 3: Assemble the final ranked picks (partial=False β†’ any still-missing TF
1087
  # is marked ai_unavailable, and specialist recommendations are attached).
1088
  picks = _assemble(partial=False)
1089
+ picks_1m = _assemble_1m()
1090
+ if _p2_degraded:
1091
+ picks_1m_note = "AI is unavailable right now β€” 1 Month picks need the AI forecast. Try again shortly."
1092
+ elif not m1_order:
1093
+ picks_1m_note = "No stock has the trend and relative strength needed for a 1-month hold right now."
1094
+ elif not picks_1m:
1095
+ picks_1m_note = "No shortlisted stock has a bullish 1-month setup right now."
1096
+ else:
1097
+ picks_1m_note = None
1098
 
1099
  total_elapsed = time.time() - start_time
1100
  msg_final = f"[TOP5] TOTAL time: {total_elapsed:.1f}s | Phase1: {phase1_elapsed:.1f}s | Phase2: {phase2_elapsed:.1f}s | {len(picks)} picks generated"
 
1103
 
1104
  return {
1105
  "picks": picks,
1106
+ "picks_1m": picks_1m,
1107
+ "picks_1m_note": picks_1m_note,
1108
  "market": market_from_scan,
1109
  "generated_at": _now_ist_str(),
1110
  "_timing": {