"""Copy Strategy (MicroStrategy): buy and sell the same day, in the same proportion, scaled so total buys = $10,000.
Uses only official ledger rows (row_type=ledger). Prices: Binance BTCUSDT daily close. PerpRoom, 2026-11. Free to use."""
import pandas as pd, json
p=pd.read_csv("strategy_bitcoin_purchases_128.csv",encoding="utf-8-sig")
p=p[p.row_type=="ledger"].copy()
p["d"]=pd.to_datetime(p.period_end.fillna(p.ledger_date))
p=p.sort_values("d")
px=pd.read_csv("btcusdt_daily_close.csv",parse_dates=["date"]).set_index("date").close
buys=p[p.btc_acquired>0]; S=10000/buys.usd_spent.sum()
def curve(df,with_sales=True):
    btc=inv=cash=0.0; rows=[]
    ev=df.groupby("d").agg(b=("btc_acquired","sum"),u=("usd_spent","sum"))
    for day,c in px.items():
        if day in ev.index:
            e=ev.loc[day]
            if e.b>0: btc+=e.b*S; inv+=e.u*S
            elif with_sales: btc+=e.b*S; cash+=abs(e.u)*S
        rows.append((day,btc,inv,btc*c+cash,cash))
    return pd.DataFrame(rows,columns=["date","btc","invested","value","cash"]).set_index("date")
def stats(c):
    c=c[c.invested>0]; pl=c.value/c.invested-1
    last=c.iloc[-1]; pk=pl.idxmax()
    under=(c.value<c.invested)
    streak=0
    for v in under[::-1]:
        if v: streak+=1
        else: break
    yr={str(y):round(float(pl[pl.index.year==y].iloc[-1])*100,1) for y in range(2020,2027)}
    return {"invested":round(last.invested,2),"btc":round(last.btc,6),"value":round(last.value,2),"pl_pct":round(float(pl.iloc[-1])*100,1),
     "avg_cost":round(last.invested/ (last.btc if last.cash==0 else last.btc),0),
     "best_pl_pct":round(float(pl.max())*100,1),"best_date":str(pk.date()),"value_at_best":round(c.value[pk],2),"invested_at_best":round(c.invested[pk],2),
     "worst_pl_pct":round(float(pl.min())*100,1),"worst_date":str(pl.idxmin().date()),
     "days_underwater_total":int(under.sum()),"days_total":len(c),"current_underwater_streak_days":streak,
     "year_end_pl_pct":yr,"cash_from_sales":round(last.cash,2)}
out={"scale_note":"total buys $%.3fB scaled to $10,000 (1/%.0f)"%(buys.usd_spent.sum()/1e9,1/S),
 "price_last":{"date":str(px.index[-1].date()),"close":float(px.iloc[-1])},
 "mirror_with_sales":stats(curve(p,True)),"mirror_never_sell":stats(curve(p,False))}
# Compare: same $10,000 in equal weekly buys over the same period, and all-in on day one
w=px[px.index>=p.d.min()].resample("W").first()
dca_btc=(10000/len(w)/w).sum(); out["dca_weekly_same_period"]={"weeks":len(w),"value":round(dca_btc*px.iloc[-1],2),"pl_pct":round((dca_btc*px.iloc[-1]/10000-1)*100,1),"avg_cost":round(10000/dca_btc,0)}
first=px[p.d.min()]; out["lump_sum_day1"]={"price":float(first),"value":round(10000/first*px.iloc[-1],2)}
# Share of dollars spent per year
by=buys.groupby(buys.d.dt.year).agg(usd=("usd_spent","sum"),btc=("btc_acquired","sum"))
out["buys_by_year"]={str(y):{"share_of_dollars_pct":round(r.usd/buys.usd_spent.sum()*100,1),"avg_price":round(r.usd/r.btc,0)} for y,r in by.iterrows()}
json.dump(out,open("mirror_result.json","w",encoding="utf-8"),ensure_ascii=False,indent=1)
print(json.dumps(out,ensure_ascii=False,indent=1))
