"""XM10 — Rank-weighted continuous momentum (demeaned xs_rank).

MECHANISM: Instead of top-k/bottom-k binary selection, weight ALL assets
proportionally to their demeaned cross-sectional rank of past return.
rank_i in [0,1] -> demeaned rank = rank_i - 0.5 -> scores in [-0.5, +0.5].
L=60 (lookback ~2 months). Continuous book approximated via large k (A//2)
and fine score (continuous rank, not discrete order).

The study_xs() engine still uses top-k/bottom-k for the actual rebalance,
but by setting k=A//2 (half the universe) and using xs_rank as the score,
the effective weight profile is nearly linear across the full distribution.
"""

import sys
sys.path.insert(0, "/opt/docker/PythagorasGoal/scripts/research/xsec")
import xslib as xs
import numpy as np

# -----------------------------------------------------------------------
# Score: demeaned cross-sectional rank of 60-day past return
# Higher score = longer weight. Causal: uses data up to and including bar i.
# -----------------------------------------------------------------------
L = 60  # lookback


def score_rank_mom(P, L=60):
    """Continuous rank-weighted momentum score.
    xs_rank -> [0,1]; demean -> [-0.5, +0.5] so it's symmetric long/short.
    """
    pr = xs.past_return(P.close, L)   # (n_days, n_assets)
    ranked = xs.xs_rank(pr)           # [0,1] cross-sectionally per row
    return ranked - 0.5               # demeaned: positive = long


# -----------------------------------------------------------------------
# Small grid: 5 studies
#   1) majors, H=10, k=large (9 ~ A//2 of 19)
#   2) all, H=10, k=large (24 ~ A//2 of 49)
#   3) all, H=5,  k=large (24) — faster rebalance
#   4) all, H=10, k=large (24), L=30 — shorter lookback
#   5) all, H=20, k=large (24) — slower rebalance
# -----------------------------------------------------------------------

results = []

print("=== XM10 Rank-Weighted Continuous Momentum ===\n")

# 1) Majors universe, H=10, k=9 (A//2 of 19)
r1 = xs.study_xs(
    "XM10-majors-H10-k9-L60",
    lambda P: score_rank_mom(P, L=60),
    universe="majors",
    H=10, k=9, long_short=True
)
print(xs.fmt(r1))
print("JSON:", xs.as_json(r1))
print()
results.append(r1)

# 2) All (49 alts), H=10, k=24 (A//2)
r2 = xs.study_xs(
    "XM10-all-H10-k24-L60",
    lambda P: score_rank_mom(P, L=60),
    universe="all",
    H=10, k=24, long_short=True
)
print(xs.fmt(r2))
print("JSON:", xs.as_json(r2))
print()
results.append(r2)

# 3) All, H=5, k=24 — faster rebalance
r3 = xs.study_xs(
    "XM10-all-H5-k24-L60",
    lambda P: score_rank_mom(P, L=60),
    universe="all",
    H=5, k=24, long_short=True
)
print(xs.fmt(r3))
print("JSON:", xs.as_json(r3))
print()
results.append(r3)

# 4) All, H=10, k=24, L=30 shorter lookback
r4 = xs.study_xs(
    "XM10-all-H10-k24-L30",
    lambda P: score_rank_mom(P, L=30),
    universe="all",
    H=10, k=24, long_short=True
)
print(xs.fmt(r4))
print("JSON:", xs.as_json(r4))
print()
results.append(r4)

# 5) All, H=20, k=24, L=60 slower rebalance
r5 = xs.study_xs(
    "XM10-all-H20-k24-L60",
    lambda P: score_rank_mom(P, L=60),
    universe="all",
    H=20, k=24, long_short=True
)
print(xs.fmt(r5))
print("JSON:", xs.as_json(r5))
print()
results.append(r5)

# -----------------------------------------------------------------------
# Pick best by: earns_slot first, then hold-out sharpe, then distinctness
# -----------------------------------------------------------------------
def score_result(r):
    es = int(r.get("earns_slot", False))
    hold_sh = r["holdout"].get("sharpe", -99)
    corr_xs01 = abs(r.get("corr_xs01") or 1.0)
    distinctness = 1.0 - corr_xs01  # higher is more distinct
    # marginal verdict
    verdict = r["marginal"].get("verdict", "")
    verdict_score = {"ADDS": 3, "NEUTRAL": 1, "DILUTES": 0, "REDUNDANT": 0, "N/A": 0}.get(verdict, 0)
    return (es, verdict_score, hold_sh, distinctness)

results_sorted = sorted(results, key=score_result, reverse=True)
best = results_sorted[0]

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