"""star_entry_report.py -- [2026-10-27] reads abl_y1.jsonl + abl_y2.jsonl (star_entry_ablation.py): per Star entry check, the trades it
blocked (they exist only when the check is removed) and what they would have made -> money the check saved; year 1 / year 2."""
import json
from collections import defaultdict
import numpy as np
DESC = {"TIMING": "0 timing: >= 15 finished bars (no buys before ~9:45)", "RVOL": "1 volume: RVOL so far >= 1.5x the 14-day normal",
        "VOL_SPIKE": "1 volume: last 15 min <= 5x normal (no spike)", "ROOM": "2 room >= 1% to 14-day resistance (or above the 14-day high)",
        "BUYSHARE": "3 buy share last 15 min >= 55%", "FALLING": "3 not falling on net selling (-1% in 30 min + net selling)",
        "SMOOTH": "4 smoothness (R2, 15 bars) >= 0.7", "STRAIGHT": "4 straightness (net move / path, 15 bars) >= 0.5",
        "EXT_OPEN": "no buy > 3% over the open unless a confirmed breakout", "VWAP": "price 0 to +2% over VWAP",
        "ACCEL": "no acceleration spike (5-bar >= 1.5 x 1-min ATR)", "LIQ": "liquidity >= 2,000 shares/min (15 min)",
        "STRETCH": "no stretched move (>= 3x normal move AND >= 4% over VWAP)",
        "EXT_ATR": "(off in Star config) hard max over the open in daily ATRs", "EXT_PREVCLOSE": "(off) max daily ATRs over yesterday's close",
        "EXT_MOVE": "(off) max x normal move", "B1": "(off) no buy right after a 10x volume bar at the high"}
T = defaultdict(lambda: defaultdict(dict))
for f, y in (("abl_y1.jsonl", "y1"), ("abl_y2.jsonl", "y2")):
    for l in open(f):
        r = json.loads(l); T[r["var"]][y][(r["day"], r["sym"], r["t"])] = r
def st(Z):
    if not Z: return dict(n=0, avg=0, s=0, up=0, dn=0)
    return dict(n=len(Z), avg=np.mean([z["pl"] for z in Z]), s=sum(z["pl"] for z in Z), up=np.mean([z["first"] == 1 for z in Z]), dn=np.mean([z["first"] == -1 for z in Z]))
A = {y: st(list(T["ALL"][y].values())) for y in ("y1", "y2")}
print("STAR ENTRY (all checks) -- C3 exit with the Star 3% safety stop, after 0.2% cost; $ = per $10,000 position")
for y, lab in (("y1", "year 1 (2024-10..2025-09)"), ("y2", "year 2 (2025-10..2026-10)")):
    a = A[y]; print(f"  {lab}: {a['n']} trades, {a['avg']:+.3f}%/trade, total {a['s']:+.1f}% = ${a['s'] * 100:+,.0f} | +1% first {a['up']:.0%} / -1% first {a['dn']:.0%}")
print("\nEACH CHECK: the trades it BLOCKED (bought only when that one check is removed) and their result; 'saved' = what the check kept you from losing")
print(f"{'check':58} | {'year 1: blocked n  avg/trade  +1%/-1% first  saved':52} | {'year 2: blocked n  avg/trade  +1%/-1% first  saved':52}")
rows = []
for var in T:
    if var == "ALL": continue
    c = var[1:]; cells = []; tot = 0
    for y in ("y1", "y2"):
        extra = [r for k, r in T[var][y].items() if k not in T["ALL"][y]]
        allv = st(list(T[var][y].values())); saved = A[y]["s"] - allv["s"]; tot += saved; e = st(extra)
        cells.append(f"{e['n']:6} {e['avg']:+.3f}%  {e['up']:3.0%}/{e['dn']:3.0%}  ${saved * 100:+9,.0f}")
    rows.append((tot, c, cells))
for tot, c, cells in sorted(rows, key=lambda x: -x[0]):
    print(f"{DESC.get(c, c)[:58]:58} | {cells[0]:52} | {cells[1]:52}")
print("\n(note: removing one check also changes which later trades happen -- one position per stock -- so 'saved' is the whole-run difference)")
