"""Exp26i: Comprehensive final tests. 5 tests: 1. SIMPLE RULE REPLACEMENT: ATR/Range filter + trailing stop (no neural net) 2. PNL SIGNIFICANCE: Bootstrap CI for per-trade PnL 3. MARKET REGIMES: Bull/Bear/Flat performance 4. ARCHITECTURE COMPARISON: MLP / Linear / PDE 5. WALK-FORWARD: Retrain every N bars """ import sys from pathlib import Path sys.path.insert(0, str(Path(__file__).parent.parent.parent / "src")) sys.path.insert(0, str(Path(__file__).parent.parent)) import numpy as np import torch import torch.nn as nn from remizov_trader.core import model as model_mod, signals, risk from remizov_trader.core.net import EnhancedRemizovNet from common.dataset import load_or_fetch from common.metrics import save_results TRAIN_RATIO = 0.3 STOP_SCALE = 0.5 STOP_MULT = 2.0 LOOKAHEAD = 30 SHIFT = 7 N_BOOTSTRAP = 2000 ASSETS = [ {"ticker": "BTC-USD", "ws": 64, "K": 3}, {"ticker": "ETH-USD", "ws": 96, "K": 2}, {"ticker": "ADA-USD", "ws": 64, "K": 3}, {"ticker": "DOGE-USD", "ws": 48, "K": 3}, {"ticker": "SOL-USD", "ws": 96, "K": 3}, ] def _sim_trail(prices, idx, direction, stop_dist): entry = prices[idx] best = entry stop = entry - direction * stop_dist for i in range(1, LOOKAHEAD + 1): if idx + i >= len(prices): break p = prices[idx + i] best, stop = risk.update_trailing_stop(p, best, stop, stop_dist, direction) if risk.is_stopped(p, stop, direction): return (p - entry) / entry * direction last = prices[min(idx + LOOKAHEAD, len(prices) - 1)] return (last - entry) / entry * direction def _train_remizov(prices, ws, train_indices=None): data = signals.prepare_windows(prices, ws, SHIFT) if train_indices is None: n_train = max(int(len(data) * TRAIN_RATIO), 20) train_data = data[:n_train] else: train_data = [d for d in data if d["price_idx"] in train_indices] if len(train_data) < 10: train_data = data[:max(int(len(data) * TRAIN_RATIO), 20)] torch.manual_seed(42) np.random.seed(42) mdl = EnhancedRemizovNet(grid_size=ws, n_steps=20, total_time=0.5, dx=1.0 / ws, use_sde=True) model_mod.train(mdl, np.array([d["norm_input"] for d in train_data]), np.array([d["norm_target"] for d in train_data]), 200, 0.003) return mdl, data def _get_model_trades(prices, mdl, data, n_train, ws, K): """Get trades from Remizov model with production filters.""" test_data = data[n_train:] trades = [] for d in test_data: idx = d["price_idx"] if idx + LOOKAHEAD >= len(prices) or idx < ws + K + 1: continue w = prices[idx - ws - K: idx - K].copy() mu, std = w.mean(), w.std() if std < 1e-10: continue pred = model_mod.predict(mdl, (w - mu) / std) pred_new = pred[-SHIFT:] pred_dir = signals.get_direction(pred_new, K) if pred_dir is None: continue pred_denorm = pred_new * std + mu pred_amp = float(np.max(pred_denorm) - np.min(pred_denorm)) atr = risk.compute_atr(prices, idx) if atr <= 0: continue confirm = prices[idx - K:idx].copy() corr, confirmed = signals.check_shape_confirmation( pred_new, confirm, mu, std, K, 0.5) confidence = abs(corr) * (pred_amp / atr) stop_dist = max(atr * STOP_MULT * STOP_SCALE, prices[idx] * 0.005) pnl = _sim_trail(prices, idx, pred_dir, stop_dist) trades.append({ "idx": idx, "pnl": pnl * 100, "pred_dir": pred_dir, "confidence": confidence, "confirmed": confirmed, "atr": atr, "pred_amp_atr": pred_amp / atr, }) return trades # ═══════════════════════════════════════════════════════════════ # TEST 1: SIMPLE RULE REPLACEMENT # ═══════════════════════════════════════════════════════════════ def test_simple_rule(prices, ws, K, model_trades): """Replace neural net with simple ATR/Range-based entry rules.""" # Get test period from model trades if not model_trades: return {} idx_min = min(t["idx"] for t in model_trades) idx_max = max(t["idx"] for t in model_trades) strategies = {} # Strategy A: Enter every SHIFT bars (periodic), always long, trailing stop trades_periodic = [] for idx in range(idx_min, idx_max, SHIFT): if idx + LOOKAHEAD >= len(prices) or idx < ws: continue atr = risk.compute_atr(prices, idx) if atr <= 0: continue stop_dist = max(atr * STOP_MULT * STOP_SCALE, prices[idx] * 0.005) pnl = _sim_trail(prices, idx, 1, stop_dist) trades_periodic.append(pnl * 100) strategies["periodic_long"] = trades_periodic # Strategy B: Enter when ATR percentile > 70% (high vol expected) trades_atr_high = [] for idx in range(idx_min, idx_max, SHIFT): if idx + LOOKAHEAD >= len(prices) or idx < ws: continue atr = risk.compute_atr(prices, idx) if atr <= 0: continue atrs_hist = [risk.compute_atr(prices, j) for j in range(max(14, idx - 100), idx)] atrs_hist = [a for a in atrs_hist if a > 0] if len(atrs_hist) < 10: continue atr_pct = sum(1 for a in atrs_hist if a <= atr) / len(atrs_hist) if atr_pct < 0.7: continue stop_dist = max(atr * STOP_MULT * STOP_SCALE, prices[idx] * 0.005) pnl = _sim_trail(prices, idx, 1, stop_dist) trades_atr_high.append(pnl * 100) strategies["atr_high_70pct"] = trades_atr_high # Strategy C: Enter when recent range > 1.5 ATR (breakout-like) trades_range = [] for idx in range(idx_min, idx_max, SHIFT): if idx + LOOKAHEAD >= len(prices) or idx < ws: continue atr = risk.compute_atr(prices, idx) if atr <= 0: continue win = prices[max(0, idx - ws):idx] price_range = float(np.max(win) - np.min(win)) if price_range / atr < 1.5: continue # Direction: last K bars trend trend = 1 if prices[idx - 1] > prices[idx - K - 1] else -1 stop_dist = max(atr * STOP_MULT * STOP_SCALE, prices[idx] * 0.005) pnl = _sim_trail(prices, idx, trend, stop_dist) trades_range.append(pnl * 100) strategies["range_breakout"] = trades_range # Strategy D: Enter when ret_vol > median (momentum-like), trend direction ret_vols = [] for idx in range(idx_min, idx_max, SHIFT): if idx < ws or idx + LOOKAHEAD >= len(prices): continue win = prices[max(0, idx - ws):idx] if len(win) > 2: returns = np.diff(win) / win[:-1] ret_vols.append((idx, float(np.std(returns)))) if ret_vols: median_vol = np.median([v for _, v in ret_vols]) trades_vol = [] for idx, vol in ret_vols: if vol < median_vol: continue atr = risk.compute_atr(prices, idx) if atr <= 0: continue trend = 1 if prices[idx - 1] > prices[idx - K - 1] else -1 stop_dist = max(atr * STOP_MULT * STOP_SCALE, prices[idx] * 0.005) pnl = _sim_trail(prices, idx, trend, stop_dist) trades_vol.append(pnl * 100) strategies["vol_momentum"] = trades_vol # Model trades for comparison model_all = [t["pnl"] for t in model_trades] model_conf = [t["pnl"] for t in model_trades if t["confirmed"] and t["confidence"] >= 1.5] result = {"model_all": _trade_stats(model_all, "Model (all)"), "model_conf": _trade_stats(model_conf, "Model (conf≥1.5)")} for name, trades in strategies.items(): result[name] = _trade_stats(trades, name) return result def _trade_stats(pnls, label): if not pnls: return {"label": label, "n": 0, "pnl": 0, "wr": 0, "total": 0} a = np.array(pnls) return { "label": label, "n": len(a), "pnl": round(float(np.mean(a)), 3), "wr": round(float(np.mean(a > 0) * 100), 1), "total": round(float(np.sum(a)), 1), } # ═══════════════════════════════════════════════════════════════ # TEST 2: PNL SIGNIFICANCE — Bootstrap CI # ═══════════════════════════════════════════════════════════════ def test_significance(model_trades): """Bootstrap CI for per-trade PnL.""" if not model_trades: return {} all_pnl = np.array([t["pnl"] for t in model_trades]) conf_pnl = np.array([t["pnl"] for t in model_trades if t["confirmed"] and t["confidence"] >= 1.5]) def _bootstrap_ci(arr): if len(arr) < 5: return {"mean": 0, "ci_lo": 0, "ci_hi": 0, "p_positive": 0} np.random.seed(42) means = [] for _ in range(N_BOOTSTRAP): sample = np.random.choice(arr, size=len(arr), replace=True) means.append(np.mean(sample)) means = np.array(means) return { "mean": round(float(np.mean(arr)), 3), "ci_lo": round(float(np.percentile(means, 2.5)), 3), "ci_hi": round(float(np.percentile(means, 97.5)), 3), "p_positive": round(float(np.mean(means > 0) * 100), 1), "n": len(arr), } return { "all_trades": _bootstrap_ci(all_pnl), "conf_trades": _bootstrap_ci(conf_pnl), } # ═══════════════════════════════════════════════════════════════ # TEST 3: MARKET REGIMES — Bull/Bear/Flat # ═══════════════════════════════════════════════════════════════ def test_regimes(prices, model_trades): """Split trades by market regime at entry.""" if not model_trades: return {} regime_trades = {"bull": [], "bear": [], "flat": []} lookback = 50 # bars to determine regime for t in model_trades: idx = t["idx"] if idx < lookback: continue # Regime = price change over lookback change = (prices[idx] - prices[idx - lookback]) / prices[idx - lookback] if change > 0.03: regime = "bull" elif change < -0.03: regime = "bear" else: regime = "flat" regime_trades[regime].append(t) result = {} for regime, trades in regime_trades.items(): all_pnl = [t["pnl"] for t in trades] conf_pnl = [t["pnl"] for t in trades if t["confirmed"] and t["confidence"] >= 1.5] result[regime] = { "n_all": len(all_pnl), "pnl_all": round(float(np.mean(all_pnl)), 3) if all_pnl else 0, "wr_all": round(float(np.mean(np.array(all_pnl) > 0) * 100), 1) if all_pnl else 0, "n_conf": len(conf_pnl), "pnl_conf": round(float(np.mean(conf_pnl)), 3) if conf_pnl else 0, } return result # ═══════════════════════════════════════════════════════════════ # TEST 4: ARCHITECTURE COMPARISON # ═══════════════════════════════════════════════════════════════ class SimpleMLP(nn.Module): def __init__(self, grid_size): super().__init__() self.net = nn.Sequential( nn.Linear(grid_size, 128), nn.ReLU(), nn.Linear(128, 64), nn.ReLU(), nn.Linear(64, grid_size), ) def forward(self, x, stochastic=True): return self.net(x) class LinearModel(nn.Module): def __init__(self, grid_size): super().__init__() self.linear = nn.Linear(grid_size, grid_size) def forward(self, x, stochastic=True): return self.linear(x) def test_architectures(prices, ws, K): """Compare PDE vs MLP vs Linear for amplitude prediction.""" data = signals.prepare_windows(prices, ws, SHIFT) n_train = max(int(len(data) * TRAIN_RATIO), 20) train_x = np.array([d["norm_input"] for d in data[:n_train]]) train_y = np.array([d["norm_target"] for d in data[:n_train]]) models = {} # PDE (Remizov) torch.manual_seed(42) np.random.seed(42) mdl_pde = EnhancedRemizovNet(grid_size=ws, n_steps=20, total_time=0.5, dx=1.0 / ws, use_sde=True) model_mod.train(mdl_pde, train_x, train_y, 200, 0.003) models["PDE"] = mdl_pde # MLP torch.manual_seed(42) mdl_mlp = SimpleMLP(ws) model_mod.train(mdl_mlp, train_x, train_y, 200, 0.003) models["MLP"] = mdl_mlp # Linear torch.manual_seed(42) mdl_lin = LinearModel(ws) model_mod.train(mdl_lin, train_x, train_y, 200, 0.003) models["Linear"] = mdl_lin results = {} for name, mdl in models.items(): trades = _get_model_trades(prices, mdl, data, n_train, ws, K) all_pnl = [t["pnl"] for t in trades] conf_trades = [t for t in trades if t["confirmed"] and t["confidence"] >= 1.5] conf_pnl = [t["pnl"] for t in conf_trades] # Amplitude correlation pred_amps = [t["pred_amp_atr"] for t in trades] # Get actual amplitudes actual_amps = [] for t in trades: idx = t["idx"] future_end = min(idx + SHIFT, len(prices)) future = prices[idx:future_end] if len(future) >= 2 and t["atr"] > 0: actual_amps.append(float(np.max(future) - np.min(future)) / t["atr"]) else: actual_amps.append(0) with np.errstate(invalid="ignore"): r_amp = np.corrcoef(pred_amps, actual_amps)[0, 1] if np.isnan(r_amp): r_amp = 0 results[name] = { "n_all": len(all_pnl), "pnl_all": round(float(np.mean(all_pnl)), 3) if all_pnl else 0, "n_conf": len(conf_pnl), "pnl_conf": round(float(np.mean(conf_pnl)), 3) if conf_pnl else 0, "r_amp": round(float(r_amp), 3), } return results # ═══════════════════════════════════════════════════════════════ # TEST 5: WALK-FORWARD VALIDATION # ═══════════════════════════════════════════════════════════════ def test_walk_forward(prices, ws, K): """Retrain every chunk_size bars, test on next chunk.""" data = signals.prepare_windows(prices, ws, SHIFT) n = len(data) chunk_size = n // 5 # 5 folds train_size = chunk_size * 2 # train on 2 chunks all_trades = [] fold_results = [] for fold in range(3): # 3 test folds (folds 2,3,4) train_end = (fold + 2) * chunk_size test_start = train_end test_end = min(test_start + chunk_size, n) if test_end <= test_start: break train_data = data[max(0, train_end - train_size):train_end] if len(train_data) < 20: continue torch.manual_seed(42) np.random.seed(42) mdl = EnhancedRemizovNet(grid_size=ws, n_steps=20, total_time=0.5, dx=1.0 / ws, use_sde=True) model_mod.train(mdl, np.array([d["norm_input"] for d in train_data]), np.array([d["norm_target"] for d in train_data]), 200, 0.003) # Test on next chunk test_data = data[test_start:test_end] fold_trades = [] for d in test_data: idx = d["price_idx"] if idx + LOOKAHEAD >= len(prices) or idx < ws + K + 1: continue w = prices[idx - ws - K: idx - K].copy() mu, std = w.mean(), w.std() if std < 1e-10: continue pred = model_mod.predict(mdl, (w - mu) / std) pred_new = pred[-SHIFT:] pred_dir = signals.get_direction(pred_new, K) if pred_dir is None: continue pred_denorm = pred_new * std + mu pred_amp = float(np.max(pred_denorm) - np.min(pred_denorm)) atr = risk.compute_atr(prices, idx) if atr <= 0: continue confirm = prices[idx - K:idx].copy() corr, confirmed = signals.check_shape_confirmation( pred_new, confirm, mu, std, K, 0.5) confidence = abs(corr) * (pred_amp / atr) stop_dist = max(atr * STOP_MULT * STOP_SCALE, prices[idx] * 0.005) pnl = _sim_trail(prices, idx, pred_dir, stop_dist) fold_trades.append({ "pnl": pnl * 100, "confidence": confidence, "confirmed": confirmed, }) all_pnl = [t["pnl"] for t in fold_trades] conf_pnl = [t["pnl"] for t in fold_trades if t["confirmed"] and t["confidence"] >= 1.5] fold_results.append({ "fold": fold, "n_all": len(all_pnl), "pnl_all": round(float(np.mean(all_pnl)), 3) if all_pnl else 0, "n_conf": len(conf_pnl), "pnl_conf": round(float(np.mean(conf_pnl)), 3) if conf_pnl else 0, }) all_trades.extend(fold_trades) # Overall walk-forward stats wf_all = [t["pnl"] for t in all_trades] wf_conf = [t["pnl"] for t in all_trades if t["confirmed"] and t["confidence"] >= 1.5] return { "folds": fold_results, "overall_pnl_all": round(float(np.mean(wf_all)), 3) if wf_all else 0, "overall_pnl_conf": round(float(np.mean(wf_conf)), 3) if wf_conf else 0, "overall_n_conf": len(wf_conf), } def main(): results_dir = Path(__file__).parent / "results" print("=" * 80) print("EXP26i: COMPREHENSIVE FINAL TESTS") print("=" * 80) dataset = load_or_fetch("default") all_results = [] for a in ASSETS: ticker = a["ticker"] if ticker not in dataset: continue prices = dataset[ticker]["prices"] ws, K = a["ws"], a["K"] print(f"\n{'═' * 80}") print(f" {ticker} (ws={ws}, K={K}, {len(prices)} prices)") print(f"{'═' * 80}") # Get model trades first (shared across tests) print(f" Training Remizov model...", end=" ", flush=True) data = signals.prepare_windows(prices, ws, SHIFT) n_train = max(int(len(data) * TRAIN_RATIO), 20) torch.manual_seed(42) np.random.seed(42) mdl = EnhancedRemizovNet(grid_size=ws, n_steps=20, total_time=0.5, dx=1.0 / ws, use_sde=True) model_mod.train(mdl, np.array([d["norm_input"] for d in data[:n_train]]), np.array([d["norm_target"] for d in data[:n_train]]), 200, 0.003) model_trades = _get_model_trades(prices, mdl, data, n_train, ws, K) print(f"{len(model_trades)} trades") # ── TEST 1 ── print(f"\n ── TEST 1: SIMPLE RULE REPLACEMENT ──") t1 = test_simple_rule(prices, ws, K, model_trades) for key in ["model_all", "model_conf", "periodic_long", "atr_high_70pct", "range_breakout", "vol_momentum"]: if key in t1: s = t1[key] print(f" {s['label']:<22s} N={s['n']:4d} " f"PnL={s['pnl']:+.3f}% WR={s['wr']:.1f}% " f"Total={s['total']:+.1f}%") # ── TEST 2 ── print(f"\n ── TEST 2: PNL SIGNIFICANCE (bootstrap) ──") t2 = test_significance(model_trades) for key in ["all_trades", "conf_trades"]: s = t2.get(key, {}) if s and s.get("n", 0) > 0: sig = "✓" if s["ci_lo"] > 0 else "✗" print(f" {key:<12s}: mean={s['mean']:+.3f}% " f"95% CI=[{s['ci_lo']:+.3f}, {s['ci_hi']:+.3f}] " f"P(>0)={s['p_positive']:.1f}% {sig} N={s['n']}") # ── TEST 3 ── print(f"\n ── TEST 3: MARKET REGIMES ──") t3 = test_regimes(prices, model_trades) for regime in ["bull", "bear", "flat"]: if regime in t3: r = t3[regime] print(f" {regime:<6s}: all N={r['n_all']:3d} PnL={r['pnl_all']:+.3f}% " f"WR={r['wr_all']:.1f}% | " f"conf N={r['n_conf']:3d} PnL={r['pnl_conf']:+.3f}%") # ── TEST 4 ── print(f"\n ── TEST 4: ARCHITECTURE COMPARISON ──") t4 = test_architectures(prices, ws, K) print(f" {'Arch':<8s} {'N_all':>5s} {'PnL_all':>8s} " f"{'N_conf':>6s} {'PnL_conf':>9s} {'r_amp':>6s}") print(f" {'-' * 45}") for name in ["PDE", "MLP", "Linear"]: if name in t4: r = t4[name] print(f" {name:<8s} {r['n_all']:>5d} {r['pnl_all']:>+7.3f}% " f"{r['n_conf']:>6d} {r['pnl_conf']:>+8.3f}% " f"{r['r_amp']:>+5.3f}") # ── TEST 5 ── print(f"\n ── TEST 5: WALK-FORWARD ──") t5 = test_walk_forward(prices, ws, K) for f_res in t5.get("folds", []): print(f" Fold {f_res['fold']}: all N={f_res['n_all']:3d} " f"PnL={f_res['pnl_all']:+.3f}% | " f"conf N={f_res['n_conf']:3d} PnL={f_res['pnl_conf']:+.3f}%") print(f" Overall WF: PnL_all={t5['overall_pnl_all']:+.3f}% " f"PnL_conf={t5['overall_pnl_conf']:+.3f}% (N={t5['overall_n_conf']})") result = { "ticker": ticker, "ws": ws, "K": K, "simple_rule": t1, "significance": t2, "regimes": t3, "architectures": t4, "walk_forward": t5, } all_results.append(result) # ── CROSS-ASSET SUMMARY ── print(f"\n{'═' * 80}") print("CROSS-ASSET SUMMARY") print(f"{'═' * 80}") print(f"\n TEST 1 — SIMPLE RULE vs MODEL (conf-filtered PnL):") print(f" {'Asset':<10s} {'Model':>8s} {'Periodic':>9s} {'ATR_hi':>8s} " f"{'Range':>8s} {'VolMom':>8s}") print(f" {'-' * 50}") for r in all_results: t = r["simple_rule"] print(f" {r['ticker']:<10s} " f"{t.get('model_conf', {}).get('pnl', 0):>+7.3f}% " f"{t.get('periodic_long', {}).get('pnl', 0):>+8.3f}% " f"{t.get('atr_high_70pct', {}).get('pnl', 0):>+7.3f}% " f"{t.get('range_breakout', {}).get('pnl', 0):>+7.3f}% " f"{t.get('vol_momentum', {}).get('pnl', 0):>+7.3f}%") print(f"\n TEST 2 — SIGNIFICANCE (conf-filtered, 95% CI):") for r in all_results: s = r["significance"].get("conf_trades", {}) if s and s.get("n", 0) > 0: sig = "SIGNIFICANT" if s["ci_lo"] > 0 else "NOT significant" print(f" {r['ticker']:<10s} {s['mean']:+.3f}% " f"[{s['ci_lo']:+.3f}, {s['ci_hi']:+.3f}] " f"P(>0)={s['p_positive']:.0f}% → {sig}") else: print(f" {r['ticker']:<10s} N/A (no conf trades)") print(f"\n TEST 3 — BEST REGIME (conf-filtered):") for r in all_results: best_regime = max(r["regimes"].items(), key=lambda x: x[1].get("pnl_conf", -999)) print(f" {r['ticker']:<10s} best={best_regime[0]} " f"PnL={best_regime[1].get('pnl_conf', 0):+.3f}% " f"N={best_regime[1].get('n_conf', 0)}") print(f"\n TEST 4 — BEST ARCHITECTURE (conf PnL):") for r in all_results: best = max(r["architectures"].items(), key=lambda x: x[1].get("pnl_conf", -999) if x[1].get("n_conf", 0) > 0 else -999) print(f" {r['ticker']:<10s} best={best[0]} " f"PnL={best[1].get('pnl_conf', 0):+.3f}% " f"(r_amp={best[1].get('r_amp', 0):+.3f})") print(f"\n TEST 5 — WALK-FORWARD (conf PnL):") for r in all_results: wf = r["walk_forward"] print(f" {r['ticker']:<10s} PnL={wf['overall_pnl_conf']:+.3f}% " f"N={wf['overall_n_conf']}") path = save_results({"results": all_results}, results_dir, "exp26i_comprehensive") print(f"\nSaved: {path}") if __name__ == "__main__": main()