From d3dab57532f546c69dd80173e295be66b4bd537b Mon Sep 17 00:00:00 2001 From: Adriano Dal Pastro Date: Tue, 9 Jun 2026 13:01:34 +0000 Subject: [PATCH] feat(games): sessione 2 del gioco Blind Traders su timing diversi (30m/2h/4h) - engine: resampling (_RESAMPLE) per 30m/2h/4h/1d + TF_BPM esteso -> nuovi timing. - arena/run_game: TIMEFRAMES estesi, out_name e GAME_SPECS_DIR/GAME_OUT parametrizzati (game 1 non sovrascritto). - Risultato: 10 finalisti tutti 30m pairs ETH/BTC (vincitore #36: OOS Sh 12.3, 43 tr/mese). La regola >=10 trade/mese filtra i tf lunghi (4h: 4/33 qualificati). Conferma la frontiera frequenza-vs-edge. Diario 2026-06-09-blind-traders-game2.md. Co-Authored-By: Claude Opus 4.8 (1M context) --- docs/diary/2026-06-09-blind-traders-game2.md | 41 ++++++++++++++++++++ scripts/games/agent_brief.py | 3 +- scripts/games/arena.py | 7 ++-- scripts/games/engine.py | 27 +++++++++++-- scripts/games/run_game.py | 5 ++- 5 files changed, 74 insertions(+), 9 deletions(-) create mode 100644 docs/diary/2026-06-09-blind-traders-game2.md diff --git a/docs/diary/2026-06-09-blind-traders-game2.md b/docs/diary/2026-06-09-blind-traders-game2.md new file mode 100644 index 0000000..5492741 --- /dev/null +++ b/docs/diary/2026-06-09-blind-traders-game2.md @@ -0,0 +1,41 @@ +# 2026-06-09 — Gioco "Blind Traders" sessione 2: timing diversi (30m/2h/4h) + +Seconda sessione del gioco (vedi `2026-06-09-blind-traders-game.md`), stesso protocollo +(100 agenti ciechi su BTC/ETH anonimi, scoring PNL+%win, ≥10 trade/mese, 90 epoche, cull +10% ogni 10 epoche → 10 finalisti, split a 3 anti-overfit) ma su **timeframe diversi**: +game 1 = 5m/15m/1h; **game 2 = 30m/2h/4h** (medio-lunghi). Engine con resampling aggiunto +(`engine._RESAMPLE`: 30m←15m, 2h/4h←1h). Specs in `data/games/specs2/`, risultato +`data/games/tournament_result2.json`. + +## Diversita' proposte (di nuovo: riscoperta cieca della mean-reversion) +100 agenti: **74 pairs, 25 zscore, 1 breakout; 100% reversion**; tf 34/33/33. Come nel +game 1, leggendo solo le statistiche anonime (autocorrelazione negativa del log-ratio, +continuazione post-mossa ~40%) gli agenti convergono sulla reversione senza sapere che +sia crypto. + +## Classifica finale — tutti 30m pairs +Vincitore **agente #36** (30m, pairs ETH/BTC): +- TEST/OOS: **PnL +1451%, win 77%, 43.4 trade/mese, Sharpe 12.3**. +- I 10 finalisti sono TUTTI 30m pairs (TEST Sharpe ~12, win 76-77%, tpm 43-49). + +## Finding chiave: la regola ≥10 trade/mese e' un FILTRO sul timeframe +Quanti agenti per tf superano la soglia di attivita' + qualita': +| tf | agenti | ≥10 trade/mese | positivi OOS | miglior OOS Sharpe (pnl/win/tpm) | +|---|---|---|---|---| +| 30m | 34 | **34 (100%)** | 26 | **11.6** (1405% 76% 56) | +| 2h | 33 | 29 (88%) | 17 | 6.1 (512% 79% 17) | +| 4h | 33 | **4 (12%)** | 6 | 1.4 (103% 68% 14) | + +A 4h solo 4/33 agenti riescono a fare ≥10 trade/mese (le barre sono troppo rade per +la reversione pairs); e l'edge cala col timeframe (Sharpe 11.6→6.1→1.4). Per questo i +finalisti sono tutti 30m. + +## Lezione cross-game (game 1 + game 2) +Esiste una **frontiera frequenza-vs-edge**: la regola ≥10 trade/mese mette un *pavimento* +sul timeframe (i lunghi non fanno abbastanza trade), il costo/edge mette un *soffitto* (i +cortissimi sono cost-fragili). Il punto ottimo e' **il timeframe piu' corto con edge ancora +robusto**: game 1 (con 15m disponibile) → vince 15m; game 2 (senza 15m) → vince 30m. Sempre +**ETH/BTC spread reversion**. Coerente con l'analisi di robustezza del 15m +(`2026-06-09-pairs15m-robustezza.md`): piu' corto = piu' trade = piu' edge di backtest, ma +piu' fragile ai costi. Il gioco trova l'edge; la prudenza di deploy (mezza size) gestisce +la fragilita'. Artefatti: `scripts/games/`, `data/games/tournament_result2.json`. diff --git a/scripts/games/agent_brief.py b/scripts/games/agent_brief.py index c936ef0..3a7b86d 100644 --- a/scripts/games/agent_brief.py +++ b/scripts/games/agent_brief.py @@ -44,7 +44,8 @@ def make_digest(tf: str, window: int = 60, seed: int = 0): n = data["n"] # finestra recente normalizzata (base 100) per "vedere" la forma s = max(0, n - window) - dig = {"timeframe_id": {"1h": "T1", "15m": "T2", "5m": "T3"}.get(tf, "T?"), + dig = {"timeframe_id": {"5m": "T1", "15m": "T2", "30m": "T3", "1h": "T4", + "2h": "T5", "4h": "T6", "1d": "T7"}.get(tf, "T?"), "n_bars_total": n, "series": {}} for name in ("A", "B"): o = data[name] diff --git a/scripts/games/arena.py b/scripts/games/arena.py index 486de70..0b33023 100644 --- a/scripts/games/arena.py +++ b/scripts/games/arena.py @@ -44,7 +44,7 @@ SPACE = { } SINGLE_FAMILIES = ["zscore", "breakout", "ma_cross", "rsi", "momentum"] DIRECTIONS = ["reversion", "trend"] -TIMEFRAMES = ["1h", "15m", "5m"] # timing diversi su cui competono gli agenti +TIMEFRAMES = ["5m", "15m", "30m", "1h", "2h", "4h", "1d"] # tutti i timing validi def _rand_param(rng, lo, hi, typ): @@ -143,7 +143,8 @@ class Agent: def run_tournament(specs, briefs=None, seed=7, - epochs=90, cull_every=10, cull_n=10, log=print): + epochs=90, cull_every=10, cull_n=10, log=print, + out_name="tournament_result.json"): rng = random.Random(seed) # carica solo i timeframe effettivamente usati dagli agenti used_tfs = sorted({_normalize(s).get("tf", "1h") for s in specs}) @@ -204,7 +205,7 @@ def run_tournament(specs, briefs=None, seed=7, "survivors": len(survivors), "results": results, "history": history, "reveal": {"A": "BTC", "B": "ETH", "tf": "1h"}} - (OUT / "tournament_result.json").write_text(json.dumps(payload, indent=2)) + (OUT / out_name).write_text(json.dumps(payload, indent=2)) return payload diff --git a/scripts/games/engine.py b/scripts/games/engine.py index 1196672..042eb8f 100644 --- a/scripts/games/engine.py +++ b/scripts/games/engine.py @@ -18,8 +18,13 @@ import pandas as pd from src.data.downloader import load_data FEE_RT = 0.001 # 0.10% round-trip (taker Deribit, baseline progetto) -TF_BPM = {"5m": 12 * 24 * 30, "15m": 4 * 24 * 30, "1h": 24 * 30} # barre/mese per tf +TF_BPM = {"5m": 12 * 24 * 30, "15m": 4 * 24 * 30, "30m": 2 * 24 * 30, + "1h": 24 * 30, "2h": 12 * 30, "4h": 6 * 30, "1d": 30} # barre/mese per tf MIN_TRADES_PER_MONTH = 10.0 +# timeframe non presenti come parquet -> resamplati da una base (open=first, +# high=max, low=min, close=last, volume=sum). Permette "timing diversi" nel gioco. +_RESAMPLE = {"30m": ("15m", "30min"), "2h": ("1h", "2h"), + "4h": ("1h", "4h"), "1d": ("1h", "1D")} # Slippage per LATO (oltre alle fee). 0 = come prima. Single-leg paga 2 lati # (ingresso+uscita), i pairs ne pagano 4 (2 gambe x 2 lati). @@ -34,14 +39,30 @@ def set_slippage(slip_per_side: float): # -------------------------------------------------------------------------- # Dati anonimizzati # -------------------------------------------------------------------------- +def _load_tf(asset: str, tf: str): + """Carica un asset al timeframe tf (parquet diretto, o resample da una base).""" + if tf in _RESAMPLE: + base_tf, rule = _RESAMPLE[tf] + d = load_data(asset, base_tf).copy() + d["dt"] = pd.to_datetime(d["datetime"]) + g = d.set_index("dt").resample(rule).agg( + {"open": "first", "high": "max", "low": "min", "close": "last", + "volume": "sum"}).dropna(subset=["open", "close"]) + g = g.reset_index() + g["datetime"] = g["dt"] + g["timestamp"] = (g["dt"].astype("int64") // 1_000_000) + return g.drop(columns=["dt"]) + return load_data(asset, tf).copy() + + def load_anon(tf: str = "1h"): """Carica BTC->A, ETH->B allineati sull'intersezione temporale. Ritorna un dict con array OHLC per A e B + datetime. I nomi reali NON compaiono: gli agenti vedono solo 'A' e 'B'. """ - btc = load_data("BTC", tf).copy() - eth = load_data("ETH", tf).copy() + btc = _load_tf("BTC", tf) + eth = _load_tf("ETH", tf) for d in (btc, eth): d["dt"] = pd.to_datetime(d["datetime"]) btc = btc.set_index("dt") diff --git a/scripts/games/run_game.py b/scripts/games/run_game.py index 68e1bfa..df2f79e 100644 --- a/scripts/games/run_game.py +++ b/scripts/games/run_game.py @@ -16,7 +16,8 @@ from pathlib import Path from scripts.games import engine from scripts.games.arena import random_spec, run_tournament, leaderboard, _normalize -SPECS_DIR = Path("data/games/specs") +SPECS_DIR = Path(os.environ.get("GAME_SPECS_DIR", "data/games/specs")) +OUT_NAME = os.environ.get("GAME_OUT", "tournament_result.json") N = 100 @@ -63,7 +64,7 @@ def main(): f"(single-leg {2*slip*100:.2f}% RT extra, pairs {4*slip*100:.2f}% extra)") specs, briefs = load_specs() payload = run_tournament(specs, briefs=briefs, seed=2026, - epochs=90, cull_every=10, cull_n=10) + epochs=90, cull_every=10, cull_n=10, out_name=OUT_NAME) leaderboard(payload, top=10) rev = payload["reveal"] print(f"\n>>> RIVELAZIONE: Serie X = {rev['A']}, Serie Y = {rev['B']} "