"""eval6.py collect A..B OUT | analyze OUT.. -- [2026-10-28] the user: on the 6-month v2 buys, was the entry at the RIGHT SPOT, TOO HIGH, or did
it SLOPE DOWN right after? Rule v2 / VWAP rising (stock_board defaults + rule="v2"). Per buy: outcome (max rise 15/30/60, max drop 30, the minute of
the 15-min high, higher after 15 min, +2% vs -2% first) and the entry LOCATION: rise from the 30-min low (in % and in daily ATRs), range
position, vs VWAP, minutes since the 30-min low."""
import gzip, json, sys
from pathlib import Path
import numpy as np
TR = Path("/var/www/screener/trade"); sys.path.insert(0, str(TR / "reports/playbook")); sys.path.insert(0, str(TR))
if sys.argv[1] == "collect":
    import v2_bar_replay as R
    import stock_board as SB
    a, b_ = sys.argv[2].split(".."); out = open(sys.argv[3], "w")
    for p in sorted(R.OW.glob("bars/bars_20*.json.gz")):
        day = p.name[5:15]
        if not (a <= day <= b_): continue
        d = json.load(gzip.open(p, "rt")); pp = R.OW / f"pm_history/{day}.json.gz"
        pmh = {r["s"]: r.get("pm_high") for r in json.load(gzip.open(pp, "rt"))["rows"]} if pp.exists() else {}
        for s in d["top30_current"]:
            fp = R.OW / "flow" / day / f"{s}.json"; ref = R.REF.load(day, s)
            if s not in d["symbols"] or not fp.exists() or not ref or not ref.get("prev_close") or not ref.get("atr14"): continue
            bars = [x for x in R.bars_of(d["symbols"][s]["bars"]) if 0 <= R.minute(x["t"]) < 390]
            if len(bars) < 150: continue
            fl = json.loads(fp.read_text()); atrp = ref["atr14"] / ref["prev_close"] * 100
            B = SB.Board(ref["prev_close"], ref["atr14"], bars[0]["o"], pm_high=pmh.get(s), vpm=ref.get("vol_per_min"), rule="v2", vwap2="rising")
            for i, x in enumerate(bars[:-1]):
                t = R.minute(x["t"])
                if t > 135: break
                r = B.update(x, t, fl["buy"][t], fl["sell"][t])
                if not r["buy"]: continue
                bi = i + 1; P = bars[bi]["o"]; w15 = bars[bi:bi + 15]; w30 = bars[bi:bi + 30]; w60 = bars[bi:bi + 60]
                f2 = 0
                for z in bars[bi:bi + 120]:
                    if z["l"] <= P * 0.98: f2 = -1; break
                    if z["h"] >= P * 1.02: f2 = 1; break
                lo_k = min(range(max(0, i - 29), i + 1), key=lambda k: bars[k]["l"]); lo30 = bars[lo_k]["l"]
                out.write(json.dumps(dict(day=day, sym=s, t=t, pid=B.buys[-1]["pid"], atr=round(atrp, 2), P=P,
                    r15=round((max(z["h"] for z in w15) / P - 1) * 100, 3), r60=round((max(z["h"] for z in w60) / P - 1) * 100, 3),
                    d30=round((min(z["l"] for z in w30) / P - 1) * 100, 3), c15=round((w15[-1]["c"] / P - 1) * 100, 3), f2=f2,
                    up_from_low=round((P / lo30 - 1) * 100, 3), up_from_low_atr=round((P / lo30 - 1) * 100 / atrp, 3), min_since_low=t - R.minute(bars[lo_k]["t"]),
                    pos=r["pos"], vs_vwap=r["vs_vwap"])) + "\n")
        del d; R.REF._CACHE.clear()
    out.close(); print("EVAL6_DONE")
else:
    X = [json.loads(l) for f in sys.argv[2:] for l in open(f)]
    W = [x for x in X if x["f2"] == 1]; L = [x for x in X if x["f2"] == -1]; N = [x for x in X if x["f2"] == 0]
    print(f"{len(X)} v2 buys (VWAP rising) {min(x['day'] for x in X)}..{max(x['day'] for x in X)}: WINNERS (+2% first) {len(W)} | LOSERS (-2% first) {len(L)} | neither {len(N)}\n")
    fade = [x for x in L if x["r15"] < 0.5]; mid = [x for x in L if 0.5 <= x["r15"] < 1.0]; upfirst = [x for x in L if x["r15"] >= 1.0]
    print("LOSERS -- what happened right after the buy:")
    print(f"   sloped DOWN right away (max rise in 15 min < +0.5%):   {len(fade):4} ({len(fade) / len(L):.0%})")
    print(f"   small rise first (+0.5% .. +1%), then down:          {len(mid):4} ({len(mid) / len(L):.0%})")
    print(f"   ROSE FIRST >= +1% in 15 min, then fell to -2%:        {len(upfirst):4} ({len(upfirst) / len(L):.0%})  <- the entry worked; the exit gave it back")
    def prof(Z):
        a = lambda k: np.median([z[k] for z in Z])
        return (f"n {len(Z):5} | up from the 30-min low: median {a('up_from_low'):+.2f}% = {a('up_from_low_atr'):.2f} x daily ATR, {a('min_since_low'):.0f} min after the low "
                f"| range position {a('pos'):.2f} | vs VWAP {a('vs_vwap'):+.2f}% | share bought > 0.5 ATR above the low {np.mean([z['up_from_low_atr'] > 0.5 for z in Z]):.0%}")
    print("\nENTRY LOCATION (medians):")
    print(f"   WINNERS              {prof(W)}")
    print(f"   LOSERS, all          {prof(L)}")
    print(f"   LOSERS, sloped down  {prof(fade)}")
    print(f"   LOSERS, rose first   {prof(upfirst)}")
    print("\nTOO HIGH? result by how far above the 30-min low the buy was (x daily ATR):")
    for a_, b2 in ((0, 0.15), (0.15, 0.3), (0.3, 0.5), (0.5, 0.8), (0.8, 9)):
        Z = [x for x in X if a_ <= x["up_from_low_atr"] < b2]
        if Z: print(f"   {a_:.2f}-{b2:.2f} ATR above the low: n {len(Z):4} | +2% first {np.mean([z['f2'] == 1 for z in Z]):3.0%} / -2% first {np.mean([z['f2'] == -1 for z in Z]):3.0%} | higher after 15m {np.mean([z['c15'] > 0 for z in Z]):3.0%} | sloped down right away {np.mean([z['r15'] < 0.5 for z in Z]):3.0%}")
    print("\nby range position at the buy:")
    for a_, b2, lab in ((-9, 0.25, "< 0.25"), (0.25, 0.5, "0.25-0.5"), (0.5, 1.0, "0.5-1.0 (breakout rule)"), (1.0, 1.5, "1.0-1.5 just above resistance"), (1.5, 99, "> 1.5 well above")):
        Z = [x for x in X if a_ <= x["pos"] < b2]
        if Z: print(f"   {lab:30}: n {len(Z):4} | +2% first {np.mean([z['f2'] == 1 for z in Z]):3.0%} / -2% first {np.mean([z['f2'] == -1 for z in Z]):3.0%} | higher after 15m {np.mean([z['c15'] > 0 for z in Z]):3.0%}")
    rec = sorted([x for x in L if x["day"] >= "2026-10-12"], key=lambda x: x["d30"])
    print("\nrecent losers (for charts):", ", ".join(f"{x['day'][5:]} {x['sym']} {9 + (30 + x['t']) // 60}:{(30 + x['t']) % 60:02d} #{x['pid']} r15 {x['r15']:+.1f} d30 {x['d30']:+.1f} lowATR {x['up_from_low_atr']:.2f}" for x in rec[:14]))
    print("EVAL6_ANALYSIS_DONE")
