"""XS05b — Risk-parity momentum (inverse-vol weighted legs).

MECHANISM: Select top-k / bottom-k by plain 60-day momentum (same as XS01),
but instead of equal-weighting within long/short legs, weight each asset by
INVERSE of its own recent volatility (60-day rolling std of daily returns).
This approximates risk-parity within the cross-sectional book: lower-vol
assets get larger weight, so each leg contributes roughly equal risk.

LIMITATION / CAVEAT:
- xslib.study_xs always equal-weights within legs (the score only determines
  SELECTION, not position sizing). We cannot pass per-asset weights directly
  through the study_xs interface.
- Workaround: encode the inverse-vol signal INTO the score. After selecting
  the top-k / bottom-k by momentum rank, the harness will still equal-weight
  — but by blending the momentum z-score with the inverse-vol z-score we bias
  the SELECTION toward low-vol winners (i.e., the most risk-efficient longs
  rank higher). This is a partial approximation: true risk-parity would rescale
  weights post-selection; here we rescale the ranking pre-selection.
- The blend is: score = z(mom60) + alpha * z(1/vol60), where alpha=1 gives
  equal weight to momentum rank and inverse-vol rank.

GRID (<=5 calls):
  1. XS05b-base  : majors, H=10, k=5, L=60, alpha=1 (blend)
  2. XS05b-all   : all (49 alts), H=10, k=5, L=60, alpha=1
  3. XS05b-a05   : majors, H=10, k=5, L=60, alpha=0.5 (lighter inv-vol)
  4. XS05b-a2    : majors, H=10, k=5, L=60, alpha=2.0 (heavier inv-vol)
  5. XS05b-H5    : majors, H=5,  k=5, L=60, alpha=1 (faster rebalance)
"""
import sys
sys.path.insert(0, "/opt/docker/PythagorasGoal/scripts/research/xsec")
import xslib as xs
import numpy as np


def score_xs05b(P, L=60, alpha=1.0):
    """Risk-parity momentum score (causal).

    score = z_cross(mom_L) + alpha * z_cross(inv_vol_L)
    Higher score -> more risk-efficient momentum winner -> long.
    Lower score  -> more risk-efficient momentum loser  -> short.
    """
    # 1. momentum signal (L-day return, causal)
    mom = xs.past_return(P.close, L)          # (n_days, n_assets), uses close[i-L:i]
    z_mom = xs.xs_zscore(mom)

    # 2. inverse-vol signal (rolling std of daily returns, causal)
    vol = xs.roll_std(P.ret, L)               # (n_days, n_assets)
    inv_vol = np.where(vol > 0, 1.0 / vol, np.nan)
    z_inv_vol = xs.xs_zscore(inv_vol)

    # 3. blend
    score = z_mom + alpha * z_inv_vol
    return score


results = {}

# --- Config 1: majors, H=10, k=5, alpha=1 (baseline blend) ---
rep1 = xs.study_xs(
    "XS05b-base",
    lambda P: score_xs05b(P, L=60, alpha=1.0),
    universe="majors",
    H=10, k=5, long_short=True
)
results["XS05b-base"] = rep1
print(xs.fmt(rep1))
print("JSON:", xs.as_json(rep1))
print()

# --- Config 2: all alts, H=10, k=5, alpha=1 ---
rep2 = xs.study_xs(
    "XS05b-all",
    lambda P: score_xs05b(P, L=60, alpha=1.0),
    universe="all",
    H=10, k=5, long_short=True
)
results["XS05b-all"] = rep2
print(xs.fmt(rep2))
print("JSON:", xs.as_json(rep2))
print()

# --- Config 3: majors, H=10, k=5, alpha=0.5 (lighter inv-vol) ---
rep3 = xs.study_xs(
    "XS05b-a05",
    lambda P: score_xs05b(P, L=60, alpha=0.5),
    universe="majors",
    H=10, k=5, long_short=True
)
results["XS05b-a05"] = rep3
print(xs.fmt(rep3))
print("JSON:", xs.as_json(rep3))
print()

# --- Config 4: majors, H=10, k=5, alpha=2.0 (heavier inv-vol) ---
rep4 = xs.study_xs(
    "XS05b-a2",
    lambda P: score_xs05b(P, L=60, alpha=2.0),
    universe="majors",
    H=10, k=5, long_short=True
)
results["XS05b-a2"] = rep4
print(xs.fmt(rep4))
print("JSON:", xs.as_json(rep4))
print()

# --- Config 5: majors, H=5, k=5, alpha=1 (faster rebalance) ---
rep5 = xs.study_xs(
    "XS05b-H5",
    lambda P: score_xs05b(P, L=60, alpha=1.0),
    universe="majors",
    H=5, k=5, long_short=True
)
results["XS05b-H5"] = rep5
print(xs.fmt(rep5))
print("JSON:", xs.as_json(rep5))
print()

# --- Summary ---
print("=" * 60)
print("SUMMARY — XS05b grid")
print("=" * 60)
fmt_h = f"{'Config':<16} {'FullSh':>7} {'HoldSh':>7} {'MaxDD':>7} {'CorrXS01':>9} {'EarnsSlot':>10} {'Verdict':>10}"
print(fmt_h)
print("-" * 70)
for name, r in results.items():
    fs = r["full"]["sharpe"]
    hs = r["holdout"]["sharpe"]
    dd = r["full"]["maxdd"]
    cxs = r.get("corr_xs01", float("nan"))
    es = r.get("earns_slot", False)
    vd = r.get("marginal", {}).get("verdict", "N/A")
    print(f"{name:<16} {fs:>7.2f} {hs:>7.2f} {dd:>7.2f} {cxs:>9.3f} {str(es):>10} {vd:>10}")
