From 84300f380da33dcdb1bb134bdb51e278942668ca Mon Sep 17 00:00:00 2001 From: anor Date: Wed, 11 Mar 2026 05:56:27 +1000 Subject: [PATCH] =?UTF-8?q?feat:=20exp26h=20=E2=80=94=20partial=20correlat?= =?UTF-8?q?ion,=20untrained=20PnL,=20shape=5Fconfirm=20edge?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Reconciliation: модель даёт уникальную info для ADA (r=0.077) и DOGE (r=0.046) после контроля за ATR+Range+Vol. BTC/ETH/SOL — Range объясняет всё. Untrained model: conf=0 (нет сигналов) → обучение нужно для генерации confidence, не для prediction quality. Co-Authored-By: Claude Opus 4.6 --- experiments/exp26_ablation/formula_final.py | 385 ++++++++++++++++++ .../results_exp26h_final_20260311_055546.json | 244 +++++++++++ 2 files changed, 629 insertions(+) create mode 100644 experiments/exp26_ablation/formula_final.py create mode 100644 experiments/exp26_ablation/results/results_exp26h_final_20260311_055546.json diff --git a/experiments/exp26_ablation/formula_final.py b/experiments/exp26_ablation/formula_final.py new file mode 100644 index 0000000..e118b26 --- /dev/null +++ b/experiments/exp26_ablation/formula_final.py @@ -0,0 +1,385 @@ +"""Exp26h: Final test — what exactly does the model add? + +Resolving contradiction between exp26f (+15% beyond ATR) and exp26g (ATR beats model). + +Questions: + 1. Does model add info BEYOND all simple predictors combined? + (partial correlation after controlling for ATR + Range + RetVol) + 2. Does UNTRAINED model work for shape_confirmation + confidence filter? + (the key production filters that drive profitability) + 3. Is shape_confirm really about the model or just trend detection? +""" +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 +SHIFT = 7 + +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 _build_model(prices, ws, trained=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) + if trained: + 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 _corr(a, b): + with np.errstate(invalid="ignore"): + r = np.corrcoef(a, b)[0, 1] + return 0.0 if np.isnan(r) else float(r) + + +def _partial_corr(x, y, controls): + """Partial correlation r(x, y | controls). + + Regress x and y on controls, correlate residuals. + """ + controls = np.column_stack(controls) + n = len(x) + # Add intercept + C = np.column_stack([controls, np.ones(n)]) + # Regress x on controls + try: + beta_x = np.linalg.lstsq(C, x, rcond=None)[0] + resid_x = x - C @ beta_x + beta_y = np.linalg.lstsq(C, y, rcond=None)[0] + resid_y = y - C @ beta_y + except np.linalg.LinAlgError: + return 0.0 + return _corr(resid_x, resid_y) + + +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 _get_signals(prices, mdl, data, n_train, ws, K): + """Get full signal data for each test point.""" + 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 + 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 + + # Shape confirmation + confidence + 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) + + # Actual amplitude + future_end = min(idx + SHIFT, len(prices)) + future = prices[idx:future_end] + if len(future) < 2: + continue + actual_amp = float(np.max(future) - np.min(future)) + + # Simple predictors + win = prices[max(0, idx - ws):idx] + price_range = float(np.max(win) - np.min(win)) + if len(win) > 2: + returns = np.diff(win) / win[:-1] + ret_vol = float(np.std(returns)) + else: + ret_vol = 0 + input_amp = float(np.max(win[-SHIFT:]) - np.min(win[-SHIFT:])) + + # Trailing stop PnL + stop_dist = max(atr * STOP_MULT * STOP_SCALE, prices[idx] * 0.005) + pnl = _sim_trail(prices, idx, pred_dir, 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, + "atr": atr, + "price_range": price_range, + "price_range_atr": price_range / atr, + "ret_vol": ret_vol, + "ret_vol_atr": ret_vol * prices[idx] / atr, # normalize to ATR scale + "input_amp": input_amp, + "input_amp_atr": input_amp / atr, + "corr": corr, + "confirmed": confirmed, + "confidence": confidence, + "pred_dir": pred_dir, + "pnl": pnl * 100, + }) + return rows + + +# ═══════════════════════════════════════════════════════════════ +# TEST 1: Partial correlation — model beyond ALL simple predictors +# ═══════════════════════════════════════════════════════════════ +def test_partial(rows): + """Does model add info beyond ATR + Range + RetVol + InputAmp combined?""" + pred = np.array([r["pred_amp_atr"] for r in rows]) + actual = np.array([r["actual_amp_atr"] for r in rows]) + atr = np.array([r["atr"] for r in rows]) + rng = np.array([r["price_range_atr"] for r in rows]) + vol = np.array([r["ret_vol_atr"] for r in rows]) + inp = np.array([r["input_amp_atr"] for r in rows]) + + r_raw = _corr(pred, actual) + r_beyond_atr = _partial_corr(pred, actual, [atr]) + r_beyond_range = _partial_corr(pred, actual, [rng]) + r_beyond_vol = _partial_corr(pred, actual, [vol]) + r_beyond_all = _partial_corr(pred, actual, [atr, rng, vol, inp]) + + # Also: does Range add beyond model? + r_range_beyond_model = _partial_corr(rng, actual, [pred]) + + return { + "r_raw": round(r_raw, 3), + "r_beyond_atr": round(r_beyond_atr, 3), + "r_beyond_range": round(r_beyond_range, 3), + "r_beyond_vol": round(r_beyond_vol, 3), + "r_beyond_all": round(r_beyond_all, 3), + "r_range_beyond_model": round(r_range_beyond_model, 3), + "model_adds_unique_info": r_beyond_all > 0.03, + } + + +# ═══════════════════════════════════════════════════════════════ +# TEST 2: Untrained model → same shape_confirm + PnL? +# ═══════════════════════════════════════════════════════════════ +def test_untrained_pnl(prices, ws, K): + """Compare PnL of trained vs untrained model with production filters.""" + # Trained + mdl_t, data, n_train = _build_model(prices, ws, trained=True) + rows_t = _get_signals(prices, mdl_t, data, n_train, ws, K) + + # Untrained (zeros init = default PDE) + mdl_u, _, _ = _build_model(prices, ws, trained=False) + rows_u = _get_signals(prices, mdl_u, data, n_train, ws, K) + + def _stats(rows, label): + all_pnl = [r["pnl"] for r in rows] + conf_rows = [r for r in rows if r["confirmed"] and r["confidence"] >= 1.5] + conf_pnl = [r["pnl"] for r in conf_rows] + return { + "label": label, + "n_all": len(rows), + "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_rows), + "pnl_conf": round(float(np.mean(conf_pnl)), 3) if conf_pnl else 0, + "wr_conf": round(float(np.mean(np.array(conf_pnl) > 0) * 100), 1) if conf_pnl else 0, + "conf_rate": round(len(conf_rows) / len(rows) * 100, 1) if rows else 0, + } + + return { + "trained": _stats(rows_t, "trained"), + "untrained": _stats(rows_u, "untrained"), + } + + +# ═══════════════════════════════════════════════════════════════ +# TEST 3: What does shape_confirm actually detect? +# ═══════════════════════════════════════════════════════════════ +def test_shape_meaning(rows): + """Is shape_confirm = trend detection (last K bars in same direction)?""" + # Compare shape_confirm with simple trend measure + confirmed_pnls = [r["pnl"] for r in rows if r["confirmed"]] + rejected_pnls = [r["pnl"] for r in rows if not r["confirmed"]] + + # Simple trend: did last K bars go in pred_dir? + trend_match_pnls = [] + trend_mismatch_pnls = [] + both_agree_pnls = [] + for r in rows: + idx = r["idx"] + # We don't have prices here directly, but corr > 0.5 ≈ trend match + if r["corr"] > 0: + trend_match_pnls.append(r["pnl"]) + else: + trend_mismatch_pnls.append(r["pnl"]) + + # Both shape_confirm AND high confidence + if r["confirmed"] and r["confidence"] >= 1.5: + both_agree_pnls.append(r["pnl"]) + + return { + "confirmed_pnl": round(float(np.mean(confirmed_pnls)), 3) if confirmed_pnls else 0, + "confirmed_wr": round(float(np.mean(np.array(confirmed_pnls) > 0) * 100), 1) if confirmed_pnls else 0, + "confirmed_n": len(confirmed_pnls), + "rejected_pnl": round(float(np.mean(rejected_pnls)), 3) if rejected_pnls else 0, + "rejected_wr": round(float(np.mean(np.array(rejected_pnls) > 0) * 100), 1) if rejected_pnls else 0, + "rejected_n": len(rejected_pnls), + "corr_pos_pnl": round(float(np.mean(trend_match_pnls)), 3) if trend_match_pnls else 0, + "corr_neg_pnl": round(float(np.mean(trend_mismatch_pnls)), 3) if trend_mismatch_pnls else 0, + "both_pnl": round(float(np.mean(both_agree_pnls)), 3) if both_agree_pnls else 0, + "both_n": len(both_agree_pnls), + } + + +def main(): + results_dir = Path(__file__).parent / "results" + print("=" * 80) + print("EXP26h: FINAL TEST — WHAT DOES THE MODEL ACTUALLY ADD?") + print("=" * 80) + print("Resolving: exp26f said +15% beyond ATR, exp26g said ATR beats model\n") + + 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})") + print(f"{'═' * 80}") + + # Build trained model and get signals + print(f" Training...", end=" ", flush=True) + mdl, data, n_train = _build_model(prices, ws) + rows = _get_signals(prices, mdl, data, n_train, ws, K) + print(f"{len(rows)} signals") + + if len(rows) < 30: + continue + + # ── TEST 1: Partial correlation ── + print(f"\n ── TEST 1: MODEL INFO BEYOND SIMPLE PREDICTORS ──") + t1 = test_partial(rows) + print(f" r(model, actual): {t1['r_raw']:+.3f}") + print(f" r(model, actual | ATR): {t1['r_beyond_atr']:+.3f}") + print(f" r(model, actual | Range): {t1['r_beyond_range']:+.3f}") + print(f" r(model, actual | RetVol): {t1['r_beyond_vol']:+.3f}") + print(f" r(model, actual | ATR+Range+Vol+Inp): {t1['r_beyond_all']:+.3f}") + print(f" r(Range, actual | model): {t1['r_range_beyond_model']:+.3f}") + verdict = "YES" if t1["model_adds_unique_info"] else "NO" + print(f" → Model adds unique info: {verdict}") + + # ── TEST 2: Untrained PnL ── + print(f"\n ── TEST 2: TRAINED vs UNTRAINED → PnL ──") + t2 = test_untrained_pnl(prices, ws, K) + for key in ["trained", "untrained"]: + s = t2[key] + print(f" {s['label']:<12s}: " + f"all N={s['n_all']:4d} PnL={s['pnl_all']:+.3f}% WR={s['wr_all']:.1f}% | " + f"conf N={s['n_conf']:3d} PnL={s['pnl_conf']:+.3f}% WR={s['wr_conf']:.1f}%") + if t2["trained"]["n_conf"] > 0 and t2["untrained"]["n_conf"] > 0: + delta = t2["trained"]["pnl_conf"] - t2["untrained"]["pnl_conf"] + print(f" Δ PnL (trained - untrained, conf filter): {delta:+.3f}pp") + + # ── TEST 3: Shape confirmation meaning ── + print(f"\n ── TEST 3: WHAT DOES SHAPE_CONFIRM DETECT? ──") + t3 = test_shape_meaning(rows) + print(f" Confirmed: PnL={t3['confirmed_pnl']:+.3f}% " + f"WR={t3['confirmed_wr']:.1f}% N={t3['confirmed_n']}") + print(f" Rejected: PnL={t3['rejected_pnl']:+.3f}% " + f"WR={t3['rejected_wr']:.1f}% N={t3['rejected_n']}") + print(f" Corr > 0: PnL={t3['corr_pos_pnl']:+.3f}%") + print(f" Corr < 0: PnL={t3['corr_neg_pnl']:+.3f}%") + print(f" Both filters: PnL={t3['both_pnl']:+.3f}% N={t3['both_n']}") + + result = {"ticker": ticker, "ws": ws, "K": K, + "partial": t1, "untrained_pnl": t2, "shape_meaning": t3} + all_results.append(result) + + # ── CROSS-ASSET SUMMARY ── + print(f"\n{'═' * 80}") + print("CROSS-ASSET SUMMARY") + print(f"{'═' * 80}") + + print(f"\n PARTIAL CORRELATION (model info beyond simple predictors):") + print(f" {'Asset':<10s} {'raw':>5s} {'|ATR':>5s} {'|Range':>6s} {'|Vol':>5s} " + f"{'|ALL':>5s} {'Rng|M':>6s} {'Unique':>7s}") + print(f" {'-' * 50}") + for r in all_results: + p = r["partial"] + print(f" {r['ticker']:<10s} {p['r_raw']:>+4.3f} {p['r_beyond_atr']:>+4.3f} " + f"{p['r_beyond_range']:>+5.3f} {p['r_beyond_vol']:>+4.3f} " + f"{p['r_beyond_all']:>+4.3f} {p['r_range_beyond_model']:>+5.3f} " + f"{'YES' if p['model_adds_unique_info'] else 'NO':>7s}") + + print(f"\n TRAINED vs UNTRAINED (conf-filtered PnL):") + print(f" {'Asset':<10s} {'Trained':>8s} {'Untrained':>10s} {'Δ':>7s} " + f"{'N_t':>4s} {'N_u':>4s}") + print(f" {'-' * 45}") + for r in all_results: + t = r["untrained_pnl"]["trained"] + u = r["untrained_pnl"]["untrained"] + delta = t["pnl_conf"] - u["pnl_conf"] if t["n_conf"] > 0 and u["n_conf"] > 0 else 0 + print(f" {r['ticker']:<10s} {t['pnl_conf']:>+7.3f}% {u['pnl_conf']:>+9.3f}% " + f"{delta:>+6.3f} {t['n_conf']:>4d} {u['n_conf']:>4d}") + + print(f"\n SHAPE_CONFIRM EFFECT:") + print(f" {'Asset':<10s} {'Conf PnL':>9s} {'Rej PnL':>8s} {'Δ':>8s}") + print(f" {'-' * 40}") + for r in all_results: + s = r["shape_meaning"] + delta = s["confirmed_pnl"] - s["rejected_pnl"] + print(f" {r['ticker']:<10s} {s['confirmed_pnl']:>+8.3f}% {s['rejected_pnl']:>+7.3f}% " + f"{delta:>+7.3f}pp") + + path = save_results({"results": all_results}, results_dir, "exp26h_final") + print(f"\nSaved: {path}") + + +if __name__ == "__main__": + main() diff --git a/experiments/exp26_ablation/results/results_exp26h_final_20260311_055546.json b/experiments/exp26_ablation/results/results_exp26h_final_20260311_055546.json new file mode 100644 index 0000000..7c8a7b0 --- /dev/null +++ b/experiments/exp26_ablation/results/results_exp26h_final_20260311_055546.json @@ -0,0 +1,244 @@ +{ + "results": [ + { + "ticker": "BTC-USD", + "ws": 64, + "K": 3, + "partial": { + "r_raw": 0.184, + "r_beyond_atr": 0.125, + "r_beyond_range": -0.088, + "r_beyond_vol": 0.085, + "r_beyond_all": 0.022, + "r_range_beyond_model": 0.325, + "model_adds_unique_info": false + }, + "untrained_pnl": { + "trained": { + "label": "trained", + "n_all": 590, + "pnl_all": 0.061, + "wr_all": 37.6, + "n_conf": 137, + "pnl_conf": 0.111, + "wr_conf": 38.7, + "conf_rate": 23.2 + }, + "untrained": { + "label": "untrained", + "n_all": 590, + "pnl_all": 0.181, + "wr_all": 40.2, + "n_conf": 0, + "pnl_conf": 0, + "wr_conf": 0, + "conf_rate": 0.0 + } + }, + "shape_meaning": { + "confirmed_pnl": 0.064, + "confirmed_wr": 36.4, + "confirmed_n": 247, + "rejected_pnl": 0.059, + "rejected_wr": 38.5, + "rejected_n": 343, + "corr_pos_pnl": 0.072, + "corr_neg_pnl": 0.05, + "both_pnl": 0.111, + "both_n": 137 + } + }, + { + "ticker": "ETH-USD", + "ws": 96, + "K": 2, + "partial": { + "r_raw": 0.128, + "r_beyond_atr": 0.103, + "r_beyond_range": -0.061, + "r_beyond_vol": 0.053, + "r_beyond_all": 0.028, + "r_range_beyond_model": 0.269, + "model_adds_unique_info": false + }, + "untrained_pnl": { + "trained": { + "label": "trained", + "n_all": 1187, + "pnl_all": 0.097, + "wr_all": 37.2, + "n_conf": 467, + "pnl_conf": 0.015, + "wr_conf": 37.5, + "conf_rate": 39.3 + }, + "untrained": { + "label": "untrained", + "n_all": 1186, + "pnl_all": 0.132, + "wr_all": 37.8, + "n_conf": 0, + "pnl_conf": 0, + "wr_conf": 0, + "conf_rate": 0.0 + } + }, + "shape_meaning": { + "confirmed_pnl": 0.099, + "confirmed_wr": 36.8, + "confirmed_n": 631, + "rejected_pnl": 0.096, + "rejected_wr": 37.8, + "rejected_n": 556, + "corr_pos_pnl": 0.099, + "corr_neg_pnl": 0.096, + "both_pnl": 0.015, + "both_n": 467 + } + }, + { + "ticker": "ADA-USD", + "ws": 64, + "K": 3, + "partial": { + "r_raw": 0.136, + "r_beyond_atr": 0.131, + "r_beyond_range": -0.008, + "r_beyond_vol": 0.067, + "r_beyond_all": 0.077, + "r_range_beyond_model": 0.183, + "model_adds_unique_info": true + }, + "untrained_pnl": { + "trained": { + "label": "trained", + "n_all": 590, + "pnl_all": 0.326, + "wr_all": 36.3, + "n_conf": 139, + "pnl_conf": 0.863, + "wr_conf": 36.0, + "conf_rate": 23.6 + }, + "untrained": { + "label": "untrained", + "n_all": 590, + "pnl_all": 0.495, + "wr_all": 37.3, + "n_conf": 0, + "pnl_conf": 0, + "wr_conf": 0, + "conf_rate": 0.0 + } + }, + "shape_meaning": { + "confirmed_pnl": 0.47, + "confirmed_wr": 37.7, + "confirmed_n": 236, + "rejected_pnl": 0.23, + "rejected_wr": 35.3, + "rejected_n": 354, + "corr_pos_pnl": 0.473, + "corr_neg_pnl": 0.177, + "both_pnl": 0.863, + "both_n": 139 + } + }, + { + "ticker": "DOGE-USD", + "ws": 48, + "K": 3, + "partial": { + "r_raw": 0.041, + "r_beyond_atr": 0.04, + "r_beyond_range": -0.067, + "r_beyond_vol": -0.011, + "r_beyond_all": 0.046, + "r_range_beyond_model": 0.176, + "model_adds_unique_info": true + }, + "untrained_pnl": { + "trained": { + "label": "trained", + "n_all": 591, + "pnl_all": 0.254, + "wr_all": 38.4, + "n_conf": 142, + "pnl_conf": 0.745, + "wr_conf": 41.5, + "conf_rate": 24.0 + }, + "untrained": { + "label": "untrained", + "n_all": 591, + "pnl_all": 0.278, + "wr_all": 37.2, + "n_conf": 0, + "pnl_conf": 0, + "wr_conf": 0, + "conf_rate": 0.0 + } + }, + "shape_meaning": { + "confirmed_pnl": 0.717, + "confirmed_wr": 42.1, + "confirmed_n": 228, + "rejected_pnl": -0.037, + "rejected_wr": 36.1, + "rejected_n": 363, + "corr_pos_pnl": 0.461, + "corr_neg_pnl": 0.067, + "both_pnl": 0.745, + "both_n": 142 + } + }, + { + "ticker": "SOL-USD", + "ws": 96, + "K": 3, + "partial": { + "r_raw": 0.169, + "r_beyond_atr": 0.15, + "r_beyond_range": -0.081, + "r_beyond_vol": 0.104, + "r_beyond_all": -0.001, + "r_range_beyond_model": 0.369, + "model_adds_unique_info": false + }, + "untrained_pnl": { + "trained": { + "label": "trained", + "n_all": 1187, + "pnl_all": -0.079, + "wr_all": 36.4, + "n_conf": 346, + "pnl_conf": 0.034, + "wr_conf": 40.2, + "conf_rate": 29.1 + }, + "untrained": { + "label": "untrained", + "n_all": 1187, + "pnl_all": -0.047, + "wr_all": 35.9, + "n_conf": 0, + "pnl_conf": 0, + "wr_conf": 0, + "conf_rate": 0.0 + } + }, + "shape_meaning": { + "confirmed_pnl": -0.057, + "confirmed_wr": 37.6, + "confirmed_n": 490, + "rejected_pnl": -0.095, + "rejected_wr": 35.6, + "rejected_n": 697, + "corr_pos_pnl": -0.126, + "corr_neg_pnl": -0.029, + "both_pnl": 0.034, + "both_n": 346 + } + } + ] +} \ No newline at end of file