"""Edgecraft Quant educational demonstration; Python standard library only.
Run: python backtest.py --data prices.csv --out results
Data source: Yahoo Finance chart/BTC-USD daily adjusted closes, retrieved 2026-10-21.
Fixed SMA(200), long/cash, no leverage. Signal at close t executes close t+1.
Adjusted closes are a total-return proxy, not executable fill prices.
Fractional exposure, idle cash earns 0%, 10 bps one-way trading costs.
No parameter fitting. Chronological splits are retrospective, not live OOS proof.
"""
import argparse,csv,json,math,statistics
from pathlib import Path
from datetime import date

def load(path):
 with open(path,newline='') as f: rows=list(csv.DictReader(f))
 prices=[float(r['adjusted_close']) for r in rows]
 dates=[r['date'] for r in rows]
 assert dates==sorted(set(dates)), 'Dates must be unique and ordered'
 assert all(math.isfinite(p) and p>0 for p in prices)
 return dates,prices

def simulate(dates,prices,start,end,bps=10,benchmark=False):
 indices=[i for i,d in enumerate(dates) if start<=d<=end and i>=201]
 assert indices
 equity=10000.;peak=equity;dd=0.;pos=0;daily=[];curve=[];orders=[];exposure=[]
 baseline=dates[indices[0]-1]
 curve.append({'date':baseline,'equity':equity,'drawdown':0.,'position':0})
 for i in indices:
  previous=equity
  # Existing exposure earns today's close-to-close return. Yesterday's signal
  # can only change exposure at today's close; it earns no earlier return.
  exposure.append(pos)
  equity*=1+pos*(prices[i]/prices[i-1]-1)
  target=1 if benchmark else int(prices[i-1]>sum(prices[i-200:i])/200)
  # Liquidate on the last close, charging both approaches the same exit cost.
  if i==indices[-1]: target=0
  if target!=pos:
   fee=equity*bps/10000
   equity-=fee
   orders.append({'date':dates[i],'action':'BUY' if target else 'SELL','cost_usd':fee,'equity_after_cost':equity})
  pos=target
  daily.append(equity/previous-1)
  peak=max(peak,equity);drawdown=equity/peak-1;dd=min(dd,drawdown)
  curve.append({'date':dates[i],'equity':equity,'drawdown':drawdown,'position':pos})
 years=(date.fromisoformat(dates[indices[-1]])-date.fromisoformat(baseline)).days/365.25
 sd=statistics.stdev(daily)
 metrics={'start':dates[indices[0]],'baseline':baseline,'end':dates[indices[-1]],'initial':10000,'final':equity,'total_return':equity/10000-1,'cagr':(equity/10000)**(1/years)-1,'max_drawdown':dd,'sharpe_zero_rf':statistics.mean(daily)/sd*math.sqrt(365) if sd else 0,'exposure':statistics.mean(exposure),'orders':len(orders),'round_trips':len(orders)//2,'cost_bps':bps}
 return {'metrics':metrics,'curve':curve,'orders':orders}

def run(data,out):
 dates,prices=load(data);out=Path(out);out.mkdir(parents=True,exist_ok=True)
 result={}
 for name,start,end in [('full','2018-01-01','2025-12-31'),('early','2018-01-01','2021-12-31'),('later','2022-01-01','2025-12-31')]:
  result[name]={k:simulate(dates,prices,start,end,benchmark=(k=='benchmark')) for k in ['strategy','benchmark']}
 result['cost_sensitivity']=[simulate(dates,prices,'2018-01-01','2025-12-31',bps=b)['metrics'] for b in [5,10,20,50]]
 (out/'summary.json').write_text(json.dumps(result,indent=2))
 for kind in ['strategy','benchmark']:
  for field in ['curve','orders']:
   rows=result['full'][kind][field]
   with (out/f'{kind}_{field}.csv').open('w',newline='') as f:
    w=csv.DictWriter(f,fieldnames=list(rows[0]));w.writeheader();w.writerows(rows)
 return result
if __name__=='__main__':
 parser=argparse.ArgumentParser();parser.add_argument('--data',default='prices.csv');parser.add_argument('--out',default='results');args=parser.parse_args()
 r=run(args.data,args.out)
 print(json.dumps({k:r['full'][k]['metrics'] for k in ['strategy','benchmark']},indent=2))
