import json, math, collections, statistics as S
import rule3
D=json.load(open('bk_clean.json'))
btc={d:v for d,v in D['btc']['line']}; bon=rule3.sma_on(sorted(btc),btc)
mj=D['majors']['line']; mon=rule3.donchian_on([d for d,_ in mj],[v for _,v in mj])
W={};RET={};R30={}
for k,v in D.items():
    if k=='btc': continue
    ds=[d for d,_ in v['line']]; L=[x for _,x in v['line']]
    _,w=rule3.run(ds,L,bon,mon,is_majors=(k=='majors'))
    W[k]=dict(zip(ds,w)); RET[k]={ds[i]:L[i+1]/L[i]-1 for i in range(len(L)-1)}
    R30[k]={ds[i]:L[i]/L[i-30]-1 for i in range(30,len(L))}
days=sorted({d for k in W for d in W[k]})
def sim(K,sign=1):
    eq=0;pk=0;mdd=0;prev={};yr=collections.defaultdict(float);ex=[]
    for d in days:
        if d<'2023-01-01': continue
        o=[(k,W[k][d]) for k in W if W[k].get(d,0)>0 and d in RET[k]]
        o=sorted(o,key=lambda x:sign*R30[x[0]].get(d,-9))[::-1][:K]
        wt={k:w/K for k,w in o}
        turn=sum(abs(wt.get(k,0)-prev.get(k,0)) for k in set(wt)|set(prev))
        r=sum(x*RET[k][d] for k,x in wt.items())-turn*0.005; prev=wt
        lr=math.log(1+r); eq+=lr; yr[d[:4]]+=lr; pk=max(pk,eq); mdd=min(mdd,eq-pk); ex.append(sum(wt.values()))
    return eq,yr,mdd,S.mean(ex)
bd=sorted(btc); e=0;pk=0;mdd=0;yb=collections.defaultdict(float)
for i in range(len(bd)-1):
    if bd[i]<'2023-01-01': continue
    lr=math.log(btc[bd[i+1]]/btc[bd[i]]); e+=lr; yb[bd[i][:4]]+=lr; pk=max(pk,e); mdd=min(mdd,e-pk)
print("BTC",round(e*100),dict((k,round(v*100)) for k,v in yb.items()),round((math.exp(mdd)-1)*100))
res={}
for K in (1,2,3,4):
    for sg,nm in ((1,'strongest'),(-1,'weakest')):
        eq,yr,m,x=sim(K,sg); print(K,nm,round(eq*100),dict((k,round(v*100)) for k,v in yr.items()),'worst',round((math.exp(m)-1)*100),'in',round(x*100))
        res[f"{K} {nm}"]=dict(total=round(eq*100),by_year={k:round(v*100) for k,v in yr.items()},worst=round((math.exp(m)-1)*100),money_in=round(x*100))
res["btc"]=dict(total=round(e*100),by_year={k:round(v*100) for k,v in yb.items()},worst=round((math.exp(mdd)-1)*100))
ev=json.load(open('evidence4.json')); ev['rotation']=res; ev['rotation_note']="log % from Jan 2023; equal slots, unused slots in cash; 0.5% cost per change"
json.dump(ev,open('evidence4.json','w'))
