"""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")