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>
470 lines
18 KiB
Python
470 lines
18 KiB
Python
"""Exp26g v2: Deep analysis — fixed bugs from v1.
|
|
|
|
Bugs fixed:
|
|
1. Random weights were identical (zeros init, seed doesn't matter)
|
|
→ Now uses Xavier/Kaiming random init
|
|
2. Simpler alternatives compared against normalized target (actual/ATR)
|
|
while using raw ATR as predictor → spurious negative correlation
|
|
→ Now uses raw actual_amp for fair comparison
|
|
3. Added Gaussian blur baseline (what untrained net actually does)
|
|
"""
|
|
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
|
|
import torch.nn as nn
|
|
|
|
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):
|
|
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 _randomize_weights(mdl, seed):
|
|
"""Actually randomize model weights (not zeros!)."""
|
|
torch.manual_seed(seed)
|
|
for name, param in mdl.named_parameters():
|
|
if param.dim() >= 2:
|
|
nn.init.xavier_normal_(param)
|
|
else:
|
|
nn.init.normal_(param, mean=0, std=0.5)
|
|
|
|
|
|
def _get_amplitude_data(prices, mdl, data, n_train, ws, K):
|
|
"""Get pred_amp and actual_amp (both raw and normalized)."""
|
|
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": pred_amp,
|
|
"pred_amp_atr": pred_amp / atr,
|
|
"actual_amp": actual_amp,
|
|
"actual_amp_atr": actual_amp / atr,
|
|
"atr": atr,
|
|
"std": std,
|
|
})
|
|
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)
|
|
|
|
|
|
def _gaussian_blur_amplitude(prices, idx, ws, K):
|
|
"""What the untrained network does: Gaussian blur of input window."""
|
|
w = prices[idx - ws - K: idx - K].copy()
|
|
mu, std = w.mean(), w.std()
|
|
if std < 1e-10:
|
|
return None
|
|
norm = (w - mu) / std
|
|
# Gaussian blur with sigma proportional to sqrt(total_time * a_init)
|
|
# a_init = softplus(0) = ln(2) ≈ 0.693
|
|
# sigma^2 = 4 * tau * a * (pi*k)^2 summed over 20 steps
|
|
# Effective: just apply Gaussian filter
|
|
from scipy.ndimage import gaussian_filter1d
|
|
# Total diffusion time: n_steps * tau * a = 20 * 0.025 * 0.693 ≈ 0.347
|
|
# sigma in grid units: sqrt(2 * 0.347) / dx ≈ sqrt(0.694) * ws ≈ 0.83 * ws
|
|
# But this is in Fourier space, effective sigma ≈ sqrt(total_time * a) / dx
|
|
sigma_grid = np.sqrt(0.5 * 0.693) * 2 # empirical approximation
|
|
blurred = gaussian_filter1d(norm, sigma=sigma_grid)
|
|
blurred_denorm = blurred[-SHIFT:] * std + mu
|
|
amp = float(np.max(blurred_denorm) - np.min(blurred_denorm))
|
|
return amp
|
|
|
|
|
|
# ═══════════════════════════════════════════════════════════════
|
|
# TEST 1: OOS STABILITY (same as v1 — no bug)
|
|
# ═══════════════════════════════════════════════════════════════
|
|
def test_stability(prices, ws, K):
|
|
mdl, data, n_train = _train_model(prices, ws)
|
|
rows = _get_amplitude_data(prices, mdl, data, n_train, ws, K)
|
|
if len(rows) < 40:
|
|
return {}
|
|
|
|
n = len(rows)
|
|
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)})
|
|
|
|
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])
|
|
rolling.append(_corr(pred_a, actual_a))
|
|
|
|
return {
|
|
"quarters": quarters,
|
|
"rolling_mean": round(float(np.mean(rolling)), 3),
|
|
"rolling_std": round(float(np.std(rolling)), 3),
|
|
"pct_positive": round(float(np.mean(np.array(rolling) > 0) * 100), 1),
|
|
}
|
|
|
|
|
|
# ═══════════════════════════════════════════════════════════════
|
|
# TEST 2: RANDOM WEIGHTS — Fixed: actual random init
|
|
# ═══════════════════════════════════════════════════════════════
|
|
def test_random_weights(prices, ws, K):
|
|
# Trained model
|
|
mdl_trained, data, n_train = _train_model(prices, ws)
|
|
rows_trained = _get_amplitude_data(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 (zeros init — what v1 tested)
|
|
torch.manual_seed(42)
|
|
mdl_zeros = EnhancedRemizovNet(grid_size=ws, n_steps=20, total_time=0.5,
|
|
dx=1.0 / ws, use_sde=True)
|
|
rows_zeros = _get_amplitude_data(prices, mdl_zeros, data, n_train, ws, K)
|
|
r_zeros = _corr(
|
|
np.array([r["pred_amp_atr"] for r in rows_zeros]),
|
|
np.array([r["actual_amp_atr"] for r in rows_zeros])
|
|
) if rows_zeros else 0
|
|
|
|
# Actually random weights (10 seeds with Xavier init)
|
|
random_rs = []
|
|
for seed in range(10):
|
|
mdl_rnd = EnhancedRemizovNet(grid_size=ws, n_steps=20, total_time=0.5,
|
|
dx=1.0 / ws, use_sde=True)
|
|
_randomize_weights(mdl_rnd, seed * 7 + 13)
|
|
rows_rnd = _get_amplitude_data(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))
|
|
|
|
# Gaussian blur baseline
|
|
blur_amps = []
|
|
actual_for_blur = []
|
|
for d in data[n_train:]:
|
|
idx = d["price_idx"]
|
|
if idx + LOOKAHEAD >= len(prices) or idx < ws + K + 1:
|
|
continue
|
|
atr = risk.compute_atr(prices, idx)
|
|
if atr <= 0:
|
|
continue
|
|
ba = _gaussian_blur_amplitude(prices, idx, ws, K)
|
|
if ba is None:
|
|
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))
|
|
blur_amps.append(ba / atr)
|
|
actual_for_blur.append(actual_amp / atr)
|
|
r_blur = _corr(np.array(blur_amps), np.array(actual_for_blur)) if blur_amps else 0
|
|
|
|
return {
|
|
"r_trained": round(r_trained, 3),
|
|
"r_zeros_init": round(r_zeros, 3),
|
|
"r_blur": round(r_blur, 3),
|
|
"r_random_mean": round(float(np.mean(random_rs)), 3) if random_rs else 0,
|
|
"r_random_std": round(float(np.std(random_rs)), 3) if random_rs else 0,
|
|
"r_random_min": round(float(np.min(random_rs)), 3) if random_rs else 0,
|
|
"r_random_max": round(float(np.max(random_rs)), 3) if random_rs else 0,
|
|
"training_vs_zeros": round(r_trained - r_zeros, 3),
|
|
"training_vs_random": round(r_trained - float(np.mean(random_rs)), 3) if random_rs else 0,
|
|
}
|
|
|
|
|
|
# ═══════════════════════════════════════════════════════════════
|
|
# TEST 3: SIMPLER ALTERNATIVES — Fixed: fair comparison
|
|
# ═══════════════════════════════════════════════════════════════
|
|
def test_simpler(prices, ws, K):
|
|
mdl, data, n_train = _train_model(prices, ws)
|
|
rows = _get_amplitude_data(prices, mdl, data, n_train, ws, K)
|
|
if len(rows) < 40:
|
|
return {}
|
|
|
|
model_preds_raw = [] # pred_amp (raw $)
|
|
model_preds_norm = [] # pred_amp / ATR
|
|
atr_vals = []
|
|
atr_pct_vals = []
|
|
range_vals = []
|
|
vol_vals = []
|
|
input_amp_vals = [] # amplitude of input window (simplest baseline!)
|
|
actual_raw = [] # actual_amp (raw $)
|
|
actual_norm = [] # actual_amp / ATR
|
|
|
|
for r in rows:
|
|
idx = r["idx"]
|
|
# ATR percentile
|
|
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 <= r["atr"]) / len(atrs_hist)
|
|
|
|
# Price range of input window
|
|
win = prices[max(0, idx - ws):idx]
|
|
price_range = float(np.max(win) - np.min(win)) if len(win) > 1 else 0
|
|
|
|
# Returns volatility
|
|
if len(win) > 2:
|
|
returns = np.diff(win) / win[:-1]
|
|
ret_vol = float(np.std(returns))
|
|
else:
|
|
ret_vol = 0
|
|
|
|
# Input window amplitude (simplest: just measure how "jumpy" input was)
|
|
input_amp = float(np.max(win[-SHIFT:]) - np.min(win[-SHIFT:])) if len(win) >= SHIFT else 0
|
|
|
|
model_preds_raw.append(r["pred_amp"])
|
|
model_preds_norm.append(r["pred_amp_atr"])
|
|
atr_vals.append(r["atr"])
|
|
atr_pct_vals.append(atr_pct)
|
|
range_vals.append(price_range)
|
|
vol_vals.append(ret_vol)
|
|
input_amp_vals.append(input_amp)
|
|
actual_raw.append(r["actual_amp"])
|
|
actual_norm.append(r["actual_amp_atr"])
|
|
|
|
# Convert to arrays
|
|
model_raw = np.array(model_preds_raw)
|
|
model_norm = np.array(model_preds_norm)
|
|
atr_a = np.array(atr_vals)
|
|
atr_pct_a = np.array(atr_pct_vals)
|
|
range_a = np.array(range_vals)
|
|
vol_a = np.array(vol_vals)
|
|
input_amp_a = np.array(input_amp_vals)
|
|
act_raw = np.array(actual_raw)
|
|
act_norm = np.array(actual_norm)
|
|
|
|
# FAIR COMPARISON: use raw actual_amp as target
|
|
# Normalize each predictor to same scale (doesn't affect correlation)
|
|
results_raw = {
|
|
"target": "actual_amp (raw $)",
|
|
"predictors": [
|
|
{"name": "Remizov pred_amp", "r": round(_corr(model_raw, act_raw), 3)},
|
|
{"name": "ATR (raw)", "r": round(_corr(atr_a, act_raw), 3)},
|
|
{"name": "ATR percentile", "r": round(_corr(atr_pct_a, act_raw), 3)},
|
|
{"name": "Price range(ws)", "r": round(_corr(range_a, act_raw), 3)},
|
|
{"name": "Returns vol", "r": round(_corr(vol_a, act_raw), 3)},
|
|
{"name": "Input amp(shift)", "r": round(_corr(input_amp_a, act_raw), 3)},
|
|
],
|
|
}
|
|
|
|
# ALSO: normalized comparison (actual_amp/ATR as target, all predictors /ATR)
|
|
# Model is already /ATR; normalize others too
|
|
range_norm = range_a / atr_a
|
|
vol_norm = vol_a / atr_a
|
|
input_amp_norm = input_amp_a / atr_a
|
|
|
|
results_norm = {
|
|
"target": "actual_amp / ATR (normalized)",
|
|
"predictors": [
|
|
{"name": "Remizov pred/ATR", "r": round(_corr(model_norm, act_norm), 3)},
|
|
{"name": "ATR percentile", "r": round(_corr(atr_pct_a, act_norm), 3)},
|
|
{"name": "Range/ATR", "r": round(_corr(range_norm, act_norm), 3)},
|
|
{"name": "RetVol/ATR", "r": round(_corr(vol_norm, act_norm), 3)},
|
|
{"name": "InputAmp/ATR", "r": round(_corr(input_amp_norm, act_norm), 3)},
|
|
],
|
|
}
|
|
|
|
# Best predictor
|
|
all_preds = results_raw["predictors"] + results_norm["predictors"]
|
|
best = max(all_preds, key=lambda x: x["r"])
|
|
|
|
return {
|
|
"raw_target": results_raw,
|
|
"norm_target": results_norm,
|
|
"best_overall": best,
|
|
"n": len(model_raw),
|
|
}
|
|
|
|
|
|
def main():
|
|
results_dir = Path(__file__).parent / "results"
|
|
print("=" * 80)
|
|
print("EXP26g v2: DEEP ANALYSIS — FIXED BUGS")
|
|
print("=" * 80)
|
|
print("Fixes: 1.Random init 2.Fair predictor comparison 3.Blur baseline\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:
|
|
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}")
|
|
print(f" % windows r>0: {t1['pct_positive']:.0f}%")
|
|
|
|
# ── TEST 2: Random Weights ──
|
|
print(f"\n ── TEST 2: TRAINED vs ZEROS vs RANDOM WEIGHTS ──")
|
|
t2 = test_random_weights(prices, ws, K)
|
|
if t2:
|
|
print(f" Trained (200 ep): r={t2['r_trained']:+.3f}")
|
|
print(f" Zeros init (default): r={t2['r_zeros_init']:+.3f}")
|
|
print(f" Gaussian blur: r={t2['r_blur']:+.3f}")
|
|
print(f" Random Xavier (10x): r={t2['r_random_mean']:+.3f} "
|
|
f"± {t2['r_random_std']:.3f} "
|
|
f"[{t2['r_random_min']:+.3f}, {t2['r_random_max']:+.3f}]")
|
|
print(f" Training Δ vs zeros: {t2['training_vs_zeros']:+.3f}")
|
|
print(f" Training Δ vs random: {t2['training_vs_random']:+.3f}")
|
|
if t2['training_vs_zeros'] > 0.02:
|
|
print(f" → Training HELPS (+{t2['training_vs_zeros']:.3f})")
|
|
elif t2['training_vs_zeros'] < -0.02:
|
|
print(f" → Training HURTS ({t2['training_vs_zeros']:+.3f})")
|
|
else:
|
|
print(f" → Training has NO EFFECT")
|
|
|
|
# ── TEST 3: Simpler Alternatives ──
|
|
print(f"\n ── TEST 3: SIMPLER ALTERNATIVES (fair comparison) ──")
|
|
t3 = test_simpler(prices, ws, K)
|
|
if t3:
|
|
print(f" RAW target (actual_amp in $):")
|
|
for p in t3["raw_target"]["predictors"]:
|
|
print(f" {p['name']:<22s} r={p['r']:+.3f}")
|
|
|
|
print(f" NORMALIZED target (actual_amp / ATR):")
|
|
for p in t3["norm_target"]["predictors"]:
|
|
print(f" {p['name']:<22s} r={p['r']:+.3f}")
|
|
|
|
print(f" Best overall: {t3['best_overall']['name']} "
|
|
f"(r={t3['best_overall']['r']:+.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 (% rolling windows with r>0):")
|
|
for r in all_results:
|
|
if "stability" in r:
|
|
s = r["stability"]
|
|
qs = " ".join(f"{q['r']:+.3f}" for q in s["quarters"])
|
|
print(f" {r['ticker']:<10s} Q1-4: {qs} | {s['pct_positive']:.0f}% positive")
|
|
|
|
print(f"\n RANDOM WEIGHTS (does training help?):")
|
|
print(f" {'Asset':<10s} {'Trained':>8s} {'Zeros':>7s} {'Blur':>7s} "
|
|
f"{'Rnd±std':>12s} {'Δ train':>8s}")
|
|
print(f" {'-' * 55}")
|
|
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_zeros_init']:>+6.3f} {w['r_blur']:>+6.3f} "
|
|
f"{w['r_random_mean']:>+5.3f}±{w['r_random_std']:.3f} "
|
|
f"{w['training_vs_zeros']:>+7.3f}")
|
|
|
|
print(f"\n SIMPLER ALTERNATIVES (r with raw actual_amp):")
|
|
print(f" {'Asset':<10s} {'Model':>7s} {'ATR':>7s} {'ATR%':>7s} "
|
|
f"{'Range':>7s} {'RetVol':>7s} {'InAmp':>7s}")
|
|
print(f" {'-' * 50}")
|
|
for r in all_results:
|
|
if "simpler" not in r:
|
|
continue
|
|
p = {x["name"]: x["r"] for x in r["simpler"]["raw_target"]["predictors"]}
|
|
print(f" {r['ticker']:<10s} "
|
|
f"{p.get('Remizov pred_amp', 0):>+6.3f} "
|
|
f"{p.get('ATR (raw)', 0):>+6.3f} "
|
|
f"{p.get('ATR percentile', 0):>+6.3f} "
|
|
f"{p.get('Price range(ws)', 0):>+6.3f} "
|
|
f"{p.get('Returns vol', 0):>+6.3f} "
|
|
f"{p.get('Input amp(shift)', 0):>+6.3f}")
|
|
|
|
path = save_results({"results": all_results}, results_dir, "exp26g_deep_v2")
|
|
print(f"\nSaved: {path}")
|
|
|
|
|
|
if __name__ == "__main__":
|
|
main()
|