Khanna, Videh Rakesh Rakesh commited on
Commit
217447c
·
1 Parent(s): 17b15cc

Fix wide NEUTRAL bands, live/pre-market target re-anchoring, stop-loss guard; add ₹ range to ML row

Browse files

- NEUTRAL/1D range-only bands now flat ±1% (falsifiable) across ai_forecast, predictor_core, ml_predictor — no more unbettable ±5% ATR bands
- Re-anchor cached targets to live/pre-market price in watchlist + top picks so ranges aren't already-surpassed
- Server-side stop-loss/target sanity guard: prevent LONG stop above entry (instant stop-out) on actual-entry drift
- Top picks now expose current_price
- ML row shows ₹ price range mirroring the AI, derived from the same tightened band
- Bump UI cache-buster 20260728h -> 20260729a

Files changed (7) hide show
  1. CLAUDE.md +1 -1
  2. ai_forecast.py +17 -25
  3. app.py +78 -2
  4. ml_predictor/infer.py +6 -5
  5. predictor_core.py +16 -13
  6. static/app.js +11 -1
  7. templates/index.html +2 -2
CLAUDE.md CHANGED
@@ -126,7 +126,7 @@ The deeper capacity fix is the two extra providers (Gemini/SambaNova) above —
126
  **Production vs tight_test ranges** — In production (`tight_test=False`), the AI's own range output is used directly. The `_BULL_RANGE`/`_BEAR_RANGE`/`_NEUT_RANGE` calibrated tables are ONLY applied when `tight_test=True` (backtest accuracy measurement mode). This ensures UI shows realistic AI-predicted targets, not hardcoded tiny ranges.
127
 
128
  **ATR clamp + directional-sign enforcement (`ai_forecast._atr_clamp_range`)** — rewritten 2026-07-17. Production-only safety net (no-op when `tight_test=True`), keyed to the stock's own ATR%, but now **fully rebuilds** the BULLISH/BEARISH/NEUTRAL band from a day-scaled power-law formula instead of just clamping the LLM's own range — the model's own lo/hi are discarded entirely; only its DIRECTION and CONFIDENCE still come from the LLM. This is a deliberate, explicitly-requested accuracy/informativeness trade-off (see `research/PRODUCTION_DELTA.md` 2026-07-17 section and `memory/repo` notes for the full discussion):
129
- - **NEUTRAL** (`_neutral_half_width_pct`): rebuilt as a clean symmetric band straddling zero. Bugfix: previously NEUTRAL had NO directional-sign check at all, so the LLM could return an all-positive or all-negative "NEUTRAL" band with zero protection against the other direction.
130
  - **BULLISH/BEARISH**: `near` bound (`_easy_near_bound_pct`) = `BASE × window_days^EXP × ATR%`, clamped to a floor/ceiling derived from the same formula; `far` bound (`_far_bound_pct`) is its own day-scaled formula (not a flat ratio of near — an earlier flat-ratio version measurably hurt INTRADAY/3D). `window_days` matches `predictor_core.TIMEFRAME_DAYS` (1D=1, 3D=3, 5D=5); INTRADAY uses its own fitted "equivalent day count" per formula since it has no calendar-day length.
131
  - Old constants removed as dead code: `_ATR_MID_CEILING`, `_ATR_MAX_WIDTH`, `_ATR_TARGET_MULT`, `_NEUT_ATR_HALF_WIDTH` (flat per-TF dicts) — all superseded by the formulas above.
132
 
 
126
  **Production vs tight_test ranges** — In production (`tight_test=False`), the AI's own range output is used directly. The `_BULL_RANGE`/`_BEAR_RANGE`/`_NEUT_RANGE` calibrated tables are ONLY applied when `tight_test=True` (backtest accuracy measurement mode). This ensures UI shows realistic AI-predicted targets, not hardcoded tiny ranges.
127
 
128
  **ATR clamp + directional-sign enforcement (`ai_forecast._atr_clamp_range`)** — rewritten 2026-07-17. Production-only safety net (no-op when `tight_test=True`), keyed to the stock's own ATR%, but now **fully rebuilds** the BULLISH/BEARISH/NEUTRAL band from a day-scaled power-law formula instead of just clamping the LLM's own range — the model's own lo/hi are discarded entirely; only its DIRECTION and CONFIDENCE still come from the LLM. This is a deliberate, explicitly-requested accuracy/informativeness trade-off (see `research/PRODUCTION_DELTA.md` 2026-07-17 section and `memory/repo` notes for the full discussion):
129
+ - **NEUTRAL** (flat by policy, `_NEUT_RANGE`): a FLAT falsifiable band (±0.5% INTRADAY, ±1% 1D/3D), NOT ATR-scaled. A NEUTRAL call must give the user an actionable "stays within X%" claim — an ATR-scaled NEUTRAL band ballooned to ±5%+ on volatile stocks, which is unbettable ("no idea what to bet on"). Kept consistent with `database._SNAP_NEUT`, `research.range_model._NEUT_FLAT`, and `ml_predictor._neutral_range` so NEUTRAL is identical across every module. (Previously ATR-scaled via a now-removed `_neutral_half_width_pct` helper — reverted 2026-07-29.)
130
  - **BULLISH/BEARISH**: `near` bound (`_easy_near_bound_pct`) = `BASE × window_days^EXP × ATR%`, clamped to a floor/ceiling derived from the same formula; `far` bound (`_far_bound_pct`) is its own day-scaled formula (not a flat ratio of near — an earlier flat-ratio version measurably hurt INTRADAY/3D). `window_days` matches `predictor_core.TIMEFRAME_DAYS` (1D=1, 3D=3, 5D=5); INTRADAY uses its own fitted "equivalent day count" per formula since it has no calendar-day length.
131
  - Old constants removed as dead code: `_ATR_MID_CEILING`, `_ATR_MAX_WIDTH`, `_ATR_TARGET_MULT`, `_NEUT_ATR_HALF_WIDTH` (flat per-TF dicts) — all superseded by the formulas above.
132
 
ai_forecast.py CHANGED
@@ -716,7 +716,6 @@ _TF_WINDOW_DAYS: dict[str, float] = {"1D": 1.0, "3D": 3.0, "5D": 5.0, "1W": 7.0}
716
  # day count" for INTRADAY — these two differ because they fit different physical quantities (a
717
  # directional bounce-target vs. a two-sided flat-range containment), not because of inconsistency.
718
  _INTRADAY_EQUIV_DAYS_NEAR = 1.31 # fitted so the near-bound formula reproduces the grid-searched INTRADAY value
719
- _INTRADAY_EQUIV_DAYS_NEUT = 0.58 # fitted so the NEUTRAL half-width formula reproduces the grid-searched INTRADAY value
720
  _INTRADAY_EQUIV_DAYS_FAR = 1.09 # fitted so the far-bound formula reproduces the grid-searched INTRADAY value
721
 
722
  # Near-bound (the "easy" side of a directional band — lo for BULLISH, hi for BEARISH).
@@ -741,11 +740,6 @@ _FAR_BOUND_EXP = 0.6354
741
  # 0.01% wide. These floors guarantee a meaningful band regardless of ATR level.
742
  _MIN_SPREAD_PCT: dict[str, float] = {"INTRADAY": 0.15, "1D": 0.40, "3D": 0.80, "5D": 1.20}
743
 
744
- # NEUTRAL band half-width, in ATR units — wider than the near-bound above since a NEUTRAL call
745
- # must absorb BOTH normal upside and downside noise, not just one side.
746
- _NEUT_HALF_WIDTH_BASE = 1.30
747
- _NEUT_HALF_WIDTH_EXP = 0.48
748
-
749
 
750
  def _easy_near_bound_pct(tf_label: str, atr_pct: float) -> float:
751
  """ATR-scaled near-bound: _NEAR_BOUND_BASE × window_days^_NEAR_BOUND_EXP × ATR%, clamped to a
@@ -766,32 +760,26 @@ def _far_bound_pct(tf_label: str, atr_pct: float, near: float) -> float:
766
  return far if far > near else near + 0.01
767
 
768
 
769
- def _neutral_half_width_pct(tf_label: str, atr_pct: float) -> float:
770
- """ATR-scaled NEUTRAL half-width: _NEUT_HALF_WIDTH_BASE × window_days^_NEUT_HALF_WIDTH_EXP."""
771
- days = _INTRADAY_EQUIV_DAYS_NEUT if tf_label == "INTRADAY" else _TF_WINDOW_DAYS.get(tf_label, 1.0)
772
- k = _NEUT_HALF_WIDTH_BASE * (days ** _NEUT_HALF_WIDTH_EXP)
773
- return max(0.05, k * atr_pct)
774
-
775
-
776
  def _atr_clamp_range(
777
  rng: Dict[str, float], tf_label: str, atr14: float,
778
  current_price: float, tight_test: bool, direction: str = "",
779
  ) -> Dict[str, float]:
780
  """Production-only safety net for accepted LLM ranges (no-op when tight_test=True).
781
 
782
- NEUTRAL and directional (BULLISH/BEARISH) bands are both rebuilt from the stock's OWN ATR%
783
- rather than trusting the LLM's raw lo/hi — this is a deliberate, aggressive accuracy/
784
- informativeness trade-off (2026-07-17 tuning pass, see memory/repo notes) chosen to push both
785
- the range-hit and the stricter midpoint-touch (target_hit_for_tf) metrics toward 90%+:
786
- - NEUTRAL: a clean symmetric band straddling zero (bugfix — previously NEUTRAL had no sign
787
- check at all, so the LLM could return an all-positive or all-negative "NEUTRAL" band that
788
- could never protect against the other direction).
 
789
  - BULLISH/BEARISH: near bound = k(days)×ATR% (clamped to a floor/ceiling), far bound = its
790
  own k(days)×ATR% formula (always kept above near) — so the midpoint sits just beyond the
791
  near bound instead of at an independently "ambitious" level the LLM proposed. The model's
792
  own lo/hi are discarded; only its DIRECTION and CONFIDENCE still come from the LLM.
793
- All bound sizes come from the day-length power-law formulas above, so an untested timeframe
794
- (5D, 1W, ...) gets an automatically consistent value instead of a guessed constant.
795
  """
796
  if tight_test or current_price <= 0 or atr14 <= 0:
797
  return rng
@@ -799,10 +787,14 @@ def _atr_clamp_range(
799
  cap = _TF_HARD_CAP_PCT.get(tf_label, 7.0)
800
  _dir = (direction or "").upper()
801
 
802
- # NEUTRAL: rebuild as a clean symmetric band straddling zero.
 
 
 
 
803
  if _dir == "NEUTRAL":
804
- half = max(0.05, min(cap, _neutral_half_width_pct(tf_label, atr_pct)))
805
- lo, hi = -half, half
806
  return {
807
  "predicted_return_lo": round(lo, 2),
808
  "predicted_return_hi": round(hi, 2),
 
716
  # day count" for INTRADAY — these two differ because they fit different physical quantities (a
717
  # directional bounce-target vs. a two-sided flat-range containment), not because of inconsistency.
718
  _INTRADAY_EQUIV_DAYS_NEAR = 1.31 # fitted so the near-bound formula reproduces the grid-searched INTRADAY value
 
719
  _INTRADAY_EQUIV_DAYS_FAR = 1.09 # fitted so the far-bound formula reproduces the grid-searched INTRADAY value
720
 
721
  # Near-bound (the "easy" side of a directional band — lo for BULLISH, hi for BEARISH).
 
740
  # 0.01% wide. These floors guarantee a meaningful band regardless of ATR level.
741
  _MIN_SPREAD_PCT: dict[str, float] = {"INTRADAY": 0.15, "1D": 0.40, "3D": 0.80, "5D": 1.20}
742
 
 
 
 
 
 
743
 
744
  def _easy_near_bound_pct(tf_label: str, atr_pct: float) -> float:
745
  """ATR-scaled near-bound: _NEAR_BOUND_BASE × window_days^_NEAR_BOUND_EXP × ATR%, clamped to a
 
760
  return far if far > near else near + 0.01
761
 
762
 
 
 
 
 
 
 
 
763
  def _atr_clamp_range(
764
  rng: Dict[str, float], tf_label: str, atr14: float,
765
  current_price: float, tight_test: bool, direction: str = "",
766
  ) -> Dict[str, float]:
767
  """Production-only safety net for accepted LLM ranges (no-op when tight_test=True).
768
 
769
+ Directional (BULLISH/BEARISH) bands are rebuilt from the stock's OWN ATR%, while NEUTRAL is a
770
+ FLAT, falsifiable band by policy — a deliberate accuracy/informativeness trade-off (2026-07-17
771
+ tuning pass, see memory/repo notes) chosen to push both the range-hit and the stricter
772
+ midpoint-touch (target_hit_for_tf) metrics toward 90%+:
773
+ - NEUTRAL: a flat symmetric band (±_NEUT_RANGE, e.g. ±1% for 1D) so the user gets an
774
+ actionable "stays within X%" claim. It is NOT ATR-scaled — an ATR band ballooned to ±5%+
775
+ on volatile stocks, which is unbettable ("no idea what to bet on"). Kept consistent with
776
+ _NEUT_RANGE / database._SNAP_NEUT / range_model._NEUT_FLAT / ml_predictor._neutral_range.
777
  - BULLISH/BEARISH: near bound = k(days)×ATR% (clamped to a floor/ceiling), far bound = its
778
  own k(days)×ATR% formula (always kept above near) — so the midpoint sits just beyond the
779
  near bound instead of at an independently "ambitious" level the LLM proposed. The model's
780
  own lo/hi are discarded; only its DIRECTION and CONFIDENCE still come from the LLM.
781
+ Directional bound sizes come from the day-length power-law formulas above, so an untested
782
+ timeframe (5D, 1W, ...) gets an automatically consistent value instead of a guessed constant.
783
  """
784
  if tight_test or current_price <= 0 or atr14 <= 0:
785
  return rng
 
787
  cap = _TF_HARD_CAP_PCT.get(tf_label, 7.0)
788
  _dir = (direction or "").upper()
789
 
790
+ # NEUTRAL: FLAT, falsifiable band by policy — NOT an ATR/volatility magnitude. A NEUTRAL call
791
+ # must give the user an actionable "stays within X%" claim they can bet on; an ATR-scaled band
792
+ # ballooned to ±5%+ on volatile stocks, which tells the user nothing ("no idea what to bet on").
793
+ # This mirrors _NEUT_RANGE, database._SNAP_NEUT, research.range_model._NEUT_FLAT and
794
+ # ml_predictor's _neutral_range — so NEUTRAL is consistent across the whole codebase.
795
  if _dir == "NEUTRAL":
796
+ lo, hi = _NEUT_RANGE.get(tf_label, (-1.0, 1.0))
797
+ lo, hi = max(-cap, lo), min(cap, hi)
798
  return {
799
  "predicted_return_lo": round(lo, 2),
800
  "predicted_return_hi": round(hi, 2),
app.py CHANGED
@@ -505,6 +505,41 @@ def _current_price(ticker: str, strict: bool = False) -> float | None:
505
  return fetch_live_price(ticker, allow_delayed=not strict)
506
 
507
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
508
  def _is_price_fresh(ticker: str) -> bool:
509
  """Check whether a current-session price is available for critical ops (stop-loss).
510
 
@@ -584,7 +619,19 @@ def _with_live_prices(payload: dict) -> dict:
584
  cloned = dict(p)
585
  ticker = p.get("ticker")
586
  if ticker and ticker in price_map:
587
- cloned["price"] = price_map[ticker]
 
 
 
 
 
 
 
 
 
 
 
 
588
  out_picks.append(cloned)
589
  out["picks"] = out_picks
590
  return out
@@ -1879,6 +1926,12 @@ def _build_watchlist_pick(item: dict, preds: dict) -> tuple[dict, dict]:
1879
  _tf_d = timeframes.get(_tf, {})
1880
  if isinstance(_tf_d, dict) and _tf_d.get("expected_entry_price") is not None:
1881
  timeframes[_tf]["expected_entry_price"] = round(live * (1 + _buf), 2)
 
 
 
 
 
 
1882
 
1883
  # Pick the timeframe with the strongest directional AI call for the Trade button default.
1884
  _conf_rank = {"HIGH": 2, "MEDIUM": 1, "LOW": 0}
@@ -2510,7 +2563,30 @@ def trades_open_new():
2510
  direction = data["direction"].upper()
2511
  max_chase_pct = float(data.get("max_chase_pct") or 0)
2512
 
2513
- # Check for existing position: require explicit user confirmation to merge
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
2514
  merge_into_id = None
2515
  existing_position = db.get_open_trade(ticker, direction)
2516
  if existing_position:
 
505
  return fetch_live_price(ticker, allow_delayed=not strict)
506
 
507
 
508
+ def _reanchor_targets_to_live(tf_dict: dict, live: float | None) -> None:
509
+ """Re-anchor a timeframe's price targets to the live price, IN PLACE.
510
+
511
+ Cached predictions anchor their target prices to the prior close (the anchor at compute
512
+ time). When the live price has since moved — most visibly a pre-market gap — the shown
513
+ target range can already be surpassed by the current price, so the card looks nonsensical
514
+ ("BULLISH, target ₹11,447" while the stock trades ₹11,549). The predicted MOVE (ret_lo /
515
+ ret_hi / midpoint, in %) is anchor-independent, so we simply re-apply those percentages to
516
+ the live price. This keeps the displayed target range consistent with — and ahead of — the
517
+ current price the user sees, and preserves the INTRADAY ≥1% floor (baked into ret_hi). No-op
518
+ without a valid live price or return %s (e.g. backtest, data errors)."""
519
+ if not isinstance(tf_dict, dict) or not live or live <= 0:
520
+ return
521
+ ret_lo = tf_dict.get("ret_lo")
522
+ ret_hi = tf_dict.get("ret_hi")
523
+ if ret_lo is None or ret_hi is None:
524
+ return
525
+ tf_dict["target_price_lo"] = round(live * (1 + ret_lo / 100.0), 2)
526
+ tf_dict["target_price_hi"] = round(live * (1 + ret_hi / 100.0), 2)
527
+ mid = tf_dict.get("midpoint")
528
+ if mid is not None:
529
+ tf_dict["expected_target_price"] = round(live * (1 + mid / 100.0), 2)
530
+ # Keep the embedded AI sub-line's targets consistent with the re-anchored range.
531
+ af = tf_dict.get("ai_forecast")
532
+ if isinstance(af, dict):
533
+ a_lo, a_hi = af.get("predicted_return_lo"), af.get("predicted_return_hi")
534
+ if a_lo is not None and a_hi is not None:
535
+ af = dict(af)
536
+ af["target_price_lo"] = round(live * (1 + a_lo / 100.0), 2)
537
+ af["target_price_hi"] = round(live * (1 + a_hi / 100.0), 2)
538
+ tf_dict["ai_forecast"] = af
539
+ tf_dict["ai_target_lo"] = af["target_price_lo"]
540
+ tf_dict["ai_target_hi"] = af["target_price_hi"]
541
+
542
+
543
  def _is_price_fresh(ticker: str) -> bool:
544
  """Check whether a current-session price is available for critical ops (stop-loss).
545
 
 
619
  cloned = dict(p)
620
  ticker = p.get("ticker")
621
  if ticker and ticker in price_map:
622
+ _live = price_map[ticker]
623
+ cloned["price"] = _live
624
+ cloned["current_price"] = _live
625
+ # Re-anchor each timeframe's targets to the fresh live price so the shown target
626
+ # range stays ahead of the current price (pre-market/gap moves otherwise leave the
627
+ # cached target already surpassed). Clone the timeframes dict to avoid mutating the
628
+ # shared cached pick.
629
+ _tfs = cloned.get("timeframes")
630
+ if isinstance(_tfs, dict):
631
+ _tfs = {k: (dict(v) if isinstance(v, dict) else v) for k, v in _tfs.items()}
632
+ for _tf_v in _tfs.values():
633
+ _reanchor_targets_to_live(_tf_v, _live)
634
+ cloned["timeframes"] = _tfs
635
  out_picks.append(cloned)
636
  out["picks"] = out_picks
637
  return out
 
1926
  _tf_d = timeframes.get(_tf, {})
1927
  if isinstance(_tf_d, dict) and _tf_d.get("expected_entry_price") is not None:
1928
  timeframes[_tf]["expected_entry_price"] = round(live * (1 + _buf), 2)
1929
+ # Re-anchor target ranges to the live price too — otherwise a cached prediction shows
1930
+ # a target computed off the prior close that the live (e.g. pre-market gap) price has
1931
+ # already blown past ("BULLISH, target below current price"). Keeps the shown range
1932
+ # ahead of the current price and preserves the INTRADAY ≥1% move floor.
1933
+ for _tf in timeframes:
1934
+ _reanchor_targets_to_live(timeframes[_tf], live)
1935
 
1936
  # Pick the timeframe with the strongest directional AI call for the Trade button default.
1937
  _conf_rank = {"HIGH": 2, "MEDIUM": 1, "LOW": 0}
 
2563
  direction = data["direction"].upper()
2564
  max_chase_pct = float(data.get("max_chase_pct") or 0)
2565
 
2566
+ # ── Stop-loss / target sanity guard ──────────────────────────────────────
2567
+ # The stop and target are copied from the prediction, which computed them at the ANCHOR price
2568
+ # (prior close / est. open / live-at-scan). The user's ACTUAL entry can drift from that anchor
2569
+ # (gap, delayed click), which can leave a LONG stop ABOVE entry or a SHORT stop BELOW it —
2570
+ # nonsense that would trigger an INSTANT stop-out (e.g. entry ₹1495.9, stop ₹1500 on a LONG).
2571
+ # Re-anchor any wrong-side stop/target to the actual entry, preserving the intended distance
2572
+ # (floored to a 1% minimum so the stop isn't razor-thin).
2573
+ _MIN_DIST_FRAC = 0.01
2574
+ _sl_in = _safe_float(data.get("stop_loss"))
2575
+ if _sl_in is not None and _sl_in > 0 and entry_price > 0:
2576
+ _dist = max(abs(entry_price - _sl_in), entry_price * _MIN_DIST_FRAC)
2577
+ if direction == "LONG" and _sl_in >= entry_price:
2578
+ data["stop_loss"] = round(entry_price - _dist, 2)
2579
+ elif direction == "SHORT" and _sl_in <= entry_price:
2580
+ data["stop_loss"] = round(entry_price + _dist, 2)
2581
+ _tgt_in = _safe_float(data.get("target"))
2582
+ if _tgt_in is not None and _tgt_in > 0 and entry_price > 0:
2583
+ _tdist = max(abs(_tgt_in - entry_price), entry_price * _MIN_DIST_FRAC)
2584
+ if direction == "LONG" and _tgt_in <= entry_price:
2585
+ data["target"] = round(entry_price + _tdist, 2)
2586
+ elif direction == "SHORT" and _tgt_in >= entry_price:
2587
+ data["target"] = round(entry_price - _tdist, 2)
2588
+
2589
+
2590
  merge_into_id = None
2591
  existing_position = db.get_open_trade(ticker, direction)
2592
  if existing_position:
ml_predictor/infer.py CHANGED
@@ -101,10 +101,11 @@ _INTRADAY_NEAR_MULT = float(os.environ.get("ML_INTRADAY_NEAR_MULT", "0.12"))
101
  # 1D range-only policy (mirrors predictor_core FORCE_1D_RANGE_ONLY): next-day 1D direction has a
102
  # proven accuracy ceiling (~46-49% for the excess-of-Nifty label — no better than raw returns;
103
  # research/ml_backtest.py + repo memory), so a directional 1D target is unreliable. The live path
104
- # forces 1D into an honest RANGE-ONLY (NEUTRAL) call, matching the AI path. Backtests call _derive
105
- # WITHOUT force_range_only, so their raw 1D direction metric is unaffected. Env-overridable.
 
106
  _FORCE_1D_RANGE_ONLY = os.environ.get("ML_FORCE_1D_RANGE_ONLY", "1") != "0"
107
- _ONE_D_RANGE_HALF_PCT = float(os.environ.get("ONE_D_RANGE_HALF_PCT", "3.5")) # shared with the AI path
108
 
109
  # ── Per-TF VOLATILITY-SCALED cap on the REPORTED range (extrapolation guard, NOT a flat limit) ──
110
  # A violent stock SHOULD be able to show a big move — that's the whole point of a volatility model.
@@ -361,8 +362,8 @@ class MLPredictor:
361
  else:
362
  n_lo, n_hi = _neutral_range(tf)
363
  if force_range_only and tf == "1D":
364
- # Range-only 1D: size the band to the realized 1D range (matches the AI path's
365
- # ONE_D_RANGE_HALF_PCT) so the shown range honestly contains the move.
366
  n_lo, n_hi = -_ONE_D_RANGE_HALF_PCT, _ONE_D_RANGE_HALF_PCT
367
  ret_lo, ret_hi = round(n_lo, 2), round(n_hi, 2)
368
  expected_pct = 0.0
 
101
  # 1D range-only policy (mirrors predictor_core FORCE_1D_RANGE_ONLY): next-day 1D direction has a
102
  # proven accuracy ceiling (~46-49% for the excess-of-Nifty label — no better than raw returns;
103
  # research/ml_backtest.py + repo memory), so a directional 1D target is unreliable. The live path
104
+ # forces 1D into an honest RANGE-ONLY (NEUTRAL) call with a FLAT ±1% falsifiable band (NOT
105
+ # ATR-scaled), matching the AI path. Backtests call _derive WITHOUT force_range_only, so their raw
106
+ # 1D direction metric is unaffected. Env-overridable.
107
  _FORCE_1D_RANGE_ONLY = os.environ.get("ML_FORCE_1D_RANGE_ONLY", "1") != "0"
108
+ _ONE_D_RANGE_HALF_PCT = float(os.environ.get("ONE_D_RANGE_HALF_PCT", "1.0")) # flat, shared with the AI path
109
 
110
  # ── Per-TF VOLATILITY-SCALED cap on the REPORTED range (extrapolation guard, NOT a flat limit) ──
111
  # A violent stock SHOULD be able to show a big move — that's the whole point of a volatility model.
 
362
  else:
363
  n_lo, n_hi = _neutral_range(tf)
364
  if force_range_only and tf == "1D":
365
+ # Range-only 1D: a FLAT ±1% falsifiable band (matches the AI path's
366
+ # ONE_D_RANGE_HALF_PCT) — actionable "stays within 1%", not a wide ATR band.
367
  n_lo, n_hi = -_ONE_D_RANGE_HALF_PCT, _ONE_D_RANGE_HALF_PCT
368
  ret_lo, ret_hi = round(n_lo, 2), round(n_hi, 2)
369
  expected_pct = 0.0
predictor_core.py CHANGED
@@ -286,14 +286,18 @@ INTRADAY_MIN_MOVE_PCT: float = float(os.getenv("INTRADAY_MIN_MOVE_PCT", "1.0"))
286
  # momentum, ml_score, intraday close-strength) reliably separates hits from misses, and strong
287
  # closes actually mean-revert. A directional 1D target is therefore structurally unreachable
288
  # ~1-in-4 times (worse in a falling market) — the "did not reach 1D target" problem. So 1D is an
289
- # honest RANGE-ONLY call: a symmetric NEUTRAL band sized to the realized 1D range rather than a
290
- # coin-flip directional bet. research/regrade_direction_policy.py verified this lifts the 1D
291
- # hit-rate 71% -> 85%. The band half-width is ATR-scaled (adapts to each stock's volatility) and
292
- # floored to the verified realized-range value so it contains the move >=85%. Both env-overridable;
293
- # set FORCE_1D_RANGE_ONLY=0 to restore the old directional 1D behaviour.
 
 
 
 
 
294
  FORCE_1D_RANGE_ONLY: bool = os.getenv("FORCE_1D_RANGE_ONLY", "1") != "0"
295
- ONE_D_RANGE_HALF_PCT: float = float(os.getenv("ONE_D_RANGE_HALF_PCT", "3.5")) # verified realized-range floor
296
- ONE_D_RANGE_ATR_MULT: float = float(os.getenv("ONE_D_RANGE_ATR_MULT", "1.30")) # ATR-scaled half-width
297
 
298
 
299
  def _load_live_strategy_stats() -> dict:
@@ -1736,16 +1740,15 @@ def predict_stock_v2(ticker: str, start_date: str, end_date: str,
1736
  # ── 1D range-only policy (proven direction-ceiling fix) ──────────────────
1737
  # See FORCE_1D_RANGE_ONLY / ONE_D_RANGE_HALF_PCT at module top. 1D next-day DIRECTION caps
1738
  # at ~74% accuracy, so a directional 1D target is unreachable ~1-in-4 times. Convert every
1739
- # 1D call into an honest RANGE-ONLY (NEUTRAL) band sized to the realized 1D range — this is
1740
- # the informative call, not a suppressed no-trade. Applied regardless of AI availability.
1741
- # Blocking states (VIX gate, AI timeout, data error) are left untouched; only a directional
1742
- # call or the plain neutral_signal suppression is replaced with the range.
1743
  range_bound = False
1744
  if (FORCE_1D_RANGE_ONLY and _tf_label == "1D"
1745
  and no_trade_reason in (None, "neutral_signal")):
1746
  direction = "NEUTRAL"
1747
- _atr_pct_1d = (atr14_val / price * 100.0) if (atr14_val and price and price > 0) else 0.0
1748
- _half_1d = round(max(ONE_D_RANGE_HALF_PCT, ONE_D_RANGE_ATR_MULT * _atr_pct_1d), 2)
1749
  ret_lo, ret_hi = -_half_1d, _half_1d
1750
  midpoint = 0.0
1751
  range_bound = True
 
286
  # momentum, ml_score, intraday close-strength) reliably separates hits from misses, and strong
287
  # closes actually mean-revert. A directional 1D target is therefore structurally unreachable
288
  # ~1-in-4 times (worse in a falling market) — the "did not reach 1D target" problem. So 1D is an
289
+ # honest RANGE-ONLY call rather than a coin-flip directional bet.
290
+ #
291
+ # The band is FLAT by policy (±1%), NOT ATR-scaled. An ATR-scaled band (the old
292
+ # max(3.5%, 1.30×ATR%)) ballooned to ±5%+ on volatile stocks — so wide the user can't bet on it
293
+ # ("somewhere between ₹10.7k and ₹11.9k" = no information) and so wide it always "hit", inflating
294
+ # the hit-rate without predicting anything. A flat ±1% band is a real, actionable "stays within 1%"
295
+ # claim and keeps 1D consistent with the NEUTRAL band everywhere else in the codebase
296
+ # (ai_forecast._NEUT_RANGE, database._SNAP_NEUT, research.range_model._NEUT_FLAT,
297
+ # ml_predictor._neutral_range). Env-overridable; set FORCE_1D_RANGE_ONLY=0 to restore directional
298
+ # 1D behaviour, or ONE_D_RANGE_HALF_PCT to widen/narrow the flat band.
299
  FORCE_1D_RANGE_ONLY: bool = os.getenv("FORCE_1D_RANGE_ONLY", "1") != "0"
300
+ ONE_D_RANGE_HALF_PCT: float = float(os.getenv("ONE_D_RANGE_HALF_PCT", "1.0")) # flat falsifiable half-width
 
301
 
302
 
303
  def _load_live_strategy_stats() -> dict:
 
1740
  # ── 1D range-only policy (proven direction-ceiling fix) ──────────────────
1741
  # See FORCE_1D_RANGE_ONLY / ONE_D_RANGE_HALF_PCT at module top. 1D next-day DIRECTION caps
1742
  # at ~74% accuracy, so a directional 1D target is unreachable ~1-in-4 times. Convert every
1743
+ # 1D call into an honest RANGE-ONLY (NEUTRAL) call with a FLAT ±1% falsifiable band — a real
1744
+ # "stays within 1%" claim the user can act on, not a ±5% ATR band that's unbettable. Applied
1745
+ # regardless of AI availability. Blocking states (VIX gate, AI timeout, data error) are left
1746
+ # untouched; only a directional call or the plain neutral_signal suppression is replaced.
1747
  range_bound = False
1748
  if (FORCE_1D_RANGE_ONLY and _tf_label == "1D"
1749
  and no_trade_reason in (None, "neutral_signal")):
1750
  direction = "NEUTRAL"
1751
+ _half_1d = round(ONE_D_RANGE_HALF_PCT, 2)
 
1752
  ret_lo, ret_hi = -_half_1d, _half_1d
1753
  midpoint = 0.0
1754
  range_bound = True
static/app.js CHANGED
@@ -1026,6 +1026,16 @@ function _renderMlRow(tf, ml) {
1026
  const rangeStr = (nLo != null && nHi != null) ? formatReturnRange(nLo, nHi, 1) : '';
1027
  const retHtml = rangeStr
1028
  ? `<div class="tf-ml-return" style="color:${color}" title="ML predicted return range">${rangeStr}</div>` : '';
 
 
 
 
 
 
 
 
 
 
1029
  // Line 2: headline MEDIAN (most-likely) target price.
1030
  // NEUTRAL / range-bound calls have no directional target (backend sends expected_target_price
1031
  // = null + range_bound = true) — show "Range-bound" instead of a target == current price.
@@ -1071,7 +1081,7 @@ function _renderMlRow(tf, ml) {
1071
  const confHtml = conf
1072
  ? `<div class="tf-conf-row" title="ML calibrated confidence: ${conf}${confPctTitle}"><span class="tf-conf-lbl">ML conf</span><div class="conf-bar"><div class="conf-bar-fill conf-${cl}" style="width:${_confPct(conf)}%"></div></div><span class="tf-conf-val conf-${cl}">${conf}</span></div>`
1073
  : '';
1074
- return `${retHtml}${priceHtml}${dirHtml}${confHtml}`;
1075
  }
1076
 
1077
  // Agreement badge between the ML and AI directional calls.
 
1026
  const rangeStr = (nLo != null && nHi != null) ? formatReturnRange(nLo, nHi, 1) : '';
1027
  const retHtml = rangeStr
1028
  ? `<div class="tf-ml-return" style="color:${color}" title="ML predicted return range">${rangeStr}</div>` : '';
1029
+ // Line 1b: ₹ price range — mirrors the AI's ₹ target range. Derived from the SAME tightened
1030
+ // band shown just above (nLo/nHi) applied to the model's current price, so the ₹ range and the
1031
+ // % range always agree. Shown for range-bound calls too (the flat ±1% band as a ₹ "stays
1032
+ // within" range), exactly like the AI ₹ range.
1033
+ const _mlCp = ml.current_price;
1034
+ let rupeeRangeHtml = '';
1035
+ if (_mlCp && _mlCp > 0 && nLo != null && nHi != null) {
1036
+ const _rA = _mlCp * (1 + nLo / 100), _rB = _mlCp * (1 + nHi / 100);
1037
+ rupeeRangeHtml = `<div class="tf-ai-target" style="color:${color}" title="ML predicted price range (₹) — same band as the % range above">₹${num(Math.min(_rA, _rB), 0)} – ₹${num(Math.max(_rA, _rB), 0)}</div>`;
1038
+ }
1039
  // Line 2: headline MEDIAN (most-likely) target price.
1040
  // NEUTRAL / range-bound calls have no directional target (backend sends expected_target_price
1041
  // = null + range_bound = true) — show "Range-bound" instead of a target == current price.
 
1081
  const confHtml = conf
1082
  ? `<div class="tf-conf-row" title="ML calibrated confidence: ${conf}${confPctTitle}"><span class="tf-conf-lbl">ML conf</span><div class="conf-bar"><div class="conf-bar-fill conf-${cl}" style="width:${_confPct(conf)}%"></div></div><span class="tf-conf-val conf-${cl}">${conf}</span></div>`
1083
  : '';
1084
+ return `${retHtml}${rupeeRangeHtml}${priceHtml}${dirHtml}${confHtml}`;
1085
  }
1086
 
1087
  // Agreement badge between the ML and AI directional calls.
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=20260728h">
37
  <script src="https://unpkg.com/lightweight-charts@4.2.0/dist/lightweight-charts.standalone.production.js"></script>
38
  </head>
39
  <body>
@@ -449,6 +449,6 @@
449
  </a>
450
  </nav>
451
 
452
- <script src="/static/app.js?v=20260728h"></script>
453
  </body>
454
  </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=20260729a">
37
  <script src="https://unpkg.com/lightweight-charts@4.2.0/dist/lightweight-charts.standalone.production.js"></script>
38
  </head>
39
  <body>
 
449
  </a>
450
  </nav>
451
 
452
+ <script src="/static/app.js?v=20260729a"></script>
453
  </body>
454
  </html>