Files
remizov-trader/experiments/exp26_ablation/direction_test.py
T
anorandClaude Opus 4.6 630d3baf99 feat: эксперименты exp23-26 — ablation study, amplitude prediction
exp23: weight optimization (EQUAL лучше всех)
exp24: realistic backtest с retrain (retrain вреден)
exp25: порт на backtrader, retrain modes comparison
exp26: ablation study ADA — shape_confirm #1 фактор
exp26b: direction accuracy = 51% (random)
exp26c: trailing stop WR edge vs random = 0pp
exp26d: amplitude prediction — r=0.164 для ADA (Q4/Q1=1.5x)

Главный вывод: формула Ремизова = детектор волатильности,
не predictor направления. Прибыльность = trailing stop
asymmetry + amplitude filter.

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-03-11 05:14:15 +10:00

298 lines
12 KiB
Python

"""Exp26b: Pure directional accuracy of Remizov formula.
No trading, no PnL — just: did the model predict the correct direction?
Tests on ALL assets, not just ADA.
Metrics:
1. Direction accuracy: pred_dir == actual_dir (hit rate %)
2. Shape correlation: corr(predicted_curve, actual_future)
3. Breakdown by horizon (1..shift candles ahead)
4. Breakdown by confidence bucket (low/mid/high)
5. Breakdown by shape confirmation (confirmed vs rejected)
"""
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
ASSETS = [
{"ticker": "BTC-USD", "ws": 32, "K": 3, "shift": 7},
{"ticker": "ETH-USD", "ws": 64, "K": 2, "shift": 7},
{"ticker": "ADA-USD", "ws": 64, "K": 3, "shift": 7},
{"ticker": "DOGE-USD", "ws": 48, "K": 2, "shift": 7},
{"ticker": "SOL-USD", "ws": 128, "K": 2, "shift": 7},
]
def _train_model(prices, ws, shift, epochs=200):
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]]),
epochs, 0.003)
return mdl, data, n_train
def _analyze_asset(ticker, prices, ws, K, shift):
"""Run direction analysis for one asset.
Two modes tested:
A) Training-aligned: window = prices[t-ws:t] (same as model training)
B) Trading-aligned: window = prices[t-ws-K:t-K] (same as prod execution)
"""
mdl, data, n_train = _train_model(prices, ws, shift)
test_data = data[n_train:]
if len(test_data) < 10:
return None
results = []
for d in test_data:
idx = d["price_idx"]
mu_train, std_train = d["mu"], d["std"]
future = d["future_prices"] # actual future: shift candles
# === MODE A: Training-aligned (model sees prices[t-ws:t]) ===
pred_a = model_mod.predict(mdl, d["norm_input"])
pred_new_a = pred_a[-shift:]
pred_dir_a = signals.get_direction(pred_new_a, K)
# === MODE B: Trading-aligned (model sees prices[t-ws-K:t-K]) ===
if idx >= ws + K:
w_trade = prices[idx - ws - K: idx - K].copy()
mu_t, std_t = w_trade.mean(), w_trade.std()
if std_t > 1e-10:
pred_b = model_mod.predict(mdl, (w_trade - mu_t) / std_t)
pred_new_b = pred_b[-shift:]
pred_dir_b = signals.get_direction(pred_new_b, K)
pred_denorm_b = pred_new_b * std_t + mu_t
# Shape confirmation (as in prod)
confirm = prices[idx - K:idx].copy()
corr_b, confirmed_b = signals.check_shape_confirmation(
pred_new_b, confirm, mu_t, std_t, K, 0.5)
atr = risk.compute_atr(prices, idx)
amp_b = float(np.max(pred_denorm_b) - np.min(pred_denorm_b))
conf_b = abs(corr_b) * (amp_b / atr) if atr > 0 else 0
else:
pred_dir_b, corr_b, confirmed_b, conf_b = None, 0, False, 0
pred_denorm_b = np.zeros(shift)
else:
pred_dir_b, corr_b, confirmed_b, conf_b = None, 0, False, 0
pred_denorm_b = np.zeros(shift)
# Actual direction for Mode A (training-aligned):
# pred_new[K-1] ↔ prices[idx+K-1], pred_new[-1] ↔ prices[idx+shift-1]
if len(future) >= shift and K <= shift:
actual_move_a = future[-1] - future[K - 1]
actual_dir_a = 1 if actual_move_a > 0 else (-1 if actual_move_a < 0 else 0)
else:
actual_dir_a = 0
# Actual direction for Mode B (trading-aligned, K-offset):
# pred_new[K-1] ↔ prices[idx-1], pred_new[-1] ↔ prices[idx+shift-K-1]
end_b = idx + shift - K - 1
start_b = idx - 1
if start_b >= 0 and end_b < len(prices):
actual_move_b = prices[end_b] - prices[start_b]
actual_dir_b = 1 if actual_move_b > 0 else (-1 if actual_move_b < 0 else 0)
else:
actual_dir_b = 0
# Shape correlation: predicted curve vs actual future
pred_denorm_a = pred_new_a * std_train + mu_train
if len(future) == len(pred_denorm_a) and len(future) >= 2:
with np.errstate(invalid="ignore"):
shape_corr_a = np.corrcoef(pred_denorm_a, future)[0, 1]
if np.isnan(shape_corr_a):
shape_corr_a = 0.0
else:
shape_corr_a = 0.0
# Confirmation correlation (training-aligned, for comparison)
confirm_a = prices[idx - K:idx].copy()
corr_a, confirmed_a = signals.check_shape_confirmation(
pred_new_a, confirm_a, mu_train, std_train, K, 0.5)
atr_a = risk.compute_atr(prices, idx)
amp_a = float(np.max(pred_denorm_a) - np.min(pred_denorm_a))
conf_a = abs(corr_a) * (amp_a / atr_a) if atr_a > 0 else 0
# Direction accuracy per horizon (h=2..shift, skip h=1 trivially 0)
horizon_hits = {}
last_known_price = prices[idx - 1] # price before prediction
for h in range(2, shift + 1):
if h <= len(future):
pred_h_up = pred_denorm_a[h - 1] > pred_denorm_a[0]
actual_h_up = future[h - 1] > future[0]
horizon_hits[h] = 1 if (pred_h_up == actual_h_up) else 0
results.append({
"idx": idx,
# Mode A (training-aligned)
"pred_dir_a": pred_dir_a,
"actual_dir_a": actual_dir_a,
"hit_a": 1 if (pred_dir_a == actual_dir_a) else 0,
"shape_corr_a": shape_corr_a,
"corr_a": corr_a, "confirmed_a": confirmed_a, "conf_a": conf_a,
# Mode B (trading-aligned, as in prod)
"pred_dir_b": pred_dir_b,
"actual_dir_b": actual_dir_b,
"hit_b": 1 if (pred_dir_b == actual_dir_b) else 0,
"corr_b": corr_b, "confirmed_b": confirmed_b, "conf_b": conf_b,
# Horizon (Mode A only)
"horizon_hits": horizon_hits,
})
return results
def _print_report(ticker, results, K, shift):
n = len(results)
valid_a = [r for r in results if r["pred_dir_a"] is not None and r["actual_dir_a"] != 0]
valid_b = [r for r in results if r["pred_dir_b"] is not None and r["actual_dir_b"] != 0]
n_a, n_b = len(valid_a), len(valid_b)
print(f"\n{'─' * 70}")
print(f" {ticker} ({n} test windows)")
print(f"{'─' * 70}")
if not n_a:
print(" No valid predictions")
return {}
# ── Mode A: Training-aligned ──
hits_a = sum(r["hit_a"] for r in valid_a)
acc_a = hits_a / n_a * 100
print(f"\n MODE A (training-aligned window):")
print(f" Direction accuracy: {hits_a}/{n_a} = {acc_a:.1f}%")
shape_corrs = [r["shape_corr_a"] for r in valid_a]
print(f" Shape correlation: mean={np.mean(shape_corrs):.3f}")
# ── Mode B: Trading-aligned (as in prod) ──
hits_b = sum(r["hit_b"] for r in valid_b)
acc_b = hits_b / n_b * 100 if n_b else 0
print(f"\n MODE B (trading-aligned, K-offset window — as in prod):")
print(f" Direction accuracy: {hits_b}/{n_b} = {acc_b:.1f}%")
# ── Mode B with filters (prod-like) ──
# Shape confirmed + confidence >= 1.5 + LONG only (as prod is long-only)
prod_like = [r for r in valid_b if r["confirmed_b"] and r["conf_b"] >= 1.5
and r["pred_dir_b"] == 1]
if prod_like:
prod_hits = sum(r["hit_b"] for r in prod_like)
prod_acc = prod_hits / len(prod_like) * 100
print(f"\n MODE B + PROD FILTERS (shape+conf>=1.5+LONG):")
print(f" Direction accuracy: {prod_hits}/{len(prod_like)} = {prod_acc:.1f}%")
print(f" (filtered from {n_b} → {len(prod_like)} signals = "
f"{len(prod_like)/n_b*100:.0f}% pass rate)")
else:
prod_acc = 0
print(f"\n MODE B + PROD FILTERS: 0 signals passed all filters")
# ── By filter stages ──
print(f"\n Filter breakdown (Mode B):")
conf_only = [r for r in valid_b if r["confirmed_b"]]
high_conf = [r for r in valid_b if r["conf_b"] >= 1.5]
longs_b = [r for r in valid_b if r["pred_dir_b"] == 1]
for label, subset in [("All", valid_b), ("Shape confirmed", conf_only),
("Confidence>=1.5", high_conf), ("LONG only", longs_b),
("Confirmed+Conf>=1.5", [r for r in valid_b
if r["confirmed_b"] and r["conf_b"] >= 1.5]),
("PROD (conf+shape+long)", prod_like)]:
if subset:
h = sum(r["hit_b"] for r in subset)
a = h / len(subset) * 100
marker = " ✓" if a > 55 else (" ✗" if a < 45 else "")
print(f" {label:<25s} {h:4d}/{len(subset):4d} = {a:5.1f}%{marker}")
# Horizon analysis (Mode A)
print(f"\n Direction by horizon (h=2..{shift}):")
for h in range(2, shift + 1):
h_hits = sum(r["horizon_hits"].get(h, 0) for r in valid_a if h in r["horizon_hits"])
h_total = sum(1 for r in valid_a if h in r["horizon_hits"])
if h_total:
h_acc = h_hits / h_total * 100
print(f" H={h}: {h_acc:.1f}%")
# Long vs Short in both modes
longs_a = [r for r in valid_a if r["pred_dir_a"] == 1]
shorts_a = [r for r in valid_a if r["pred_dir_a"] == -1]
return {
"ticker": ticker, "total": n_a,
"acc_train": round(acc_a, 1),
"acc_trade": round(acc_b, 1),
"acc_prod_filtered": round(prod_acc, 1),
"prod_signals": len(prod_like) if prod_like else 0,
"shape_corr_mean": round(float(np.mean(shape_corrs)), 3),
}
def main():
results_dir = Path(__file__).parent / "results"
print("=" * 70)
print("EXP26b: DIRECTIONAL ACCURACY OF REMIZOV FORMULA")
print("=" * 70)
print("Mode A: training-aligned window (model sees latest data)")
print("Mode B: trading-aligned window (K-offset, as in prod)")
print("PROD filter: shape confirmed + confidence >= 1.5 + LONG only\n")
dataset = load_or_fetch("default")
all_summaries = []
for a in ASSETS:
ticker = a["ticker"]
if ticker not in dataset:
print(f" {ticker}: not in dataset, skip")
continue
prices = dataset[ticker]["prices"]
print(f" Training {ticker} (ws={a['ws']}, K={a['K']})...", end=" ", flush=True)
results = _analyze_asset(ticker, prices, a["ws"], a["K"], a["shift"])
if results is None:
print("not enough data")
continue
print(f"{len(results)} test windows")
summary = _print_report(ticker, results, a["K"], a["shift"])
if summary:
all_summaries.append(summary)
# Cross-asset summary
print(f"\n{'=' * 70}")
print("CROSS-ASSET SUMMARY")
print(f"{'=' * 70}")
print(f" {'Asset':<10s} {'Train':>6s} {'Trade':>6s} {'PROD':>6s} {'Sigs':>5s} {'Shape r':>7s}")
print(f" {'-' * 45}")
for s in all_summaries:
print(f" {s['ticker']:<10s} {s['acc_train']:>5.1f}% {s['acc_trade']:>5.1f}% "
f"{s['acc_prod_filtered']:>5.1f}% {s['prod_signals']:>5d} "
f"{s['shape_corr_mean']:>7.3f}")
if all_summaries:
print(f"\n Train avg: {np.mean([s['acc_train'] for s in all_summaries]):.1f}%")
print(f" Trade avg: {np.mean([s['acc_trade'] for s in all_summaries]):.1f}%")
prod_accs = [s['acc_prod_filtered'] for s in all_summaries if s['prod_signals'] > 0]
if prod_accs:
print(f" PROD filtered avg: {np.mean(prod_accs):.1f}%")
path = save_results({"summaries": all_summaries}, results_dir, "exp26b_direction")
print(f"\nSaved: {path}")
if __name__ == "__main__":
main()