"""Gold September / November component tests on Dukascopy-derived bid/ask bars.

This is an EUR CFD accounting research model, NOT a broker/tick FTMO certification.
Source: Quantpedia, 2018-08-06, original rule combines September and November.
Usage: python backtest.py --data-dir data --out results
"""
from __future__ import annotations
import argparse, dataclasses, hashlib, json, math, os, tempfile
os.environ.setdefault("MPLCONFIGDIR",os.path.join(tempfile.gettempdir(),"edgequant-matplotlib"))
from pathlib import Path
import numpy as np
import pandas as pd
import matplotlib
matplotlib.use('Agg')
import matplotlib.pyplot as plt

SOURCE='https://quantpedia.com/an-extensive-test-of-market-timing-strategies-in-the-gold-market/'
START=pd.Timestamp('2016-01-01',tz='UTC'); END=pd.Timestamp('2026-01-01',tz='UTC')

@dataclasses.dataclass(frozen=True)
class Config:
    initial_eur: float=10000.0
    slippage_usd_per_oz: float=0.10
    commission_usd_per_lot_side: float=3.50
    contract_oz: float=100.0
    lot_step: float=0.01
    min_lot: float=0.01
    funding_annual: float=0.05
    seconds_per_year: float=365*86400
    bar_seconds: int=300

def usd_eur(value:float,bid:float,ask:float)->float:
    return value/(ask if value>=0 else bid)

def load_data(directory:Path):
    paths={s:directory/f'{s}_5m.csv.gz' for s in ['XAUUSD','EURUSD']}
    if not all(p.exists() for p in paths.values()):
        raise FileNotFoundError('Both genuine XAUUSD_5m.csv.gz and EURUSD_5m.csv.gz are required; no proxy or fixed FX substitution.')
    frames={}; provenance={}
    for symbol,path in paths.items():
        manifests=list(directory.glob(path.name.replace('.csv.gz','')+'*.json'))
        if not manifests:
            manifests=[p for p in directory.glob('*.json') if symbol in p.name]
        if not manifests: raise ValueError(f'Missing data provenance manifest for {symbol}')
        digest=hashlib.sha256(path.read_bytes()).hexdigest()
        manifest=json.loads(manifests[0].read_text())
        expected=manifest.get('file_sha256') or manifest.get('sha256')
        if expected and expected!=digest: raise ValueError(f'Manifest hash mismatch: {symbol}')
        df=pd.read_csv(path,parse_dates=['timestamp']); df['timestamp']=pd.to_datetime(df['timestamp'],utc=True)
        df=df[(df.timestamp>=START)&(df.timestamp<END)].reset_index(drop=True)
        cols=[f'{side}_{field}' for side in ['bid','ask'] for field in ['open','high','low','close']]
        values=df[cols].to_numpy(float)
        if not np.isfinite(values).all() or (values<=0).any(): raise ValueError(f'Invalid prices: {symbol}')
        if not df.timestamp.is_monotonic_increasing or df.timestamp.duplicated().any(): raise ValueError('Nonunique/unsorted timestamps')
        if (df.ask_open<df.bid_open).any() or (df.ask_close<df.bid_close).any(): raise ValueError('Crossed opening/closing quotes')
        years=df.groupby(df.timestamp.dt.year).size().to_dict()
        if set(years)!=set(range(2016,2026)) or min(years.values())<1000: raise ValueError(f'Incomplete calendar years: {years}')
        if df.timestamp.iloc[0]>START+pd.Timedelta(days=10) or df.timestamp.iloc[-1]<END-pd.Timedelta(days=10): raise ValueError('Incomplete outer dates')
        frames[symbol]=df
        provenance[symbol]={'path':path.name,'sha256':digest,'manifest':manifests[0].name,'source':manifest.get('source'),
            'attribution':manifest.get('attribution'),'rows':len(df),'years':years,'first':str(df.timestamp.iloc[0]),'last':str(df.timestamp.iloc[-1])}
    g=frames['XAUUSD']; f=frames['EURUSD'][['timestamp','bid_open','ask_open','bid_close','ask_close']].copy()
    f=f.rename(columns={c:'fx_'+c for c in f if c!='timestamp'}); f['fx_timestamp']=f.timestamp
    joined=pd.merge_asof(g,f,on='timestamp',direction='backward')
    if joined.fx_timestamp.isna().any(): raise ValueError('No prior FX quote at start of gold history')
    stale=(joined.timestamp-joined.fx_timestamp).dt.total_seconds()
    if stale.max()>7*86400: raise ValueError('FX quote more than a week old')
    # Exact same-time FX open is available for gold open. For missing FX bars,
    # use the previous bar close, which is already observed, never a future close.
    prior=stale>0
    for side in ['bid','ask']:
        joined.loc[prior,'fx_'+side+'_open']=joined.loc[prior,'fx_'+side+'_close']
    provenance['alignment']={'fx_exact_timestamp_fraction':float((stale==0).mean()),'fx_stale_max_seconds':float(stale.max()),
        'missing_gold_bars_filled':0,'currency_alignment':'backward only; exact opens or known previous close; no future FX observations'}
    return joined,provenance

def simulate(df:pd.DataFrame,month:int|None,cfg:Config=Config(),label:str|None=None):
    label=label or ('Buy and hold' if month is None else ('September' if month==9 else 'November'))
    ts=df.timestamp.astype('int64').to_numpy()/1e9
    fx_age=(df.timestamp-df.fx_timestamp).dt.total_seconds().to_numpy() if 'fx_timestamp' in df else np.zeros(len(df))
    held_fx_age_max=0.;held_fx_stale_count=0;held_fx_stale_over_hour_count=0
    months=df.timestamp.dt.month.to_numpy()
    names=['bid_open','bid_close','ask_open','fx_bid_open','fx_ask_open','fx_bid_close','fx_ask_close']
    arrays={n:df[n].to_numpy(float) for n in names}
    cash=cfg.initial_eur; units=0.; entry=0.; initial_notional=0.; last_funding=0.; entry_cash=0.; entry_time=None
    fees_eur=fund_eur=0.; total_fees=total_funding=0.; held_seconds=0.; trades=[]; rows=[]
    last_month=None; yearly_entries={}
    prague_days=df.timestamp.dt.tz_convert('Europe/Prague').dt.strftime('%Y-%m-%d').to_numpy()
    day=None; day_balance=cfg.initial_eur; first_daily_breach=None; first_total_breach=None
    first_1_daily=None;first_1_trailing=None;highest_day_balance=cfg.initial_eur
    def charge(now,fxb,fxa):
        nonlocal cash,last_funding,fund_eur,total_funding,held_seconds
        if units:
            elapsed=max(0.,now-last_funding)
            cost= -usd_eur(-initial_notional*cfg.funding_annual*elapsed/cfg.seconds_per_year,fxb,fxa)
            cash-=cost; fund_eur+=cost; total_funding+=cost; held_seconds+=elapsed;last_funding=now
    def close(now,price,fxb,fxa):
        nonlocal cash,units,total_fees,fees_eur
        exitprice=price-cfg.slippage_usd_per_oz
        pnl=usd_eur(units*(exitprice-entry),fxb,fxa)
        fee= -usd_eur(-units/cfg.contract_oz*cfg.commission_usd_per_lot_side,fxb,fxa)
        cash+=pnl-fee; total_fees+=fee;fees_eur+=fee
        trades.append({'entry_utc':pd.Timestamp(entry_time,unit='s',tz='UTC').isoformat(),
            'exit_utc':pd.Timestamp(now,unit='s',tz='UTC').isoformat(),'lots':units/cfg.contract_oz,'ounces':units,
            'entry_usd_oz':entry,'exit_usd_oz':exitprice,'price_pnl_eur':pnl,'commission_eur':fees_eur,
            'funding_eur':fund_eur,'net_pnl_eur':cash-entry_cash,'balance_after_eur':cash})
        units=0.
    for i,t in enumerate(ts):
        fxb=arrays['fx_bid_open'][i];fxa=arrays['fx_ask_open'][i]
        if prague_days[i]!=day:
            day=prague_days[i];day_balance=cash;highest_day_balance=max(highest_day_balance,day_balance)
        if units:charge(t,fxb,fxa)
        desired=(month is None or months[i]==month)
        if units and not desired:close(t,arrays['bid_open'][i],fxb,fxa)
        enter=(not units and desired and (month is None and i==0 or month is not None and months[i]!=last_month))
        if enter and cash>0:
            entry=arrays['ask_open'][i]+cfg.slippage_usd_per_oz
            # Floor to whole broker lot steps; reserve the entry commission.
            lot=cash/(entry*cfg.contract_oz/fxa+cfg.commission_usd_per_lot_side/fxb)
            lot=math.floor((lot+1e-12)/cfg.lot_step)*cfg.lot_step
            if lot>=cfg.min_lot:
                entry_cash=cash;units=lot*cfg.contract_oz;initial_notional=units*entry;entry_time=t;last_funding=t
                fee= -usd_eur(-lot*cfg.commission_usd_per_lot_side,fxb,fxa)
                cash-=fee;fees_eur=fee;fund_eur=0.;total_fees+=fee
                y=pd.Timestamp(t,unit='s',tz='UTC').year;yearly_entries[y]=yearly_entries.get(y,0)+1
        if units:
            held_fx_age_max=max(held_fx_age_max,float(fx_age[i]));held_fx_stale_count+=int(fx_age[i]>0);held_fx_stale_over_hour_count+=int(fx_age[i]>3600)
        fxb=arrays['fx_bid_close'][i];fxa=arrays['fx_ask_close'][i]
        close_t=t+cfg.bar_seconds
        if units:charge(close_t,fxb,fxa)
        # Bid marking reflects immediate liquidation, with exit commission/slippage
        # accrued only upon exit, not deducted twice from floating equity.
        equity=cash+usd_eur(units*(arrays['bid_close'][i]-entry),fxb,fxa) if units else cash
        if i==len(ts)-1 and units:
            close(close_t,arrays['bid_close'][i],fxb,fxa);equity=cash
        daily_floor=day_balance-.05*cfg.initial_eur
        if equity<daily_floor and first_daily_breach is None:first_daily_breach={'utc':pd.Timestamp(close_t,unit='s',tz='UTC').isoformat(),'equity_eur':equity,'floor_eur':daily_floor}
        if equity<.9*cfg.initial_eur and first_total_breach is None:first_total_breach={'utc':pd.Timestamp(close_t,unit='s',tz='UTC').isoformat(),'equity_eur':equity,'floor_eur':.9*cfg.initial_eur}
        if equity<day_balance-.03*cfg.initial_eur and first_1_daily is None:first_1_daily={'utc':pd.Timestamp(close_t,unit='s',tz='UTC').isoformat(),'equity_eur':equity,'floor_eur':day_balance-.03*cfg.initial_eur}
        if equity<highest_day_balance-.10*cfg.initial_eur and first_1_trailing is None:first_1_trailing={'utc':pd.Timestamp(close_t,unit='s',tz='UTC').isoformat(),'equity_eur':equity,'floor_eur':highest_day_balance-.10*cfg.initial_eur}
        rows.append((close_t,equity,cash,units))
        last_month=months[i]
    curve=pd.DataFrame(rows,columns=['unix','equity_eur','balance_eur','ounces'])
    curve.index=pd.to_datetime(curve.pop('unix'),unit='s',utc=True);curve.index.name='timestamp'
    daily=curve.resample('1D').last().reindex(pd.date_range(START,END-pd.Timedelta(days=1),freq='D',name='timestamp')).ffill()
    daily[['equity_eur','balance_eur']]=daily[['equity_eur','balance_eur']].fillna(cfg.initial_eur);daily.ounces=daily.ounces.fillna(0.)
    log=pd.DataFrame(trades)
    info={'label':label,'held_fx_max_quote_age_seconds':held_fx_age_max,'held_bars_with_stale_fx':held_fx_stale_count,'held_bars_with_fx_older_than_hour':held_fx_stale_over_hour_count,'funding_eur':total_funding,'commission_eur':total_fees,'exposure_time_pct':100*held_seconds/(END-START).total_seconds(),
        'entries_by_year':yearly_entries,'screen_2step':{'classification':'static-total-loss sampled breach under model' if first_total_breach else 'approximate daily-loss flag; pass NOT certified' if first_daily_breach else 'no sampled breach; pass NOT certified',
        'approximate_daily_loss_flag':first_daily_breach,'daily_loss_breach':first_daily_breach,'total_loss_breach':first_total_breach,
        'limits':'EUR500 daily loss from sampled balance at first quote of Prague day; EUR9000 static equity floor',
        'scope':'single continuous account from 2016; no phase restart or target-based exit; sampled bar-close equity only',
        'limitations':'Daily flags are approximate, not definitive breach proof: day balance uses first quoted timestamp, not reconstructed exact midnight. 00:00 Prague may fall inside missing/session bars. No tick path, actual historical broker swaps, spread beyond candles, target/verification reset, or funded restrictions. Minimum four opening days is not the same as four held days.'}}
    closed_by_day=log.groupby(pd.to_datetime(log.exit_utc,utc=True).dt.tz_convert('Europe/Prague').dt.date).net_pnl_eur.sum() if len(log) else pd.Series(dtype=float)
    net_closed=float(log.net_pnl_eur.sum()) if len(log) else 0.
    best_closed=float(closed_by_day.max()) if len(closed_by_day) else 0.
    info['screen_1step']={'classification':'approximate screening only; pass NOT certified',
        'approximate_daily_loss_flag':first_1_daily,'approximate_trailing_loss_flag':first_1_trailing,
        'total_net_closed_profit_eur':net_closed,'best_closed_profit_day_eur':max(0.,best_closed),
        'best_day_share_of_net_profit_pct':100*max(0.,best_closed)/net_closed if net_closed>0 else None,
        'consistency_condition_at_end':bool(best_closed<=.5*net_closed) if net_closed>0 else False,
        'profit_target_eur':.10*cfg.initial_eur,'ending_closed_profit_meets_target':net_closed>=.10*cfg.initial_eur,
        'rule_date':'new orders on or after 2026-10-12; best closed-profit day <=50% total net closed profit, including losing days',
        'limits':'3% daily initial capital; 10% initial capital below highest prior Prague-midnight balance (floored at initial capital)',
        'limitations':'First observed balance of each Prague day approximates midnight; no intrabar tick path, actual swaps, target-based stop, restart, or full challenge replay.'}
    return daily,log,info,curve

def metrics(daily:pd.DataFrame,trades:pd.DataFrame,initial:float=10000.):
    eq=daily.equity_eur;ret=eq.pct_change();ret.iloc[0]=eq.iloc[0]/initial-1
    peak=np.maximum.accumulate(np.r_[initial,eq.to_numpy()])[1:];dd=eq.to_numpy()-peak;ddpct=eq.to_numpy()/peak-1
    net=float(eq.iloc[-1]-initial); years=len(eq)/365.25
    pnl=trades.net_pnl_eur.to_numpy() if len(trades) else np.array([])
    wins=float(pnl[pnl>0].sum());losses=float(-pnl[pnl<0].sum())
    return {'initial_eur':initial,'final_equity_eur':float(eq.iloc[-1]),'net_profit_eur':net,'total_return_pct':net/initial*100,
        'cagr_pct':100*((eq.iloc[-1]/initial)**(1/years)-1) if eq.iloc[-1]>0 else None,
        'max_drawdown_eur':float(-dd.min()),'max_drawdown_pct':float(-ddpct.min()*100),
        'profit_factor':wins/losses if losses>0 else None,'sharpe':float(ret.mean()/ret.std(ddof=1)*np.sqrt(365)) if ret.std(ddof=1)>0 else None,
        'recovery_factor':net/float(-dd.min()) if dd.min()<0 else None,'closed_trades':len(pnl),
        'win_rate_pct':float((pnl>0).mean()*100) if len(pnl) else None,
        'best_daily_return_pct':float(ret.max()*100),'worst_daily_return_pct':float(ret.min()*100)}

def safe_json(obj):
    if isinstance(obj,dict):return {k:safe_json(v) for k,v in obj.items()}
    if isinstance(obj,list):return [safe_json(x) for x in obj]
    if isinstance(obj,np.generic):return obj.item()
    if isinstance(obj,float) and not np.isfinite(obj):return None
    return obj

def run(directory:Path,out:Path):
    df,prov=load_data(directory);out.mkdir(exist_ok=True,parents=True);cfg=Config()
    results={}; curves={}
    for slug,month,label in [('september',9,'September only'),('november',11,'November only'),('buy_hold',None,'Buy and hold')]:
        daily,trades,info,sampled=simulate(df,month,cfg,label)
        daily.to_csv(out/f'{slug}_daily_equity.csv',float_format='%.8f');trades.to_csv(out/f'{slug}_trades.csv',index=False,float_format='%.8f')
        row={**metrics(daily,trades),**info}; row['sampled_max_drawdown_pct']=float((1-sampled.equity_eur/np.maximum.accumulate(np.r_[cfg.initial_eur,sampled.equity_eur.to_numpy()])[1:]).max()*100)
        row['diagnostic_splits']={}
        for a,b in [('2016','2020'),('2021','2025')]:
            subset=daily.loc[a:b]; before=daily[daily.index<subset.index[0]]
            initial=float(before.equity_eur.iloc[-1]) if len(before) else cfg.initial_eur
            ts=pd.to_datetime(trades.exit_utc,utc=True)
            # Trade PF for split uses completed trades; buyhold's full-decade trade
            # belongs to neither diagnostic split to avoid allocating its whole P&L.
            entry=pd.to_datetime(trades.entry_utc,utc=True)
            subtrades=trades[(entry>=subset.index[0])&(ts<subset.index[-1]+pd.Timedelta(days=1))]
            m=metrics(subset,subtrades,initial);m['trade_metric_scope']='only trades fully contained in split; buyhold trade PF undefined'
            row['diagnostic_splits'][a+'-'+b]=m
        yr=daily.equity_eur.resample('YE').last(); yrret=yr.pct_change();yrret.iloc[0]=yr.iloc[0]/cfg.initial_eur-1
        row['annual_returns_pct']={str(t.year):float(v*100) for t,v in yrret.items()}
        results[slug]=row;curves[slug]=daily
    report={'status':'completed historical research model','period':'2016-01-01 through 2025-12-31 UTC','source_rule':SOURCE,
        'cases':'September only and November only are separate components of the source combined calendar rule; buyhold is benchmark.',
        'config':dataclasses.asdict(cfg),'data':prov,'results':results,
        'limitations':['EV Trading Labs aggregates Dukascopy ticks; these are third-party aggregates, not a direct bank export or FTMO broker history.',
          'Funding is an assumed 5% annual debit on entry USD notional accrued across all calendar time. It is not measured historical swap. Cash earns zero interest.',
          'No parameter optimization. 2016-2020 and 2021-2025 are retrospective diagnostic splits; 2018 source publication overlaps first split; neither is a prospective untouched out-of-sample experiment.',
          'Gold CFD P&L is converted into EUR; this is not physical gold priced in EUR, where FX changes also revalue principal.',
          'Profit factor and win rate derive from closed trades net of funding and commissions. Buyhold has one trade, so its trade PF often is undefined and not comparable.',
          'Maximum drawdown and Sharpe headline metrics use calendar daily close equity. A separate sampled bar-close maximum drawdown is provided; neither captures the tick path.',
          'FTMO is an incomplete historical model screen, never a claimed certification. One annual trade in each case is ill suited to the four separate opening-days-per-phase rule.']}
    (out/'summary.json').write_text(json.dumps(safe_json(report),indent=2)+'\n')
    pd.DataFrame({k:{key:val for key,val in v.items() if isinstance(val,(int,float,str)) or val is None} for k,v in results.items()}).T.to_csv(out/'summary.csv',index_label='case')
    charts(curves,results,out)
    print(json.dumps(safe_json({k:{x:v[x] for x in ['final_equity_eur','net_profit_eur','profit_factor','sharpe','max_drawdown_pct','recovery_factor','closed_trades']} for k,v in results.items()}),indent=2))

def charts(curves,results,out):
    plt.rcParams.update({'figure.facecolor':'#101b17','axes.facecolor':'#101b17','axes.edgecolor':'#648171','text.color':'#e7eee8','axes.labelcolor':'#e7eee8','xtick.color':'#bac9bc','ytick.color':'#bac9bc','grid.color':'#34483d','font.size':10,'savefig.facecolor':'#101b17'})
    colors={'september':'#d4ed8d','november':'#70bfd0','buy_hold':'#d9a678'}
    fig,ax=plt.subplots(2,1,figsize=(12,8),sharex=True)
    for key,d in curves.items():
        ax[0].plot(d.index,d.equity_eur,label=results[key]['label'],color=colors[key],lw=1.5)
        peak=np.maximum.accumulate(np.r_[10000,d.equity_eur.to_numpy()])[1:]
        ax[1].plot(d.index,100*(d.equity_eur/peak-1),color=colors[key],lw=1.3)
    ax[0].set(ylabel='Equity (EUR)',title='Gold calendar components | EUR 10,000 | 2016–2025')
    ax[1].set(ylabel='Drawdown (%)',xlabel='UTC date');ax[0].legend(facecolor='#101b17',labelcolor='#e7eee8')
    for a in ax:a.grid(alpha=.35)
    fig.text(.5,.01,'Dukascopy via EV Trading Labs | Bid/ask + slippage + commissions + assumed 5% annual funding | Historical model',ha='center',fontsize=8,color='#bac9bc')
    fig.tight_layout(rect=(0,.03,1,1));fig.savefig(out/'equity_drawdown.png',dpi=160);plt.close(fig)
    fig,axs=plt.subplots(2,3,figsize=(12,7))
    specs=[('net_profit_eur','Net profit (EUR)'),('profit_factor','Trade profit factor'),('sharpe','Annualized daily Sharpe'),('recovery_factor','Recovery factor'),('cagr_pct','CAGR (%)'),('max_drawdown_pct','Daily max drawdown (%)')]
    for ax,(field,title) in zip(axs.flat,specs):
        for i,(key,v) in enumerate(results.items()):
            val=v[field]
            if val is None:ax.text(i,0,'undefined',rotation=90,ha='center',va='bottom',fontsize=8,color='#bac9bc')
            else:ax.bar(i,val,color=colors[key]);ax.annotate(f'{val:,.2f}',(i,val),ha='center',va='bottom' if val>=0 else 'top',fontsize=8)
        ax.set_xticks(range(3),['Sep','Nov','B&H']);ax.set_title(title);ax.axhline(0,color='#648171',lw=.7);ax.grid(axis='y',alpha=.25)
    fig.suptitle('After modeled costs | two calendar cases and buy-and-hold benchmark')
    fig.text(.5,.01,'Trade PF for a single buy-and-hold trade is not a meaningful cross-strategy risk comparison. Sharpe risk-free rate = 0.',ha='center',fontsize=8,color='#bac9bc')
    fig.tight_layout(rect=(0,.04,1,.96));fig.savefig(out/'performance_metrics.png',dpi=160);plt.close(fig)
    fig,ax=plt.subplots(figsize=(12,5))
    for k,d in curves.items():ax.plot(d.index,d.equity_eur-10000,label=results[k]['label'],color=colors[k],lw=1.5)
    ax.axhline(0,color='#648171',lw=.7);ax.set(ylabel='Cumulative net P&L (EUR)',xlabel='UTC date',title='Gold CFD modeled profit on an EUR 10,000 account')
    ax.legend(facecolor='#101b17',labelcolor='#e7eee8');ax.grid(alpha=.25);fig.tight_layout();fig.savefig(out/'profit.png',dpi=160);plt.close(fig)
    fig,ax=plt.subplots(figsize=(12,5));xs=np.arange(10);w=.25
    for i,(k,v) in enumerate(results.items()):ax.bar(xs+(i-1)*w,list(v['annual_returns_pct'].values()),w,label=v['label'],color=colors[k])
    ax.set_xticks(xs,range(2016,2026));ax.set_ylabel('Return (%)');ax.set_title('Calendar-year returns after modeled costs');ax.legend(facecolor='#101b17',labelcolor='#e7eee8');ax.grid(axis='y',alpha=.25);fig.tight_layout();fig.savefig(out/'annual_returns.png',dpi=160);plt.close(fig)

if __name__=='__main__':
    p=argparse.ArgumentParser(description=__doc__);p.add_argument('--data-dir',type=Path,default=Path(__file__).parent/'data');p.add_argument('--out',type=Path,default=Path(__file__).parent/'results');a=p.parse_args();run(a.data_dir,a.out)
