Files
remizov-trader/experiments/exp26_ablation/formula_edge.py
T
anorandClaude Opus 4.6 67a256af5b feat: exp26f — систематический анализ edge формулы Ремизова
4 теста × 5 активов: timing, beyond-ATR, ranking, regime.
Timing/regime = NO. Beyond-ATR + ranking = YES для 4/5 активов.
Формула = статзначимый ранкер амплитуды (+10-15% info поверх ATR).
DOGE: no edge found.

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

520 lines
19 KiB
Python

"""Exp26f: What is the Remizov formula actually good at?
Known: direction accuracy = random (51%), amplitude corr = 0.16-0.23.
Unknown:
1. TIMING: Does model enter before big moves? (vs random entries)
2. VALUE BEYOND ATR: Does pred_amp add info beyond current ATR?
3. RANKING SIGNIFICANCE: Is amplitude correlation statistically significant?
4. REGIME DETECTION: Can model distinguish high-vol vs low-vol periods?
"""
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
N_RANDOM = 1000 # random entries for Monte Carlo
N_BOOTSTRAP = 1000
# Best ws/K from exp26e
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 _train_model(prices, ws):
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 _mfe(prices, idx, direction, lookahead=LOOKAHEAD):
"""Max favorable excursion from entry."""
entry = prices[idx]
best = 0.0
for i in range(1, lookahead + 1):
if idx + i >= len(prices):
break
move = (prices[idx + i] - entry) / entry * direction
best = max(best, move)
return best
def _realized_vol(prices, idx, window=LOOKAHEAD):
"""Realized volatility (range / mean) over next window bars."""
end = min(idx + window, len(prices))
seg = prices[idx:end]
if len(seg) < 2:
return 0
return float((np.max(seg) - np.min(seg)) / np.mean(seg))
def _get_model_signals(prices, ws, K):
"""Get all model signal points with their predictions."""
mdl, data, n_train = _train_model(prices, ws)
test_data = data[n_train:]
sigs = []
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
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)
sigs.append({
"idx": idx,
"pred_dir": pred_dir,
"pred_amp": pred_amp,
"pred_amp_atr": pred_amp / atr,
"atr": atr,
"confidence": confidence,
"confirmed": confirmed,
})
return sigs
# ═══════════════════════════════════════════════════════════════
# TEST 1: TIMING — Model entries vs Random entries
# ═══════════════════════════════════════════════════════════════
def test_timing(prices, sigs):
"""Compare model entry MFE vs random entry MFE."""
if not sigs:
return {}
# Model MFE (using model direction)
model_mfes = []
for s in sigs:
mfe = _mfe(prices, s["idx"], s["pred_dir"])
model_mfes.append(mfe * 100)
# Model MFE (always long — direction doesn't matter)
model_mfes_long = []
for s in sigs:
mfe = _mfe(prices, s["idx"], 1)
model_mfes_long.append(mfe * 100)
# Random entries: same number of entries, same test period
idx_min = min(s["idx"] for s in sigs)
idx_max = max(s["idx"] for s in sigs)
np.random.seed(42)
random_mfes_trials = []
for _ in range(N_RANDOM):
rand_idx = np.random.randint(idx_min, idx_max - LOOKAHEAD)
mfe_long = _mfe(prices, rand_idx, 1)
random_mfes_trials.append(mfe_long * 100)
# Also: random entries at same count as model
random_same_n = []
for _ in range(20): # 20 trials
rand_indices = np.random.choice(
range(idx_min, idx_max - LOOKAHEAD), size=len(sigs), replace=False)
trial_mfes = [_mfe(prices, int(i), 1) * 100 for i in rand_indices]
random_same_n.append(np.mean(trial_mfes))
# Realized vol at model entry points vs random
model_vols = [_realized_vol(prices, s["idx"]) * 100 for s in sigs]
random_vols = [_realized_vol(prices, int(i)) * 100
for i in np.random.randint(idx_min, idx_max - LOOKAHEAD, size=N_RANDOM)]
return {
"model_mfe_mean": round(float(np.mean(model_mfes)), 3),
"model_mfe_long_mean": round(float(np.mean(model_mfes_long)), 3),
"random_mfe_mean": round(float(np.mean(random_mfes_trials)), 3),
"random_mfe_std": round(float(np.std(random_mfes_trials)), 3),
"random_same_n_mean": round(float(np.mean(random_same_n)), 3),
"random_same_n_std": round(float(np.std(random_same_n)), 3),
"timing_edge": round(float(np.mean(model_mfes_long)) - float(np.mean(random_mfes_trials)), 3),
"model_vol_mean": round(float(np.mean(model_vols)), 3),
"random_vol_mean": round(float(np.mean(random_vols)), 3),
"vol_edge": round(float(np.mean(model_vols)) - float(np.mean(random_vols)), 3),
"n_model": len(sigs),
}
# ═══════════════════════════════════════════════════════════════
# TEST 2: VALUE BEYOND ATR — Does pred_amp add info beyond ATR?
# ═══════════════════════════════════════════════════════════════
def test_beyond_atr(prices, sigs):
"""Partial correlation: pred_amp vs actual_amp, controlling for ATR."""
if len(sigs) < 20:
return {}
pred_amps = []
actual_amps = []
atrs = []
for s in sigs:
idx = s["idx"]
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))
pred_amps.append(s["pred_amp_atr"])
actual_amps.append(actual_amp / s["atr"] if s["atr"] > 0 else 0)
atrs.append(s["atr"])
pred_a = np.array(pred_amps)
actual_a = np.array(actual_amps)
atr_a = np.array(atrs)
# Raw correlation
with np.errstate(invalid="ignore"):
r_raw = np.corrcoef(pred_a, actual_a)[0, 1]
if np.isnan(r_raw):
r_raw = 0
# Partial correlation: r(pred, actual | ATR)
# Regress out ATR from both pred and actual, then correlate residuals
if np.std(atr_a) > 1e-10:
# pred residual
atr_mean = np.mean(atr_a)
atr_std_val = np.std(atr_a)
atr_norm = (atr_a - atr_mean) / atr_std_val
# Linear regression: pred = a*atr + b → residual
cov_pred_atr = np.mean(pred_a * atr_norm) - np.mean(pred_a) * np.mean(atr_norm)
var_atr = np.var(atr_norm)
if var_atr > 1e-10:
beta_pred = cov_pred_atr / var_atr
resid_pred = pred_a - beta_pred * atr_norm - np.mean(pred_a)
cov_act_atr = np.mean(actual_a * atr_norm) - np.mean(actual_a) * np.mean(atr_norm)
beta_act = cov_act_atr / var_atr
resid_act = actual_a - beta_act * atr_norm - np.mean(actual_a)
with np.errstate(invalid="ignore"):
r_partial = np.corrcoef(resid_pred, resid_act)[0, 1]
if np.isnan(r_partial):
r_partial = 0
else:
r_partial = r_raw
else:
r_partial = r_raw
# How much does ATR alone predict actual amplitude?
with np.errstate(invalid="ignore"):
r_atr_actual = np.corrcoef(atr_a, actual_a * atr_a)[0, 1] # actual_amp (not /atr)
if np.isnan(r_atr_actual):
r_atr_actual = 0
# Correlation of pred_amp with ATR (are they redundant?)
with np.errstate(invalid="ignore"):
r_pred_atr = np.corrcoef(pred_a, atr_a)[0, 1]
if np.isnan(r_pred_atr):
r_pred_atr = 0
return {
"r_raw": round(float(r_raw), 3),
"r_partial_given_atr": round(float(r_partial), 3),
"r_pred_vs_atr": round(float(r_pred_atr), 3),
"r_atr_vs_actual": round(float(r_atr_actual), 3),
"info_beyond_atr": r_partial > 0.05,
"n": len(pred_amps),
}
# ═══════════════════════════════════════════════════════════════
# TEST 3: RANKING SIGNIFICANCE — Bootstrap CI for amplitude corr
# ═══════════════════════════════════════════════════════════════
def test_ranking(prices, sigs):
"""Bootstrap confidence interval for amplitude correlation."""
if len(sigs) < 20:
return {}
pred_amps = []
actual_amps = []
for s in sigs:
idx = s["idx"]
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))
pred_amps.append(s["pred_amp_atr"])
actual_amps.append(actual_amp / s["atr"] if s["atr"] > 0 else 0)
pred_a = np.array(pred_amps)
actual_a = np.array(actual_amps)
n = len(pred_a)
# Pearson correlation
with np.errstate(invalid="ignore"):
r_pearson = np.corrcoef(pred_a, actual_a)[0, 1]
if np.isnan(r_pearson):
r_pearson = 0
# Spearman rank correlation
from scipy.stats import spearmanr, pearsonr
r_spearman, p_spearman = spearmanr(pred_a, actual_a)
_, p_pearson = pearsonr(pred_a, actual_a)
# Bootstrap CI
np.random.seed(42)
boot_corrs = []
for _ in range(N_BOOTSTRAP):
idx_boot = np.random.choice(n, size=n, replace=True)
with np.errstate(invalid="ignore"):
r_b = np.corrcoef(pred_a[idx_boot], actual_a[idx_boot])[0, 1]
if not np.isnan(r_b):
boot_corrs.append(r_b)
boot_corrs = np.array(boot_corrs)
ci_lo = float(np.percentile(boot_corrs, 2.5))
ci_hi = float(np.percentile(boot_corrs, 97.5))
# Monotonicity check: Q1 < Q2 < Q3 < Q4?
pcts = np.percentile(pred_a, [25, 50, 75])
q_means = []
for lo, hi in [(0, pcts[0]), (pcts[0], pcts[1]),
(pcts[1], pcts[2]), (pcts[2], 1e10)]:
mask = (pred_a >= lo) & (pred_a < hi)
if np.any(mask):
q_means.append(float(np.mean(actual_a[mask])))
else:
q_means.append(0)
monotonic = all(q_means[i] <= q_means[i + 1] for i in range(3))
return {
"r_pearson": round(float(r_pearson), 3),
"p_pearson": round(float(p_pearson), 4),
"r_spearman": round(float(r_spearman), 3),
"p_spearman": round(float(p_spearman), 4),
"ci_95_lo": round(ci_lo, 3),
"ci_95_hi": round(ci_hi, 3),
"significant_95": ci_lo > 0,
"quartile_means": [round(q, 3) for q in q_means],
"monotonic": monotonic,
"n": n,
}
# ═══════════════════════════════════════════════════════════════
# TEST 4: REGIME DETECTION — High-vol vs Low-vol classification
# ═══════════════════════════════════════════════════════════════
def test_regime(prices, sigs):
"""Can the model distinguish high-vol from low-vol periods?"""
if len(sigs) < 20:
return {}
# For each signal, compute predicted vol bucket and actual vol
pred_amps = []
actual_vols = []
for s in sigs:
idx = s["idx"]
rv = _realized_vol(prices, idx)
pred_amps.append(s["pred_amp_atr"])
actual_vols.append(rv)
pred_a = np.array(pred_amps)
actual_v = np.array(actual_vols)
# Binary classification: above/below median
pred_high = pred_a >= np.median(pred_a)
actual_high = actual_v >= np.median(actual_v)
# Accuracy
acc = float(np.mean(pred_high == actual_high) * 100)
# Precision/recall for high-vol detection
tp = np.sum(pred_high & actual_high)
fp = np.sum(pred_high & ~actual_high)
fn = np.sum(~pred_high & actual_high)
precision = float(tp / (tp + fp) * 100) if (tp + fp) > 0 else 0
recall = float(tp / (tp + fn) * 100) if (tp + fn) > 0 else 0
# Tertile analysis: pred Low/Mid/High → actual vol
pcts = np.percentile(pred_a, [33, 67])
tertile_vols = []
for lo, hi, name in [(0, pcts[0], "Low pred"),
(pcts[0], pcts[1], "Mid pred"),
(pcts[1], 1e10, "High pred")]:
mask = (pred_a >= lo) & (pred_a < hi)
if np.any(mask):
tertile_vols.append({
"name": name,
"actual_vol_mean": round(float(np.mean(actual_v[mask])) * 100, 2),
"n": int(np.sum(mask)),
})
return {
"binary_accuracy": round(acc, 1),
"precision_high_vol": round(precision, 1),
"recall_high_vol": round(recall, 1),
"tertile_vols": tertile_vols,
"n": len(sigs),
}
def main():
results_dir = Path(__file__).parent / "results"
print("=" * 80)
print("EXP26f: WHAT IS THE REMIZOV FORMULA GOOD AT?")
print("=" * 80)
print("Tests: 1.Timing 2.Beyond-ATR 3.Ranking 4.Regime detection\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}")
print(f" Training model...", end=" ", flush=True)
sigs = _get_model_signals(prices, ws, K)
print(f"{len(sigs)} signals")
if len(sigs) < 20:
print(" Too few signals, skip")
continue
# ── TEST 1: Timing ──
print(f"\n ── TEST 1: TIMING (model entries vs random) ──")
t1 = test_timing(prices, sigs)
print(f" Model MFE (model dir): {t1['model_mfe_mean']:+.3f}%")
print(f" Model MFE (always long): {t1['model_mfe_long_mean']:+.3f}%")
print(f" Random MFE (N={N_RANDOM}): {t1['random_mfe_mean']:+.3f}% ± {t1['random_mfe_std']:.3f}")
print(f" Timing edge (long): {t1['timing_edge']:+.3f}pp")
print(f" Model entry vol: {t1['model_vol_mean']:.3f}%")
print(f" Random entry vol: {t1['random_vol_mean']:.3f}%")
print(f" Vol edge: {t1['vol_edge']:+.3f}pp")
verdict = "YES" if t1['timing_edge'] > 0.1 else "NO"
print(f" → Timing edge: {verdict}")
# ── TEST 2: Beyond ATR ──
print(f"\n ── TEST 2: VALUE BEYOND ATR ──")
t2 = test_beyond_atr(prices, sigs)
print(f" r(pred_amp, actual_amp): {t2['r_raw']:+.3f}")
print(f" r(pred_amp, actual_amp | ATR): {t2['r_partial_given_atr']:+.3f}")
print(f" r(pred_amp, ATR): {t2['r_pred_vs_atr']:+.3f}")
print(f" r(ATR, actual_amp): {t2['r_atr_vs_actual']:+.3f}")
print(f" → Beyond ATR: {'YES' if t2['info_beyond_atr'] else 'NO'}")
# ── TEST 3: Ranking ──
print(f"\n ── TEST 3: RANKING SIGNIFICANCE ──")
t3 = test_ranking(prices, sigs)
print(f" Pearson r: {t3['r_pearson']:+.3f} (p={t3['p_pearson']:.4f})")
print(f" Spearman r: {t3['r_spearman']:+.3f} (p={t3['p_spearman']:.4f})")
print(f" 95% CI: [{t3['ci_95_lo']:+.3f}, {t3['ci_95_hi']:+.3f}]")
print(f" Significant (CI excludes 0): {'YES' if t3['significant_95'] else 'NO'}")
print(f" Quartile means: {t3['quartile_means']}")
print(f" Monotonic Q1<Q2<Q3<Q4: {'YES' if t3['monotonic'] else 'NO'}")
# ── TEST 4: Regime ──
print(f"\n ── TEST 4: REGIME DETECTION ──")
t4 = test_regime(prices, sigs)
print(f" Binary accuracy (high/low vol): {t4['binary_accuracy']:.1f}%")
print(f" Precision (high-vol): {t4['precision_high_vol']:.1f}%")
print(f" Recall (high-vol): {t4['recall_high_vol']:.1f}%")
for tv in t4["tertile_vols"]:
print(f" {tv['name']:<12s} → actual vol = {tv['actual_vol_mean']:.2f}% (N={tv['n']})")
result = {
"ticker": ticker, "ws": ws, "K": K,
"timing": t1, "beyond_atr": t2,
"ranking": t3, "regime": t4,
}
all_results.append(result)
# ── CROSS-ASSET SUMMARY ──
print(f"\n{'═' * 80}")
print("CROSS-ASSET SUMMARY")
print(f"{'═' * 80}")
print(f" {'Asset':<10s} {'Timing':>8s} {'BeyondATR':>10s} {'Pearson':>8s} "
f"{'Spearman':>9s} {'CI_lo':>6s} {'Regime':>7s} {'Monoton':>8s}")
print(f" {'-' * 70}")
for r in all_results:
t = r["timing"]
b = r["beyond_atr"]
rk = r["ranking"]
rg = r["regime"]
print(f" {r['ticker']:<10s} "
f"{t['timing_edge']:>+7.3f}pp "
f"{b['r_partial_given_atr']:>+9.3f} "
f"{rk['r_pearson']:>+7.3f} "
f"{rk['r_spearman']:>+8.3f} "
f"{rk['ci_95_lo']:>+5.3f} "
f"{rg['binary_accuracy']:>6.1f}% "
f"{'YES' if rk['monotonic'] else 'NO':>8s}")
# Verdicts
print(f"\n VERDICTS:")
for r in all_results:
ticker = r["ticker"]
edges = []
if r["timing"]["timing_edge"] > 0.1:
edges.append("timing")
if r["beyond_atr"]["info_beyond_atr"]:
edges.append("beyond-ATR")
if r["ranking"]["significant_95"]:
edges.append("ranking-significant")
if r["ranking"]["monotonic"]:
edges.append("monotonic")
if r["regime"]["binary_accuracy"] > 55:
edges.append("regime-detect")
status = ", ".join(edges) if edges else "NO EDGE FOUND"
print(f" {ticker:<10s}: {status}")
path = save_results({"results": all_results}, results_dir, "exp26f_formula_edge")
print(f"\nSaved: {path}")
if __name__ == "__main__":
main()