"""Exp27: Scan top crypto pairs for Remizov formula edge. Pipeline per asset: 1. Fetch 4h OHLCV from Bybit (need 2000+ bars) 2. Train model (30% train / 70% test) 3. Amplitude correlation test 4. Confidence-filtered PnL test 5. Statistical significance (bootstrap) 6. Walk-forward (3 folds) Only pairs passing all tests proceed to realistic backtest. """ 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 from scipy import stats from remizov_trader.core import model as model_mod, signals, risk from remizov_trader.core.net import EnhancedRemizovNet from remizov_trader.core.signals import fetch_ohlcv_ccxt from common.metrics import save_results SHIFT = 7 MIN_CONFIDENCE = 1.5 TRAIN_RATIO = 0.3 MIN_BARS = 2000 # Top 50 crypto on Bybit spot/USDC (excluding already tested BTC/ETH/ADA/DOGE/SOL/DOT/XRP) CANDIDATES = [ "AVAX/USDC", "LINK/USDC", "MATIC/USDC", "UNI/USDC", "ATOM/USDC", "FIL/USDC", "LTC/USDC", "NEAR/USDC", "APT/USDC", "OP/USDC", "ARB/USDC", "SUI/USDC", "PEPE/USDC", "SHIB/USDC", "WIF/USDC", "FET/USDC", "RENDER/USDC", "INJ/USDC", "SEI/USDC", "TIA/USDC", "STX/USDC", "IMX/USDC", "SAND/USDC", "MANA/USDC", "CRV/USDC", ] WS_OPTIONS = [48, 64] K_OPTIONS = [2, 3] def _ticker(symbol): return symbol.replace("/", "-").replace("USDC", "USD") def _train_model(prices, ws): data = signals.prepare_windows(prices, ws, SHIFT) n_train = max(int(len(data) * TRAIN_RATIO), 20) train = data[:n_train] test = data[n_train:] 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) w = np.array([d["norm_input"] for d in train]) t = np.array([d["norm_target"] for d in train]) model_mod.train(mdl, w, t, 200, 0.003) return mdl, train, test def _amplitude_test(mdl, test_data, prices, ws, K): """Test amplitude prediction correlation.""" pred_amps, actual_amps = [], [] for d in test_data: idx = d["price_idx"] if idx + SHIFT >= len(prices): continue pred = model_mod.predict(mdl, d["norm_input"]) pred_new = pred[-SHIFT:] pred_denorm = pred_new * d["std"] + d["mu"] pred_amp = float(np.max(pred_denorm) - np.min(pred_denorm)) future = prices[idx:idx + SHIFT] actual_amp = float(np.max(future) - np.min(future)) pred_amps.append(pred_amp) actual_amps.append(actual_amp) if len(pred_amps) < 50: return {"r": 0, "n": len(pred_amps)} r, p = stats.pearsonr(pred_amps, actual_amps) return {"r": round(float(r), 4), "p": round(float(p), 4), "n": len(pred_amps)} def _conf_pnl_test(mdl, test_data, prices, ws, K): """Test confidence-filtered PnL (trailing stop sim).""" trades = [] for d in test_data: idx = d["price_idx"] if idx + SHIFT >= len(prices) or idx < ws + K: continue pred = model_mod.predict(mdl, d["norm_input"]) pred_new = pred[-SHIFT:] # Shape confirmation confirm = prices[idx - K:idx] corr, confirmed = signals.check_shape_confirmation( pred_new, confirm, d["mu"], d["std"], K, 0.5) if not confirmed: continue # Confidence filter atr = risk.compute_atr(prices, idx) if atr <= 0: continue pred_denorm = pred_new * d["std"] + d["mu"] amp = float(np.max(pred_denorm) - np.min(pred_denorm)) conf = abs(corr) * (amp / atr) if conf < MIN_CONFIDENCE: continue # Direction (long only) direction = signals.get_direction(pred_new, K) if direction != 1: continue # Trailing stop PnL entry = prices[idx] _, stop_mult = risk.regime_adaptive_params(prices, idx, K) stop_dist = max(atr * stop_mult * 0.5, entry * 0.005) stop = entry - stop_dist best = entry pnl_pct = 0.0 for j in range(1, SHIFT + 1): if idx + j >= len(prices): break p = prices[idx + j] if p > best: best = p stop = best - stop_dist if p <= stop: pnl_pct = (p - entry) / entry * 100 break else: pnl_pct = (prices[min(idx + SHIFT, len(prices) - 1)] - entry) / entry * 100 trades.append(pnl_pct) if not trades: return {"mean_pnl": 0, "n": 0, "wr": 0} wins = sum(1 for t in trades if t > 0) return { "mean_pnl": round(float(np.mean(trades)), 4), "n": len(trades), "wr": round(wins / len(trades) * 100, 1), } def _bootstrap_significance(mdl, test_data, prices, ws, K, n_boot=1000): """Bootstrap test for PnL significance.""" # Collect trade PnLs trade_pnls = [] for d in test_data: idx = d["price_idx"] if idx + SHIFT >= len(prices) or idx < ws + K: continue pred = model_mod.predict(mdl, d["norm_input"]) pred_new = pred[-SHIFT:] confirm = prices[idx - K:idx] corr, confirmed = signals.check_shape_confirmation( pred_new, confirm, d["mu"], d["std"], K, 0.5) if not confirmed: continue atr = risk.compute_atr(prices, idx) if atr <= 0: continue pred_denorm = pred_new * d["std"] + d["mu"] amp = float(np.max(pred_denorm) - np.min(pred_denorm)) conf = abs(corr) * (amp / atr) if conf < MIN_CONFIDENCE: continue direction = signals.get_direction(pred_new, K) if direction != 1: continue entry = prices[idx] _, stop_mult = risk.regime_adaptive_params(prices, idx, K) stop_dist = max(atr * stop_mult * 0.5, entry * 0.005) stop = entry - stop_dist best = entry pnl_pct = 0.0 for j in range(1, SHIFT + 1): if idx + j >= len(prices): break p = prices[idx + j] if p > best: best = p stop = best - stop_dist if p <= stop: pnl_pct = (p - entry) / entry * 100 break else: pnl_pct = (prices[min(idx + SHIFT, len(prices) - 1)] - entry) / entry * 100 trade_pnls.append(pnl_pct) if len(trade_pnls) < 10: return {"p_positive": 0, "ci_lo": 0, "ci_hi": 0, "n": len(trade_pnls)} arr = np.array(trade_pnls) means = [float(np.mean(np.random.choice(arr, len(arr), replace=True))) for _ in range(n_boot)] means = np.array(means) p_pos = float(np.mean(means > 0)) ci = np.percentile(means, [2.5, 97.5]) return { "p_positive": round(p_pos * 100, 1), "ci_lo": round(float(ci[0]), 4), "ci_hi": round(float(ci[1]), 4), "n": len(trade_pnls), "mean": round(float(np.mean(arr)), 4), } def _walk_forward(prices, ws, K, n_folds=3): """Walk-forward validation with 3 folds.""" data = signals.prepare_windows(prices, ws, SHIFT) n = len(data) chunk = n // (n_folds + 1) if chunk < 30: return {"folds": [], "stable": False} fold_results = [] for i in range(n_folds): train_end = chunk * (i + 2) test_start = train_end test_end = min(train_end + chunk, n) train_data = data[:train_end] test_data = data[test_start:test_end] if len(test_data) < 10: 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) 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, 200, 0.003) r = _conf_pnl_test(mdl, test_data, prices, ws, K) fold_results.append(r["mean_pnl"]) positive_folds = sum(1 for f in fold_results if f > 0) return { "folds": [round(f, 4) for f in fold_results], "positive": positive_folds, "total": len(fold_results), "stable": positive_folds == len(fold_results) and len(fold_results) >= 2, } def main(): results_dir = Path(__file__).parent / "results" results_dir.mkdir(parents=True, exist_ok=True) print("=" * 80) print("EXP27: SCAN NEW PAIRS FOR REMIZOV FORMULA EDGE") print("=" * 80) print(f"Candidates: {len(CANDIDATES)} pairs") print(f"Tests: amplitude corr → conf PnL → bootstrap → walk-forward") print(f"WS options: {WS_OPTIONS}, K options: {K_OPTIONS}") all_results = [] for symbol in CANDIDATES: ticker = _ticker(symbol) print(f"\n{'─' * 60}") print(f" {ticker} ({symbol})") print(f"{'─' * 60}") # Fetch data try: ohlcv, dates = fetch_ohlcv_ccxt(symbol, "4h", "max") except Exception as e: print(f" SKIP: fetch error: {e}") all_results.append({"ticker": ticker, "status": "fetch_error", "error": str(e)}) continue if ohlcv is None or len(ohlcv) < MIN_BARS: bars = len(ohlcv) if ohlcv is not None else 0 print(f" SKIP: only {bars} bars (need {MIN_BARS})") all_results.append({"ticker": ticker, "status": "insufficient_data", "bars": bars}) continue prices = ohlcv[:, 3] # close print(f" {len(prices)} bars, price ${prices[-1]:.4f}") best_config = None best_sharpe_proxy = -999 for ws in WS_OPTIONS: for K in K_OPTIONS: label = f"ws={ws} K={K}" print(f"\n [{label}]", end=" ", flush=True) mdl, train, test = _train_model(prices, ws) # Test 1: Amplitude correlation amp = _amplitude_test(mdl, test, prices, ws, K) print(f"amp_r={amp['r']:.3f}", end=" ", flush=True) if amp["r"] < 0.05: print("← LOW, skip") continue # Test 2: Conf-filtered PnL pnl = _conf_pnl_test(mdl, test, prices, ws, K) print(f"PnL={pnl['mean_pnl']:+.3f}% N={pnl['n']}", end=" ", flush=True) if pnl["n"] < 10 or pnl["mean_pnl"] <= 0: print("← NO EDGE, skip") continue # Test 3: Bootstrap significance boot = _bootstrap_significance(mdl, test, prices, ws, K) print(f"P={boot['p_positive']:.0f}%", end=" ", flush=True) if boot["p_positive"] < 90: print("← NOT SIGNIFICANT, skip") continue # Test 4: Walk-forward wf = _walk_forward(prices, ws, K) print(f"WF={wf['positive']}/{wf['total']}", end=" ", flush=True) # Score score = pnl["mean_pnl"] * boot["p_positive"] / 100 print(f"score={score:.3f}") result = { "ticker": ticker, "ws": ws, "K": K, "bars": len(prices), "amplitude": amp, "conf_pnl": pnl, "bootstrap": boot, "walk_forward": wf, "score": round(score, 4), "status": "tested", } if score > best_sharpe_proxy: best_sharpe_proxy = score best_config = result if best_config: all_results.append(best_config) elif not any(r["ticker"] == ticker for r in all_results): all_results.append({"ticker": ticker, "status": "no_edge"}) # Summary tested = [r for r in all_results if r.get("status") == "tested"] tested.sort(key=lambda r: r["score"], reverse=True) print(f"\n{'═' * 80}") print("RESULTS — PAIRS WITH EDGE") print(f"{'═' * 80}") if tested: print(f" {'Ticker':<12s} {'ws':>3s} {'K':>2s} {'amp_r':>6s} " f"{'PnL%':>7s} {'N':>4s} {'P%':>5s} {'WF':>5s} {'Score':>6s}") print(f" {'-' * 55}") for r in tested: wf = r["walk_forward"] print(f" {r['ticker']:<12s} {r['ws']:>3d} {r['K']:>2d} " f"{r['amplitude']['r']:>6.3f} " f"{r['conf_pnl']['mean_pnl']:>+6.3f}% " f"{r['conf_pnl']['n']:>4d} " f"{r['bootstrap']['p_positive']:>4.0f}% " f"{wf['positive']}/{wf['total']} " f"{r['score']:>6.3f}") else: print(" No pairs found with edge.") failed = [r for r in all_results if r.get("status") != "tested"] if failed: print(f"\n Skipped: {len(failed)} pairs") for r in failed: print(f" {r['ticker']}: {r.get('status', 'unknown')}") path = save_results({"results": all_results}, results_dir, "exp27_scan") print(f"\nSaved: {path}") if __name__ == "__main__": main()