"""XR01 — Short-term Reversal on the Hyperliquid certified alt panel.

Score = -past_return(close, L)   (long losers / short winners)
Grid: L in {1, 3, 5, 7}
Known prior: REV5 negative — confirm / diagnose.

We try <=5 study_xs calls:
  1. L=1  majors   H=5  k=5  L/S
  2. L=3  majors   H=5  k=5  L/S
  3. L=5  majors   H=5  k=5  L/S  (baseline to confirm negative prior)
  4. L=7  majors   H=5  k=5  L/S
  5. best L (by hold-out) on universe="all"  (same H/k)
"""
import sys
sys.path.insert(0, "/opt/docker/PythagorasGoal/scripts/research/xsec")
import xslib as xs
import numpy as np

UNIVERSE_BASE = "majors"
H = 5
K = 5

results = []

for L in [1, 3, 5, 7]:
    def score_fn(P, L=L):
        return -xs.past_return(P.close, L)

    rep = xs.study_xs(
        f"XR01_L{L}_maj",
        score_fn,
        universe=UNIVERSE_BASE,
        H=H,
        k=K,
        long_short=True,
        target_vol=0.20,
    )
    print(xs.fmt(rep))
    print("JSON:", xs.as_json(rep))
    results.append((L, rep))

# Pick best L by hold-out Sharpe
best_L, best_rep = max(results, key=lambda x: x[1]["holdout"]["sharpe"])
print(f"\n=== Best L on majors: L={best_L} (hold-out Sharpe={best_rep['holdout']['sharpe']:.3f}) ===\n")

# Run the best L on "all" universe
def score_best(P, L=best_L):
    return -xs.past_return(P.close, L)

rep_all = xs.study_xs(
    f"XR01_L{best_L}_all",
    score_best,
    universe="all",
    H=H,
    k=K,
    long_short=True,
    target_vol=0.20,
)
print(xs.fmt(rep_all))
print("JSON:", xs.as_json(rep_all))

# Final summary: pick the overall best (by earns_slot, then hold-out)
all_reps = [r for _, r in results] + [rep_all]
all_reps_sorted = sorted(all_reps, key=lambda r: (r.get("earns_slot", False), r["holdout"]["sharpe"]), reverse=True)
final = all_reps_sorted[0]
print("\n=== FINAL BEST ===")
print(xs.fmt(final))
print("JSON:", xs.as_json(final))
