"""eval6b.py collect A..B OUT | analyze OUT.. -- [2026-10-28] the user: for the v2 losers, did the price rise at least +2% above the buy AT ANY
TIME during the rest of the day? Per buy (rule v2, VWAP rising): did it hit +2% before the close, the minute it got there, the deepest drop
BEFORE it got there, the best price to the close, and the close."""
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()); M = [R.minute(x["t"]) for x in bars]
            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 = M[i]
                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"]; rest = [z for z, m in zip(bars[bi:], M[bi:]) if m <= 385]
                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
                hit = next((k for k, z in enumerate(rest) if z["h"] >= P * 1.02), None)
                low_before = min(z["l"] for z in rest[:hit + 1]) if hit is not None else min(z["l"] for z in rest)
                out.write(json.dumps(dict(day=day, sym=s, t=t, f2=f2, hit2=hit is not None, hit_min=hit, low_before=round((low_before / P - 1) * 100, 3),
                                          best=round((max(z["h"] for z in rest) / P - 1) * 100, 3), close=round((rest[-1]["c"] / P - 1) * 100, 3))) + "\n")
        del d; R.REF._CACHE.clear()
    out.close(); print("EV6B_DONE")
else:
    X = [json.loads(l) for f in sys.argv[2:] for l in open(f)]
    def show(lab, Z):
        if not Z: return
        H = [z for z in Z if z["hit2"]]
        print(f"{lab}: {len(Z)} buys")
        print(f"   rose to +2% above the buy at SOME time before 15:55: {len(H)} ({len(H) / len(Z):.0%})")
        if H:
            m = lambda k, ZZ: np.median([z[k] for z in ZZ])
            print(f"      when: median {m('hit_min', H):.0f} min after the buy (25% within {np.percentile([z['hit_min'] for z in H], 25):.0f} min, 75% within {np.percentile([z['hit_min'] for z in H], 75):.0f} min)")
            print(f"      how deep it went BEFORE reaching +2%: median {m('low_before', H):+.2f}% (25% of them went below {np.percentile([z['low_before'] for z in H], 25):+.2f}%)")
            for th in (-2, -3, -4, -5):
                print(f"      reached +2% after first dropping below {th}%: {sum(1 for z in H if z['low_before'] <= th)} buys", end="")
                print(f"  ({sum(1 for z in H if z['low_before'] <= th) / max(1, sum(1 for z in Z if z['low_before'] <= th or (not z['hit2'] and z['low_before'] <= th))):.0%} of all that dropped that far)")
        N = [z for z in Z if not z["hit2"]]
        if N: print(f"   never reached +2%: {len(N)} | best price median {np.median([z['best'] for z in N]):+.2f}% | close median {np.median([z['close'] for z in N]):+.2f}% | lowest median {np.median([z['low_before'] for z in N]):+.2f}%")
    print(f"{len(X)} v2 buys (VWAP rising), {min(x['day'] for x in X)}..{max(x['day'] for x in X)}; measured from the buy price to 15:55\n")
    show("LOSERS (-2% came first)", [x for x in X if x["f2"] == -1]); print()
    show("NEITHER +2% nor -2% in the first 2 hours", [x for x in X if x["f2"] == 0]); print()
    show("WINNERS (+2% first)", [x for x in X if x["f2"] == 1]); print()
    show("ALL v2 buys", X)
    print("EV6B_ANALYSIS_DONE")
