"""
eu_day_stats_v1.py — how often does EU trade 2+ times a day, and what
does the worst day cost? Full history vs quiet years, at 1x/1.5x/2x.
Run: python src\\research\\eu_day_stats_v1.py
"""
import csv, sys
from pathlib import Path
from datetime import datetime
from collections import defaultdict

QUIET={2005,2011,2017,2019,2020,2021,2024,2025}
DAILY_LIMIT=5000

def resolve_base():
    for b in [Path(r"C:\Users\Administrator\OneDrive\fx_macro_intraday"),
              Path(r"C:\Users\paul_\OneDrive\fx_macro_intraday"),
              Path(__file__).resolve().parents[2]]:
        if b.exists(): return b
    sys.exit("base not found")
BASE=resolve_base()

def parse_dt(s):
    for f in ("%Y-%m-%d %H:%M:%S","%Y-%m-%d %H:%M"):
        try: return datetime.strptime((s or "").strip()[:19], f)
        except ValueError: continue
    return None

# realized P&L lands on EXIT day (matches FTMO daily accounting)
day_pnl=defaultdict(float); day_n=defaultdict(int)
p=BASE/"data"/"processed"/"trades"/"trades_real_costs.csv"
with open(p, newline="", encoding="utf-8-sig") as f:
    for r in csv.DictReader(f):
        x=parse_dt(r.get("exit_time")) or parse_dt(r.get("entry_time"))
        if x is None: continue
        try:
            za=float(r.get("zscore_abs",2.0)); pnl=float(r["dollar_pnl_real"])
        except (ValueError,KeyError): continue
        day_pnl[x.date()]+=pnl   # at $300k x tier (as recorded)
        day_n[x.date()]+=1

def report(days,label):
    n=len(days)
    dist=defaultdict(int)
    for d in days: dist[min(day_n[d],5)]+=1
    print(f"\n{label}: {n:,} trading days")
    print("  Trades/day: " + "  ".join(
        f"{k}{'+' if k==5 else ''}:{v} ({100*v/n:.0f}%)"
        for k,v in sorted(dist.items())))
    multi=[d for d in days if day_n[d]>=2]
    print(f"  Days with 2+ trades: {len(multi)} "
          f"({100*len(multi)/n:.1f}%)  |  3+: "
          f"{sum(1 for d in days if day_n[d]>=3)}")
    losses=sorted((day_pnl[d],d) for d in days)[:5]
    print("  5 worst realized days (at $300k tiers):")
    for pnl,d in losses:
        print(f"    {d}  ${pnl:>9,.0f}  ({day_n[d]} trades)"
              f"   x1.5 = ${pnl*1.5:>9,.0f}   x2 = ${pnl*2:>9,.0f}")
    for b in (1.0,1.5,2.0):
        breach=sum(1 for d in days if day_pnl[d]*b <= -DAILY_LIMIT)
        yrs=len({d.year for d in days})
        print(f"  Days breaching $5k on REALIZED alone at x{b}: {breach} "
              f"(~{breach/max(1,yrs):.1f}/yr)")

all_days=sorted(day_pnl)
report(all_days,"FULL HISTORY")
report([d for d in all_days if d.year in QUIET],"QUIET YEARS "+str(sorted(QUIET)))
print("\nNote: realized-only. Floating loss on the day adds on top of this")
print("before the daily limit is checked — these are FLOOR numbers.")
