"""OPT03 — Calendar Spread (DVOL term proxy).

IDEA: A calendar spread (sell short-dated, buy long-dated option) profits when:
- Term structure is in contango (short vol < long vol) -> theta decay favors the short leg
- The vol term slope is MEAN-REVERTING: extreme backwardation -> enter long calendar

MODELED APPROACH (since we lack real term surface):
  - Short-dated vol proxy: EMA(DVOL, span_short) — reacts quickly to spot moves
  - Long-dated vol proxy: EMA(DVOL, span_long)  — slower, represents long-term expectation
  - Term slope = short_proxy - long_proxy (positive = backwardation, negative = contango)
  - Position: go long calendar when slope is high (extreme backwardation -> mean-revert to flat)
              go short calendar when slope is very negative (extreme contango -> normalize)

  Signal: zscore of (short_ema - long_ema) over rolling window.
  Direction: mean-reversion -> go LONG when z is high (backwardation = short vol elevated)
             because short vol will eventually fall back to long vol.

  Vol-target the position (20%, cap 2x).

GRID: 4 configs (short_span x long_span)
  - (7d, 30d): short-term vs monthly
  - (7d, 60d): short-term vs 2-month
  - (14d, 60d): 2-week vs 2-month
  - (14d, 90d): 2-week vs 3-month

CAVEAT: premiums are MODELED using DVOL (no real term surface available).
        This is a lead/research indicator only, not deployable as-is.
        Data starts 2021-03 (DVOL history constraint).
"""
import sys
sys.path.insert(0, "/opt/docker/PythagorasGoal/scripts/research/alt")
import altlib as al
import numpy as np

# DVOL is daily -> span parameters in DAYS
CONFIGS = [
    {"short_days": 7,  "long_days": 30,  "zscore_win": 60},
    {"short_days": 7,  "long_days": 60,  "zscore_win": 90},
    {"short_days": 14, "long_days": 60,  "zscore_win": 90},
    {"short_days": 14, "long_days": 90,  "zscore_win": 120},
]


def make_target(short_days: int, long_days: int, zscore_win: int):
    """Return target_fn(df) -> position array."""
    def target_fn(df):
        n = len(df)
        bpd = al.bars_per_day(df)

        # DVOL aligned causally to df bars
        dv = al.dvol(df, "BTC")  # NOTE: asset-specific handled below via closure

        # Mask where DVOL is available
        valid = np.isfinite(dv)

        # Compute EMAs of DVOL as short/long term structure proxies
        # spans in days -> convert to bars
        short_span = max(2, int(short_days * bpd))
        long_span  = max(4, int(long_days * bpd))

        import pandas as pd
        dv_s = pd.Series(dv)

        # EMA on valid-filled series (forward-fill to avoid NaN inside EMA)
        dv_ffilled = dv_s.ffill()

        ema_short = dv_ffilled.ewm(span=short_span, adjust=False).mean().values
        ema_long  = dv_ffilled.ewm(span=long_span,  adjust=False).mean().values

        # Term slope: positive = backwardation (short > long)
        slope = ema_short - ema_long

        # Z-score of slope over rolling window
        zscore_win_bars = max(10, int(zscore_win * bpd))
        z = al.zscore(slope, zscore_win_bars)

        # Mean-reversion signal: when backwardation is extreme (high z),
        # short vol is elevated -> will mean-revert down -> calendar spread gains
        # Position: +1 when z > 0 (backwardation -> long calendar)
        #            -1 when z < 0 (contango -> short calendar / flat)
        # Use continuous sizing based on z-score, clipped to [-1, 1]
        direction = np.clip(z, -1.0, 1.0)

        # NaN where DVOL not available (pre-2021-03)
        direction = np.where(valid & np.isfinite(z), direction, 0.0)

        # Vol-target
        tgt = al.vol_target(direction, df, target_vol=0.20, vol_win_days=30, leverage_cap=2.0)
        return tgt

    return target_fn


def make_target_asset(short_days: int, long_days: int, zscore_win: int, asset: str):
    """Per-asset version that uses the correct DVOL."""
    def target_fn(df):
        n = len(df)
        bpd = al.bars_per_day(df)

        dv = al.dvol(df, asset)

        valid = np.isfinite(dv)

        short_span = max(2, int(short_days * bpd))
        long_span  = max(4, int(long_days * bpd))

        import pandas as pd
        dv_s = pd.Series(dv)
        dv_ffilled = dv_s.ffill()

        ema_short = dv_ffilled.ewm(span=short_span, adjust=False).mean().values
        ema_long  = dv_ffilled.ewm(span=long_span,  adjust=False).mean().values

        slope = ema_short - ema_long

        zscore_win_bars = max(10, int(zscore_win * bpd))
        z = al.zscore(slope, zscore_win_bars)

        direction = np.clip(z, -1.0, 1.0)
        direction = np.where(valid & np.isfinite(z), direction, 0.0)

        tgt = al.vol_target(direction, df, target_vol=0.20, vol_win_days=30, leverage_cap=2.0)
        return tgt

    return target_fn


def run_config(cfg: dict, tfs=("1d", "12h")) -> dict:
    """Run one config across assets+tfs."""
    sd, ld, zw = cfg["short_days"], cfg["long_days"], cfg["zscore_win"]
    name = f"OPT03-CAL-s{sd}d-l{ld}d-z{zw}d"

    # Build per-asset closures
    btc_fn = make_target_asset(sd, ld, zw, "BTC")
    eth_fn = make_target_asset(sd, ld, zw, "ETH")

    cells = []
    for tf in tfs:
        per_asset = {}
        fee_ok_all = True
        for a, fn in [("BTC", btc_fn), ("ETH", eth_fn)]:
            df = al.get(a, tf)
            tgt = fn(df)
            base = al.eval_weights(df, tgt, fee_side=al.FEE_SIDE)
            sweep = {f"{2*f*100:.2f}%RT": al.eval_weights(df, tgt, fee_side=f)["full"]["sharpe"]
                     for f in al.FEE_SWEEP}
            fee_ok = sweep.get("0.20%RT", -9) > 0
            fee_ok_all = fee_ok_all and fee_ok
            per_asset[a] = dict(
                full=base["full"], holdout=base["holdout"],
                tim=base["time_in_market"], turnover=base["turnover_per_year"],
                fee_sweep=sweep, yearly=base["yearly"]
            )

        min_full = min(per_asset[a]["full"]["sharpe"] for a in ("BTC", "ETH"))
        min_hold = min(per_asset[a]["holdout"].get("sharpe", 0.0) for a in ("BTC", "ETH"))
        cells.append(dict(
            tf=tf, per_asset=per_asset,
            min_asset_full_sharpe=round(min_full, 3),
            min_asset_holdout_sharpe=round(min_hold, 3),
            full_sharpe=round(np.mean([per_asset[a]["full"]["sharpe"] for a in ("BTC", "ETH")]), 3),
            fee_survives=fee_ok_all
        ))

    return dict(name=name, kind="weights", cells=cells,
                verdict=al._verdict(cells), config=cfg)


if __name__ == "__main__":
    print("OPT03 — Calendar Spread via DVOL term proxy")
    print("CAVEAT: premiums are MODELED (DVOL only, no real term surface) — lead/research only")
    print("DVOL history starts 2021-03 -> effective backtest from ~2021-Q3")
    print()

    # Run all 4 configs on 1d only (DVOL is daily; 12h would repeat same info)
    # We test 1d and 12h to see if intraday resolution helps, but expect 1d to be canonical
    results = []
    for cfg in CONFIGS:
        print(f"Running config: short={cfg['short_days']}d long={cfg['long_days']}d zscore={cfg['zscore_win']}d ...")
        rep = run_config(cfg, tfs=("1d",))
        results.append(rep)
        print(al.fmt(rep))
        print()

    # Pick best config by min_asset_holdout_sharpe
    best = max(results, key=lambda r: max(
        (c["min_asset_holdout_sharpe"] for c in r["cells"]), default=-9))

    print("=" * 60)
    print("BEST CONFIG:", best["name"])
    print(al.fmt(best))
    print()
    print("JSON:", al.as_json(best))
