import json, gzip, statistics as st
from datetime import datetime
from zoneinfo import ZoneInfo
import sys; sys.path.insert(0,'/var/www/screener/trade'); from alpaca_client import get_client
ET=ZoneInfo("America/New_York"); POS=1670
rows=json.load(open('winner_features.json'))
cache={}; client=None
def bars(d,s):
    global client
    if d not in cache:
        p=f'bars/bars_{d}.json.gz'
        try: cache[d]=json.load(gzip.open(p,'rt'))['symbols']
        except FileNotFoundError: cache[d]={}
    if s in cache[d]:
        e=cache[d][s]
        return e['_b'] if '_b' in e else [(datetime.fromtimestamp(b[0],ET),*b[1:]) for b in e['bars']]
    client=client or get_client(); dd=datetime.fromisoformat(d).replace(tzinfo=ET)
    raw=client.get_minute_bars(s,start=dd.replace(hour=9,minute=30),end=dd.replace(hour=16),limit=1000)
    bl=[(b.timestamp.astimezone(ET),float(b.open),float(b.high),float(b.low),float(b.close),float(b.volume)) for b in raw]
    cache[d][s]={'_b':bl}; return bl
def sim(r, mode):
    bl=[b for b in bars(r['date'],r['symbol']) if b[0].strftime('%H:%M')<'16:00']
    pre=[b for b in bl if b[0].strftime('%H:%M')<'10:30']; post=[b for b in bl if b[0].strftime('%H:%M')>='10:30']
    if not pre or not post: return None
    entry=pre[-1][4]
    stop=min(b[3] for b in pre if b[0].strftime('%H:%M')>='10:00')   # the 10:00-10:30 higher low
    pv=sum((b[2]+b[3]+b[4])/3*b[5] for b in pre); v=sum(b[5] for b in pre)
    for b in post:
        pv+=(b[2]+b[3]+b[4])/3*b[5]; v+=b[5]; vw=pv/v
        if b[0].strftime('%H:%M')>='15:55': return (b[4]/entry-1)*100
        if mode!='hold' and b[3]<=stop: return (stop/entry-1)*100
        if mode=='vwap' and b[4]<vw: return (b[4]/entry-1)*100
    return (post[-1][4]/entry-1)*100
sets={"up>=3% + higher low + above VWAP (at 10:30)": lambda r: r.get('higher_low_1030') and r['vs_vwap_1030']>0 and r['chg_1030']>=3,
      "up>=1% + higher low + above VWAP": lambda r: r.get('higher_low_1030') and r['vs_vwap_1030']>0 and r['chg_1030']>=1,
      "higher low + higher high + above VWAP": lambda r: r.get('higher_low_1030') and r.get('higher_high_1030') and r['vs_vwap_1030']>0}
for name,sel in sets.items():
    s=[r for r in rows if sel(r)]
    print(f"\n{name}: n={len(s)}, big winners among them {sum(r['big'] for r in s)}")
    for mode,label in (('hold','hold to 15:55'),('stop','stop at 10:00-10:30 low, else hold to 15:55'),('vwap','stop at that low OR first 1-min close below VWAP')):
        v=[x for x in (sim(r,mode) for r in s) if x is not None]
        print(f"   {label:52} win {sum(x>0 for x in v)/len(v)*100:3.0f}%  avg {st.mean(v):+.2f}%  ${sum(POS*x/100 for x in v):+7.0f}  per day ${sum(POS*x/100 for x in v)/21:+.0f}  trades/day {len(v)/21:.1f}")
