feat(stability): sweep stabilità — fix TR01 mean(rets), XS01 phase-tranching K=3, z-stop pairs bocciato

Audit anti-overfit su tutte le 19 sleeve (diario 2026-06-11-stability-sweep.md):

- FIX BasketTrendWorker: mean(rets) sui soli asset in posizione sovrappesava N/k
  a paniere parziale (1 long = 0.45 del capitale invece di 0.09) -> replay -44%
  vs ref +42%. Ora sum(rets)/N (convenzione canonica 1/N): replay +32% vs +42%
  (residuo = convenzione dichiarata). Solo statistica PAPER.
- XS01 PHASE-TRANCHING (gate xs01_tranche_gate: plateau K=2 E K=3 promossi,
  PORT06 OOS Sh 10.07->10.15 DD 1.48->1.38, FULL pari): la fase del roll e'
  timing-luck (Sharpe daily 1.52-2.33, DD 13.8-33% sulle 12 fasi). Worker con
  param tranches (default 1), 3 sub-book sfasati hold/3 su capitale comune,
  migrazione status legacy, last_bar_ts solo-avanti; runner forward del param;
  _defs tranches=3; hourly_report aggrega i sub-book; validatore esteso e
  PASSATO (K=1 == xsec_sim esatto, K=3 == unione fasi esatto).
- Disaster-cap z sui pairs: pre-registrato e BOCCIATO su tutti i criteri (coda
  OOS peggiora 4/6 coppie, Sharpe -10..-49%, plateau solo del danno; 5a conferma
  stop-su-MR). Record pairs_zstop_research.py; pairs restano senza stop.
- Audit drift: regression-lock trendmax OK (parita' 1.00000, plateau 2.5/3.0/3.5
  confermato), correlazioni cross-famiglia ~0 invariate; PORT06 rolling al
  19-28mo pct (normale) ma FADE 120g al 2o percentile storico -> monitor in TODO
  (nessun ritocco parametri).
- TODO: forming-bar ROT02/TSM01 era gia' fixato (v1.1.10), item chiuso.

Test: pytest 99 passed; validate_honest_workers OK; validate_xsec_worker OK.

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
This commit is contained in:
Adriano Dal Pastro
2026-06-11 13:29:14 +00:00
parent ba5ec7bd6b
commit 9d15506b05
12 changed files with 693 additions and 72 deletions
+46 -17
View File
@@ -20,35 +20,64 @@ from src.live.xsec_worker import CrossSectionalWorker
from scripts.strategies.XS01_cross_sectional import aligned_panel, xsec_sim, UNIVERSE, LB, HOLD
def main():
print("=" * 88)
print(" VALIDAZIONE CrossSectionalWorker — replay live vs backtest xsec_sim (fee 0.10% RT/book)")
print("=" * 88)
M = aligned_panel(UNIVERSE)
dfs = {a: pd.DataFrame({"timestamp": M.index.values, "close": M[a].values}) for a in UNIVERSE}
def _replay(M, dfs, params):
"""Alimenta il worker bar-per-bar su finestre trailing; ritorna il worker."""
n = len(M)
tmp = Path(tempfile.mkdtemp(prefix="xsec_val_"))
try:
w = CrossSectionalWorker(UNIVERSE, tf="1h", params={"lb": LB, "hold": HOLD},
w = CrossSectionalWorker(UNIVERSE, tf="1h", params=params,
fee_rt=0.0005, data_dir=tmp)
w._save = lambda: None; w._log = lambda *a, **k: None; w._notify = lambda *a, **k: None
window = LB + 6
for k in range(LB + 1, n + 1): # prima finestra = lb+1 barre -> ingresso al bar lb
lo = max(0, k - window)
w.tick({a: dfs[a].iloc[lo:k] for a in UNIVERSE})
bt = xsec_sim(UNIVERSE)
bt_cap = 1000.0 * (1 + bt["ret"] / 100)
cap_ok = abs(w.capital - bt_cap) / bt_cap < 0.02 if bt_cap else False
trd_ok = abs(w.total_trades - bt["trades"]) <= max(2, bt["trades"] * 0.02)
ww = w.total_wins / w.total_trades * 100 if w.total_trades else 0
print(f"\n {'':<6}{'cap':>14}{'trades':>8}{'win%':>7}")
print(f" WORKER{w.capital:>14.0f}{w.total_trades:>8d}{ww:>7.1f}")
print(f" BCKTST{bt_cap:>14.0f}{bt['trades']:>8d}{bt['win']:>7.1f}")
print(f"\n ESITO: {'OK (replay == backtest)' if (cap_ok and trd_ok) else 'DIFF -> INDAGARE'}")
print(" (diff minime attese da bar finale aperta / troncamento)")
return w
finally:
shutil.rmtree(tmp, ignore_errors=True)
def main():
print("=" * 88)
print(" VALIDAZIONE CrossSectionalWorker — replay live vs backtest xsec_sim (fee 0.10% RT/book)")
print("=" * 88)
M = aligned_panel(UNIVERSE)
dfs = {a: pd.DataFrame({"timestamp": M.index.values, "close": M[a].values}) for a in UNIVERSE}
# [1] K=1: parita' storica col backtest canonico
w = _replay(M, dfs, {"lb": LB, "hold": HOLD})
bt = xsec_sim(UNIVERSE)
bt_cap = 1000.0 * (1 + bt["ret"] / 100)
cap_ok = abs(w.capital - bt_cap) / bt_cap < 0.02 if bt_cap else False
trd_ok = abs(w.total_trades - bt["trades"]) <= max(2, bt["trades"] * 0.02)
ww = w.total_wins / w.total_trades * 100 if w.total_trades else 0
print(f"\n [K=1] {'':<6}{'cap':>14}{'trades':>8}{'win%':>7}")
print(f" WORKER{w.capital:>14.0f}{w.total_trades:>8d}{ww:>7.1f}")
print(f" BCKTST{bt_cap:>14.0f}{bt['trades']:>8d}{bt['win']:>7.1f}")
ok1 = cap_ok and trd_ok
print(f" ESITO: {'OK (replay == backtest)' if ok1 else 'DIFF -> INDAGARE'}")
# [2] K=3 (tranching live): parita' con l'unione delle fasi 0,4,8 (gate
# xs01_tranche_gate) — capitale comune, PnL/K per trade in ordine di exit
from scripts.analysis.xs01_tranche_research import xsec_trades
K = 3
w3 = _replay(M, dfs, {"lb": LB, "hold": HOLD, "tranches": K})
step = HOLD // K
allt = sorted([t for j in range(K) for t in xsec_trades(phase=j * step, M=M)],
key=lambda t: t[1])
cap = 1000.0
for _, _, net in allt:
cap = max(cap + cap * 0.15 * 3.0 * net / K, 10.0)
cap_ok3 = abs(w3.capital - cap) / cap < 0.02
trd_ok3 = abs(w3.total_trades - len(allt)) <= max(2, len(allt) * 0.02)
print(f"\n [K=3] {'':<6}{'cap':>14}{'trades':>8}")
print(f" WORKER{w3.capital:>14.0f}{w3.total_trades:>8d}")
print(f" BCKTST{cap:>14.0f}{len(allt):>8d}")
ok3 = cap_ok3 and trd_ok3
print(f" ESITO: {'OK (replay == unione fasi)' if ok3 else 'DIFF -> INDAGARE'}")
print(f"\n ESITO COMPLESSIVO: {'OK' if (ok1 and ok3) else 'DIFF -> INDAGARE'}")
print(" (diff minime attese da bar finale aperta / troncamento)")
if __name__ == "__main__":
main()