"""XVa1 — Distance-from-MA value signal.

Score = -(close / roll_mean(close, W) - 1)
Long assets furthest BELOW their rolling MA (cheap / mean-reverting).
Short assets furthest ABOVE their rolling MA (expensive).

Grid: W in {60, 100}, universe all/majors, H in {10, 20}.
Max 5 study_xs calls.
"""

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


def score_val(close, W):
    """Causal value score: -(close / MA - 1). Higher = more below MA = long."""
    ma = xs.roll_mean(close, W)
    return -(close / ma - 1.0)


results = []

# Config 1: W=60, all assets, H=10, k=5, LS
r1 = xs.study_xs(
    "XVa1-W60-all-H10",
    lambda P: score_val(P.close, 60),
    universe="all", H=10, k=5, long_short=True
)
print(xs.fmt(r1))
print("JSON:", xs.as_json(r1))
results.append(r1)

# Config 2: W=100, all assets, H=10, k=5, LS
r2 = xs.study_xs(
    "XVa1-W100-all-H10",
    lambda P: score_val(P.close, 100),
    universe="all", H=10, k=5, long_short=True
)
print(xs.fmt(r2))
print("JSON:", xs.as_json(r2))
results.append(r2)

# Config 3: W=60, majors, H=10, k=5, LS
r3 = xs.study_xs(
    "XVa1-W60-majors-H10",
    lambda P: score_val(P.close, 60),
    universe="majors", H=10, k=5, long_short=True
)
print(xs.fmt(r3))
print("JSON:", xs.as_json(r3))
results.append(r3)

# Config 4: W=60, all assets, H=20, k=5, LS (slower rebal)
r4 = xs.study_xs(
    "XVa1-W60-all-H20",
    lambda P: score_val(P.close, 60),
    universe="all", H=20, k=5, long_short=True
)
print(xs.fmt(r4))
print("JSON:", xs.as_json(r4))
results.append(r4)

# Config 5: W=100, all assets, H=20, k=5, LS
r5 = xs.study_xs(
    "XVa1-W100-all-H20",
    lambda P: score_val(P.close, 100),
    universe="all", H=20, k=5, long_short=True
)
print(xs.fmt(r5))
print("JSON:", xs.as_json(r5))
results.append(r5)

# Pick best by: earns_slot first, then hold-out Sharpe, then full Sharpe
def rank_key(r):
    earns = int(r["earns_slot"])
    hold_sh = r["holdout"].get("sharpe", -99)
    full_sh = r["full"].get("sharpe", -99)
    return (earns, hold_sh, full_sh)

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