Khanna, Videh Rakesh Rakesh commited on
Commit
e61a2dc
Β·
1 Parent(s): 697340b

Self-learning: fix N=0 (missing validation cols), all-history window, why-missed notes; INTRADAY final-call cache after close

Browse files

Self-learning (Improve AI / ML):
- get_prediction_snapshots now SELECTs validation_status/result + window/actual
cols so analyze_and_update actually sees validated rows (was always N=0).
- Remove 30-day window: analyze all history (days=None); idempotent aggregation
rebuilt from dedup union of DB rows + pruned history (fixes double-count on re-run).
- Add target-reach diagnostics (predicted high/low/mid vs actual window high/low)
explaining why a target was missed; styled MISS/CAUTION/OK in the panel.

INTRADAY final call:
- Cache the last valid intraday call (with target) per ticker during the session
and show it as the session's Final Call after NSE closes / past 14:15, instead
of the 'market closed' stub. Wired into single/per-TF/batch watchlist endpoints
and the intraday refresh scheduler; frontend shows a 'Final call' badge.
- Cache-buster v=20260727b.

Files changed (6) hide show
  1. app.py +113 -7
  2. database.py +18 -10
  3. self_learning.py +145 -56
  4. static/app.js +11 -3
  5. static/style.css +9 -0
  6. templates/index.html +2 -2
app.py CHANGED
@@ -93,6 +93,81 @@ _TOP5_PROGRESS_LOCK = __import__("threading").Lock()
93
  _WATCHLIST_PICK_CACHE: dict = {}
94
  _WATCHLIST_PICK_AI_UNAVAILABLE_TTL = 125 # short TTL when AI was unavailable (>120s Ollama backoff so retry fires after cooldown clears)
95
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
96
  # ── Watchlist AI concurrency cap (process-wide) ───────────────────────────────
97
  # Without this, the frontend fires N per-ticker requests in parallel Γ— up to 3 TFs each =
98
  # up to 3N simultaneous LLM calls, which 429s every free-tier provider at once β†’ the
@@ -1753,6 +1828,8 @@ def _build_watchlist_pick(item: dict, preds: dict) -> tuple[dict, dict]:
1753
  "no_trade_reason": p.get("no_trade_reason"),
1754
  "ai_disclaimer": p.get("ai_disclaimer"),
1755
  "signal_count": p.get("signal_count", 0),
 
 
1756
  "predicted_direction": p.get("predicted_direction"),
1757
  "predicted_return_lo": p.get("predicted_return_lo"),
1758
  "predicted_return_hi": p.get("predicted_return_hi"),
@@ -1878,9 +1955,9 @@ def watchlist_pick_single(ticker: str):
1878
  preds: dict = {}
1879
 
1880
  if not market_is_open:
1881
- preds["INTRADAY"] = _INTRADAY_CLOSED_STUB
1882
  elif _intraday_too_late:
1883
- preds["INTRADAY"] = _INTRADAY_TOO_LATE_STUB
1884
 
1885
  # Check per-TF cache; only fetch TFs whose cache is stale
1886
  tfs_to_run = []
@@ -1976,6 +2053,10 @@ def watchlist_pick_single(ticker: str):
1976
  }
1977
 
1978
  pick, market = _build_watchlist_pick(item, preds)
 
 
 
 
1979
  if tfs_to_run:
1980
  try:
1981
  _archive_top5_predictions({"picks": [pick]}, source="watchlist")
@@ -2039,6 +2120,13 @@ def watchlist_pick_single_tf(ticker: str, tf: str):
2039
  market_is_open = mkt_status.get("status") == "OPEN"
2040
 
2041
  if tf == "INTRADAY" and not market_is_open:
 
 
 
 
 
 
 
2042
  return jsonify({
2043
  "tf": tf, "ticker": t,
2044
  "data": {"no_trade_reason": "market_closed", "direction": "N/A",
@@ -2050,6 +2138,13 @@ def watchlist_pick_single_tf(ticker: str, tf: str):
2050
  _ist = timezone(timedelta(hours=5, minutes=30))
2051
  _now_ist = datetime.now(timezone.utc).astimezone(_ist)
2052
  if (_now_ist.hour, _now_ist.minute) >= (14, 15):
 
 
 
 
 
 
 
2053
  return jsonify({
2054
  "tf": tf, "ticker": t,
2055
  "data": {"no_trade_reason": "too_close_to_close", "direction": "N/A",
@@ -2090,6 +2185,9 @@ def watchlist_pick_single_tf(ticker: str, tf: str):
2090
  if _reason != "timeout":
2091
  ttl = _WATCHLIST_PICK_AI_UNAVAILABLE_TTL if _reason == "ai_unavailable" else _cache_ttl_for_tf(tf)
2092
  _WATCHLIST_PICK_CACHE[(t, tf)] = {"ts": now, "pred": pred, "ttl": ttl}
 
 
 
2093
 
2094
  return jsonify({
2095
  "tf": tf, "ticker": t,
@@ -2182,10 +2280,10 @@ def watchlist_picks():
2182
  tf_results: dict = {}
2183
  if not market_is_open:
2184
  for t in tickers:
2185
- tf_results.setdefault(t, {})["INTRADAY"] = _INTRADAY_CLOSED_STUB
2186
  elif _intraday_too_late:
2187
  for t in tickers:
2188
- tf_results.setdefault(t, {})["INTRADAY"] = _INTRADAY_TOO_LATE_STUB
2189
  # Limit to 3 concurrent tickers (Γ—3 TFs = 9 threads) to avoid exhausting
2190
  # provider rate limits. Cloud providers handle 3 tickers in ~15-30s; Ollama
2191
  # handles ~2 tickers in 170s. Incomplete tickers show as timeout.
@@ -2213,6 +2311,9 @@ def watchlist_picks():
2213
  for item in wl:
2214
  ticker = item["ticker"]
2215
  preds = tf_results.get(ticker, {})
 
 
 
2216
  pick, pick_market = _build_watchlist_pick(item, preds)
2217
 
2218
  # Add loophole checking for the primary prediction
@@ -3373,7 +3474,7 @@ def validation_execute():
3373
  if validated_count > 0:
3374
  try:
3375
  from self_learning import analyze_and_update
3376
- learn_result = analyze_and_update(days=30)
3377
  if learn_result.get("status") != "insufficient_data":
3378
  pruned = db.prune_validated_snapshots()
3379
  if pruned:
@@ -3396,7 +3497,10 @@ def ai_learn():
3396
  """Manually trigger self-learning analysis from validation history."""
3397
  try:
3398
  from self_learning import analyze_and_update
3399
- days = int((request.get_json(silent=True) or {}).get("days", 30))
 
 
 
3400
  result = analyze_and_update(days=days)
3401
  pruned = 0
3402
  if result.get("status") != "insufficient_data":
@@ -3894,7 +3998,7 @@ def _start_validation_scheduler():
3894
 
3895
  if validated > 0:
3896
  try:
3897
- learn_result = analyze_and_update(days=30)
3898
  if learn_result.get("status") != "insufficient_data":
3899
  pruned = db.prune_validated_snapshots()
3900
  if pruned:
@@ -3960,6 +4064,8 @@ def _start_intraday_refresh_scheduler():
3960
  "pred": pred,
3961
  "ttl": _ttl,
3962
  }
 
 
3963
  except Exception as exc:
3964
  app.logger.debug("INTRADAY refresh failed for %s: %s", tk, exc)
3965
  app.logger.info("INTRADAY cache refreshed for %d tickers", len(tickers))
 
93
  _WATCHLIST_PICK_CACHE: dict = {}
94
  _WATCHLIST_PICK_AI_UNAVAILABLE_TTL = 125 # short TTL when AI was unavailable (>120s Ollama backoff so retry fires after cooldown clears)
95
 
96
+ # ── Final INTRADAY call of the session ────────────────────────────────────────
97
+ # Once NSE closes (or we pass the 14:15 cutoff) INTRADAY can't be predicted live, so we
98
+ # normally show a "market closed" stub. Instead, remember the last REAL intraday call
99
+ # (direction + target price) made during the session and surface it after close, so the
100
+ # user can still see "what was the final call for the day". Keyed by ticker; kept for the
101
+ # most recent trading day. In-memory (mirrors _WATCHLIST_PICK_CACHE); resets on restart.
102
+ _INTRADAY_FINAL_CALL: dict = {}
103
+ _INTRADAY_FINAL_CALL_LOCK = __import__("threading").Lock()
104
+
105
+
106
+ def _intraday_pred_has_target(pred) -> bool:
107
+ """True if `pred` is a real, actionable INTRADAY call carrying a target price band."""
108
+ if not isinstance(pred, dict):
109
+ return False
110
+ if (pred.get("direction") or "").upper() in ("N/A", "NO TRADE", "NEUTRAL", ""):
111
+ return False
112
+ if pred.get("no_trade_reason"):
113
+ return False
114
+ lo = pred.get("target_price_lo") or 0
115
+ hi = pred.get("target_price_hi") or 0
116
+ return bool(lo and hi and lo > 0 and hi > 0)
117
+
118
+
119
+ def _last_trading_day(today):
120
+ """Most recent NSE trading day on/before `today` (walks back up to 10 days)."""
121
+ d = today
122
+ for _ in range(10):
123
+ if nse_is_trading_day(d):
124
+ return d
125
+ d = d - timedelta(days=1)
126
+ return today
127
+
128
+
129
+ def _remember_intraday_call(ticker: str, pred: dict) -> None:
130
+ """Cache the latest valid INTRADAY call (has a target price) for `ticker`, tagged with
131
+ today's IST date, so it can be surfaced after the session closes."""
132
+ if not isinstance(pred, dict) or pred.get("intraday_final_call"):
133
+ return # don't re-stamp an already-served final call (would corrupt its session date)
134
+ if not _intraday_pred_has_target(pred):
135
+ return
136
+ ist = timezone(timedelta(hours=5, minutes=30))
137
+ now_ist = datetime.now(timezone.utc).astimezone(ist)
138
+ with _INTRADAY_FINAL_CALL_LOCK:
139
+ _INTRADAY_FINAL_CALL[ticker] = {
140
+ "pred": pred,
141
+ "date": now_ist.strftime("%Y-%m-%d"),
142
+ "time": now_ist.strftime("%H:%M"),
143
+ }
144
+
145
+
146
+ def _get_intraday_final_call(ticker: str):
147
+ """Return a copy of the cached final INTRADAY call for `ticker` if it was made on the
148
+ most recent NSE trading day, annotated (`intraday_final_call`, `final_call_time`) so the
149
+ UI renders it as the session's final call rather than a live prediction. Else None."""
150
+ with _INTRADAY_FINAL_CALL_LOCK:
151
+ entry = _INTRADAY_FINAL_CALL.get(ticker)
152
+ if not entry:
153
+ return None
154
+ ist = timezone(timedelta(hours=5, minutes=30))
155
+ today = datetime.now(timezone.utc).astimezone(ist).date()
156
+ if entry.get("date") != _last_trading_day(today).isoformat():
157
+ return None
158
+ pred = dict(entry["pred"])
159
+ pred.pop("no_trade_reason", None)
160
+ pred["intraday_final_call"] = True
161
+ pred["final_call_time"] = entry.get("time")
162
+ pred["final_call_date"] = entry.get("date")
163
+ return pred
164
+
165
+
166
+ def _intraday_closed_value(ticker: str, stub: dict):
167
+ """When INTRADAY can't be predicted live (market closed / past 14:15 cutoff), return the
168
+ cached final call for the last session if we have one, otherwise the given stub."""
169
+ return _get_intraday_final_call(ticker) or stub
170
+
171
  # ── Watchlist AI concurrency cap (process-wide) ───────────────────────────────
172
  # Without this, the frontend fires N per-ticker requests in parallel Γ— up to 3 TFs each =
173
  # up to 3N simultaneous LLM calls, which 429s every free-tier provider at once β†’ the
 
1828
  "no_trade_reason": p.get("no_trade_reason"),
1829
  "ai_disclaimer": p.get("ai_disclaimer"),
1830
  "signal_count": p.get("signal_count", 0),
1831
+ "intraday_final_call": p.get("intraday_final_call"),
1832
+ "final_call_time": p.get("final_call_time"),
1833
  "predicted_direction": p.get("predicted_direction"),
1834
  "predicted_return_lo": p.get("predicted_return_lo"),
1835
  "predicted_return_hi": p.get("predicted_return_hi"),
 
1955
  preds: dict = {}
1956
 
1957
  if not market_is_open:
1958
+ preds["INTRADAY"] = _intraday_closed_value(t, _INTRADAY_CLOSED_STUB)
1959
  elif _intraday_too_late:
1960
+ preds["INTRADAY"] = _intraday_closed_value(t, _INTRADAY_TOO_LATE_STUB)
1961
 
1962
  # Check per-TF cache; only fetch TFs whose cache is stale
1963
  tfs_to_run = []
 
2053
  }
2054
 
2055
  pick, market = _build_watchlist_pick(item, preds)
2056
+ # Remember a fresh valid INTRADAY call so it can be shown as the session's final call
2057
+ # after the market closes.
2058
+ if "INTRADAY" in preds:
2059
+ _remember_intraday_call(t, preds["INTRADAY"])
2060
  if tfs_to_run:
2061
  try:
2062
  _archive_top5_predictions({"picks": [pick]}, source="watchlist")
 
2120
  market_is_open = mkt_status.get("status") == "OPEN"
2121
 
2122
  if tf == "INTRADAY" and not market_is_open:
2123
+ _final = _get_intraday_final_call(t)
2124
+ if _final:
2125
+ return jsonify({
2126
+ "tf": tf, "ticker": t, "data": _final,
2127
+ "generated_at": datetime.now().strftime("%Y-%m-%d %H:%M"),
2128
+ "intraday_final_call": True,
2129
+ })
2130
  return jsonify({
2131
  "tf": tf, "ticker": t,
2132
  "data": {"no_trade_reason": "market_closed", "direction": "N/A",
 
2138
  _ist = timezone(timedelta(hours=5, minutes=30))
2139
  _now_ist = datetime.now(timezone.utc).astimezone(_ist)
2140
  if (_now_ist.hour, _now_ist.minute) >= (14, 15):
2141
+ _final = _get_intraday_final_call(t)
2142
+ if _final:
2143
+ return jsonify({
2144
+ "tf": tf, "ticker": t, "data": _final,
2145
+ "generated_at": datetime.now().strftime("%Y-%m-%d %H:%M"),
2146
+ "intraday_final_call": True,
2147
+ })
2148
  return jsonify({
2149
  "tf": tf, "ticker": t,
2150
  "data": {"no_trade_reason": "too_close_to_close", "direction": "N/A",
 
2185
  if _reason != "timeout":
2186
  ttl = _WATCHLIST_PICK_AI_UNAVAILABLE_TTL if _reason == "ai_unavailable" else _cache_ttl_for_tf(tf)
2187
  _WATCHLIST_PICK_CACHE[(t, tf)] = {"ts": now, "pred": pred, "ttl": ttl}
2188
+ # Remember a valid INTRADAY call so it survives as the session's final call after close.
2189
+ if tf == "INTRADAY":
2190
+ _remember_intraday_call(t, pred)
2191
 
2192
  return jsonify({
2193
  "tf": tf, "ticker": t,
 
2280
  tf_results: dict = {}
2281
  if not market_is_open:
2282
  for t in tickers:
2283
+ tf_results.setdefault(t, {})["INTRADAY"] = _intraday_closed_value(t, _INTRADAY_CLOSED_STUB)
2284
  elif _intraday_too_late:
2285
  for t in tickers:
2286
+ tf_results.setdefault(t, {})["INTRADAY"] = _intraday_closed_value(t, _INTRADAY_TOO_LATE_STUB)
2287
  # Limit to 3 concurrent tickers (Γ—3 TFs = 9 threads) to avoid exhausting
2288
  # provider rate limits. Cloud providers handle 3 tickers in ~15-30s; Ollama
2289
  # handles ~2 tickers in 170s. Incomplete tickers show as timeout.
 
2311
  for item in wl:
2312
  ticker = item["ticker"]
2313
  preds = tf_results.get(ticker, {})
2314
+ # Remember a fresh valid INTRADAY call so it shows as the session's final call after close.
2315
+ if "INTRADAY" in preds:
2316
+ _remember_intraday_call(ticker, preds["INTRADAY"])
2317
  pick, pick_market = _build_watchlist_pick(item, preds)
2318
 
2319
  # Add loophole checking for the primary prediction
 
3474
  if validated_count > 0:
3475
  try:
3476
  from self_learning import analyze_and_update
3477
+ learn_result = analyze_and_update() # all history
3478
  if learn_result.get("status") != "insufficient_data":
3479
  pruned = db.prune_validated_snapshots()
3480
  if pruned:
 
3497
  """Manually trigger self-learning analysis from validation history."""
3498
  try:
3499
  from self_learning import analyze_and_update
3500
+ # Default: analyze the ENTIRE validated history (days=None). A positive `days`
3501
+ # override still restricts the window when explicitly requested.
3502
+ _days_req = (request.get_json(silent=True) or {}).get("days")
3503
+ days = int(_days_req) if _days_req and int(_days_req) > 0 else None
3504
  result = analyze_and_update(days=days)
3505
  pruned = 0
3506
  if result.get("status") != "insufficient_data":
 
3998
 
3999
  if validated > 0:
4000
  try:
4001
+ learn_result = analyze_and_update() # all history
4002
  if learn_result.get("status") != "insufficient_data":
4003
  pruned = db.prune_validated_snapshots()
4004
  if pruned:
 
4064
  "pred": pred,
4065
  "ttl": _ttl,
4066
  }
4067
+ # Capture the freshest valid call as the session's final call.
4068
+ _remember_intraday_call(tk, pred)
4069
  except Exception as exc:
4070
  app.logger.debug("INTRADAY refresh failed for %s: %s", tk, exc)
4071
  app.logger.info("INTRADAY cache refreshed for %d tickers", len(tickers))
database.py CHANGED
@@ -977,32 +977,40 @@ def save_prediction_snapshot(
977
 
978
  def get_prediction_snapshots(
979
  ticker: Optional[str] = None,
980
- days: int = 30,
981
  limit: int = 100,
982
  ) -> list[dict]:
983
- """Retrieve prediction snapshots. If ticker is None, fetch all recent snapshots."""
984
- ticker_filter = ""
 
985
  params = []
986
  if ticker:
987
  ticker = ticker.upper().strip()
988
  if "." not in ticker:
989
  ticker += ".NS"
990
- ticker_filter = "AND ticker = ?"
991
  params.append(ticker)
992
-
993
- params.append(days)
 
 
 
 
 
994
  params.append(limit)
995
-
996
  with _conn() as conn:
997
  rows = conn.execute(
998
  f"""
999
  SELECT id, ticker, timeframe, direction, confidence,
1000
  target_price_lo, target_price_hi,
1001
  predicted_return_lo, predicted_return_hi,
1002
- current_price, snapshot_source, created_at, snapshot_data
 
 
 
1003
  FROM prediction_snapshots
1004
- WHERE datetime(created_at) > datetime('now', '-' || ? || ' days')
1005
- {ticker_filter}
1006
  ORDER BY created_at DESC
1007
  LIMIT ?
1008
  """,
 
977
 
978
  def get_prediction_snapshots(
979
  ticker: Optional[str] = None,
980
+ days: Optional[int] = 30,
981
  limit: int = 100,
982
  ) -> list[dict]:
983
+ """Retrieve prediction snapshots. If ticker is None, fetch all recent snapshots.
984
+ Pass days=None (or days<=0) to fetch the ENTIRE history with no time window."""
985
+ where = []
986
  params = []
987
  if ticker:
988
  ticker = ticker.upper().strip()
989
  if "." not in ticker:
990
  ticker += ".NS"
991
+ where.append("ticker = ?")
992
  params.append(ticker)
993
+
994
+ # Only apply a time window when days is a positive number; None/0 = all history.
995
+ if days is not None and days > 0:
996
+ where.append("datetime(created_at) > datetime('now', '-' || ? || ' days')")
997
+ params.append(days)
998
+
999
+ where_clause = ("WHERE " + " AND ".join(where)) if where else ""
1000
  params.append(limit)
1001
+
1002
  with _conn() as conn:
1003
  rows = conn.execute(
1004
  f"""
1005
  SELECT id, ticker, timeframe, direction, confidence,
1006
  target_price_lo, target_price_hi,
1007
  predicted_return_lo, predicted_return_hi,
1008
+ current_price, snapshot_source, created_at, snapshot_data,
1009
+ validation_target_date, validation_status, validation_result,
1010
+ actual_price_at_validation, actual_return_at_validation,
1011
+ window_high, window_low, validated_at
1012
  FROM prediction_snapshots
1013
+ {where_clause}
 
1014
  ORDER BY created_at DESC
1015
  LIMIT ?
1016
  """,
self_learning.py CHANGED
@@ -23,6 +23,7 @@ def _data_dir() -> str:
23
 
24
 
25
  _MIN_SAMPLES = 10 # require at least this many validated rows before injecting learnings
 
26
 
27
 
28
  def _slim_record(r: dict) -> dict:
@@ -53,71 +54,68 @@ def _slim_record(r: dict) -> dict:
53
 
54
  def _analyze_bucket_set(new_validated: list, existing: dict, days: int, use_llm: bool = True) -> dict:
55
  """Compute calibration stats (buckets, confidence, notes, records) for ONE prediction
56
- source (AI or ML). `existing` is that source's previously-written block, seeded first so
57
- historical accuracy survives after validated DB rows are pruned. Returns a block dict;
58
- does not write to disk."""
 
 
 
 
 
59
  existing = existing or {}
60
- is_existing_valid = (
61
- existing.get("status") != "insufficient_data"
62
- and existing.get("total_validated", 0) >= _MIN_SAMPLES
63
- )
 
 
 
 
64
 
65
  merged_buckets: dict = {}
66
  merged_conf: dict = {}
67
- historical_total = 0
68
- historical_hits = 0
69
- existing_records: list = existing.get("records", [])
70
- existing_record_ids: set = {r["id"] for r in existing_records if r.get("id")}
71
-
72
- if is_existing_valid:
73
- for k, v in existing.get("buckets", {}).items():
74
- parts = k.split("_", 1)
75
- merged_buckets[k] = {
76
- "hits": v["hits"],
77
- "total": v["total"],
78
- "direction": parts[0],
79
- "timeframe": parts[1] if len(parts) > 1 else "1D",
80
- }
81
- for k, v in existing.get("confidence_stats", {}).items():
82
- merged_conf[k] = {"hits": v["hits"], "total": v["total"]}
83
- historical_total = existing.get("total_validated", 0)
84
- historical_hits = sum(b["hits"] for b in merged_buckets.values())
85
-
86
- new_hits = 0
87
- new_records = []
88
- for r in new_validated:
89
- direction = r["direction"].upper()
90
  timeframe = (r.get("timeframe") or "1D").upper()
91
  confidence = (r.get("confidence") or "LOW").upper()
92
- hit = r["validation_result"] == "HIT"
93
 
94
  key = f"{direction}_{timeframe}"
95
- if key not in merged_buckets:
96
- merged_buckets[key] = {"hits": 0, "total": 0, "direction": direction, "timeframe": timeframe}
97
- merged_buckets[key]["hits"] += int(hit)
98
- merged_buckets[key]["total"] += 1
99
-
100
- if confidence not in merged_conf:
101
- merged_conf[confidence] = {"hits": 0, "total": 0}
102
- merged_conf[confidence]["hits"] += int(hit)
103
- merged_conf[confidence]["total"] += 1
104
 
105
- new_hits += int(hit)
 
 
106
 
107
- if r.get("id") and r["id"] not in existing_record_ids:
108
- new_records.append(_slim_record(r))
 
109
 
110
- all_records = new_records + existing_records
111
  all_records.sort(key=lambda x: x.get("validated_at") or "", reverse=True)
112
- all_records = all_records[:500]
113
 
114
- total = historical_total + len(new_validated)
 
 
 
115
 
116
  if total < _MIN_SAMPLES:
117
  return {
118
  "status": "insufficient_data",
119
  "total_validated": total,
120
- "new_in_this_run": len(new_validated),
121
  "min_required": _MIN_SAMPLES,
122
  "calibration_notes": [],
123
  "buckets": {},
@@ -137,8 +135,7 @@ def _analyze_bucket_set(new_validated: list, existing: dict, days: int, use_llm:
137
  "miss_rate": round(1 - hit_rate, 3),
138
  }
139
 
140
- overall_hits = historical_hits + new_hits
141
- overall_accuracy = round(overall_hits / total, 3) if total else 0
142
 
143
  if use_llm:
144
  try:
@@ -151,9 +148,15 @@ def _analyze_bucket_set(new_validated: list, existing: dict, days: int, use_llm:
151
  # arithmetic β€” same WARN/CAUTION/OK hit-miss blocks, no LLM cost.
152
  calibration_notes = _arithmetic_calibration_notes(bucket_stats, merged_conf)
153
 
 
 
 
 
 
 
154
  return {
155
  "total_validated": total,
156
- "new_in_this_run": len(new_validated),
157
  "overall_accuracy": overall_accuracy,
158
  "buckets": bucket_stats,
159
  "calibration_notes": calibration_notes,
@@ -165,10 +168,13 @@ def _analyze_bucket_set(new_validated: list, existing: dict, days: int, use_llm:
165
  }
166
 
167
 
168
- def analyze_and_update(days: int = 30) -> dict:
169
  """
170
  Query prediction_snapshots for validated results and write learnings.json.
171
 
 
 
 
172
  AI and ML predictions are analyzed SEPARATELY (by snapshot_source) so each gets its own
173
  hit/miss buckets, confidence stats, and calibration notes β€” the panel shows both. The
174
  top-level fields mirror the AI block for backward compatibility: get_learning_context()
@@ -176,7 +182,9 @@ def analyze_and_update(days: int = 30) -> dict:
176
  """
177
  import database as db
178
 
179
- rows = db.get_prediction_snapshots(days=days)
 
 
180
  validated = [
181
  r for r in rows
182
  if r.get("validation_status") == "VALIDATED"
@@ -205,7 +213,7 @@ def analyze_and_update(days: int = 30) -> dict:
205
  seen.add(rid)
206
  combined.append(rec)
207
  combined.sort(key=lambda x: x.get("validated_at") or "", reverse=True)
208
- combined = combined[:500]
209
 
210
  result = {
211
  "updated_at": _today_ist(),
@@ -242,11 +250,12 @@ def get_learning_context() -> str:
242
  return ""
243
 
244
  accuracy = data.get("overall_accuracy", 0)
245
- days = data.get("days", 30)
246
  updated = data.get("updated_at", "")
 
247
 
248
  lines = [
249
- f"LEARNING FROM RECENT PREDICTIONS (last {days} days, N={total}, accuracy={accuracy:.0%}, updated {updated}):"
250
  ]
251
  for note in notes:
252
  lines.append(f"- {note}")
@@ -298,6 +307,86 @@ def _arithmetic_calibration_notes(bucket_stats: dict, merged_conf: dict) -> list
298
  return notes
299
 
300
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
301
  def _llm_calibration_notes(
302
  bucket_stats: dict,
303
  merged_conf: dict,
@@ -406,7 +495,7 @@ def _today_ist() -> str:
406
 
407
  if __name__ == "__main__":
408
  import sys
409
- days = int(sys.argv[1]) if len(sys.argv) > 1 else 30
410
  result = analyze_and_update(days=days)
411
  print(json.dumps(result, indent=2))
412
  print("\n--- Prompt context ---")
 
23
 
24
 
25
  _MIN_SAMPLES = 10 # require at least this many validated rows before injecting learnings
26
+ _MAX_STORED_RECORDS = 5000 # slim records kept in learnings.json (preserves history post-prune)
27
 
28
 
29
  def _slim_record(r: dict) -> dict:
 
54
 
55
  def _analyze_bucket_set(new_validated: list, existing: dict, days: int, use_llm: bool = True) -> dict:
56
  """Compute calibration stats (buckets, confidence, notes, records) for ONE prediction
57
+ source (AI or ML).
58
+
59
+ Aggregates are rebuilt from a DEDUPLICATED union of (a) the current DB validated rows
60
+ and (b) previously-stored slim records that are no longer in the DB (pruned history).
61
+ Dedup is by snapshot id, so a row present in BOTH the DB and the stored history is counted
62
+ exactly once β€” the analysis is idempotent and safe to re-run without pruning in between
63
+ (the old approach seeded historical totals AND re-counted un-pruned DB rows, double-counting).
64
+ """
65
  existing = existing or {}
66
+ existing_records: list = existing.get("records", [])
67
+
68
+ # Union of records: current DB rows first, then stored records whose id isn't in the DB set.
69
+ new_ids: set = {r.get("id") for r in new_validated if r.get("id") is not None}
70
+ combined_src: list = list(new_validated)
71
+ for er in existing_records:
72
+ if er.get("id") not in new_ids:
73
+ combined_src.append(er)
74
 
75
  merged_buckets: dict = {}
76
  merged_conf: dict = {}
77
+ total = 0
78
+ total_hits = 0
79
+ all_records: list = []
80
+ for r in combined_src:
81
+ result = r.get("validation_result")
82
+ if result not in ("HIT", "MISS"):
83
+ continue
84
+ direction = (r.get("direction") or "").upper()
85
+ if direction in ("N/A", "NO TRADE", "NEUTRAL", ""):
86
+ continue
 
 
 
 
 
 
 
 
 
 
 
 
 
87
  timeframe = (r.get("timeframe") or "1D").upper()
88
  confidence = (r.get("confidence") or "LOW").upper()
89
+ hit = result == "HIT"
90
 
91
  key = f"{direction}_{timeframe}"
92
+ b = merged_buckets.setdefault(
93
+ key, {"hits": 0, "total": 0, "direction": direction, "timeframe": timeframe}
94
+ )
95
+ b["hits"] += int(hit)
96
+ b["total"] += 1
 
 
 
 
97
 
98
+ c = merged_conf.setdefault(confidence, {"hits": 0, "total": 0})
99
+ c["hits"] += int(hit)
100
+ c["total"] += 1
101
 
102
+ total += 1
103
+ total_hits += int(hit)
104
+ all_records.append(_slim_record(r))
105
 
 
106
  all_records.sort(key=lambda x: x.get("validated_at") or "", reverse=True)
107
+ all_records = all_records[:_MAX_STORED_RECORDS]
108
 
109
+ new_in_this_run = sum(
110
+ 1 for r in new_validated
111
+ if r.get("id") is not None and r.get("id") not in {er.get("id") for er in existing_records}
112
+ )
113
 
114
  if total < _MIN_SAMPLES:
115
  return {
116
  "status": "insufficient_data",
117
  "total_validated": total,
118
+ "new_in_this_run": new_in_this_run,
119
  "min_required": _MIN_SAMPLES,
120
  "calibration_notes": [],
121
  "buckets": {},
 
135
  "miss_rate": round(1 - hit_rate, 3),
136
  }
137
 
138
+ overall_accuracy = round(total_hits / total, 3) if total else 0
 
139
 
140
  if use_llm:
141
  try:
 
148
  # arithmetic β€” same WARN/CAUTION/OK hit-miss blocks, no LLM cost.
149
  calibration_notes = _arithmetic_calibration_notes(bucket_stats, merged_conf)
150
 
151
+ # Prepend target-reach diagnostics (predicted high/low/mid vs the stock's ACTUAL high/low)
152
+ # so the panel explains WHY a target was missed β€” e.g. a high target price never touched.
153
+ target_notes = _target_reach_notes(all_records)
154
+ if target_notes:
155
+ calibration_notes = target_notes + calibration_notes
156
+
157
  return {
158
  "total_validated": total,
159
+ "new_in_this_run": new_in_this_run,
160
  "overall_accuracy": overall_accuracy,
161
  "buckets": bucket_stats,
162
  "calibration_notes": calibration_notes,
 
168
  }
169
 
170
 
171
+ def analyze_and_update(days: Optional[int] = None) -> dict:
172
  """
173
  Query prediction_snapshots for validated results and write learnings.json.
174
 
175
+ `days=None` (the default) analyzes the ENTIRE validated history β€” every prediction
176
+ matters, so there is no rolling window. Pass a positive int only to restrict the window.
177
+
178
  AI and ML predictions are analyzed SEPARATELY (by snapshot_source) so each gets its own
179
  hit/miss buckets, confidence stats, and calibration notes β€” the panel shows both. The
180
  top-level fields mirror the AI block for backward compatibility: get_learning_context()
 
182
  """
183
  import database as db
184
 
185
+ # Pull the FULL history (days=None β‡’ no time window). get_prediction_snapshots caps at
186
+ # `limit`, so request a high cap to capture every validated row.
187
+ rows = db.get_prediction_snapshots(days=days, limit=100000)
188
  validated = [
189
  r for r in rows
190
  if r.get("validation_status") == "VALIDATED"
 
213
  seen.add(rid)
214
  combined.append(rec)
215
  combined.sort(key=lambda x: x.get("validated_at") or "", reverse=True)
216
+ combined = combined[:_MAX_STORED_RECORDS]
217
 
218
  result = {
219
  "updated_at": _today_ist(),
 
250
  return ""
251
 
252
  accuracy = data.get("overall_accuracy", 0)
253
+ days = data.get("days")
254
  updated = data.get("updated_at", "")
255
+ window = f"last {days} days" if days else "all history"
256
 
257
  lines = [
258
+ f"LEARNING FROM RECENT PREDICTIONS ({window}, N={total}, accuracy={accuracy:.0%}, updated {updated}):"
259
  ]
260
  for note in notes:
261
  lines.append(f"- {note}")
 
307
  return notes
308
 
309
 
310
+ def _target_reach_notes(records: list) -> list:
311
+ """Compare the predicted target band (high/low/mid) against the stock's ACTUAL price
312
+ window (window_high/window_low) to explain WHY a prediction missed β€” e.g. a high target
313
+ the price never reached. Groups by direction+timeframe and reports the reach rate plus
314
+ the average shortfall, so the panel says exactly how far off the target was. Works for
315
+ both AI and ML records (both carry window_high/low + target band)."""
316
+ from collections import defaultdict
317
+
318
+ groups: dict = defaultdict(list)
319
+ for r in records:
320
+ direction = (r.get("direction") or "").upper()
321
+ tf = (r.get("timeframe") or "1D").upper()
322
+ if direction not in ("BULLISH", "BEARISH", "SLIGHTLY BULLISH", "SLIGHTLY BEARISH"):
323
+ continue
324
+ entry = r.get("current_price") or 0
325
+ wh = r.get("window_high")
326
+ wl = r.get("window_low")
327
+ t_lo = r.get("target_price_lo")
328
+ t_hi = r.get("target_price_hi")
329
+ if not entry or wh is None or wl is None or t_lo is None or t_hi is None:
330
+ continue
331
+ groups[(direction, tf)].append((entry, wh, wl, t_lo, t_hi))
332
+
333
+ notes = []
334
+ for (direction, tf), rows in sorted(groups.items(), key=lambda x: -len(x[1])):
335
+ n = len(rows)
336
+ if n < 5:
337
+ continue
338
+ bullish = "BULLISH" in direction
339
+ reached = 0
340
+ shortfalls = [] # how far short of the target the price stopped (% of entry)
341
+ pred_target_pcts = [] # predicted best-case target as % move
342
+ actual_extreme_pcts = [] # actual best-case reached as % move
343
+ mid_reached = 0 # did price at least touch the midpoint?
344
+ for entry, wh, wl, t_lo, t_hi in rows:
345
+ mid = (t_lo + t_hi) / 2.0
346
+ if bullish:
347
+ pred_target_pcts.append((t_hi - entry) / entry * 100)
348
+ actual_extreme_pcts.append((wh - entry) / entry * 100)
349
+ if wh >= t_hi:
350
+ reached += 1
351
+ else:
352
+ shortfalls.append((t_hi - wh) / entry * 100)
353
+ if wh >= mid:
354
+ mid_reached += 1
355
+ else:
356
+ pred_target_pcts.append((t_lo - entry) / entry * 100)
357
+ actual_extreme_pcts.append((wl - entry) / entry * 100)
358
+ if wl <= t_lo:
359
+ reached += 1
360
+ else:
361
+ shortfalls.append((wl - t_lo) / entry * 100)
362
+ if wl <= mid:
363
+ mid_reached += 1
364
+
365
+ reach_rate = reached / n
366
+ mid_rate = mid_reached / n
367
+ avg_pred = sum(pred_target_pcts) / n
368
+ avg_actual = sum(actual_extreme_pcts) / n
369
+ edge = "high" if bullish else "low"
370
+ if reach_rate < 0.5 and shortfalls:
371
+ avg_short = sum(shortfalls) / len(shortfalls)
372
+ notes.append(
373
+ f"MISS {direction} {tf}: {edge} target hit only {reach_rate:.0%} (N={n}) β€” "
374
+ f"predicted {edge} avg {avg_pred:+.1f}% but price only reached {avg_actual:+.1f}% "
375
+ f"(~{avg_short:.1f}% too far); midpoint touched {mid_rate:.0%} β€” pull the {edge} target in"
376
+ )
377
+ elif reach_rate >= 0.85:
378
+ notes.append(
379
+ f"OK {direction} {tf}: {edge} target hit {reach_rate:.0%} (N={n}) β€” "
380
+ f"band well-placed (pred {avg_pred:+.1f}% vs reached {avg_actual:+.1f}%)"
381
+ )
382
+ elif mid_rate < 0.6:
383
+ notes.append(
384
+ f"CAUTION {direction} {tf}: midpoint hit only {mid_rate:.0%} (N={n}) β€” "
385
+ f"predicted {edge} avg {avg_pred:+.1f}% vs actual {avg_actual:+.1f}%; narrow the band"
386
+ )
387
+ return notes
388
+
389
+
390
  def _llm_calibration_notes(
391
  bucket_stats: dict,
392
  merged_conf: dict,
 
495
 
496
  if __name__ == "__main__":
497
  import sys
498
+ days = int(sys.argv[1]) if len(sys.argv) > 1 else None
499
  result = analyze_and_update(days=days)
500
  print(json.dumps(result, indent=2))
501
  print("\n--- Prompt context ---")
static/app.js CHANGED
@@ -839,9 +839,15 @@ function _renderOneTfCell(tf, d, pick) {
839
  const _mlSlotInner = _mlData ? _renderMlRow(tf, _mlData) : '<div class="tf-ml-mini-loader">πŸ€– ML…</div>';
840
  const _aiDirAttr = (af && af.direction) ? af.direction : '';
841
  const _agreeInner = _agreeHtml(_mlData && _mlData.direction, _aiDirAttr, _mlData && _mlData.dir_basis);
842
- return `<div class="tf-cell${isBestTf ? ' tf-cell--best' : ''}" id="tf-${safeId}-${tf}" data-ai-dir="${_aiDirAttr}">
 
 
 
 
 
843
  ${isBestTf ? '<span class="best-tf-badge">Best Bet</span>' : ''}
844
  <div class="tf-label">${tf === 'INTRADAY' ? 'Today' : tf}</div>
 
845
  <div class="tf-return" style="color:${isNoTrade ? 'var(--text-muted)' : retColor(d.midpoint||0)}">${retLabel}</div>
846
  ${noTradeDetail}
847
  ${priceRange}
@@ -3269,7 +3275,9 @@ function renderAiLearnPanel(data, { showToast = false, newInRun = null } = {}) {
3269
  : '<li>No validated predictions for this model yet.</li>';
3270
  } else {
3271
  notesList.innerHTML = notes.map(n => {
3272
- const cls = n.startsWith('WARN') ? 'warn' : n.startsWith('OK') ? 'ok' : '';
 
 
3273
  return `<li class="${cls}">${n}</li>`;
3274
  }).join('');
3275
  }
@@ -3309,7 +3317,7 @@ document.getElementById('ai-learn-btn')?.addEventListener('click', async () => {
3309
  btn.disabled = true;
3310
  btn.textContent = '🧠 Analyzing...';
3311
  try {
3312
- const res = await fetch('/api/ai-learn', { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ days: 30 }) });
3313
  if (!res.ok) throw new Error('Analysis failed');
3314
  const data = await res.json();
3315
  renderAiLearnPanel(data, { showToast: true, newInRun: data.new_in_this_run ?? null });
 
839
  const _mlSlotInner = _mlData ? _renderMlRow(tf, _mlData) : '<div class="tf-ml-mini-loader">πŸ€– ML…</div>';
840
  const _aiDirAttr = (af && af.direction) ? af.direction : '';
841
  const _agreeInner = _agreeHtml(_mlData && _mlData.direction, _aiDirAttr, _mlData && _mlData.dir_basis);
842
+ // Session's final INTRADAY call, shown after the market closes instead of a "market closed"
843
+ // stub β€” it's the last real call made during the session, not a live prediction.
844
+ const finalCallBadge = d.intraday_final_call
845
+ ? `<div class="tf-final-call" title="NSE is closed β€” this was the last intraday call of the session${d.final_call_time ? ' (as of ' + d.final_call_time + ' IST)' : ''}">πŸ• Final call${d.final_call_time ? ' Β· ' + d.final_call_time : ''}</div>`
846
+ : '';
847
+ return `<div class="tf-cell${isBestTf ? ' tf-cell--best' : ''}${d.intraday_final_call ? ' tf-cell--final' : ''}" id="tf-${safeId}-${tf}" data-ai-dir="${_aiDirAttr}">
848
  ${isBestTf ? '<span class="best-tf-badge">Best Bet</span>' : ''}
849
  <div class="tf-label">${tf === 'INTRADAY' ? 'Today' : tf}</div>
850
+ ${finalCallBadge}
851
  <div class="tf-return" style="color:${isNoTrade ? 'var(--text-muted)' : retColor(d.midpoint||0)}">${retLabel}</div>
852
  ${noTradeDetail}
853
  ${priceRange}
 
3275
  : '<li>No validated predictions for this model yet.</li>';
3276
  } else {
3277
  notesList.innerHTML = notes.map(n => {
3278
+ const cls = /^(WARN|MISS)/.test(n) ? 'warn'
3279
+ : n.startsWith('CAUTION') ? 'caution'
3280
+ : n.startsWith('OK') ? 'ok' : '';
3281
  return `<li class="${cls}">${n}</li>`;
3282
  }).join('');
3283
  }
 
3317
  btn.disabled = true;
3318
  btn.textContent = '🧠 Analyzing...';
3319
  try {
3320
+ const res = await fetch('/api/ai-learn', { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({}) });
3321
  if (!res.ok) throw new Error('Analysis failed');
3322
  const data = await res.json();
3323
  renderAiLearnPanel(data, { showToast: true, newInRun: data.new_in_this_run ?? null });
static/style.css CHANGED
@@ -442,6 +442,14 @@ input::placeholder { color: var(--text-dim); }
442
  border-radius: 3px; padding: 1px 5px; margin-bottom: 2px;
443
  }
444
  .tf-label { font-size: 11px; color: var(--text-muted); text-transform: uppercase; letter-spacing: .6px; font-weight: 600; }
 
 
 
 
 
 
 
 
445
  .tf-return { font-size: 16px; font-weight: 700; font-variant-numeric: tabular-nums; line-height: 1.1; }
446
  .no-trade-label { font-size: 13px; font-weight: 500; color: var(--text-muted); font-style: italic; }
447
  .tf-no-trade-reason {
@@ -972,6 +980,7 @@ input::placeholder { color: var(--text-dim); }
972
  font-size: 12px; color: var(--text1); padding: 2px 0; line-height: 1.5;
973
  }
974
  .ai-learn-notes li.warn { color: var(--red); }
 
975
  .ai-learn-notes li.ok { color: var(--green); }
976
 
977
  .validation-history-card {
 
442
  border-radius: 3px; padding: 1px 5px; margin-bottom: 2px;
443
  }
444
  .tf-label { font-size: 11px; color: var(--text-muted); text-transform: uppercase; letter-spacing: .6px; font-weight: 600; }
445
+ .tf-final-call {
446
+ display: inline-flex; align-items: center; gap: 3px;
447
+ font-size: 9px; font-weight: 700; letter-spacing: 0.3px; text-transform: uppercase;
448
+ color: var(--yellow);
449
+ background: rgba(234, 179, 8, 0.12); border: 1px solid rgba(234, 179, 8, 0.3);
450
+ border-radius: 3px; padding: 1px 5px; margin: 1px 0 2px;
451
+ }
452
+ .tf-cell--final { border-color: rgba(234, 179, 8, 0.35); }
453
  .tf-return { font-size: 16px; font-weight: 700; font-variant-numeric: tabular-nums; line-height: 1.1; }
454
  .no-trade-label { font-size: 13px; font-weight: 500; color: var(--text-muted); font-style: italic; }
455
  .tf-no-trade-reason {
 
980
  font-size: 12px; color: var(--text1); padding: 2px 0; line-height: 1.5;
981
  }
982
  .ai-learn-notes li.warn { color: var(--red); }
983
+ .ai-learn-notes li.caution { color: var(--yellow); }
984
  .ai-learn-notes li.ok { color: var(--green); }
985
 
986
  .validation-history-card {
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=20260724c">
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=20260724c"></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=20260727b">
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=20260727b"></script>
453
  </body>
454
  </html>