"""COMBO DEPLOYABLE — TP01 (Deribit) + GTAA (IB): le DUE gambe realmente eseguibili a basso capitale.

Il combo crypto-pieno (TP01+XS01+VRP01)+GTAA diversificava (Sharpe 1.6->1.8), ma XS01/VRP01 sono
STAT-MODE (non eseguibili a $600). Qui il combo ONESTO/deployable: solo le gambe eseguibili —
  * TP01: TSMOM difensivo BTC/ETH, long-flat, gia' ARMATO live su Deribit;
  * GTAA: trend difensivo multi-asset su ETF, eseguibile su IB (frazioni, switch mensile).
Domanda: due trend difensivi su mercati diversi, scorrelati, danno un blend migliore di ciascuno?

ALLINEAMENTO: TP01 e' calendario-giornaliero (crypto 7gg), GTAA giorni di borsa -> compoundo TP01 sul
grid dei giorni di borsa (cattura i weekend). Finestra = era TP01 (BTC/ETH dal 2019).
Confronto anche col combo crypto-pieno per quantificare il COSTO della deployability.
"""
import sys
from pathlib import Path
import numpy as np, pandas as pd

ROOT = Path(__file__).resolve().parents[2]
sys.path.insert(0, str(ROOT)); sys.path.insert(0, str(ROOT / "scripts" / "research"))
from eq_sector_momentum import _sh, _cagr, _dd, EQ_HOLDOUT
from eq_gtaa_trend import gtaa
from eq_crypto_combo import compound_to_grid, _ann_vol
from src.portfolio.sleeves import _tp01_returns, active_sleeves
from src.portfolio.portfolio import StrategyPortfolio

ANN = np.sqrt(252.0)


def _stat(nm, r):
    print(f"    {nm:26} Sh {_sh(r):>5.2f}  CAGR {_cagr(r.values,r.index)*100:>5.1f}%  "
          f"volAnn {_ann_vol(r)*100:>4.1f}%  maxDD {_dd(r.values)*100:>4.0f}%")


def main():
    print("=" * 96)
    print("  COMBO DEPLOYABLE — TP01 (Deribit) + GTAA (IB)")
    print("=" * 96)
    tp01 = _tp01_returns()
    if tp01.index.tz is None:
        tp01.index = tp01.index.tz_localize("UTC")
    eq = gtaa(target_vol=0.12).dropna()
    grid = eq.index[eq.index >= tp01.index[0]]
    tp = compound_to_grid(tp01, grid)
    J = pd.concat({"tp01": tp, "gtaa": eq.reindex(tp.index)}, axis=1).dropna()
    print(f"  finestra comune {J.index[0].date()}..{J.index[-1].date()}  ({len(J)} giorni di borsa, ~{len(J)//252}y)\n")
    t, g = J["tp01"], J["gtaa"]

    print("  --- STANDALONE (finestra comune) ---")
    _stat("TP01 (crypto, Deribit)", t)
    _stat("GTAA vt12 (equity, IB)", g)
    c = t.corr(g)
    print(f"\n  --- CORRELAZIONE TP01 <-> GTAA = {c:+.3f} ---")

    print("\n  --- BLEND (capitale) ---")
    print(f"    {'mix':20} {'Sharpe':>7} {'CAGR%':>6} {'volAnn%':>7} {'maxDD%':>6}")
    best = (-9, None)
    for wt in (1.0, 0.75, 0.6, 0.5, 0.4, 0.25, 0.0):
        b = wt * t + (1 - wt) * g
        if _sh(b) > best[0]:
            best = (_sh(b), wt)
        print(f"    TP01 {int(wt*100):>3}/{int((1-wt)*100):<3} GTAA  {_sh(b):>7.2f} {_cagr(b.values,b.index)*100:>6.1f} {_ann_vol(b)*100:>7.1f} {_dd(b.values)*100:>6.0f}")

    vt, vg = _ann_vol(t), _ann_vol(g)
    wt_rp = (1/vt) / (1/vt + 1/vg)
    b_rp = wt_rp * t + (1 - wt_rp) * g
    print(f"\n  --- RISK-PARITY (inv-vol: TP01 {wt_rp*100:.0f}% / GTAA {(1-wt_rp)*100:.0f}%) ---")
    _stat("risk-parity blend", b_rp)

    # OOS (post-2023, per dare un taglio fuori dai primi anni TP01)
    cut = pd.Timestamp("2023-01-01", tz="UTC")
    print(f"\n  --- robustezza: blend 50/50 per taglio ---")
    b50 = 0.5 * t + 0.5 * g
    for lbl, sub in (("full", b50), (">=2023", b50[b50.index >= cut])):
        print(f"    {lbl:10} Sh {_sh(sub):.2f}  maxDD {_dd(sub.values)*100:.0f}%")
    print("    Sharpe 50/50 per anno:", {y: round(_sh(b50[b50.index.year == y]), 2) for y in sorted(set(b50.index.year))})

    # VERDETTO + costo della deployability
    best_solo = max(_sh(t), _sh(g))
    print(f"\n  --- VERDETTO ---")
    print(f"    miglior standalone {best_solo:.2f} | blend 50/50 {_sh(b50):.2f} | risk-parity {_sh(b_rp):.2f} | "
          f"miglior cap-mix {best[0]:.2f} (TP01 {int(best[1]*100)}%)")
    print(f"    -> {'DIVERSIFICA (blend > solo)' if max(_sh(b50),_sh(b_rp)) > best_solo + 0.03 else 'nessun guadagno netto'}")
    # costo vs combo crypto-pieno
    full = StrategyPortfolio(active_sleeves()).combined_daily()
    if full.index.tz is None: full.index = full.index.tz_localize("UTC")
    fc = compound_to_grid(full, J.index)
    Jf = pd.concat({"f": fc, "g": g.reindex(fc.index)}, axis=1).dropna()
    print(f"    costo deployability: blend 50/50 con crypto-PIENO Sh {_sh(0.5*Jf['f']+0.5*Jf['g']):.2f} "
          f"vs deployable {_sh(b50):.2f}  (la differenza = cio' che lasciano XS01/VRP01 STAT-MODE)")
    print(f"    (cross-venue Deribit+IB; entrambe switch mensile/basso turnover; frazionabili a $0.5-2k)")


if __name__ == "__main__":
    main()
