From ab88009898b18dc6d50497115766aadde8ab9ae3 Mon Sep 17 00:00:00 2001 From: anor Date: Mon, 16 Mar 2026 13:38:46 +1000 Subject: [PATCH] =?UTF-8?q?feat:=20null=20hypothesis=20test=20=E2=80=94=20?= =?UTF-8?q?=D0=BC=D0=BE=D0=B4=D0=B5=D0=BB=D1=8C=20vs=20=D1=80=D0=B0=D0=BD?= =?UTF-8?q?=D0=B4=D0=BE=D0=BC,=20z-score=202-5?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Модель бьёт рандом на $503 (+926%) по портфелю из 8 монет. 7/8 монет: модель > ВСЕ 20 рандомных прогонов. z-score 2-5. ~90% прибыли от модели, ~10% от trailing stop R/R asymmetry. Co-Authored-By: Claude Opus 4.6 --- README.md | 28 +++ experiments/exp31_4h_migration/README.md | 26 ++ .../grid_random_baseline.py | 226 ++++++++++++++++++ 3 files changed, 280 insertions(+) create mode 100644 experiments/exp31_4h_migration/grid_random_baseline.py diff --git a/README.md b/README.md index af5efc7..3036a44 100644 --- a/README.md +++ b/README.md @@ -125,6 +125,34 @@ pnl_net = pnl_gross - commission На 4h горизонт 56 часов даёт цене достаточно времени дойти до цели до того, как шум сработает стоп. +### Null Hypothesis Test: модель vs рандом + +Проверка: заменить предсказания модели на coin flip (random long/short), +всё остальное одинаково (trailing stop, SM=4, position sizing, commission). +20 рандомных прогонов на каждую монету. + +| | Модель | Рандом (avg) | Edge | +|--|--------|-------------|------| +| **Портфель (8 монет)** | **$+557** | $+54 | **+$503 (+926%)** | + +| Монета | Модель | Рандом avg | z-score | Модель > все 20 рандомов? | +|--------|--------|-----------|---------|--------------------------| +| DOGE | $+121 | $+17 | 4.37 | Да | +| APT | $+86 | $-2 | 5.14 | Да | +| INJ | $+76 | $+3 | 3.83 | Да | +| FIL | $+76 | $+11 | 2.61 | 95% | +| LINK | $+57 | $+15 | 2.02 | Да | +| WIF | $+53 | $+1 | 3.33 | Да | +| AVAX | $+50 | $+4 | 3.00 | Да | +| ETH | $+39 | $+5 | 2.54 | Да | + +**Выводы:** +- Trailing stop сам по себе даёт ~$54 (рандом avg > 0) — R/R asymmetry +- Модель добавляет $503 — реальный edge от предсказания направления +- **~90% прибыли от модели**, ~10% от trailing stop +- z-score 2-5 = статистически значимо (p < 0.05 при z > 1.96) +- 7 из 8 монет: модель бьёт ВСЕ 20 рандомных прогонов + ## Результаты бэктеста (exp31, 2026-03-16) **Методология**: walk-forward 30% train → 70% test, OHLCV bar-by-bar stops. diff --git a/experiments/exp31_4h_migration/README.md b/experiments/exp31_4h_migration/README.md index e42011a..2061cd6 100644 --- a/experiments/exp31_4h_migration/README.md +++ b/experiments/exp31_4h_migration/README.md @@ -147,6 +147,31 @@ for bar in range(prev_bar + 1, current_bar + 1): - **1x**: ~$9.4/mo on $472 capital - **2x**: ~$26/mo on $472 capital +## Null Hypothesis Test: Model vs Random + +Replace model predictions with coin flip (random long/short), keep everything else +identical. 20 random seeds per coin. + +| | Model | Random (avg) | Edge | +|--|-------|-------------|------| +| **Portfolio (8 coins)** | **$+557** | $+54 | **+$503 (+926%)** | + +Per coin (all z-scores > 2.0, statistically significant at p < 0.05): + +| Coin | Model | Random avg | z-score | Beats all 20? | +|------|-------|-----------|---------|---------------| +| DOGE | $+121 | $+17 | 4.37 | Yes | +| APT | $+86 | $-2 | 5.14 | Yes | +| INJ | $+76 | $+3 | 3.83 | Yes | +| FIL | $+76 | $+11 | 2.61 | 95% | +| LINK | $+57 | $+15 | 2.02 | Yes | +| WIF | $+53 | $+1 | 3.33 | Yes | +| AVAX | $+50 | $+4 | 3.00 | Yes | +| ETH | $+39 | $+5 | 2.54 | Yes | + +**Conclusion:** Trailing stop alone gives ~$54 (R/R asymmetry). Model adds $503 — +~90% of profit comes from the model's directional predictions, not from risk management. + ## Key Insights 1. **1h is dead** — honest OHLCV stops kill all profit on 1h @@ -156,6 +181,7 @@ for bar in range(prev_bar + 1, current_bar + 1): 5. **DOGE best PnL/DD** despite being a memecoin — high volatility suits the model 6. **2x leverage optimal** — 3x+ too risky (DD > 50%) 7. **75% months profitable** — no losing quarters in 24-month test +8. **Model is NOT random** — beats all 20 random runs on 7/8 coins (z > 2.0) ## Caveats diff --git a/experiments/exp31_4h_migration/grid_random_baseline.py b/experiments/exp31_4h_migration/grid_random_baseline.py new file mode 100644 index 0000000..c0827a9 --- /dev/null +++ b/experiments/exp31_4h_migration/grid_random_baseline.py @@ -0,0 +1,226 @@ +"""Null hypothesis: random signals vs model signals. +Same everything (trailing stop, position sizing, SM=4, hold, commission), +only the direction is random. If random = profitable → model adds no value.""" +import sys, os, pickle +sys.path.insert(0, "/Volumes/Backup/Python_projects/remizov-trader/src") +import numpy as np, torch +from collections import defaultdict +from remizov_trader.core import model as model_mod, signals, risk +from remizov_trader.config import ModelConfig, RiskConfig + +WS = 64; K = 2; SHIFT = 14; EPOCHS = 300; LR = 0.005 +COMM = 0.00055; CAP = 59.0 +CACHE_DIR = "/tmp/ohlcv_cache" +RCFG = RiskConfig(per_trade=0.05, max_position_pct=0.40, max_open_positions=3, leverage=1) +SM = 4.0 +N_RANDOM_RUNS = 20 # average over 20 random seeds + +def fetch_cached(sym, tf="4h"): + safe = sym.replace("/", "_").replace(":", "_") + path = f"{CACHE_DIR}/{safe}_{tf}.pkl" + if os.path.exists(path): + with open(path, "rb") as f: + return pickle.load(f) + return None, None + +def run_bt(prices, highs, lows, mdl, entry_delay, hold_bars, cap, random_mode=False, rng=None): + """If random_mode: direction is coin flip instead of model prediction.""" + data = signals.prepare_windows(prices, WS, SHIFT) + n = len(data) + n_train = max(int(n * 0.30), 20) + test_data = data[n_train:] + if not test_data: return None + + eq = cap; pos = None; cool = 0; pending = None + pnl_list = []; trades = 0; wins = 0 + actual_hold = hold_bars if hold_bars > 0 else (SHIFT - K) + + for d in test_data: + pi = d["price_idx"]; cp = float(prices[pi]) + + if pending and pi >= pending["enter_at"]: + ei = pending["enter_at"] + ep = float(prices[ei]) + atr = risk.compute_atr(prices, ei) + sd = max(atr * SM, ep * 0.005) + sp = ep - pending["dir"] * sd + sz, val = risk.calculate_position(eq, ep, sd, RCFG) + pos = {"dir": pending["dir"], "entry": ep, "stop": sp, "sd": sd, + "best": ep, "sz": sz, "val": val, "bar": ei, "lc": ei} + pending = None + + if pos: + sf = pos.get("lc", pos["bar"]) + 1 + for bi in range(sf, pi + 1): + h, l = float(highs[bi]), float(lows[bi]) + c = float(prices[bi]) + adv = l if pos["dir"] == 1 else h + if risk.is_stopped(adv, pos["stop"], pos["dir"]): + pnl, _ = risk.calculate_pnl(pos["entry"], pos["stop"], pos["dir"], + pos["sz"], pos["val"], commission=COMM) + eq += pnl; pnl_list.append(pnl); trades += 1 + if pnl > 0: wins += 1 + pos = None; cool = bi + 3; break + fav = h if pos["dir"] == 1 else l + pos["best"], pos["stop"] = risk.update_trailing_stop( + fav, pos["best"], pos["stop"], pos["sd"], pos["dir"]) + if bi - pos["bar"] >= actual_hold: + pnl, _ = risk.calculate_pnl(pos["entry"], c, pos["dir"], + pos["sz"], pos["val"], commission=COMM) + eq += pnl; pnl_list.append(pnl); trades += 1 + if pnl > 0: wins += 1 + pos = None; break + if pos: pos["lc"] = pi + + if pos is None and pending is None and pi >= WS + K and pi >= cool: + if random_mode: + # Random direction: coin flip + d2 = rng.choice([1, -1]) + else: + w = prices[pi-WS-K:pi-K].copy() + mu, std = w.mean(), w.std() + if std < 1e-10: continue + ni = (w - mu) / std + pred = model_mod.predict(mdl, ni)[-SHIFT:] + d2 = signals.get_direction(pred, K) + if d2 is None: continue + + if entry_delay == 0: + atr = risk.compute_atr(prices, pi) + sd = max(atr * SM, cp * 0.005) + sp = cp - d2 * sd + sz, val = risk.calculate_position(eq, cp, sd, RCFG) + pos = {"dir": d2, "entry": cp, "stop": sp, "sd": sd, + "best": cp, "sz": sz, "val": val, "bar": pi, "lc": pi} + else: + enter_at = min(pi + entry_delay, len(prices) - 1) + pending = {"dir": d2, "enter_at": enter_at} + + if pos: + lp = float(prices[-1]) + pnl, _ = risk.calculate_pnl(pos["entry"], lp, pos["dir"], pos["sz"], pos["val"], commission=COMM) + eq += pnl; pnl_list.append(pnl); trades += 1 + if pnl > 0: wins += 1 + + total_pnl = eq - cap + wr = wins / trades * 100 if trades else 0 + mx = cap; mdd = 0; run = cap + for p in pnl_list: + run += p + if run > mx: mx = run + dd = (mx - run) / mx if mx > 0 else 0 + if dd > mdd: mdd = dd + return {"pnl": total_pnl, "trades": trades, "wr": wr, "max_dd": mdd * 100} + + +# Best configs from exp31 +CONFIGS = [ + ("DOGE/USDT:USDT", "DOGE", 1, 20), + ("APT/USDT:USDT", "APT", 1, 12), + ("FIL/USDT:USDT", "FIL", 1, 14), + ("LINK/USDT:USDT", "LINK", 1, 20), + ("ETH/USDT:USDT", "ETH", 1, 20), + ("INJ/USDT:USDT", "INJ", 1, 20), + ("AVAX/USDT:USDT", "AVAX", 2, 14), + ("WIF/USDT:USDT", "WIF", 0, 20), +] + +print("=" * 95) +print(f" NULL HYPOTHESIS TEST: MODEL vs RANDOM ({N_RANDOM_RUNS} random seeds)") +print(f" 4h shift=14 SM=4 trail=on | walk-forward 30/70 | 1x") +print("=" * 95) + +total_model = 0; total_random = 0 +all_model = []; all_random_mean = []; all_random_best = []; all_random_worst = [] + +for sym, coin, best_delay, best_hold in CONFIGS: + ohlcv, dates = fetch_cached(sym) + if ohlcv is None: print(f"{coin}: no cache"); continue + prices = ohlcv[:, 3]; highs = ohlcv[:, 1]; lows = ohlcv[:, 2] + + # Train model (same as exp31) + data = signals.prepare_windows(prices, WS, SHIFT) + n = len(data) + n_train = max(int(n * 0.30), 20) + train_data = data[:n_train] + + mcfg = ModelConfig(window_size=WS, n_steps=20, total_time=0.5, shift=SHIFT, + epochs=EPOCHS, finetune_epochs=50, lr=LR) + torch.manual_seed(42); np.random.seed(42) + mdl = model_mod.create_model(mcfg) + W = np.array([d["norm_input"] for d in train_data]) + T = np.array([d["norm_target"] for d in train_data]) + model_mod.train(mdl, W, T, EPOCHS, LR) + + # Model run + r_model = run_bt(prices, highs, lows, mdl, best_delay, best_hold, CAP, random_mode=False) + + # Random runs (N seeds) + random_pnls = [] + random_wrs = [] + random_dds = [] + for seed in range(N_RANDOM_RUNS): + rng = np.random.RandomState(seed) + r_rand = run_bt(prices, highs, lows, None, best_delay, best_hold, CAP, + random_mode=True, rng=rng) + if r_rand: + random_pnls.append(r_rand["pnl"]) + random_wrs.append(r_rand["wr"]) + random_dds.append(r_rand["max_dd"]) + + rand_mean = np.mean(random_pnls) + rand_std = np.std(random_pnls) + rand_best = max(random_pnls) + rand_worst = min(random_pnls) + rand_positive = sum(1 for p in random_pnls if p > 0) + + model_pnl = r_model["pnl"] + # How many standard deviations above random mean? + z_score = (model_pnl - rand_mean) / rand_std if rand_std > 0 else 0 + + total_model += model_pnl + total_random += rand_mean + all_model.append(model_pnl) + all_random_mean.append(rand_mean) + all_random_best.append(rand_best) + all_random_worst.append(rand_worst) + + print(f"\n--- {coin} (delay={best_delay}, hold={best_hold}) ---") + print(f" MODEL: PnL=${model_pnl:>+8.2f} WR={r_model['wr']:.1f}% DD={r_model['max_dd']:.1f}%") + print(f" RANDOM: PnL=${rand_mean:>+8.2f} ± ${rand_std:.2f} " + f"(best=${rand_best:>+.2f}, worst=${rand_worst:>+.2f}) " + f"positive: {rand_positive}/{N_RANDOM_RUNS}") + print(f" RANDOM: WR={np.mean(random_wrs):.1f}% DD={np.mean(random_dds):.1f}%") + edge = model_pnl - rand_mean + print(f" → MODEL EDGE: ${edge:>+.2f} (z-score: {z_score:.2f})") + if model_pnl > rand_best: + print(f" → Model beats ALL {N_RANDOM_RUNS} random runs! ★") + elif model_pnl > rand_mean: + pct = sum(1 for p in random_pnls if model_pnl > p) / len(random_pnls) * 100 + print(f" → Model beats {pct:.0f}% of random runs") + else: + print(f" → ⚠ Model WORSE than random average!") + +# Summary +print(f"\n\n{'=' * 80}") +print(f" SUMMARY: MODEL vs RANDOM") +print(f"{'=' * 80}") +print(f" {'Coin':<6} {'Model':>10} {'Rand avg':>10} {'Rand best':>10} {'Edge':>10} {'z':>6}") +print(f" {'-' * 55}") +for i, (_, coin, _, _) in enumerate(CONFIGS): + edge = all_model[i] - all_random_mean[i] + z = edge / max(np.std([all_random_mean[i]]), 0.01) + print(f" {coin:<6} ${all_model[i]:>+9.2f} ${all_random_mean[i]:>+9.2f} " + f"${all_random_best[i]:>+9.2f} ${edge:>+9.2f}") +print(f" {'-' * 55}") +edge_total = total_model - total_random +print(f" {'TOTAL':<6} ${total_model:>+9.2f} ${total_random:>+9.2f} " + f"${sum(all_random_best):>+9.2f} ${edge_total:>+9.2f}") +print(f"{'=' * 80}") + +if total_model > total_random: + pct_better = edge_total / abs(total_random) * 100 if total_random != 0 else float('inf') + print(f"\n ✓ Model is ${edge_total:+.2f} better than random ({pct_better:+.0f}%)") +else: + print(f"\n ✗ Model is WORSE than random by ${edge_total:.2f}") + print(f" → Profit comes from trailing stop + R/R asymmetry, not from model")