"""RI-ESECUZIONE FADE sul feed PULITO (data/raw ricostruito da Deribit mainnet, 2026-06-19).

Dopo il rebuild (scripts/analysis/rebuild_history.py) i parquet canonici in data/raw
sono storia Deribit mainnet reale (ccxt pubblico), certificata vs Coinbase USD. Qui giro
le 6 fade (MR01/MR02/MR07 x BTC/ETH) con l'ENGINE CANONICO (risk_management.build_trades,
strats_for) sul feed pulito, su ENTRAMBI i timeframe:
  - 1h  = config dei claim storici "validati OOS" (CLAUDE.md: MR01 BTC +201% / ETH +1238%)
  - 15m = config LIVE attuale (swap 1h->15m, v1.1.30)

Stessi parametri del live: pos 0.15, leva 3x, trend_max 3.0, fee 0.10% RT. OOS = ultimo 30%
per indice (convenzione OOS_FRAC del progetto). Read-only, nessuna scrittura.

    uv run python scripts/analysis/clean_fade_rerun.py
"""
from __future__ import annotations
import sys
from pathlib import Path
PROJECT_ROOT = Path(__file__).resolve().parents[2]
sys.path.insert(0, str(PROJECT_ROOT))
import numpy as np
import pandas as pd
from src.data.downloader import load_data
from scripts.analysis.risk_management import strats_for, build_trades, POS, LEV, OOS_FRAC

TFS = ["1h", "15m"]
YEARS = list(range(2018, 2027))


def metrics(ts, trades, split_idx, pos=POS):
    """trades = [(i, j, r_netto)]. Ritorna (per-anno%, FULL%, FULL Sharpe, OOS%, OOS Sharpe)."""
    by = {y: 0.0 for y in YEARS}
    capF = capO = 1000.0
    rF, rO = [], []
    for i, j, r in trades:
        y = ts.iloc[i].year
        if y in by:
            by[y] += r * pos * 1000.0  # contributo lineare per la riga annuale
        capF = max(capF + capF * pos * r, 10.0)
        rF.append(r * pos)
        if i >= split_idx:
            capO = max(capO + capO * pos * r, 10.0)
            rO.append(r * pos)
    yr = {y: by[y] / 1000.0 * 100 for y in YEARS}
    shF = float(np.mean(rF) / np.std(rF) * np.sqrt(len(rF))) if len(rF) > 1 and np.std(rF) > 0 else 0.0
    shO = float(np.mean(rO) / np.std(rO) * np.sqrt(len(rO))) if len(rO) > 1 and np.std(rO) > 0 else 0.0
    return yr, (capF / 1000 - 1) * 100, shF, (capO / 1000 - 1) * 100, shO


def main():
    years_present = set()
    results = {}
    for tf in TFS:
        for asset in ("BTC", "ETH"):
            df = load_data(asset, tf)
            ts = pd.to_datetime(df["timestamp"], unit="ms", utc=True)
            years_present |= set(ts.dt.year.unique().tolist())
            split_idx = int(len(df) * (1 - OOS_FRAC))
            cov = f"{ts.iloc[0].date()} -> {ts.iloc[-1].date()} ({len(df)} barre, OOS da {ts.iloc[split_idx].date()})"
            for code in ("MR01", "MR02", "MR07"):
                fn, params = strats_for(asset)[code]
                trades = build_trades(fn(df, **params), df, trend_max=3.0)
                results[(tf, asset, code)] = (metrics(ts, trades, split_idx), len(trades), cov)

    years = [y for y in YEARS if y in years_present]
    for tf in TFS:
        print("\n" + "=" * (62 + 9 * len(years)))
        print(f"  FADE su FEED PULITO (Deribit mainnet) — {tf} | pos {POS}, leva {LEV:.0f}x, trend 3.0, fee 0.10% RT")
        # mostra la copertura una volta per asset
        for asset in ("BTC", "ETH"):
            print(f"    {asset}: {results[(tf, asset, 'MR01')][2]}")
        print("=" * (62 + 9 * len(years)))
        print(f"  {'sleeve':<11s}" + "".join(f"{y:>9d}" for y in years) +
              f"{'Trd':>7s}{'FULL%':>9s}{'Shrp':>7s}{'OOS%':>8s}{'Shrp':>7s}")
        print("  " + "-" * (60 + 9 * len(years)))
        for asset in ("BTC", "ETH"):
            for code in ("MR01", "MR02", "MR07"):
                (yr, fF, shF, fO, shO), ntr, _ = results[(tf, asset, code)]
                print(f"  {code+'_'+asset:<11s}" + "".join(f"{yr[y]:>+9.0f}" for y in years) +
                      f"{ntr:>7d}{fF:>+9.0f}{shF:>7.2f}{fO:>+8.0f}{shO:>7.2f}")
    print()


if __name__ == "__main__":
    main()
