"""runner_study.py -- [2026-10-26] analysis of the runner snapshots. (1) today: runners (rise >= 5% after T) vs the rest, medians.
(2) 2024-26: per T, buying everything = baseline; each reading in 5 groups (cuts from YEAR 1) -> C3 per trade in year 1 / year 2;
(3) trend candidates (rules written BEFORE looking: steady up-day readings) per T, year 1 / year 2."""
import json, sys
import numpy as np
F = ["ret_open", "gap", "vs_vwap", "atr", "rvol", "bs5", "bs15", "bs_all", "hl_share", "r2", "pos_day", "off_high", "max_dd", "first15",
     "price", "above_vwap_share", "breadth", "breadth_up", "peer_corr_max", "peers_corr50"]
hm = lambda T: f"{9 + (30 + T) // 60}:{(30 + T) % 60:02d}"
def med(X, k):
    v = [x[k] for x in X if x.get(k) is not None]; return np.median(v) if v else np.nan
if len(sys.argv) > 1:
    D = json.load(open(sys.argv[1]))
    print(f"(1) TODAY {sys.argv[1]}: runners = rose >= 5% after T (buy at T+1)")
    for T in sorted({x["T"] for x in D}):
        X = [x for x in D if x["T"] == T]; Rn = [x for x in X if x["rise"] >= 5]; O = [x for x in X if x["rise"] < 5]
        print(f"  {hm(T)}: {len(Rn)} runners of {len(X)} | " + " ".join(f"{k} {med(Rn, k):.2f}/{med(O, k):.2f}" for k in F if k in X[0]))
        print(f"        runners: {', '.join(sorted(x['sym'] for x in Rn))}")
S = json.load(open("runner_snap.json"))
Y1 = lambda X: [x for x in X if x["day"] < "2025-10-01"]; Y2 = lambda X: [x for x in X if x["day"] >= "2025-10-01"]
m = lambda X: f"{np.mean([x['c3'] for x in X]):+.3f}% ({len(X)})" if X else "-"
print("\n(2) 2024-26 snapshots, C3 per trade after 0.2% (stop 1.5%, arm 2%): year 1 | year 2")
for T in sorted({x["T"] for x in S}):
    X = [x for x in S if x["T"] == T]
    print(f"  {hm(T)} ALL  {m(Y1(X))} | {m(Y2(X))}   (rise>=5% share {np.mean([x['rise'] >= 5 for x in X]):.0%})")
    for k in F:
        v1 = np.array([x[k] for x in Y1(X) if x.get(k) is not None], float)
        if len(v1) < 200: continue
        q = np.quantile(v1, [0.2, 0.4, 0.6, 0.8]); g = lambda v: int(np.searchsorted(q, v))
        cells = []
        for gi in range(5):
            a = [x for x in Y1(X) if x.get(k) is not None and g(x[k]) == gi]; b = [x for x in Y2(X) if x.get(k) is not None and g(x[k]) == gi]
            cells.append(f"{np.mean([x['c3'] for x in a]):+.2f}/{np.mean([x['c3'] for x in b]):+.2f}" if a and b else "-")
        flag = " <==" if any(c != "-" and all(float(z) > 0 for z in c.split("/")) for c in cells) else ""
        print(f"     {k:16} {' | '.join(cells)}{flag}")
print("\n(3) trend candidates (steady up-day at T), C3 year 1 | year 2:")
C = {"T1 up >=2%, above VWAP >=80% of the time, higher lows >=60%, buyers 15m >=55%":
         lambda x: x["ret_open"] >= 2 and x["above_vwap_share"] >= 0.8 and x["hl_share"] >= 0.6 and x["bs15"] >= 0.55,
     "T2 T1 + smooth (R2 >= 0.6) + max drawdown < 3%": lambda x: x["ret_open"] >= 2 and x["above_vwap_share"] >= 0.8 and x["hl_share"] >= 0.6 and x["bs15"] >= 0.55 and x["r2"] >= 0.6 and x["max_dd"] < 3,
     "T3 T1 + breadth (list avg move >= +1%)": lambda x: x["ret_open"] >= 2 and x["above_vwap_share"] >= 0.8 and x["hl_share"] >= 0.6 and x["bs15"] >= 0.55 and x["breadth"] >= 1,
     "T4 T1 + moves with the group (peer corr max >= 0.5)": lambda x: x["ret_open"] >= 2 and x["above_vwap_share"] >= 0.8 and x["hl_share"] >= 0.6 and x["bs15"] >= 0.55 and x["peer_corr_max"] >= 0.5,
     "T5 T1 + RVOL >= 2": lambda x: x["ret_open"] >= 2 and x["above_vwap_share"] >= 0.8 and x["hl_share"] >= 0.6 and x["bs15"] >= 0.55 and (x["rvol"] or 0) >= 2,
     "T6 T1 + near the high (off high > -1.5%)": lambda x: x["ret_open"] >= 2 and x["above_vwap_share"] >= 0.8 and x["hl_share"] >= 0.6 and x["bs15"] >= 0.55 and x["off_high"] > -1.5}
for T in sorted({x["T"] for x in S}):
    X = [x for x in S if x["T"] == T]
    for lab, f in C.items():
        Z = [x for x in X if f(x)]
        print(f"  {hm(T)} {lab[:70]:70} {m(Y1(Z))} | {m(Y2(Z))}  hit+3% {np.mean([bool(x['hit3']) for x in Z]):.0%}" if Z else f"  {hm(T)} {lab[:70]:70} -")
print("RUNNER_STUDY_DONE")
