"""Exp26d: Does Remizov formula predict amplitude (volatility)? Hypothesis: the model's VALUE is in amplitude prediction, not direction. Confidence filter selects high-amplitude predictions → high-amplitude actuals. Tests: 1. Correlation: predicted amplitude vs actual amplitude 2. Predicted amplitude buckets → actual MFE (max favorable excursion) 3. Does high predicted amplitude = high actual volatility? 4. Random-direction + amplitude filter → still profitable? """ 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 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 ASSETS = [ {"ticker": "BTC-USD", "ws": 32, "K": 3, "shift": 7, "tf_h": 4}, {"ticker": "ETH-USD", "ws": 64, "K": 2, "shift": 7, "tf_h": 2}, {"ticker": "ADA-USD", "ws": 64, "K": 3, "shift": 7, "tf_h": 4}, {"ticker": "DOGE-USD", "ws": 48, "K": 2, "shift": 7, "tf_h": 4}, {"ticker": "SOL-USD", "ws": 128, "K": 2, "shift": 7, "tf_h": 2}, ] def _train_model(prices, ws, shift): 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) return mdl, data, n_train def _sim_trail(prices, idx, direction, stop_dist): entry = prices[idx] best = entry stop = entry - direction * stop_dist mfe = 0.0 for i in range(1, LOOKAHEAD + 1): if idx + i >= len(prices): break p = prices[idx + i] move = (p - entry) / entry * direction mfe = max(mfe, move) best, stop = risk.update_trailing_stop(p, best, stop, stop_dist, direction) if risk.is_stopped(p, stop, direction): pnl = (p - entry) / entry * direction return pnl, mfe last = prices[min(idx + LOOKAHEAD, len(prices) - 1)] return (last - entry) / entry * direction, mfe def _analyze(ticker, prices, ws, K, shift): mdl, data, n_train = _train_model(prices, ws, shift) test_data = data[n_train:] rows = [] for d in test_data: idx = d["price_idx"] if idx + LOOKAHEAD >= len(prices) or idx < ws + K + 1: continue # Trading-aligned prediction 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 # Predicted amplitude (denormalized) pred_denorm = pred_new * std + mu pred_amp = float(np.max(pred_denorm) - np.min(pred_denorm)) # ATR and confidence atr = risk.compute_atr(prices, idx) 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) if atr > 0 else 0 pred_amp_atr = pred_amp / atr if atr > 0 else 0 # amplitude in ATR units # Actual amplitude (next shift-K bars = actual future) future_end = min(idx + shift - K, len(prices)) actual_future = prices[idx:future_end] actual_amp = float(np.max(actual_future) - np.min(actual_future)) if len(actual_future) > 1 else 0 actual_amp_atr = actual_amp / atr if atr > 0 else 0 # Actual realized vol (next LOOKAHEAD bars) lookahead_prices = prices[idx:min(idx + LOOKAHEAD, len(prices))] actual_range = float(np.max(lookahead_prices) - np.min(lookahead_prices)) actual_range_atr = actual_range / atr if atr > 0 else 0 # Trailing stop with MODEL direction stop_dist = max(atr * STOP_MULT * STOP_SCALE, prices[idx] * 0.005) pnl_model, mfe_model = _sim_trail(prices, idx, pred_dir, stop_dist) # Trailing stop with RANDOM direction (always LONG for consistency) pnl_long, mfe_long = _sim_trail(prices, idx, 1, stop_dist) rows.append({ "idx": idx, "pred_amp": pred_amp, "pred_amp_atr": pred_amp_atr, "actual_amp": actual_amp, "actual_amp_atr": actual_amp_atr, "actual_range_atr": actual_range_atr, "confidence": confidence, "corr": corr, "confirmed": confirmed, "atr": atr, "pred_dir": pred_dir, "pnl_model": pnl_model * 100, "mfe_model": mfe_model * 100, "pnl_long": pnl_long * 100, "mfe_long": mfe_long * 100, }) return rows def _print_report(ticker, rows): n = len(rows) print(f"\n{'═' * 70}") print(f" {ticker} — {n} signals") print(f"{'═' * 70}") if not rows: return {} pred_amps = np.array([r["pred_amp_atr"] for r in rows]) actual_amps = np.array([r["actual_amp_atr"] for r in rows]) actual_ranges = np.array([r["actual_range_atr"] for r in rows]) # ── 1. Amplitude correlation ── print(f"\n 1. AMPLITUDE CORRELATION (predicted vs actual)") with np.errstate(invalid="ignore"): corr_amp = np.corrcoef(pred_amps, actual_amps)[0, 1] corr_range = np.corrcoef(pred_amps, actual_ranges)[0, 1] if np.isnan(corr_amp): corr_amp = 0 if np.isnan(corr_range): corr_range = 0 print(f" Pred amplitude vs actual amplitude (shift bars): r = {corr_amp:.3f}") print(f" Pred amplitude vs actual range (30 bars): r = {corr_range:.3f}") print(f" Pred amp mean: {np.mean(pred_amps):.2f} ATR | " f"Actual amp mean: {np.mean(actual_amps):.2f} ATR") # ── 2. Amplitude buckets → MFE and PnL ── print(f"\n 2. PREDICTED AMPLITUDE BUCKETS → ACTUAL OUTCOME") pcts = np.percentile(pred_amps, [25, 50, 75]) buckets = [(0, pcts[0], "Q1 (low)"), (pcts[0], pcts[1], "Q2"), (pcts[1], pcts[2], "Q3"), (pcts[2], 1e10, "Q4 (high)")] print(f" {'Bucket':<15s} {'Pred amp':>8s} {'Act amp':>8s} {'Act rng':>8s} " f"{'MFE':>6s} {'PnL':>7s} {'WR':>5s} N") print(f" {'-' * 70}") bucket_data = [] for lo, hi, name in buckets: b = [r for r in rows if lo <= r["pred_amp_atr"] < hi] if b: pa = np.mean([r["pred_amp_atr"] for r in b]) aa = np.mean([r["actual_amp_atr"] for r in b]) ar = np.mean([r["actual_range_atr"] for r in b]) mfe = np.mean([r["mfe_model"] for r in b]) pnl = np.mean([r["pnl_model"] for r in b]) wr = sum(1 for r in b if r["pnl_model"] > 0) / len(b) * 100 print(f" {name:<15s} {pa:>7.2f}x {aa:>7.2f}x {ar:>7.2f}x " f"{mfe:>+5.2f}% {pnl:>+6.2f}% {wr:>4.1f}% {len(b):>4d}") bucket_data.append({"name": name, "pred": pa, "actual": aa, "mfe": mfe, "pnl": pnl, "wr": wr}) # Does actual amplitude increase with predicted amplitude? if len(bucket_data) >= 2: q1_actual = bucket_data[0]["actual"] q4_actual = bucket_data[-1]["actual"] ratio = q4_actual / q1_actual if q1_actual > 0 else 0 print(f"\n Q4/Q1 actual amplitude ratio: {ratio:.2f}x " f"{'← model predicts volatility!' if ratio > 1.3 else ''}") # ── 3. Confidence filter effect on MFE ── print(f"\n 3. CONFIDENCE FILTER → MFE (does filter select better trades?)") for lo, hi, name in [(0, 0.5, "conf<0.5"), (0.5, 1.0, "0.5-1.0"), (1.0, 1.5, "1.0-1.5"), (1.5, 2.5, "1.5-2.5"), (2.5, 99, "conf>=2.5")]: b = [r for r in rows if lo <= r["confidence"] < hi] if b: mfe = np.mean([r["mfe_model"] for r in b]) pnl = np.mean([r["pnl_model"] for r in b]) aa = np.mean([r["actual_amp_atr"] for r in b]) wr = sum(1 for r in b if r["pnl_model"] > 0) / len(b) * 100 print(f" {name:<12s} MFE={mfe:>+5.2f}% PnL={pnl:>+6.2f}% " f"WR={wr:>4.1f}% act_amp={aa:.2f}x N={len(b)}") # ── 4. Random direction + amplitude filter ── print(f"\n 4. ALWAYS-LONG + AMPLITUDE FILTER (no model direction needed)") for label, subset in [ ("All (always long)", rows), ("Pred amp > median", [r for r in rows if r["pred_amp_atr"] >= np.median(pred_amps)]), ("Pred amp > Q3", [r for r in rows if r["pred_amp_atr"] >= pcts[2]]), ("Conf >= 1.5", [r for r in rows if r["confidence"] >= 1.5]), ("Conf >= 1.5 + confirmed", [r for r in rows if r["confidence"] >= 1.5 and r["confirmed"]]), ]: if subset: pnl = np.mean([r["pnl_long"] for r in subset]) mfe = np.mean([r["mfe_long"] for r in subset]) wr = sum(1 for r in subset if r["pnl_long"] > 0) / len(subset) * 100 print(f" {label:<30s} PnL={pnl:>+6.2f}% MFE={mfe:>+5.2f}% " f"WR={wr:>4.1f}% N={len(subset)}") # ── 5. Model direction vs always-long ── print(f"\n 5. MODEL DIRECTION vs ALWAYS-LONG (same signals)") model_pnl = np.mean([r["pnl_model"] for r in rows]) long_pnl = np.mean([r["pnl_long"] for r in rows]) model_wr = sum(1 for r in rows if r["pnl_model"] > 0) / n * 100 long_wr = sum(1 for r in rows if r["pnl_long"] > 0) / n * 100 print(f" Model direction: PnL={model_pnl:>+6.2f}% WR={model_wr:.1f}%") print(f" Always LONG: PnL={long_pnl:>+6.2f}% WR={long_wr:.1f}%") print(f" Direction edge: PnL Δ={model_pnl - long_pnl:>+6.2f}pp") return { "ticker": ticker, "n": n, "corr_amp": round(float(corr_amp), 3), "corr_range": round(float(corr_range), 3), "q4_q1_ratio": round(ratio, 2) if len(bucket_data) >= 2 else 0, "model_pnl": round(model_pnl, 2), "long_pnl": round(long_pnl, 2), "dir_edge": round(model_pnl - long_pnl, 2), } def main(): results_dir = Path(__file__).parent / "results" print("=" * 70) print("EXP26d: AMPLITUDE PREDICTION — REMIZOV FORMULA") print("=" * 70) print("Hypothesis: model predicts volatility/amplitude, not direction") print(f"Trailing stop: ATR×{STOP_MULT}×{STOP_SCALE}, lookahead={LOOKAHEAD}\n") dataset = load_or_fetch("default") all_summaries = [] for a in ASSETS: ticker = a["ticker"] if ticker not in dataset: continue prices = dataset[ticker]["prices"] print(f" Training {ticker}...", end=" ", flush=True) rows = _analyze(ticker, prices, a["ws"], a["K"], a["shift"]) if not rows: print("no data"); continue print(f"{len(rows)} signals") s = _print_report(ticker, rows) if s: all_summaries.append(s) print(f"\n{'═' * 70}") print("CROSS-ASSET SUMMARY") print(f"{'═' * 70}") print(f" {'Asset':<10s} {'Amp r':>5s} {'Rng r':>5s} {'Q4/Q1':>5s} " f"{'Model':>6s} {'Long':>6s} {'DirEdge':>7s}") print(f" {'-' * 50}") for s in all_summaries: print(f" {s['ticker']:<10s} {s['corr_amp']:>5.3f} {s['corr_range']:>5.3f} " f"{s['q4_q1_ratio']:>4.1f}x {s['model_pnl']:>+5.2f}% " f"{s['long_pnl']:>+5.2f}% {s['dir_edge']:>+6.2f}pp") if all_summaries: print(f"\n Avg amplitude correlation: " f"{np.mean([s['corr_amp'] for s in all_summaries]):.3f}") print(f" Avg Q4/Q1 ratio: " f"{np.mean([s['q4_q1_ratio'] for s in all_summaries]):.2f}x") print(f" Avg direction edge: " f"{np.mean([s['dir_edge'] for s in all_summaries]):+.2f}pp") path = save_results({"summaries": all_summaries}, results_dir, "exp26d_amplitude") print(f"\nSaved: {path}") if __name__ == "__main__": main()