"""rule_study.py NAME [EXIT=c3] -- per reading: 5 groups (cut points from YEAR 1 only), per trade after 0.2% in year 1 and year 2.
Then pairs of the best single cuts (chosen on year 1) checked on year 2. A filter counts only if positive in BOTH years."""
import json, sys
from itertools import combinations
import numpy as np
name = sys.argv[1]; ex = sys.argv[2] if len(sys.argv) > 2 else "c3"
X = [x for x in json.load(open(f"{name}_feat.json"))]
F = ["minute", "gap", "atr", "vs_open", "vs_vwap", "vs_pc", "day_range", "pos_day", "off_high", "rvol", "vol15x", "bs1", "bs5", "bs15", "bs60",
     "rng15", "ch15", "ch60", "spm5", "price", "vs_prev_low", "n_today", "low_vs_vwap", "off"]
Y1 = [x for x in X if x["y1"]]; Y2 = [x for x in X if not x["y1"]]
m = lambda S: (np.mean([x[ex] for x in S]), len(S)) if S else (np.nan, 0)
print(f"{name.upper()} exit {ex}: year 1 {len(Y1)} trades {m(Y1)[0]:+.3f}%, year 2 {len(Y2)} trades {m(Y2)[0]:+.3f}%")
cands = []
for f in F:
    v1 = np.array([x[f] for x in Y1 if x.get(f) is not None], float)
    if len(v1) < 100:
        continue
    q = np.quantile(v1, [0.2, 0.4, 0.6, 0.8])
    grp = lambda v: int(np.searchsorted(q, v))
    cells = []
    for g in range(5):
        a = [x for x in Y1 if x.get(f) is not None and grp(x[f]) == g]; b = [x for x in Y2 if x.get(f) is not None and grp(x[f]) == g]
        cells.append((m(a), m(b)))
    edges = [-np.inf] + list(q) + [np.inf]
    line = " | ".join(f"{c[0][0]:+.2f}/{c[1][0]:+.2f}" for c in cells)
    print(f"  {f:12} cuts {' '.join(f'{z:.3g}' for z in q):34} y1/y2 by group: {line}")
    for g in range(5):
        for lo_g, hi_g in ((g, g), (g, 4), (0, g)):
            lo, hi = edges[lo_g], edges[hi_g + 1]
            cands.append((f, lo, hi))
def sel(S, conds):
    return [x for x in S if all(x.get(f) is not None and lo <= x[f] < hi for f, lo, hi in conds)]
single = []
for c in cands:
    a = sel(Y1, [c])
    if len(a) >= 300:
        single.append((m(a)[0], c))
single.sort(key=lambda z: -z[0])
print("\nbest single cuts on YEAR 1 (>= 300 trades) -> year 2:")
for v, c in single[:12]:
    b = sel(Y2, [c]); print(f"  {c[0]:12} [{c[1]:.3g}, {c[2]:.3g})  y1 {v:+.3f}% ({len(sel(Y1, [c]))})  y2 {m(b)[0]:+.3f}% ({len(b)})")
top = [c for _, c in single[:40]]
pairs = []
for c1, c2 in combinations(top, 2):
    if c1[0] == c2[0]:
        continue
    a = sel(Y1, [c1, c2])
    if len(a) >= 150:
        pairs.append((m(a)[0], c1, c2))
pairs.sort(key=lambda z: -z[0])
print("\nbest pairs on YEAR 1 (>= 150 trades) -> year 2:")
for v, c1, c2 in pairs[:15]:
    b = sel(Y2, [c1, c2])
    print(f"  {c1[0]} [{c1[1]:.3g},{c1[2]:.3g}) & {c2[0]} [{c2[1]:.3g},{c2[2]:.3g})  y1 {v:+.3f}% ({len(sel(Y1, [c1, c2]))})  y2 {m(b)[0]:+.3f}% ({len(b)})")
