"""One EURUSD three-lower-observed-weekday-closes transfer test.
Source public section34/FAQ https://quantifiedstrategies.substack.com/p/spy-trading-strategies
SPY idea adapted to UTC BID daily observations and next-quote execution.
Streamed exit on next observed source weekday completion; exit-first re-entry.
Run: python backtest.py --data-dir data --out results
"""
from __future__ import annotations
import argparse,dataclasses,hashlib,json,math,os,tempfile,sys,platform
from datetime import datetime,timezone
from pathlib import Path
os.environ.setdefault('MPLCONFIGDIR',os.path.join(tempfile.gettempdir(),'edgequant-matplotlib'))
import numpy as np
import pandas as pd
import matplotlib
matplotlib.use('Agg')
import matplotlib.pyplot as plt
SOURCE='https://quantifiedstrategies.substack.com/p/spy-trading-strategies'
START=pd.Timestamp('2016-01-01',tz='UTC');END=pd.Timestamp('2026-01-01',tz='UTC');WARMUP=pd.Timestamp('2015-01-01',tz='UTC')
@dataclasses.dataclass(frozen=True)
class Config:
    initial_eur:float=10000.
    required_strict_drops:int=3
    slippage_usd_per_unit:float=.00001
    commission_usd_per_lot_side:float=3.50
    contract_base_units:float=100000.
    lot_step:float=.01
    min_lot:float=.01
    funding_annual:float=.05
    seconds_per_year:float=365*86400
    bar_seconds:int=300
    max_entry_fx_age_seconds:int=900

def usd_eur(value,bid,ask):return value/(ask if value>=0 else bid)
def load_data(directory:Path):
    frames={};prov={}
    for pair in ['EURUSD']:
        path=directory/f'{pair}_5m.csv.gz';mp=directory/f'{pair}_5m.manifest.json'
        manifest=json.loads(mp.read_text());digest=hashlib.sha256(path.read_bytes()).hexdigest()
        if manifest.get('file_sha256')!=digest:raise ValueError(f'Manifest hash mismatch: {pair}')
        d=pd.read_csv(path,parse_dates=['timestamp']);d.timestamp=pd.to_datetime(d.timestamp,utc=True)
        d=d[(d.timestamp>=WARMUP)&(d.timestamp<END)].reset_index(drop=True)
        cols=[f'{s}_{f}' for s in ['bid','ask'] for f in ['open','high','low','close']];v=d[cols].to_numpy(float)
        if not np.isfinite(v).all() or (v<=0).any():raise ValueError('Invalid positive prices')
        if not d.timestamp.is_monotonic_increasing or d.timestamp.duplicated().any():raise ValueError('Unsorted/duplicate prices')
        if (d.ask_open<d.bid_open).any() or (d.ask_close<d.bid_close).any():raise ValueError('Crossed quotes')
        for side in ['bid','ask']:
            if ((d[side+'_low']>d[[side+'_open',side+'_close']].min(axis=1))|(d[side+'_high']<d[[side+'_open',side+'_close']].max(axis=1))).any():raise ValueError('Invalid OHLC')
        years=d.groupby(d.timestamp.dt.year).size().to_dict()
        if set(years)!=set(range(2015,2026)) or min(years.values())<1000:raise ValueError('Require genuine2015 prior context and ten evaluation years')
        frames[pair]=d;prov[pair]={'file':path.name,'sha256':digest,'manifest':mp.name,'source':manifest.get('source'),
            'attribution':manifest.get('attribution'),'rows_with_prior_context':len(d),'candles_by_year':years,
            'first_utc':str(d.timestamp.iloc[0]),'last_utc':str(d.timestamp.iloc[-1]),'imputed_bars':0}
    fx=frames['EURUSD'][['timestamp','bid_open','ask_open','bid_close','ask_close']].rename(columns={c:'fx_'+c for c in ['bid_open','ask_open','bid_close','ask_close']});fx['fx_timestamp']=fx.timestamp
    joined={}
    for pair in ['EURUSD']:
        j=pd.merge_asof(frames[pair],fx,on='timestamp',direction='backward')
        if j.fx_timestamp.isna().any():raise ValueError('No past EURUSD conversion quote')
        age=(j.timestamp-j.fx_timestamp).dt.total_seconds();j['fx_quote_age_seconds']=age
        if age.max()>7*86400:raise ValueError('FX quote more than a week old')
        prior=age>0
        for side in ['bid','ask']:j.loc[prior,'fx_'+side+'_open']=j.loc[prior,'fx_'+side+'_close']
        prov[pair]['fx_alignment']={'exact_timestamp_fraction':float((age==0).mean()),'stale_rows':int(prior.sum()),'max_quote_age_seconds':float(age.max()),
            'rule':'Backward-only; exact current FX open, otherwise known previous FX close. Entry source-bar age<=900sec; stale exit/valuation carried and disclosed.'}
        joined[pair]=j
    return joined,prov

def strict_lower(current,previous):
    epsilon=1e-12*max(1.,abs(current),abs(previous))
    return previous-current>epsilon

def three_down(closes_current_to_oldest):
    if len(closes_current_to_oldest)!=4 or not all(pd.notna(x) for x in closes_current_to_oldest):return False
    return all(strict_lower(closes_current_to_oldest[i],closes_current_to_oldest[i+1]) for i in range(3))

def build_daily_signals(quotes:pd.DataFrame):
    q=quotes.set_index('timestamp').sort_index()
    d=q.resample('1D',label='left',closed='left').agg({'bid_open':'first','bid_high':'max','bid_low':'min','bid_close':'last'})
    d=d.dropna();d=d[d.index.weekday<5].copy()
    for n in [1,2,3]:
        d['previous_close_'+str(n)]=d.bid_close.shift(n)
        d['previous_date_'+str(n)]=d.index.to_series().shift(n)
    d['four_close_context_ready']=d.previous_close_3.notna()
    d['three_down']=[three_down(v) for v in zip(d.bid_close,d.previous_close_1,d.previous_close_2,d.previous_close_3)]
    d['signal_date']=d.index;d['available_at']=d.index+pd.Timedelta(days=1);d['initial_2015_seed']=False
    before=d[d.index<START]
    if len(before):d.loc[before.index[-1],'initial_2015_seed']=True
    events=d[((d.index>=START)|d.initial_2015_seed)&(d.available_at<END)].copy()
    return d,events.reset_index(drop=True)

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 simulate(quotes:pd.DataFrame,pair:str,role:str,cfg:Config=Config()):
    if role not in ['strategy','buy_hold']:raise ValueError('Unknown role')
    _,events=build_daily_signals(quotes)
    q=quotes[(quotes.timestamp>=START)&(quotes.timestamp<END)].reset_index(drop=True)
    ts=q.timestamp.astype('int64').to_numpy()/1e9
    names=['bid_open','ask_open','bid_close','ask_close','fx_bid_open','fx_ask_open','fx_bid_close','fx_ask_close']
    a={n:q[n].to_numpy(float) for n in names};ages=q.fx_quote_age_seconds.to_numpy(float)
    fxstamps=q.fx_timestamp.astype('int64').to_numpy()/1e9
    event_map={}
    diag={'daily_events_available':len(events),'processed_daily_events':0,'initial_2015_seed_events':0,
        'three_down_events':0,'non_pattern_events':0,'insufficient_context_events':0,
        'filled_entries':0,'next_observed_weekday_exits':0,'same_quote_reentries':0,'ignored_pattern_while_long':0,'skipped_entry_fx_stale':0,'skipped_minimum_lot':0,
        'delayed_entry_count':0,'max_entry_delay_seconds':0.,'delayed_exit_count':0,'max_exit_delay_seconds':0.,
        'forced_window_end_exits':0,'unfilled_final_daily_events':0,'filled_longs':0,'filled_shorts':0,'exit_reason_counts':{}}
    if role=='strategy':
        for e in events.itertuples(index=False):
            i=int(np.searchsorted(ts,e.available_at.timestamp(),side='left'))
            if i>=len(ts):diag['unfilled_final_daily_events']+=1;continue
            event_map.setdefault(i,[]).append(e)
    cash=cfg.initial_eur;units=0.;direction=0;entry=entry_t=entry_cash=notional=lastfund=0.;entry_event=None;entry_fx={}
    tradefees=tradefund=totalfees=totalfund=heldseconds=turnover=slip_est=spread_est=0.
    prior_exposure_eur=prior_exposure_ratio=exposure_eur_seconds=exposure_ratio_seconds=0.
    heldage=0.;heldstale=heldold=0;trades=[];eventlog=[];rows=[];entries_year={}
    closed_net_by_prague_day={};max_flat_balance=cfg.initial_eur;first10=first5=first10_consistent=None
    day=None;daybalance=cfg.initial_eur;highestdaybalance=cfg.initial_eur
    prague=q.timestamp.dt.tz_convert('Europe/Prague').dt.strftime('%Y-%m-%d').to_numpy()
    first2daily=first2total=first1daily=first1trailing=None
    def charge(now,fxbid):
        nonlocal cash,lastfund,tradefund,totalfund,heldseconds,exposure_eur_seconds,exposure_ratio_seconds
        elapsed=max(0.,now-lastfund)
        debit=notional*cfg.funding_annual*elapsed/cfg.seconds_per_year/fxbid
        cash-=debit;tradefund+=debit;totalfund+=debit;heldseconds+=elapsed;lastfund=now
        exposure_eur_seconds+=prior_exposure_eur*elapsed;exposure_ratio_seconds+=prior_exposure_ratio*elapsed
    def set_exposure(bid,ask,fxbid,fxask):
        nonlocal prior_exposure_eur,prior_exposure_ratio
        mark=bid if direction==1 else ask
        equity=cash+usd_eur(direction*units*(mark-entry),fxbid,fxask)
        prior_exposure_eur=abs(units)*(bid+ask)/2/((fxbid+fxask)/2)
        prior_exposure_ratio=prior_exposure_eur/equity if equity>0 else 0.
    def enter(now,bid,ask,fxbid,fxask,fxstamp,age,chosen,event):
        nonlocal cash,units,direction,entry,entry_t,entry_cash,notional,lastfund,tradefees,tradefund,totalfees,turnover,slip_est,spread_est,entry_event,entry_fx
        actual=ask+cfg.slippage_usd_per_unit if chosen==1 else bid-cfg.slippage_usd_per_unit
        raw=max(0.,cash)/(cfg.contract_base_units*actual/fxask+cfg.commission_usd_per_lot_side/fxbid)
        lots=math.floor(raw/cfg.lot_step+1e-12)*cfg.lot_step
        if lots<cfg.min_lot:diag['skipped_minimum_lot']+=1;return False
        entry_cash=cash;units=lots*cfg.contract_base_units;direction=chosen;entry=actual;entry_t=now
        entry_event=event;entry_fx={'bid':fxbid,'ask':fxask,'timestamp':fxstamp,'age_seconds':age}
        notional=abs(units*entry);lastfund=now;tradefund=0.;tradefees=lots*cfg.commission_usd_per_lot_side/fxbid
        cash-=tradefees;totalfees+=tradefees;turnover+=notional/fxask
        slip_est+=units*cfg.slippage_usd_per_unit/fxbid;spread_est+=units*(ask-bid)/2/fxbid
        year=pd.Timestamp(now,unit='s',tz='UTC').year;entries_year[year]=entries_year.get(year,0)+1
        diag['filled_longs' if chosen==1 else 'filled_shorts']+=1
        return True
    def close(now,bid,ask,fxbid,fxask,fxstamp,age,reason,trigger=None):
        nonlocal cash,units,tradefees,totalfees,turnover,slip_est,spread_est,max_flat_balance,first10,first5,first10_consistent
        actual=bid-cfg.slippage_usd_per_unit if direction==1 else ask+cfg.slippage_usd_per_unit
        pnl_usd=direction*units*(actual-entry);pnl=usd_eur(pnl_usd,fxbid,fxask)
        fee=units/cfg.contract_base_units*cfg.commission_usd_per_lot_side/fxbid
        cash+=pnl-fee;tradefees+=fee;totalfees+=fee;turnover+=abs(units*actual)/fxask
        slip_est+=units*cfg.slippage_usd_per_unit/fxbid;spread_est+=units*(ask-bid)/2/fxbid
        delay=0. if trigger is None else now-trigger.available_at.timestamp()
        if delay>0:diag['delayed_exit_count']+=1;diag['max_exit_delay_seconds']=max(diag['max_exit_delay_seconds'],delay)
        diag['exit_reason_counts'][reason]=diag['exit_reason_counts'].get(reason,0)+1
        e=entry_event
        trade={'pair':pair,'role':role,'direction':'long' if direction==1 else 'short','entry_utc':pd.Timestamp(entry_t,unit='s',tz='UTC').isoformat(),
            'entry_signal_date':str(e.signal_date) if e is not None else '',
            'entry_signal_available_at':str(e.available_at) if e is not None else '',
            'entry_signal_bid_open':e.bid_open if e is not None else None,'entry_signal_bid_high':e.bid_high if e is not None else None,
            'entry_signal_bid_low':e.bid_low if e is not None else None,'entry_signal_bid_close':e.bid_close if e is not None else None,
            'entry_previous_close_1':e.previous_close_1 if e is not None else None,'entry_previous_close_2':e.previous_close_2 if e is not None else None,'entry_previous_close_3':e.previous_close_3 if e is not None else None,
            'entry_previous_date_1':str(e.previous_date_1) if e is not None else '', 'entry_previous_date_2':str(e.previous_date_2) if e is not None else '', 'entry_previous_date_3':str(e.previous_date_3) if e is not None else '',
            'entry_three_down':bool(e.three_down) if e is not None else False,'initial_2015_seed':bool(e.initial_2015_seed) if e is not None else False,
            'entry_delay_seconds':entry_t-e.available_at.timestamp() if e is not None else 0.,
            'exit_signal_date':str(trigger.signal_date) if trigger is not None else '',
            'exit_signal_available_at':str(trigger.available_at) if trigger is not None else '',
            'exit_signal_bid_close':trigger.bid_close if trigger is not None else None,'exit_signal_three_down':bool(trigger.three_down) if trigger is not None else False,
            'exit_utc':pd.Timestamp(now,unit='s',tz='UTC').isoformat(),'exit_reason':reason,'exit_delay_seconds':delay,
            'lots':units/cfg.contract_base_units,'base_units':units,'entry_usd_per_base':entry,'exit_usd_per_base':actual,'entry_usd_notional':notional,
            'entry_fx_bid':entry_fx['bid'],'entry_fx_ask':entry_fx['ask'],'entry_fx_timestamp':pd.Timestamp(entry_fx['timestamp'],unit='s',tz='UTC').isoformat(),
            'entry_fx_quote_age_seconds':entry_fx['age_seconds'],'exit_fx_bid':fxbid,'exit_fx_ask':fxask,
            'exit_fx_timestamp':pd.Timestamp(fxstamp,unit='s',tz='UTC').isoformat(),'exit_fx_quote_age_seconds':age,
            'price_pnl_usd':pnl_usd,'price_pnl_eur':pnl,'commission_eur':tradefees,'funding_eur':tradefund,
            'net_pnl_eur':cash-entry_cash,'balance_after_eur':cash,'holding_hours':(now-entry_t)/3600}
        trades.append(trade)
        localday=pd.Timestamp(now,unit='s',tz='UTC').tz_convert('Europe/Prague').date().isoformat()
        closed_net_by_prague_day[localday]=closed_net_by_prague_day.get(localday,0.)+trade['net_pnl_eur']
        net=cash-cfg.initial_eur;best=max(0.,max(closed_net_by_prague_day.values()));share=100*best/net if net>0 else None
        point={'utc':pd.Timestamp(now,unit='s',tz='UTC').isoformat(),'flat_balance_eur':cash,'cumulative_net_closed_profit_eur':net,
           'best_closed_profit_day_eur':best,'best_day_share_of_net_profit_pct':share,'model_1step_consistency':bool(net>0 and best<=.5*net)}
        max_flat_balance=max(max_flat_balance,cash)
        if cash>=1.10*cfg.initial_eur-1e-8:
            if first10 is None:first10=point.copy()
            if point['model_1step_consistency'] and first10_consistent is None:first10_consistent=point.copy()
        if cash>=1.05*cfg.initial_eur-1e-8 and first5 is None:first5=point.copy()
        units=0.
    for i,t in enumerate(ts):
        bid=a['bid_open'][i];ask=a['ask_open'][i];fxbid=a['fx_bid_open'][i];fxask=a['fx_ask_open'][i]
        if prague[i]!=day:day=prague[i];daybalance=cash;highestdaybalance=max(highestdaybalance,daybalance)
        if units:charge(t,fxbid)
        if role=='buy_hold' and i==0:
            if ages[i]>cfg.max_entry_fx_age_seconds:raise ValueError('Benchmark initial FX older than900sec')
            enter(t,bid,ask,fxbid,fxask,fxstamps[i],ages[i],1,None)
        for e in event_map.get(i,[]):
            event=e._asdict();event['entry_executed']=False;event['exit_executed']=False;event['same_quote_reentry']=False;event['entry_skip_reason']=''
            event['execution_quote_utc']=pd.Timestamp(t,unit='s',tz='UTC');event['execution_delay_seconds']=t-e.available_at.timestamp()
            event['position_before']=bool(units);diag['processed_daily_events']+=1;diag['initial_2015_seed_events']+=int(e.initial_2015_seed)
            # Stream completion events. No future-date lookup or 24h timer:
            # the first later observed source day closes the current position.
            exited=False
            if units and e.signal_date>entry_event.signal_date:
                close(t,bid,ask,fxbid,fxask,fxstamps[i],ages[i],'next_observed_weekday_exit',e)
                diag['next_observed_weekday_exits']+=1;event['exit_executed']=True;exited=True
            if not e.four_close_context_ready:diag['insufficient_context_events']+=1;event['entry_skip_reason']='fewer_than_four_observed_closes'
            elif not e.three_down:diag['non_pattern_events']+=1;event['entry_skip_reason']='three_strict_drops_absent'
            else:
                diag['three_down_events']+=1
                if units:diag['ignored_pattern_while_long']+=1;event['entry_skip_reason']='already_long'
                elif ages[i]>cfg.max_entry_fx_age_seconds:diag['skipped_entry_fx_stale']+=1;event['entry_skip_reason']='fx_quote_older_than_900sec'
                elif enter(t,bid,ask,fxbid,fxask,fxstamps[i],ages[i],1,e):
                    diag['filled_entries']+=1;event['entry_executed']=True
                    if t>e.available_at.timestamp():diag['delayed_entry_count']+=1;diag['max_entry_delay_seconds']=max(diag['max_entry_delay_seconds'],t-e.available_at.timestamp())
                    if exited:diag['same_quote_reentries']+=1;event['same_quote_reentry']=True
                else:event['entry_skip_reason']='below_minimum_lot'
            event['position_after']=bool(units);eventlog.append(event)
        if units:
            heldage=max(heldage,float(ages[i]));heldstale+=int(ages[i]>0);heldold+=int(ages[i]>3600)
            set_exposure(bid,ask,fxbid,fxask)
        now=t+cfg.bar_seconds;bid=a['bid_close'][i];ask=a['ask_close'][i];fxbid=a['fx_bid_close'][i];fxask=a['fx_ask_close'][i]
        if units:charge(now,fxbid)
        liquidation=bid if direction==1 else ask
        equity=cash+usd_eur(direction*units*(liquidation-entry),fxbid,fxask) if units else cash
        if units:set_exposure(bid,ask,fxbid,fxask)
        close_prague_day=pd.Timestamp(now,unit='s',tz='UTC').tz_convert('Europe/Prague').date().isoformat()
        if close_prague_day!=day:
            day=close_prague_day;daybalance=cash;highestdaybalance=max(highestdaybalance,daybalance)
        if i==len(ts)-1 and units:close(now,bid,ask,fxbid,fxask,fxstamps[i],ages[i],'forced_window_end');equity=cash;diag['forced_window_end_exits']+=1
        stamp=pd.Timestamp(now,unit='s',tz='UTC').isoformat()
        if equity<daybalance-.05*cfg.initial_eur and first2daily is None:first2daily={'utc':stamp,'equity_eur':equity,'floor_eur':daybalance-.05*cfg.initial_eur}
        if equity<.9*cfg.initial_eur and first2total is None:first2total={'utc':stamp,'equity_eur':equity,'floor_eur':.9*cfg.initial_eur}
        if equity<daybalance-.03*cfg.initial_eur and first1daily is None:first1daily={'utc':stamp,'equity_eur':equity,'floor_eur':daybalance-.03*cfg.initial_eur}
        if equity<highestdaybalance-.1*cfg.initial_eur and first1trailing is None:first1trailing={'utc':stamp,'equity_eur':equity,'floor_eur':highestdaybalance-.1*cfg.initial_eur}
        rows.append((now,equity,cash,direction*units,daybalance,highestdaybalance))
    curve=pd.DataFrame(rows,columns=['unix','equity_eur','balance_eur','signed_base_units','approx_prague_day_start_balance_eur','approx_prague_peak_midnight_balance_eur']);curve.index=pd.to_datetime(curve.pop('unix'),unit='s',utc=True);curve.index.name='timestamp'
    daily=curve.set_axis(curve.index-pd.Timedelta(nanoseconds=1)).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.signed_base_units=daily.signed_base_units.fillna(0.)
    log=pd.DataFrame(trades)
    if log.empty:log=pd.DataFrame(columns=['entry_utc','exit_utc','net_pnl_eur','funding_eur','commission_eur'])
    net=float(log.net_pnl_eur.sum()) if len(log) else 0.;best=max(0.,max(closed_net_by_prague_day.values())) if closed_net_by_prague_day else 0.
    duration=(END-START).total_seconds()
    info={'pair':pair,'role':role,'label':pair+(' three-down reversal' if role=='strategy' else ' buy and hold'),'commission_eur':totalfees,'funding_eur':totalfund,
       'modeled_slippage_eur_indicative':slip_est,'quoted_spread_eur_indicative':spread_est,
       'embedded_cost_estimate_note':'Spread/slippage valued at contemporaneous FX bid are embedded in execution P&L, not additional debits. Net USD conversion makes indicative attribution non-additive.',
       'exposure_time_pct':100*heldseconds/duration,'time_average_abs_eur_notional':exposure_eur_seconds/duration,
       'time_average_abs_eur_notional_over_equity':exposure_ratio_seconds/duration,
       'exposure_measurement':'Previous observed M5/open mark carried over elapsed intervals, including gaps; absolute base notional at instrument/FX mid divided by modeled equity. A sampled proxy, no future mark used for prior intervals.',
       'turnover_multiple_of_initial':turnover/cfg.initial_eur,'held_fx_max_quote_age_seconds':heldage,'held_bars_with_stale_fx':heldstale,'held_bars_with_fx_older_than_hour':heldold,
       'entries_by_year':entries_year,'execution_diagnostics':diag,
       'screen_2step':{'classification':'static-total-loss sampled breach on continuous path' if first2total else 'no static sampled breach; no formal pass',
         'approximate_daily_loss_flag':first2daily,'total_loss_breach':first2total,'max_flat_balance_eur':max_flat_balance,
         'first_phase1_10pct_target_at_flat':first10,'continuous_account_5pct_flat_threshold':first5,
         'limits':'5% initial daily; static EUR9000 equity floor; phase1 targetEUR11000, separate verification freshEUR10000 targetEUR10500; four opening days per phase',
         'limitations':'The5% record is a threshold on this continuous curve, NOT fresh verification. No separate phase reset/replay, target stop or rolling starts. First Prague-day quote approximates midnight; M5-close not tick equity, actual swap unknown.'},
       'screen_1step':{'classification':'approximate necessary-condition screen; no formal pass','approximate_daily_loss_flag':first1daily,'approximate_trailing_loss_flag':first1trailing,
         'max_flat_balance_eur':max_flat_balance,'first_10pct_target_at_flat':first10,'first_target_with_model_net_consistency':first10_consistent,
         'total_net_closed_profit_eur':net,'best_closed_profit_day_eur':best,'best_day_share_of_net_profit_pct':100*best/net if net>0 else None,
         'consistency_condition_at_end':bool(net>0 and best<=.5*net),'profit_target_eur':1000.,'ending_closed_profit_meets_target':net>=1000.,
         'limits':'3% initial daily; highest prior Prague-midnight balance anchored atinitial minus10% initial floor; target10%; best closed-profit day<=50% TOTAL NET CLOSED PROFIT including losing days, current orders>=12Oct2026',
         'limitations':'First Prague-day quote approximates midnight; net trade costs allocated to exit day, including as-of-target consistency. No full sequential challenge replay, actual broker swap or tick-equity certification.'}}
    return daily,log,info,curve,pd.DataFrame(eventlog)

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={'strategy':'#d4ed8d','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='EURUSD three-down reversal | 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]);display=f'{val:,.4f}' if field=='profit_factor' or field=='recovery_factor' and abs(val)<.01 else f'{val:,.2f}'
                ax.annotate(display,(i,val),ha='center',va='bottom' if val>=0 else 'top',fontsize=8)
        ax.set_xticks(range(2),['Three-down','B&H']);ax.set_title(title);ax.axhline(0,color='#648171',lw=.7);ax.grid(axis='y',alpha=.25)
    fig.suptitle('After modeled costs | one long-only three-down case 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='EURUSD three-down 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-.5)*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)




def run(directory:Path,out:Path):
    root=Path(__file__).parent;pp=root/'protocol.json';protocol_hash=hashlib.sha256(pp.read_bytes()).hexdigest()
    if protocol_hash!=(root/'protocol.sha256').read_text().split()[0]:raise ValueError('Frozen protocol hash changed')
    run_environment={'started_at_utc':datetime.now(timezone.utc).isoformat(),'status':'running','python':sys.version,'platform':platform.platform(),
       'packages':{'numpy':np.__version__,'pandas':pd.__version__,'matplotlib':matplotlib.__version__},'protocol_sha256':protocol_hash,
       'source_sha256':hashlib.sha256(Path(__file__).read_bytes()).hexdigest(),'tests_sha256':hashlib.sha256((root/'test_backtest.py').read_bytes()).hexdigest(),
       'note':'Captured at start of this actual historical run, not reconstructed from a later session.'}
    (root/'run_environment.json').write_text(json.dumps(run_environment,indent=2)+'\n')
    all_quotes,prov=load_data(directory);quotes=all_quotes['EURUSD'];cfg=Config();daily_inputs,events=build_daily_signals(quotes)
    out.mkdir(parents=True,exist_ok=True);daily_inputs.to_csv(out/'daily_bid_three_down.csv',index_label='date',float_format='%.12f')
    results={};curves={};samples={}
    for role in ['strategy','buy_hold']:
        daily,trades,info,sampled,trace=simulate(quotes,'EURUSD',role,cfg)
        daily.to_csv(out/f'{role}_daily_equity.csv',float_format='%.8f');trades.to_csv(out/f'{role}_trades.csv',index=False,float_format='%.12f')
        sampled.to_csv(out/f'{role}_m5_equity.csv.gz',float_format='%.8f')
        if role=='strategy':trace.to_csv(out/'strategy_daily_events.csv',index=False,float_format='%.12f')
        row={**metrics(daily,trades),**info};peak=np.maximum.accumulate(np.r_[cfg.initial_eur,sampled.equity_eur.to_numpy()])[1:]
        row['sampled_max_drawdown_pct']=float((1-sampled.equity_eur/peak).max()*100);row['sampled_max_drawdown_eur']=float(-(sampled.equity_eur-peak).min())
        row['diagnostic_splits']={}
        for first,last in [('2016','2020'),('2021','2025')]:
            sub=daily.loc[first:last];before=daily[daily.index<sub.index[0]];initial=float(before.equity_eur.iloc[-1]) if len(before) else cfg.initial_eur
            en=pd.to_datetime(trades.entry_utc,utc=True);ex=pd.to_datetime(trades.exit_utc,utc=True)
            closed=trades[(en>=sub.index[0])&(ex<sub.index[-1]+pd.Timedelta(days=1))]
            m=metrics(sub,closed,initial);m['trade_metric_scope']='Only trades fully contained in split; marked equity remains continuous.'
            row['diagnostic_splits'][first+'-'+last]=m
        annual=daily.equity_eur.resample('YE').last();ret=annual.pct_change();ret.iloc[0]=annual.iloc[0]/cfg.initial_eur-1
        row['annual_returns_pct']={str(t.year):float(v*100) for t,v in ret.items()}
        if abs(trades.net_pnl_eur.sum()-(row['final_equity_eur']-cfg.initial_eur))>1e-5:raise AssertionError('Trade P&L does not reconcile')
        if abs(trades.funding_eur.sum()-info['funding_eur'])>1e-5 or abs(trades.commission_eur.sum()-info['commission_eur'])>1e-5:raise AssertionError('Trade cost reconciliation failed')
        results[role]=row;curves[role]=daily;samples[role]=sampled
    weight=results['strategy']['time_average_abs_eur_notional']/results['buy_hold']['time_average_abs_eur_notional']
    scaled=curves['buy_hold'][['equity_eur','balance_eur']].copy();scaled=cfg.initial_eur+weight*(scaled-cfg.initial_eur)
    scaled.to_csv(out/'exposure_scaled_passive_daily.csv',float_format='%.8f')
    diagnostic=metrics(scaled,pd.DataFrame({'net_pnl_eur':[weight*results['buy_hold']['net_profit_eur']]}),cfg.initial_eur)
    diagnostic.update({'weight':weight,'commission_eur':weight*results['buy_hold']['commission_eur'],'funding_eur':weight*results['buy_hold']['funding_eur'],
        'target_average_abs_eur_notional':results['strategy']['time_average_abs_eur_notional'],
        'method':'EX-POST diagnostic only: strategy average absolute EURnotional / primarypassive average; linear net P&L/costs around EUR10000, cash0. Synthetic fractional allocation, not lotdeployable or another strategy case.'})
    results['strategy']['exposure_scaled_passive_diagnostic']=diagnostic
    report={'status':'completed retrospective EURUSD three-down transfer model','period':'2016-01-01 through2025-12-31 UTC;2015 four-close context',
       'source_rule':SOURCE,'source_published':'2026-11-23, after entire evaluation window',
       'protocol_sha256':protocol_hash,'protocol_frozen_at_utc':json.loads(pp.read_text())['frozen_at_utc'],
       'cases':'ONE EURUSD long-only rolling three-strict-drop case plus matched long buyhold. Public SPY section34/FAQ transfer, paid settings unread; not source replication.',
       'config':dataclasses.asdict(cfg),'data':prov,'signal_diagnostics':{'observed_weekday_daily_rows_including2015':len(daily_inputs),'daily_events_available':len(events),
          'three_down_events':int(events.three_down.sum()),'initial_seed_date':str(events[events.initial_2015_seed].signal_date.iloc[0]) if events.initial_2015_seed.any() else None,
          'rule':'Four successive OBSERVED UTCMon–Fri closes: each adjacent previous-current drop>1e-12*max(1,abs(pair)); equality breaks streak. Missing dates absent, Sunday notdaily.',
          'exit':'At each completed source-day event, first exit held position if day>entrySIGNALday; then reenter samequote if current three-down. No24htimer/future-next-date planner.'},
       'results':results,'limitations':[
          'Only public source section34/FAQ summary used. Paid settings unread. SPY idea transferred to EURUSD UTC BID observations and nextquote execution, not source equity replication.',
          'Four successive observed weekdaycloses form three strict drops. Equal closes break streak; missing dates absent, Sunday excluded, observed partial weekdays retained; no otherfilter orfakebar.',
          'Daily event available following00UTC and consumed once at firstM5OPEN>=availability. Current execution-bar H/L/C never selects entry. No executiondelayexpiry; FXage>900skipentryevent, no laterfreshrescue.',
          '2016 starts flat, retaining only latest observed2015weekday event usingfourclosecontext; no oldposition carry or replayofall2015signals.',
          'EXITFIRST when a later observed completedweekday than entrySIGNALday arrives. This is streamed completion, not futurecalendarselection orfixed24hhold. Then sameeventmayreenter ifrollingthree-downremains true, payingnewfees/slippage/spread. Oneposition/noSLTP/otherfilters.',
          'EURCFDcash/PnL,100kEURcontract/.01lotfloor,1xentrynotionalcap+feereserve; historicalbidask,adverse0.1pipeachleg,USD3.50/lot/side. PositiveUSDpnl/FXask; losses,fees,funding/FXbid.',
          'Funding ASSUMED5% annual absoluteentryUSDnotional overactualcalendar/365, notobservedhistoricalswap/carry;cashinterest0. Marketgapsandweekendpendingordersretained.',
          'Buyholdmatchesinitialentrycap/costsbutdifferentholdingduration. Expostexposure-scaledpassivefractional/synthetic,notlotdeployableoranothercase. Exposureusespreviousobservedmarksincludinggaps.',
          'Dukascopy-attributedM5aggregatesviaEVTradingLabs,notindependentlyreconciledbankticksorFTMObrokerhistory. All2016–2020/2021–2025diagnosticsretrospectivebefore2026sourcepublication;notpristineprospectiveOOS;noresult-dependenttuning.',
          'NetPF/winrateincludeallcosts;singletradepassivePFnotrobust. CalendarSharpe sqrt365/riskfree0;dailybarendattributedtointervalcompletedwith1nsboundaryshift. Daily/M5drawdownomitstickpath;remainingpositionforcedlast2025closeandflagged.',
          'FTMOcontinuousM5necessaryconditionsonly: firstflat10%target/maxflatbalance/firstfloorflags/asof1stepNETbestdayincllosses. Missingmidnightfirstquoteapproximationandtradecostallocationatexits;freshverificationnotreplayed,nocertifiedpass.']}
    (out/'summary.json').write_text(json.dumps(safe_json(report),indent=2)+'\n')
    pd.DataFrame({k:{key:v for key,v in row.items() if isinstance(v,(str,int,float)) or v is None} for k,row in results.items()}).T.to_csv(out/'summary.csv',index_label='case')
    charts(curves,results,out)
    run_environment.update({'status':'completed','completed_at_utc':datetime.now(timezone.utc).isoformat(),
       'output_sha256':{p.name:hashlib.sha256(p.read_bytes()).hexdigest() for p in sorted(out.iterdir()) if p.is_file()}})
    (root/'run_environment.json').write_text(json.dumps(run_environment,indent=2)+'\n')
    print(json.dumps({k:{x:v[x] for x in ['final_equity_eur','net_profit_eur','profit_factor','sharpe','max_drawdown_pct','closed_trades','execution_diagnostics']} for k,v in results.items()},indent=2))

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)
