fix(live): smoke test REALE pairs -> live solo ETH/BTC (alt assenti su Deribit)

Test reale (scripts/analysis/live_smoke_pairs.py): fetch live Cerbero + tick vero per
coppia. Scoperta: l'endpoint Deribit serve solo BTC/ETH freschi; LTC/ADA-PERPETUAL sono
VUOTI e SOL ha pochi dati. Il backtest usava i parquet locali (8 asset completi), ma la
pipeline live no -> tradabile live SOLO ETH/BTC.

- strategies.yml: abilitata solo la coppia ETH/BTC; le altre 4 disabilitate con nota
  (valide a backtest, off finche' non si aggiunge un feed live per gli alt).
- live_smoke_pairs.py (nuovo): verifica end-to-end della pipeline live (no ordini reali).
- CLAUDE.md / docstring PR01: distinzione esplicita logica-validata vs live-disponibile.

Onesta': la validazione precedente era backtest-equivalence (ESATTA), NON test live;
il test live ha rivelato il limite del feed alt.

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
This commit is contained in:
2026-05-29 09:16:50 +02:00
parent 4dc0e77ee5
commit bd31a15548
4 changed files with 114 additions and 18 deletions
+5 -2
View File
@@ -160,8 +160,11 @@ quest'ultima riconferma la dominanza mean-reversion). Due edge reali:
(1.96, la più debole). Pattern: sempre alt-liquido vs major. Plateau confermato
(heatmap 20/20 Sharpe>1) + walk-forward (ETH/BTC 11/12 finestre+). **BNB/ETH scartata**
(overfit). Corr col mercato ~0.02-0.08. Fee su **2 gambe**: worker live implementato
(`src/live/pairs_worker.py`, sezione `pairs:` in `strategies.yml`) e validato — il replay
combacia ESATTAMENTE col backtest (`scripts/analysis/validate_worker_pairs.py`). Verifica edge: `pairs_research.py`.
(`src/live/pairs_worker.py`, sezione `pairs:` in `strategies.yml`). LOGICA validata
(`validate_worker_pairs.py`: replay == backtest ESATTO). LIVE (`live_smoke_pairs.py`,
smoke reale Cerbero): tradabile **solo ETH/BTC** — LTC/ADA-PERPETUAL VUOTI su Deribit,
SOL pochi dati → le altre 4 coppie restano valide a backtest ma DISABILITATE finché non
si aggiunge un feed live alt. Verifica edge: `pairs_research.py`.
- **TSM01** (`scripts/analysis/tsmom_research.py`): TSMOM multi-orizzonte 3/6/12m + risk-off,
**gross 0.30**, distinto da ROT02 (corr 0.62), DD 15-22%, mai un anno negativo. Robusto
(36/36 config OOS+) ma diversificatore, non motore di ritorno (rende meno di ROT02).
+87
View File
@@ -0,0 +1,87 @@
"""Smoke test REALE dei pairs: fetch live da Cerbero + un tick vero per coppia.
A differenza di validate_worker_pairs.py (replay su parquet storici), questo verifica
la PIPELINE LIVE end-to-end: chiama Cerbero per entrambe le gambe, controlla che lo
strumento esista e sia fresco, fa un tick reale del PairsWorker e riporta lo stato.
Serve a scoprire i problemi che il backtest nasconde (es. un perp alt non disponibile
sull'endpoint Deribit). NON apre ordini reali: e' solo paper/lettura.
"""
from __future__ import annotations
import sys
import shutil
import tempfile
from datetime import datetime, timezone, timedelta
from pathlib import Path
import numpy as np
import pandas as pd
PROJECT_ROOT = Path(__file__).resolve().parents[2]
sys.path.insert(0, str(PROJECT_ROOT))
from src.live.cerbero_client import CerberoClient
from src.live.multi_runner import INSTRUMENT_MAP
from src.live.pairs_worker import PairsWorker
from scripts.strategies.PR01_pairs_reversion import PAIRS
def fetch(cli, asset, start, end):
inst = INSTRUMENT_MAP.get(asset, f"{asset}-PERPETUAL")
try:
cs = cli.get_historical(inst, start.strftime("%Y-%m-%d"), end.strftime("%Y-%m-%d"), "60")
if not cs:
return inst, None, "VUOTO (strumento assente sull'endpoint)"
df = pd.DataFrame(cs)
df["timestamp"] = df["timestamp"].astype("int64")
df = df.sort_values("timestamp").reset_index(drop=True)
last = pd.to_datetime(df["timestamp"].iloc[-1], unit="ms", utc=True)
age = (datetime.now(timezone.utc) - last).total_seconds() / 3600
return inst, df, f"{len(df)} barre, ultima {last:%Y-%m-%d %H:%M} ({age:.1f}h fa)"
except Exception as e:
return inst, None, f"ERRORE {type(e).__name__}: {str(e)[:60]}"
def main():
cli = CerberoClient()
end = datetime.now(timezone.utc)
start = end - timedelta(days=60)
assets = sorted({a for a, _, _ in PAIRS} | {b for _, b, _ in PAIRS})
print("=" * 80)
print(" SMOKE TEST LIVE PAIRS — fetch reale Cerbero + tick (no ordini reali)")
print("=" * 80)
data = {}
for a in assets:
inst, df, msg = fetch(cli, a, start, end)
data[a] = df
print(f" {a:<4s} [{inst:<16s}] {msg}")
print("\n tick reale per coppia:")
tmp = Path(tempfile.mkdtemp())
try:
for a, b, p in PAIRS:
if data.get(a) is None or data.get(b) is None:
print(f" {a}/{b:<4s}: SKIP (manca feed live di una gamba) -> non tradabile live ora")
continue
w = PairsWorker(a, b, "1h", params=p, fee_rt=0.001, data_dir=tmp)
w._log = lambda *x, **k: None
w._notify = lambda *x, **k: None
m = data[a][["timestamp", "close"]].merge(
data[b][["timestamp", "close"]], on="timestamp", how="inner")
if len(m) < p["n"] + 2:
print(f" {a}/{b:<4s}: merge {len(m)} barre < n+2 ({p['n']+2}) -> dati insufficienti")
continue
z, _ = w._zscore(m["close_x"].values, m["close_y"].values)
w.tick(data[a], data[b])
state = ("IN POS " + ("LONG " + a if w.direction == 1 else "SHORT " + a)
if w.in_position else "FLAT")
print(f" {a}/{b:<4s}: OK merge {len(m)} barre, z_ora={z[-1]:+.2f} -> {state}")
finally:
shutil.rmtree(tmp, ignore_errors=True)
print("\n Solo le coppie con entrambe le gambe fresche su Cerbero sono tradabili live.")
if __name__ == "__main__":
main()
+7 -4
View File
@@ -27,10 +27,13 @@ Validazione anti-overfit (netto, fee 0.20% RT/coppia a 2 gambe, leva 3x, OOS = u
- SCARTATA BNB/ETH: robusta solo coi suoi parametri (overfit), crolla con la universale.
WORKER LIVE: implementato `src/live/pairs_worker.py` (2 gambe, fee doppie, stato
persistente) e wired in `multi_runner` (sezione `pairs:` in strategies.yml). Validato
da `scripts/analysis/validate_worker_pairs.py`: il replay live combacia ESATTAMENTE col
backtest pairs_sim (ETH/BTC: capitale, n.trade e win% identici). Resta da verificare in
trading reale la shortabilita'/liquidita' del perp B sugli alt (LTC/SOL/ADA).
persistente) e wired in `multi_runner` (sezione `pairs:` in strategies.yml). Validato:
- LOGICA: `validate_worker_pairs.py` -> replay storico == backtest pairs_sim ESATTO
(ETH/BTC: capitale, n.trade, win% identici).
- LIVE: `live_smoke_pairs.py` (smoke reale Cerbero) -> tradabile live SOLO ETH/BTC.
LTC/ADA-PERPETUAL sono VUOTI sull'endpoint Deribit, SOL ha pochi dati. Le altre 4
coppie sono valide nel BACKTEST (parquet locali) ma DISABILITATE in strategies.yml
finche' non si aggiunge un feed live per gli alt (Bybit/Hyperliquid via Cerbero).
"""
from __future__ import annotations
+15 -12
View File
@@ -94,37 +94,40 @@ strategies:
# ---------------------------------------------------------------------------
# PR01 — PAIRS market-neutral spread reversion (worker a 2 GAMBE: src/live/pairs_worker.py)
# Config UNIVERSALE n50 z2 zx0.75 mb72 (anti-overfit, validata walk-forward).
# fee_rt 0.001/gamba -> 0.20% RT/coppia. ATTENZIONE: richiede perp shortabile per
# entrambe le gambe; su alt (LTC/SOL/ADA) verificare liquidita'/fill prima del live reale.
# fee_rt 0.001/gamba -> 0.20% RT/coppia.
# SMOKE TEST LIVE (scripts/analysis/live_smoke_pairs.py, 2026-05-29): l'endpoint
# Cerbero/Deribit serve solo BTC/ETH freschi; LTC/ADA-PERPETUAL sono VUOTI e SOL ha
# pochi dati. Quindi LIVE e' tradabile SOLO ETH/BTC. Le altre coppie restano valide nel
# backtest (parquet locali completi) ma DISABILITATE finche' non si aggiunge un feed live
# per gli alt (Bybit/Hyperliquid via Cerbero). Il runner comunque salta i pair senza feed.
pairs:
- name: PR01_pairs_reversion
- name: PR01_pairs_reversion # UNICA tradabile live (feed Cerbero OK)
a: ETH
b: BTC
tf: 1h
enabled: true
params: {n: 50, z_in: 2.0, z_exit: 0.75, max_bars: 72, jump_max: 0.08}
- name: PR01_pairs_reversion
- name: PR01_pairs_reversion # feed alt assente su Deribit -> off
a: LTC
b: ETH
tf: 1h
enabled: true
enabled: false
params: {n: 50, z_in: 2.0, z_exit: 0.75, max_bars: 72, jump_max: 0.08}
- name: PR01_pairs_reversion
- name: PR01_pairs_reversion # feed alt assente su Deribit -> off
a: ADA
b: ETH
tf: 1h
enabled: true
enabled: false
params: {n: 50, z_in: 2.0, z_exit: 0.75, max_bars: 72, jump_max: 0.08}
- name: PR01_pairs_reversion
- name: PR01_pairs_reversion # LTC assente su Deribit -> off
a: BTC
b: LTC
tf: 1h
enabled: true
enabled: false
params: {n: 50, z_in: 2.0, z_exit: 0.75, max_bars: 72, jump_max: 0.08}
# ETH/SOL: la piu' debole (DD ~63%, storia SOL corta) -> peso ridotto consigliato
- name: PR01_pairs_reversion
- name: PR01_pairs_reversion # SOL pochi dati su Deribit; la piu' debole -> off
a: ETH
b: SOL
tf: 1h
enabled: true
enabled: false
params: {n: 50, z_in: 2.0, z_exit: 0.75, max_bars: 72, jump_max: 0.08}