"""XM04 — Residual / Idiosyncratic Momentum
IDEA: Instead of raw past return, score = cumulative idiosyncratic (beta-removed) return
over the last L days. Should be a cleaner momentum signal: strips out the common market
component and scores assets on their STOCK-SPECIFIC performance.

Signal: for each day i and asset a, sum the daily residual_returns over [i-L+1 .. i].
  residual_ret[t,a] = ret[t,a] - beta_t_a * market_ret[t]
  score[i,a] = sum(residual_ret[i-L+1:i+1, a])   (causal: uses data <= i)

Grid (<=5 calls):
  1. XM04-L30-maj   : majors universe, L=30, H=10, k=5, LS
  2. XM04-L60-maj   : majors universe, L=60, H=10, k=5, LS
  3. XM04-L30-all   : all universe,    L=30, H=10, k=5, LS
  4. XM04-L30-maj-H5: majors, L=30, H=5, k=5, LS (faster rebal)
  5. XM04-L30-maj-LO: majors, L=30, H=10, k=5, long-only (LO)
"""
import sys
sys.path.insert(0, "/opt/docker/PythagorasGoal/scripts/research/xsec")
import xslib as xs
import numpy as np


def resid_mom_score(P, L=30, beta_win=60):
    """Cumulative residual return over the last L days.
    residual_ret[t,a] = ret[t,a] - beta(win)*market_ret[t]
    score[i,a] = rolling sum of residual_ret over window L.
    All causal: roll_beta uses data <=i, rolling sum uses [i-L+1..i].
    """
    # daily idiosyncratic returns (n_days x n_assets), causal
    resid = xs.residual_return(P.ret, win=beta_win)
    # rolling sum over L days = cumulative idiosyncratic momentum
    score = xs.roll_mean(resid, L) * L   # equiv to rolling sum (roll_mean * win)
    return score


configs = [
    # name,              universe,   L,  H,  k, long_short
    ("XM04-L30-maj",    "majors",   30, 10,  5, True),
    ("XM04-L60-maj",    "majors",   60, 10,  5, True),
    ("XM04-L30-all",    "all",      30, 10,  5, True),
    ("XM04-L30-maj-H5", "majors",   30,  5,  5, True),
    ("XM04-L30-maj-LO", "majors",   30, 10,  5, False),
]

results = []
for name, univ, L, H, k, ls in configs:
    print(f"\nRunning {name} ...")
    rep = xs.study_xs(
        name,
        lambda P, _L=L: resid_mom_score(P, L=_L, beta_win=60),
        universe=univ,
        H=H,
        k=k,
        long_short=ls,
    )
    print(xs.fmt(rep))
    results.append(rep)

# Pick best: prefer earns_slot, then highest hold-out Sharpe, then most distinct from XS01
def score_config(r):
    earns = r["earns_slot"]
    hold_sh = r["holdout"].get("sharpe", -99)
    full_sh = r["full"]["sharpe"]
    corr_xs = r["corr_xs01"] or 1.0
    # primary: earns_slot; secondary: holdout Sharpe; tiebreak: distinctness
    return (earns, hold_sh, full_sh, -abs(corr_xs))

best = max(results, key=score_config)
print("\n" + "="*60)
print("BEST CONFIG:")
print(xs.fmt(best))
print("JSON:", xs.as_json(best))
