"""t935.py collect A..B OUT | analyze OUT.. -- [2026-10-31] user's #42 option: BUY AT 9:35 (the 9:35 bar's open, bars 9:30-9:34 known) if EMA9 AND VWAP
are rising (each higher than 1 and 2 bars before) and the last 3 bars' volume is right for the time of day (>= the 14-day normal for those
minutes); V2/V3 = + 3m buy share >= 50% / 55%; V0 = no volume check. SELL (bar close -> next open) when EMA9 flat/down (<= the bar before) +
volume fade (last 3 bars < the 3 before) + buy share fade (3m < 15m): ALL3 | ANY2 | EMA9-only; + 3% safety stop + 15:55. Also the trade bot's
C3 (sim_2y, 2% stop). Baseline: every stock bought at 9:35. 0.2% cost."""
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)); sys.path.insert(0, str(TR / "reports/ev3"))
COST = 0.2
def rise(b, bi, P):
    f2 = 0
    for z in b[bi:bi + 120]:
        if z["l"] <= P * 0.98: f2 = -1; break
        if z["h"] >= P * 1.02: f2 = 1; break
    return dict(r60=round((max(z["h"] for z in b[bi:bi + 60]) / P - 1) * 100, 3), d30=round((min(z["l"] for z in b[bi:bi + 30]) / P - 1) * 100, 3), f2=f2)
if sys.argv[1] == "collect":
    import v2_bar_replay as R
    from queue_test import Day
    from sim_2y import sim
    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"))
        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("vol_per_min") or not ref.get("prev_close"): continue
            bars = [x for x in R.bars_of(d["symbols"][s]["bars"]) if 0 <= R.minute(x["t"]) < 390]
            if len(bars) < 300 or [R.minute(x["t"]) for x in bars[:6]] != [0, 1, 2, 3, 4, 5]: continue
            M = [R.minute(x["t"]) for x in bars]; fl = json.loads(fp.read_text()); fb, fs = fl["buy"], fl["sell"]; vpm = ref["vol_per_min"]
            C = [x["c"] for x in bars]; V = [x["v"] for x in bars]
            E9, VW = [], []; e9 = C[0]; cv = pv = 0
            for x in bars:
                e9 += (x["c"] - e9) * 0.2; E9.append(e9); cv += x["v"]; pv += (x["h"] + x["l"] + x["c"]) / 3 * x["v"]; VW.append(pv / max(cv, 1))
            sh = lambda m, k: sum(fb[max(0, m - k + 1):m + 1]) / max(sum(fb[max(0, m - k + 1):m + 1]) + sum(fs[max(0, m - k + 1):m + 1]), 1)
            i = 4; bi = 5; P = bars[bi]["o"]
            up = E9[4] > E9[3] > E9[2] and VW[4] > VW[3] > VW[2]
            vol = sum(V[2:5]) >= sum(vpm[2:5]); s3 = sh(4, 3)
            kinds = ["ALL"] + ([k for k, ok in (("V0", up), ("V1", up and vol), ("V2", up and vol and s3 >= 0.5), ("V3", up and vol and s3 >= 0.55)) if ok])
            end = max(j for j in range(len(bars)) if M[j] <= 385)
            def ex(rule):
                stop = P * 0.97
                for j in range(bi, end + 1):
                    x = bars[j]
                    if x["l"] <= stop: return round((min(stop, x["o"]) if j > bi else stop) / P * 100 - 100 - COST, 3), M[j] - M[bi]
                    if j >= bi + 1 and j + 1 <= end and j >= 5:
                        f1 = E9[j] <= E9[j - 1]; f2_ = sum(V[j - 2:j + 1]) < sum(V[j - 5:j - 2]); f3 = sh(M[j], 3) < sh(M[j], 15)
                        hit = {"ALL3": f1 and f2_ and f3, "ANY2": f1 + f2_ + f3 >= 2, "EMA9": f1}[rule]
                        if hit: return round(bars[j + 1]["o"] / P * 100 - 100 - COST, 3), M[j + 1] - M[bi]
                return round(C[end] / P * 100 - 100 - COST, 3), M[end] - M[bi]
            res = {}
            for r in ("ALL3", "ANY2", "EMA9"): res[r], res[r + "_min"] = ex(r)
            pl, j, why = sim(Day(bars, M, fl, ref), bi, P, P * 0.98, 2.0, "C3"); res["C3"] = round(pl, 3)
            row = dict(day=day, sym=s, gap=round((bars[0]["o"] / ref["prev_close"] - 1) * 100, 2), up_pc=P > ref["prev_close"], **rise(bars, bi, P), **res)
            for k in kinds: out.write(json.dumps(dict(kind=k, **row)) + "\n")
        del d; R.REF._CACHE.clear(); out.flush()
    out.close(); print("T935_DONE")
else:
    X = [json.loads(l) for f in sys.argv[2:] for l in open(f)]
    Y = lambda Z, h: [z for z in Z if (z["day"] < "2025-10-01") == (h == 1)]
    def r(Z):
        a = lambda k: np.mean([z[k] for z in Z])
        return f"n {len(Z):5} | max rise 60m {a('r60'):+.2f}% | max drop 30m {a('d30'):+.2f}% | +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%}"
    def t(Z, k):
        v = np.array([z[k] for z in Z]); mn = f" hold {np.median([z[k + '_min'] for z in Z]):3.0f}m" if k + "_min" in Z[0] else ""
        return f"{v.mean():+.3f}% win {np.mean(v > 0):3.0%} {v[v > 0].mean():+.2f}/{v[v <= 0].mean():+.2f}{mn}"
    lab = {"ALL": "BASELINE: every stock bought at 9:35", "V0": "EMA9 + VWAP rising (no volume check)", "V1": "+ last 3 bars volume >= normal for the time",
           "V2": "+ volume + 3m buy share >= 50%", "V3": "+ volume + 3m buy share >= 55%"}
    xl = {"ALL3": "sell: EMA9 flat + volume fade + buy share fade (all 3)", "ANY2": "sell: any 2 of the 3", "EMA9": "sell: EMA9 flat/down only", "C3": "trade-bot C3, 2% stop"}
    print("#42 option: BUY AT 9:35, 2 years (year 1 < 2025-10-01 <= year 2); profit per trade after 0.2% cost\n")
    for k in ("ALL", "V0", "V1", "V2", "V3"):
        Z = [x for x in X if x["kind"] == k]
        print(f"{lab[k]}\n   RISE  year 1 {r(Y(Z, 1))}\n         year 2 {r(Y(Z, 2))}")
        for e in ("ALL3", "ANY2", "EMA9", "C3"): print(f"   {xl[e]:56} y1 {t(Y(Z, 1), e):42} | y2 {t(Y(Z, 2), e)}")
        print()
    print("T935_ANALYSIS_DONE")
