"""
entry_guards_test.py -- [2026-10-07] The user (XPOF 10/7, option b): test, then apply to both bots
  FIX 1  the breakout exception to the 3%-above-open rule counts only REAL levels (yesterday's high), not the stock's own
         earlier high of today (DXC 10/5, XPOF 10/7)
  FIX 2  liquidity: no buy unless the last 15 minutes traded >= N shares per minute on average (XPOF: 100-1,500/min)
         -- also shown as dollars per minute
On the 2-year v2 replay (v2_bar_replay_2024-10-01_2026-10-02.jsonl, live entry rules + live exits) with the per-minute
volume from the library bars. Scored at the realistic 0.2% cost per trade (real fills, 10/7) as well as the replay's 0.1%.
    python3 entry_guards_test.py
"""
import gzip
import json
import sys
from pathlib import Path

import numpy as np

sys.path.insert(0, "/var/www/screener/trade/reports/playbook")
import lib_v2 as L2

T = [json.loads(l) for l in open("/var/www/screener/trade/reports/playbook/v2_bar_replay_2024-10-01_2026-10-02.jsonl")]
bars = {}
for day in sorted({t["day"] for t in T}):
    d = json.load(gzip.open(L2.BARS / f"bars_{day}.json.gz", "rt"))
    for s in {t["sym"] for t in T if t["day"] == day}:
        if s in d["symbols"]:
            bars[(day, s)] = L2._minutes(d["symbols"][s]["bars"])
for t in T:
    by = bars.get((t["day"], t["sym"]), {})
    m = t["buy_m"]
    vols = [by[k][5] for k in range(max(0, m - 15), m) if k in by]
    t["shares_min"] = sum(vols) / 15 if vols else 0.0
    t["dollars_min"] = t["shares_min"] * t["buy"]
p1 = np.array([t["pl"] for t in T]); p2 = p1 - 0.1                     # 0.1% -> 0.2% cost
y1 = np.array([t["day"] < "2025-10-01" for t in T])
top = np.percentile(p1, 90)
print(f"{len(T)} v2 trades (2 years). All: {p1.mean():+.3f}%/trade at 0.1% cost, {p2.mean():+.3f}% at 0.2%; "
      f"shares/min before the buy: median {np.median([t['shares_min'] for t in T]):.0f}")


def report(name, block):
    b = np.array(block); k = ~b
    print(f"\n{name}: blocks {b.sum()} ({b.mean():.0%}) | blocked winners {(p1[b] > 0).sum()} / losers {(p1[b] <= 0).sum()} | "
          f"best-10% trades cut {(p1[b] >= top).sum()}/{(p1 >= top).sum()}")
    for lab, p in (("0.1% cost", p1), ("0.2% cost", p2)):
        print(f"   {lab}: kept trades {p[k].mean():+.3f}%/trade vs all {p.mean():+.3f}% | blocked trades total {p[b].sum():+.1f}% "
              f"(year 1 {p[b & y1].sum():+.1f}% / year 2 {p[b & ~y1].sum():+.1f}%; negative = the guard removed losses)")


report("FIX 1: breakout exception only on real levels", [(t["feat"].get("breakout") or "").startswith("today") for t in T])
for n in (500, 1000, 2000, 3000, 5000):
    report(f"FIX 2: >= {n} shares/min (last 15 min)", [t["shares_min"] < n for t in T])
for d in (5000, 10000, 20000):
    report(f"FIX 2b: >= ${d:,}/min (last 15 min)", [t["dollars_min"] < d for t in T])
report("FIX 1 + FIX 2 (>= 2000 shares/min)", [(t["feat"].get("breakout") or "").startswith("today") or t["shares_min"] < 2000 for t in T])
