v1: обнаружил что random weights = trained (баг: zeros init). v2 fix: Xavier random init, корректное сравнение предикторов. Результат: обучение не помогает (Δ = -0.005 to -0.075). ATR и price range бьют модель у 4/5 активов. Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
437 lines
17 KiB
Python
437 lines
17 KiB
Python
"""Exp26g: Deep analysis of Remizov formula edge.
|
||
|
||
Three tests:
|
||
1. OOS STABILITY: Is r=0.15 stable across time, or concentrated in one period?
|
||
2. RANDOM WEIGHTS: Does untrained network give same edge? (architecture vs learning)
|
||
3. SIMPLER ALTERNATIVES: Does ATR percentile filter give same edge without neural net?
|
||
"""
|
||
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 _train_model(prices, ws, trained=True, seed=42):
|
||
data = signals.prepare_windows(prices, ws, SHIFT)
|
||
n_train = max(int(len(data) * TRAIN_RATIO), 20)
|
||
torch.manual_seed(seed)
|
||
np.random.seed(seed)
|
||
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 _get_predictions(prices, mdl, data, n_train, ws, K):
|
||
"""Get pred_amp_atr and actual_amp_atr for test data."""
|
||
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
|
||
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))
|
||
rows.append({
|
||
"idx": idx, "pred_amp_atr": pred_amp / atr,
|
||
"actual_amp_atr": actual_amp / atr, "atr": atr,
|
||
})
|
||
return rows
|
||
|
||
|
||
def _corr(a, b):
|
||
with np.errstate(invalid="ignore"):
|
||
r = np.corrcoef(a, b)[0, 1]
|
||
return 0 if np.isnan(r) else float(r)
|
||
|
||
|
||
# ═══════════════════════════════════════════════════════════════
|
||
# TEST 1: OOS STABILITY — Rolling window correlation
|
||
# ═══════════════════════════════════════════════════════════════
|
||
def test_stability(prices, ws, K):
|
||
"""Split test period into chunks, compute r per chunk."""
|
||
mdl, data, n_train = _train_model(prices, ws)
|
||
rows = _get_predictions(prices, mdl, data, n_train, ws, K)
|
||
if len(rows) < 40:
|
||
return {}
|
||
|
||
n = len(rows)
|
||
# Split into 4 quarters
|
||
chunk_size = n // 4
|
||
quarters = []
|
||
for i in range(4):
|
||
start = i * chunk_size
|
||
end = (i + 1) * chunk_size if i < 3 else n
|
||
chunk = rows[start:end]
|
||
pred_a = np.array([r["pred_amp_atr"] for r in chunk])
|
||
actual_a = np.array([r["actual_amp_atr"] for r in chunk])
|
||
r = _corr(pred_a, actual_a)
|
||
quarters.append({
|
||
"quarter": f"Q{i+1}",
|
||
"r": round(r, 3),
|
||
"n": len(chunk),
|
||
"idx_range": f"{chunk[0]['idx']}-{chunk[-1]['idx']}",
|
||
})
|
||
|
||
# Rolling window (window = n//5, step = n//10)
|
||
win = max(n // 5, 30)
|
||
step = max(n // 10, 15)
|
||
rolling = []
|
||
for start in range(0, n - win, step):
|
||
chunk = rows[start:start + win]
|
||
pred_a = np.array([r["pred_amp_atr"] for r in chunk])
|
||
actual_a = np.array([r["actual_amp_atr"] for r in chunk])
|
||
r = _corr(pred_a, actual_a)
|
||
rolling.append(round(r, 3))
|
||
|
||
# Overall
|
||
all_pred = np.array([r["pred_amp_atr"] for r in rows])
|
||
all_actual = np.array([r["actual_amp_atr"] for r in rows])
|
||
r_all = _corr(all_pred, all_actual)
|
||
|
||
return {
|
||
"r_overall": round(r_all, 3),
|
||
"quarters": quarters,
|
||
"rolling_r": rolling,
|
||
"rolling_mean": round(float(np.mean(rolling)), 3),
|
||
"rolling_std": round(float(np.std(rolling)), 3),
|
||
"rolling_min": round(float(np.min(rolling)), 3),
|
||
"rolling_max": round(float(np.max(rolling)), 3),
|
||
"pct_positive": round(float(np.mean(np.array(rolling) > 0) * 100), 1),
|
||
"n": n,
|
||
}
|
||
|
||
|
||
# ═══════════════════════════════════════════════════════════════
|
||
# TEST 2: RANDOM WEIGHTS — Untrained vs Trained network
|
||
# ═══════════════════════════════════════════════════════════════
|
||
def test_random_weights(prices, ws, K):
|
||
"""Compare trained model vs untrained (random weights) vs multiple random seeds."""
|
||
# Trained model
|
||
mdl_trained, data, n_train = _train_model(prices, ws, trained=True)
|
||
rows_trained = _get_predictions(prices, mdl_trained, data, n_train, ws, K)
|
||
if len(rows_trained) < 20:
|
||
return {}
|
||
pred_t = np.array([r["pred_amp_atr"] for r in rows_trained])
|
||
actual_t = np.array([r["actual_amp_atr"] for r in rows_trained])
|
||
r_trained = _corr(pred_t, actual_t)
|
||
|
||
# Untrained model (random weights, seed=42)
|
||
mdl_random, _, _ = _train_model(prices, ws, trained=False, seed=42)
|
||
rows_random = _get_predictions(prices, mdl_random, data, n_train, ws, K)
|
||
if rows_random:
|
||
pred_r = np.array([r["pred_amp_atr"] for r in rows_random])
|
||
actual_r = np.array([r["actual_amp_atr"] for r in rows_random])
|
||
r_untrained = _corr(pred_r, actual_r)
|
||
else:
|
||
r_untrained = 0
|
||
|
||
# Multiple random seeds (untrained)
|
||
random_rs = []
|
||
for seed in range(10):
|
||
mdl_rnd, _, _ = _train_model(prices, ws, trained=False, seed=seed * 7 + 13)
|
||
rows_rnd = _get_predictions(prices, mdl_rnd, data, n_train, ws, K)
|
||
if rows_rnd:
|
||
p = np.array([r["pred_amp_atr"] for r in rows_rnd])
|
||
a = np.array([r["actual_amp_atr"] for r in rows_rnd])
|
||
random_rs.append(_corr(p, a))
|
||
|
||
# Partially trained (50 epochs instead of 200)
|
||
torch.manual_seed(42)
|
||
np.random.seed(42)
|
||
mdl_partial = EnhancedRemizovNet(grid_size=ws, n_steps=20, total_time=0.5,
|
||
dx=1.0 / ws, use_sde=True)
|
||
model_mod.train(mdl_partial,
|
||
np.array([d["norm_input"] for d in data[:n_train]]),
|
||
np.array([d["norm_target"] for d in data[:n_train]]),
|
||
50, 0.003)
|
||
rows_partial = _get_predictions(prices, mdl_partial, data, n_train, ws, K)
|
||
if rows_partial:
|
||
p = np.array([r["pred_amp_atr"] for r in rows_partial])
|
||
a = np.array([r["actual_amp_atr"] for r in rows_partial])
|
||
r_partial = _corr(p, a)
|
||
else:
|
||
r_partial = 0
|
||
|
||
return {
|
||
"r_trained": round(r_trained, 3),
|
||
"r_untrained": round(r_untrained, 3),
|
||
"r_partial_50ep": round(r_partial, 3),
|
||
"random_seeds_mean": round(float(np.mean(random_rs)), 3) if random_rs else 0,
|
||
"random_seeds_std": round(float(np.std(random_rs)), 3) if random_rs else 0,
|
||
"random_seeds_max": round(float(np.max(random_rs)), 3) if random_rs else 0,
|
||
"training_adds_value": r_trained > (np.mean(random_rs) + np.std(random_rs)) if random_rs else False,
|
||
"n_trained": len(rows_trained),
|
||
"n_untrained": len(rows_random) if rows_random else 0,
|
||
}
|
||
|
||
|
||
# ═══════════════════════════════════════════════════════════════
|
||
# TEST 3: SIMPLER ALTERNATIVES — ATR percentile vs neural net
|
||
# ═══════════════════════════════════════════════════════════════
|
||
def test_simpler(prices, ws, K):
|
||
"""Compare Remizov amplitude prediction vs simple ATR-based alternatives."""
|
||
mdl, data, n_train = _train_model(prices, ws)
|
||
rows = _get_predictions(prices, mdl, data, n_train, ws, K)
|
||
if len(rows) < 40:
|
||
return {}
|
||
|
||
# For each signal point, compute alternative "amplitude predictors"
|
||
model_preds = []
|
||
atr_preds = [] # raw ATR
|
||
atr_pct_preds = [] # ATR percentile (rank in recent history)
|
||
range_preds = [] # recent price range
|
||
vol_preds = [] # recent returns volatility
|
||
actuals = []
|
||
|
||
for r in rows:
|
||
idx = r["idx"]
|
||
atr = r["atr"]
|
||
|
||
# ATR percentile: where does current ATR rank in last 100 ATRs?
|
||
atrs_hist = []
|
||
for j in range(max(14, idx - 100), idx):
|
||
a = risk.compute_atr(prices, j)
|
||
if a > 0:
|
||
atrs_hist.append(a)
|
||
if len(atrs_hist) < 10:
|
||
continue
|
||
atr_pct = sum(1 for a in atrs_hist if a <= atr) / len(atrs_hist)
|
||
|
||
# Recent range (last ws bars)
|
||
recent = prices[max(0, idx - ws):idx]
|
||
recent_range = (np.max(recent) - np.min(recent)) / np.mean(recent) if len(recent) > 1 else 0
|
||
|
||
# Recent returns volatility
|
||
if len(recent) > 2:
|
||
returns = np.diff(recent) / recent[:-1]
|
||
ret_vol = float(np.std(returns))
|
||
else:
|
||
ret_vol = 0
|
||
|
||
model_preds.append(r["pred_amp_atr"])
|
||
atr_preds.append(atr)
|
||
atr_pct_preds.append(atr_pct)
|
||
range_preds.append(recent_range)
|
||
vol_preds.append(ret_vol)
|
||
actuals.append(r["actual_amp_atr"])
|
||
|
||
model_a = np.array(model_preds)
|
||
atr_a = np.array(atr_preds)
|
||
atr_pct_a = np.array(atr_pct_preds)
|
||
range_a = np.array(range_preds)
|
||
vol_a = np.array(vol_preds)
|
||
actual_a = np.array(actuals)
|
||
|
||
# Correlations with actual amplitude
|
||
r_model = _corr(model_a, actual_a)
|
||
r_atr = _corr(atr_a, actual_a)
|
||
r_atr_pct = _corr(atr_pct_a, actual_a)
|
||
r_range = _corr(range_a, actual_a)
|
||
r_vol = _corr(vol_a, actual_a)
|
||
|
||
# Q4/Q1 ratio for each predictor
|
||
def q4q1(pred, actual):
|
||
pcts = np.percentile(pred, [25, 75])
|
||
q1 = actual[pred <= pcts[0]]
|
||
q4 = actual[pred >= pcts[1]]
|
||
if len(q1) == 0 or np.mean(q1) == 0:
|
||
return 0
|
||
return float(np.mean(q4) / np.mean(q1))
|
||
|
||
# Combined: model + ATR percentile
|
||
combined = model_a * atr_pct_a
|
||
r_combined = _corr(combined, actual_a)
|
||
|
||
results = {
|
||
"predictors": [
|
||
{"name": "Remizov model", "r": round(r_model, 3),
|
||
"q4q1": round(q4q1(model_a, actual_a), 2)},
|
||
{"name": "Raw ATR", "r": round(r_atr, 3),
|
||
"q4q1": round(q4q1(atr_a, actual_a), 2)},
|
||
{"name": "ATR percentile", "r": round(r_atr_pct, 3),
|
||
"q4q1": round(q4q1(atr_pct_a, actual_a), 2)},
|
||
{"name": "Price range(ws)", "r": round(r_range, 3),
|
||
"q4q1": round(q4q1(range_a, actual_a), 2)},
|
||
{"name": "Returns vol", "r": round(r_vol, 3),
|
||
"q4q1": round(q4q1(vol_a, actual_a), 2)},
|
||
{"name": "Model×ATR_pct", "r": round(r_combined, 3),
|
||
"q4q1": round(q4q1(combined, actual_a), 2)},
|
||
],
|
||
"model_beats_all_simple": r_model > max(r_atr, r_atr_pct, r_range, r_vol),
|
||
"best_simple": max(
|
||
[("ATR", r_atr), ("ATR_pct", r_atr_pct),
|
||
("range", r_range), ("vol", r_vol)],
|
||
key=lambda x: x[1]),
|
||
"n": len(model_preds),
|
||
}
|
||
return results
|
||
|
||
|
||
def main():
|
||
results_dir = Path(__file__).parent / "results"
|
||
print("=" * 80)
|
||
print("EXP26g: DEEP ANALYSIS OF REMIZOV FORMULA EDGE")
|
||
print("=" * 80)
|
||
print("Tests: 1.OOS Stability 2.Random Weights 3.Simpler Alternatives\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}")
|
||
|
||
# ── TEST 1: Stability ──
|
||
print(f"\n ── TEST 1: OOS STABILITY ──")
|
||
t1 = test_stability(prices, ws, K)
|
||
if t1:
|
||
print(f" Overall r: {t1['r_overall']}")
|
||
for q in t1["quarters"]:
|
||
marker = " ✓" if q["r"] > 0.05 else (" ✗" if q["r"] < -0.05 else "")
|
||
print(f" {q['quarter']}: r={q['r']:+.3f} (N={q['n']}){marker}")
|
||
print(f" Rolling: mean={t1['rolling_mean']:+.3f} ± {t1['rolling_std']:.3f} "
|
||
f"[{t1['rolling_min']:+.3f}, {t1['rolling_max']:+.3f}]")
|
||
print(f" % windows with r>0: {t1['pct_positive']:.0f}%")
|
||
|
||
# ── TEST 2: Random Weights ──
|
||
print(f"\n ── TEST 2: RANDOM WEIGHTS vs TRAINED ──")
|
||
t2 = test_random_weights(prices, ws, K)
|
||
if t2:
|
||
print(f" Trained (200 ep): r={t2['r_trained']:+.3f}")
|
||
print(f" Partial (50 ep): r={t2['r_partial_50ep']:+.3f}")
|
||
print(f" Untrained (seed=42): r={t2['r_untrained']:+.3f}")
|
||
print(f" Random seeds (10x): r={t2['random_seeds_mean']:+.3f} "
|
||
f"± {t2['random_seeds_std']:.3f} "
|
||
f"(max={t2['random_seeds_max']:+.3f})")
|
||
verdict = "YES" if t2["training_adds_value"] else "NO"
|
||
print(f" → Training adds value: {verdict}")
|
||
|
||
# ── TEST 3: Simpler Alternatives ──
|
||
print(f"\n ── TEST 3: SIMPLER ALTERNATIVES ──")
|
||
t3 = test_simpler(prices, ws, K)
|
||
if t3:
|
||
print(f" {'Predictor':<20s} {'r':>6s} {'Q4/Q1':>6s}")
|
||
print(f" {'-' * 35}")
|
||
for p in t3["predictors"]:
|
||
best = " ← BEST" if p["r"] == max(x["r"] for x in t3["predictors"]) else ""
|
||
print(f" {p['name']:<20s} {p['r']:>+5.3f} {p['q4q1']:>5.2f}x{best}")
|
||
beats = "YES" if t3["model_beats_all_simple"] else "NO"
|
||
print(f" → Model beats all simple: {beats}")
|
||
print(f" Best simple: {t3['best_simple'][0]} (r={t3['best_simple'][1]:+.3f})")
|
||
|
||
result = {"ticker": ticker, "ws": ws, "K": K}
|
||
if t1:
|
||
result["stability"] = t1
|
||
if t2:
|
||
result["random_weights"] = t2
|
||
if t3:
|
||
result["simpler"] = t3
|
||
all_results.append(result)
|
||
|
||
# ── CROSS-ASSET SUMMARY ──
|
||
print(f"\n{'═' * 80}")
|
||
print("CROSS-ASSET SUMMARY")
|
||
print(f"{'═' * 80}")
|
||
|
||
print(f"\n STABILITY:")
|
||
print(f" {'Asset':<10s} {'r_all':>6s} {'Q1':>6s} {'Q2':>6s} {'Q3':>6s} {'Q4':>6s} "
|
||
f"{'%pos':>5s} {'roll_std':>8s}")
|
||
print(f" {'-' * 55}")
|
||
for r in all_results:
|
||
if "stability" not in r:
|
||
continue
|
||
s = r["stability"]
|
||
qs = [q["r"] for q in s["quarters"]]
|
||
print(f" {r['ticker']:<10s} {s['r_overall']:>+5.3f} "
|
||
f"{qs[0]:>+5.3f} {qs[1]:>+5.3f} {qs[2]:>+5.3f} {qs[3]:>+5.3f} "
|
||
f"{s['pct_positive']:>4.0f}% {s['rolling_std']:>7.3f}")
|
||
|
||
print(f"\n RANDOM WEIGHTS:")
|
||
print(f" {'Asset':<10s} {'Trained':>8s} {'Untrained':>10s} {'Rnd mean':>9s} "
|
||
f"{'Rnd max':>8s} {'Adds value':>11s}")
|
||
print(f" {'-' * 60}")
|
||
for r in all_results:
|
||
if "random_weights" not in r:
|
||
continue
|
||
w = r["random_weights"]
|
||
print(f" {r['ticker']:<10s} {w['r_trained']:>+7.3f} "
|
||
f"{w['r_untrained']:>+9.3f} {w['random_seeds_mean']:>+8.3f} "
|
||
f"{w['random_seeds_max']:>+7.3f} "
|
||
f"{'YES' if w['training_adds_value'] else 'NO':>11s}")
|
||
|
||
print(f"\n SIMPLER ALTERNATIVES:")
|
||
print(f" {'Asset':<10s} {'Model':>6s} {'ATR':>6s} {'ATR%':>6s} {'Range':>6s} "
|
||
f"{'RetVol':>6s} {'M×ATR%':>7s} {'Beats':>6s}")
|
||
print(f" {'-' * 55}")
|
||
for r in all_results:
|
||
if "simpler" not in r:
|
||
continue
|
||
p = {x["name"]: x["r"] for x in r["simpler"]["predictors"]}
|
||
print(f" {r['ticker']:<10s} "
|
||
f"{p.get('Remizov model', 0):>+5.3f} "
|
||
f"{p.get('Raw ATR', 0):>+5.3f} "
|
||
f"{p.get('ATR percentile', 0):>+5.3f} "
|
||
f"{p.get('Price range(ws)', 0):>+5.3f} "
|
||
f"{p.get('Returns vol', 0):>+5.3f} "
|
||
f"{p.get('Model×ATR_pct', 0):>+6.3f} "
|
||
f"{'YES' if r['simpler']['model_beats_all_simple'] else 'NO':>6s}")
|
||
|
||
path = save_results({"results": all_results}, results_dir, "exp26g_deep")
|
||
print(f"\nSaved: {path}")
|
||
|
||
|
||
if __name__ == "__main__":
|
||
main()
|