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 <noreply@anthropic.com>
386 lines
16 KiB
Python
386 lines
16 KiB
Python
"""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()
|