Files
PythagorasGoal/scripts/research/xsec/runs/XR02.py
T
Adriano Dal Pastro 9612560479 research(xsec): sweep cross-sectional su Hyperliquid (43 script/257 config) + verifica avversariale
Nuova harness condivisa xslib.py (panel HL certificato, score per-asset causale, book
long-k/short-k vol-targeted leak-free) + 43 script in runs/ su 11 famiglie (MOM/REV/VOL/
DIST/LIQ/VAL/STRUCT/UNIV). Scoring = earns_slot (full>0 AND hold-out>0 AND marginal ADDS
al portafoglio live AND corr XS01<0.6, con jackknife drop-one-month).

Find: 42/257 config earns_slot=True, ma TUTTE con corr TP01 -0.2..-0.4 e PnL ~solo 2025.
Verify (verify_survivors.py, 3 scettici deterministici):
 - S1 redundancy: cluster low-vol = UNA scommessa (XV01=XU02=1.00, XV02/XV03 r 0.44-0.67);
   XM09/XL02/XS06b/XR02 distinti (corr media off-diag +0.20).
 - S2 short-beta: cluster low-vol carica 0.44-0.70 su short-market -> NON market-neutral,
   e' un tilt short-alt-beta di regime. XM09(0.08)/XR02(-0.21) NON short-beta.
 - S3 per-anno: cluster low-vol decade (XV01/XU02 2026 -0.09); XL02 morto (2025 -0.14,
   2026 -0.43); XM09 (0.82/0.50/0.74) e XR02 (0.84/0.40/2.68) positivi in tutti e 3 gli anni.

Esito: nessuna sleeve nuova. Cluster low-vol RIGETTATO (regime-bet), XL02 RIGETTATO (overfit).
2 LEAD genuini (XM09 trend-gated x-sec momentum, XR02 reversal vol-gated) -> forward-monitor,
non deployabili (panel 2.5y regime unico + STAT-MODE esecuzione). Portafoglio live invariato.

Incluso anche options_vrp_managed.py (A/B VRP01 hold-to-expiry vs gestione attiva del doc
credit-spread): la gestione attiva DISTRUGGE l'edge (combo FULL managed Sh -1.29 vs HtE +0.96,
il delta-exit taglia i vincenti) -> scartata, VRP01 resta hold-to-expiry.

Diari: 2026-06-20-xsec-strategies-sweep.md, 2026-06-20-vrp-active-management.md.
gitignore: data/paper_portfolio/ (stato runtime paper) + scripts/research/xsec/runs/out/ (output rigenerabile).

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-06-20 21:36:57 +00:00

172 lines
5.9 KiB
Python

"""XR02 — Short-term Reversal gated by high-vol regime (L=3).
MECHANISM:
Plain reversal: short the recent winners, long the recent losers (L=3 days lookback).
GATE: only active when market volatility is HIGH — defined as the 30-day rolling std of
the equal-weight market return exceeding its own 90-day expanding percentile (p70 threshold).
In low-vol / calm regimes, the book is flat (score = NaN -> no position).
Rationale: short-term reversal is a classic effect but is often diluted by trend in calm
regimes. In panic / high-vol regimes (sharp market moves), mean-reversion / liquidity
provision logic is stronger (overshoot + reversal). Gate concentrates the signal in those
regimes while avoiding trend-contamination in smooth uptrends.
Causal: all quantities computed at close[i], applied to return of bar i+1.
"""
import sys
sys.path.insert(0, "/opt/docker/PythagorasGoal/scripts/research/xsec")
import xslib as xs
import numpy as np
import pandas as pd
def rev_gate_score(P, L=3, vol_win=30, baseline_win=90, vol_pct=70, use_residual=False):
"""Short-term reversal score gated by high market-vol regime.
Parameters
----------
P : Panel
L : int
Reversal lookback in days (price L days ago vs today).
vol_win : int
Rolling window for realised market-vol (std of equal-weight market return).
baseline_win : int
Expanding window for computing the percentile threshold on market-vol.
vol_pct : float
Percentile threshold: market vol must exceed this percentile to be active.
use_residual : bool
If True, compute reversal on idiosyncratic (market-beta-neutral) returns instead of raw.
"""
n, A = P.close.shape
# --- 1. Reversal score: negative of L-day return (higher = long the loser) ---
raw_ret = xs.past_return(P.close, L) # (n, A), causal: uses close[i-L..i]
if use_residual:
# use idiosyncratic cumulative return instead of total
resid = xs.residual_return(P.ret, 30) # (n, A), causal
# cumulate idiosyncratic over L days
resid_cum = np.full_like(raw_ret, np.nan)
for lag in range(1, L + 1):
shifted = np.roll(resid, lag, axis=0)
shifted[:lag] = np.nan
resid_cum = np.nansum([resid_cum, resid], axis=0)
signal = -resid_cum
else:
signal = -raw_ret # reversal: short winners, long losers
# --- 2. Market-vol regime gate (expanding percentile, causal) ---
mkt = xs.market_ret(P.ret) # (n,) equal-weight mkt return
mkt_vol = pd.Series(mkt).rolling(vol_win, min_periods=max(5, vol_win // 2)).std().values
# expanding percentile of mkt_vol up to each row i (causal)
thresh = np.full(n, np.nan)
for i in range(baseline_win, n):
hist = mkt_vol[max(0, i - baseline_win):i + 1]
hist = hist[np.isfinite(hist)]
if len(hist) >= 10:
thresh[i] = np.nanpercentile(hist, vol_pct)
# gate: active only when mkt_vol > threshold (high-vol regime)
active = (mkt_vol > thresh) # (n,) boolean, NaN -> False
active[~np.isfinite(mkt_vol) | ~np.isfinite(thresh)] = False
# --- 3. Apply gate: set score to NaN when flat ---
score = signal.copy()
score[~active, :] = np.nan
return score
# ---------------------------------------------------------------------------
# GRID — <=5 study_xs calls
# Config space: L in {3, 5}, vol_pct in {60, 70}, universe in {majors, all}
# ---------------------------------------------------------------------------
print("=" * 70)
print("XR02: Short-term Reversal gated by high-vol regime")
print("=" * 70)
results = []
# Config 1: L=3, pct=70, majors (baseline config)
print("\n[1/5] L=3, vol_pct=70, universe=majors")
rep1 = xs.study_xs(
"XR02-L3-p70-maj",
lambda P: rev_gate_score(P, L=3, vol_win=30, baseline_win=90, vol_pct=70),
universe="majors",
H=3,
k=5,
long_short=True,
)
print(xs.fmt(rep1))
results.append(rep1)
# Config 2: L=3, pct=70, all (wider universe)
print("\n[2/5] L=3, vol_pct=70, universe=all")
rep2 = xs.study_xs(
"XR02-L3-p70-all",
lambda P: rev_gate_score(P, L=3, vol_win=30, baseline_win=90, vol_pct=70),
universe="all",
H=3,
k=5,
long_short=True,
)
print(xs.fmt(rep2))
results.append(rep2)
# Config 3: L=3, pct=60 (more permissive gate), majors
print("\n[3/5] L=3, vol_pct=60, universe=majors")
rep3 = xs.study_xs(
"XR02-L3-p60-maj",
lambda P: rev_gate_score(P, L=3, vol_win=30, baseline_win=90, vol_pct=60),
universe="majors",
H=3,
k=5,
long_short=True,
)
print(xs.fmt(rep3))
results.append(rep3)
# Config 4: L=5, pct=70, majors (longer lookback)
print("\n[4/5] L=5, vol_pct=70, universe=majors")
rep4 = xs.study_xs(
"XR02-L5-p70-maj",
lambda P: rev_gate_score(P, L=5, vol_win=30, baseline_win=90, vol_pct=70),
universe="majors",
H=5,
k=5,
long_short=True,
)
print(xs.fmt(rep4))
results.append(rep4)
# Config 5: L=3, pct=70, majors, H=5 (slower rebalance)
print("\n[5/5] L=3, vol_pct=70, universe=majors, H=5")
rep5 = xs.study_xs(
"XR02-L3-p70-maj-H5",
lambda P: rev_gate_score(P, L=3, vol_win=30, baseline_win=90, vol_pct=70),
universe="majors",
H=5,
k=5,
long_short=True,
)
print(xs.fmt(rep5))
results.append(rep5)
# ---------------------------------------------------------------------------
# BEST: pick by earns_slot, then holdout sharpe, then distinctness
# ---------------------------------------------------------------------------
def score_result(r):
earns = int(r.get("earns_slot", False))
hold_sh = r["holdout"].get("sharpe", -99)
full_sh = r["full"].get("sharpe", -99)
corr_xs01 = r.get("corr_xs01") or 1.0
# prefer earns_slot, then hold-out, then distinctness, then full
return (earns, hold_sh, full_sh, -abs(corr_xs01))
best = max(results, key=score_result)
print("\n" + "=" * 70)
print("BEST CONFIG:")
print(xs.fmt(best))
print("JSON:", xs.as_json(best))