import json, statistics as st
rows=json.load(open('winner_features.json')); POS=1670
for r in rows:
    c=r['open_close_pct']
    for L in ('1000','1030'):
        if r.get('chg_'+L) is not None:
            p=1+r['chg_'+L]/100; r['rest_'+L]=((1+c/100)/p-1)*100
def show(label, sel, L):
    s=[r for r in rows if sel(r) and r.get('rest_'+L) is not None]
    if not s: return
    v=[r['rest_'+L] for r in s]
    print(f"  {label:58} n={len(s):4} bigW {sum(r['big'] for r in s):3}  rest-of-day win {sum(x>0 for x in v)/len(s)*100:4.0f}%  avg {st.mean(v):+.2f}%  median {st.median(v):+.2f}%  ${sum(POS*x/100 for x in v):+7.0f}")
for L in ('1000','1030'):
    print(f"\n=== buy at {L[:2]}:{L[2:]}, sell at the close ===")
    show("ALL stocks", lambda r:True, L)
    for a,b in ((-100,-1),(-1,0),(0,1),(1,3),(3,100)):
        show(f"up {a}..{b}% from open", lambda r,a=a,b=b: a<=r['chg_'+L]<b, L)
    for a,b in ((-100,0),(0,1),(1,2),(2,100)):
        show(f"vs VWAP {a}..{b}%", lambda r,a=a,b=b: a<=r['vs_vwap_'+L]<b, L)
    if L=='1030':
        show("higher low (10:00-10:30 low > 9:30-10:00 low)", lambda r: r.get('higher_low_1030') is True, L)
        show("higher high", lambda r: r.get('higher_high_1030') is True, L)
        show("higher low + higher high", lambda r: r.get('higher_low_1030') and r.get('higher_high_1030'), L)
        show("HL+HH + above VWAP", lambda r: r.get('higher_low_1030') and r.get('higher_high_1030') and r['vs_vwap_1030']>0, L)
        show("HL+HH + above VWAP 0..2%", lambda r: r.get('higher_low_1030') and r.get('higher_high_1030') and 0<r['vs_vwap_1030']<2, L)
        show("HL+HH + above VWAP + ATR>=5%", lambda r: r.get('higher_low_1030') and r.get('higher_high_1030') and r['vs_vwap_1030']>0 and (r['daily_atr_pct'] or 0)>=5, L)
        show("HL+HH + above VWAP + ATR>=5% + up>=1%", lambda r: r.get('higher_low_1030') and r.get('higher_high_1030') and r['vs_vwap_1030']>0 and (r['daily_atr_pct'] or 0)>=5 and r['chg_1030']>=1, L)
        show("HL + above VWAP + up >=3%", lambda r: r.get('higher_low_1030') and r['vs_vwap_1030']>0 and r['chg_1030']>=3, L)
        show("NOT HL (made a lower low)", lambda r: r.get('higher_low_1030') is False, L)
    for k,a,b in (("daily_atr_pct",0,5),("daily_atr_pct",5,8),("daily_atr_pct",8,100),("gap_pct",5,10),("gap_pct",10,500),("chg_5d_pct",10,1000),("prev_day_chg_pct",15,1000)):
        show(f"9:28 {k} {a}..{b}", lambda r,k=k,a=a,b=b: r.get(k) is not None and a<=r[k]<b, L)
    show("big winner on an earlier day", lambda r: r['big_winner_before'], L)
