"""
notrade_test.py -- [2026-10-23] the user: "QBTS (2/24/25) shouldn't be traded at all". At the R1A buy (10:00 bar) QBTS was down
10% from the open in a straight sell-off, under the previous day's low, 2.7% under a falling VWAP, 15-min buy share 44%,
every high lower than the one before. Candidate NO-TRADE blocks (read at the trigger bar, finished bars only), each measured on
the 833 EV3 buys with the live give-back exit (e2_fix.json "B"): what it removes, and what is left.
  N1  A6 falling on net selling: down >= 1% over the last 15 bars AND 15-min buy share < 50%
  N2  under the previous day's low
  N3  15-min buy share < 45%
  N4  lower highs: high of the last 15 bars < high of the 15 bars before AND close > 2% under VWAP
  N5  down >= 8% from the open
  N6  down from the open by >= 0.8 x daily ATR
"""
import gzip, json, sys
from collections import defaultdict
import numpy as np
sys.path.insert(0, "/var/www/screener/trade/reports/playbook"); sys.path.insert(0, "/var/www/screener/trade")
import v2_bar_replay as R
SPLIT = "2025-10-01"
rows = json.load(open("/var/www/screener/trade/reports/ev3/e2_fix.json"))
by = defaultdict(list)
for r in rows:
    by[r["day"]].append(r)
for day in sorted(by):
    d = json.load(gzip.open(R.OW / "bars" / f"bars_{day}.json.gz", "rt"))
    for r in by[day]:
        s = r["sym"]; ref = R.REF.load(day, s); fl = json.loads((R.OW / "flow" / day / f"{s}.json").read_text())
        bars = [b for b in R.bars_of(d["symbols"][s]["bars"]) if 0 <= R.minute(b["t"]) < 390]
        M = [R.minute(b["t"]) for b in bars]; k = M.index(r["m"]); m = r["m"]
        done = bars[:k + 1]; c = done[-1]["c"]; o = done[0]["o"]
        pv = sum((b["h"] + b["l"] + b["c"]) / 3 * b["v"] for b in done); cv = sum(b["v"] for b in done)
        vw = pv / cv if cv else c
        B = sum(fl["buy"][max(0, m - 14):m + 1]); S = sum(fl["sell"][max(0, m - 14):m + 1]); bs15 = B / (B + S) if B + S else .5
        c15 = done[max(0, k - 15)]["c"]
        h1 = max(b["h"] for b in done[-15:]); h0 = max([b["h"] for b in done[-30:-15]] or [h1 + 1])
        f = r["f"] = {}
        f["N1"] = (c / c15 - 1) * 100 <= -1 and bs15 < 0.5
        f["N2"] = bool(ref.get("prev_low")) and c < ref["prev_low"]
        f["N3"] = bs15 < 0.45
        f["N4"] = h1 < h0 and c < vw * 0.98
        f["N5"] = (c / o - 1) * 100 <= -8
        f["N6"] = (o - c) >= 0.8 * ref["atr14"]
    R.REF._CACHE.clear(); del d
print(f"{len(rows)} EV3 buys, live give-back exit, per trade after 0.2% cost (year 1 / year 2)")
a = np.array([r["B"] for r in rows]); y = np.array([r["day"] < SPLIT for r in rows])
print(f"   all          {len(rows):4}  {a.mean():+.3f}% ({a[y].mean():+.3f} / {a[~y].mean():+.3f})  total {a.sum():+.1f}%")
q = [r for r in rows if r["sym"] == "QBTS" and r["day"] == "2025-02-24"]
print("   QBTS 2/24/25 flags:", [k for k, v in q[0]["f"].items() if v] if q else "-")
for n in ["N1", "N2", "N3", "N4", "N5", "N6"]:
    rem = [r for r in rows if r["f"][n]]; kept = [r for r in rows if not r["f"][n]]
    if not rem:
        continue
    ra = np.array([r["B"] for r in rem]); ry = np.array([r["day"] < SPLIT for r in rem])
    ka = np.array([r["B"] for r in kept]); ky = np.array([r["day"] < SPLIT for r in kept])
    print(f"   {n} blocks {len(rem):4}: {ra.mean():+.3f}% ({ra[ry].mean() if ry.any() else 0:+.3f} / {ra[~ry].mean() if (~ry).any() else 0:+.3f}) "
          f"stops {np.mean([r['B_why'] == 'stop' for r in rem]):.0%} | kept {len(kept)}: {ka.mean():+.3f}% ({ka[ky].mean():+.3f} / {ka[~ky].mean():+.3f}) total {ka.sum():+.1f}%")
    for st in ("R1A", "R1B", "R3", "R4"):
        X = [r["B"] for r in rem if r["setup"] == st]
        if X:
            print(f"        {st}: {len(X)} blocked {np.mean(X):+.3f}%")
json.dump(rows, open("/var/www/screener/trade/reports/ev3/notrade.json", "w"))
