import json, math, statistics as S, collections
from stages import stage_series
exec(open('it1.py').read().split("keys=[k for k in D")[0])
keys=[k for k in D if k!='btc']
MEMES_IS={"sol_pump","sol_bonk","sol_memes","base_memes"}
def trades_don(ds,L,nin,nout,delay=0,btc=None,btc_mode=None,stop=None,hot=False,ma=None,cost=0.01):
    st=stage_series(L) if hot else None
    m=sma(L,ma) if ma else None
    out=[]; i=max(nin,nout)
    while i<len(L)-1:
        sig=L[i]>max(L[i-nin:i])
        if sig and btc_mode and not btc[i]: sig=False
        if sig and ma and (m[i] is None or L[i]<m[i]): sig=False
        if not sig: i+=1; continue
        j0=i+delay
        if j0>=len(L)-1: break
        ent=L[j0]; ex=None; why=''
        for j in range(j0+1,len(L)):
            if L[j]<min(L[j-nout:j]): ex=j; why='low'; break
            if stop and L[j]/ent-1<=-stop: ex=j; why='stop'; break
            if hot and st[j][0]=='HOT': ex=j; why='hot'; break
            if btc_mode=='always' and not btc[j]: ex=j; why='btc'; break
        if ex is None: break
        out.append(dict(sig=ds[i],ret=L[ex]/ent-1-cost,bars=ex-j0,why=why)); i=ex+1
    return out
def bt_on(ds):
    bl=[BT.get(d) for d in ds]; o=[]
    for i in range(len(ds)):
        xs=[x for x in bl[max(0,i-99):i+1] if x]
        o.append(bool(bl[i] and len(xs)>=90 and bl[i]>sum(xs)/len(xs)))
    return o
def st_(ts):
    xs=[t['ret'] for t in ts]
    if not xs: return "n=0"
    w=[x for x in xs if x>0]; l=[x for x in xs if x<=0]
    pf=sum(w)/-sum(l) if l else 9
    return f"n={len(xs):3d} mean {S.mean(xs)*100:+5.1f}% med {S.median(xs)*100:+5.1f}% win {len(w)/len(xs)*100:3.0f}% PF {pf:4.2f} sum {sum(math.log(1+x) for x in xs)*100:+6.0f}%"
V={'D30/15':dict(nin=30,nout=15),'D20/10':dict(nin=20,nout=10),'D40/20':dict(nin=40,nout=20),
   'D30/15 next-day entry':dict(nin=30,nout=15,delay=1),
   'D30/15 BTC on at entry':dict(nin=30,nout=15,btc_mode='entry'),
   'D30/15 BTC on always':dict(nin=30,nout=15,btc_mode='always'),
   'D30/15 stop12':dict(nin=30,nout=15,stop=0.12),
   'D30/15 sell HOT':dict(nin=30,nout=15,hot=True),
   'D30/15 above MA100':dict(nin=30,nout=15,ma=100),
   'D30/15 BTC entry + MA100':dict(nin=30,nout=15,btc_mode='entry',ma=100)}
for nm,kw in V.items():
    G=collections.defaultdict(list)
    for k in keys:
        ds=[d for d,_ in D[k]['line']]; L=[v for _,v in D[k]['line']]
        ts=trades_don(ds,L,btc=bt_on(ds),**kw)
        for t in ts:
            G['all'].append(t)
            G['H1 <Sep24' if t['sig']<'2024-09-01' else 'H2 >=Sep24'].append(t)
            G['memes' if 'meme' in k or k in ('sol_pump','sol_bonk') else ('majors' if k=='majors' else 'non-memes')].append(t)
    print("\n==",nm)
    for g in ('all','H1 <Sep24','H2 >=Sep24','memes','non-memes','majors'): print(f"  {g:12s}",st_(G[g]))
