Files
remizov-trader/experiments/exp26_ablation/window_sweep.py
T
anorandClaude Opus 4.6 b87402edaa feat: exp26e — window size sweep для amplitude prediction
60 конфигов (5 активов × 6 ws × 2 K).
BTC: ws=64 K=3 → r=0.229 (8x лучше текущего ws=32).
ADA ws=48 K=3: лучший conf_PnL +1.028% per trade.
ws≥96 даёт высокий r но 0 прод-сигналов.

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

289 lines
9.8 KiB
Python
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
"""Exp26e: Window size sweep for amplitude prediction across all assets.
Tests whether different window sizes improve amplitude prediction (r correlation)
for assets that showed weak results with default windows.
Previous results (default windows):
BTC ws=32: r=0.029 (weak)
ETH ws=64: r=0.054 (weak)
ADA ws=64: r=0.164 (significant)
DOGE ws=48: r=0.077 (weak)
SOL ws=128: r=0.166 (flat pred)
"""
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
ASSETS = ["BTC-USD", "ETH-USD", "ADA-USD", "DOGE-USD", "SOL-USD"]
WINDOW_SIZES = [16, 32, 48, 64, 96, 128]
K_VALUES = [2, 3]
SHIFT = 7
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 _sim_trail(prices, idx, direction, stop_dist):
entry = prices[idx]
best = entry
stop = entry - direction * stop_dist
mfe = 0.0
for i in range(1, LOOKAHEAD + 1):
if idx + i >= len(prices):
break
p = prices[idx + i]
move = (p - entry) / entry * direction
mfe = max(mfe, move)
best, stop = risk.update_trailing_stop(p, best, stop, stop_dist, direction)
if risk.is_stopped(p, stop, direction):
pnl = (p - entry) / entry * direction
return pnl, mfe
last = prices[min(idx + LOOKAHEAD, len(prices) - 1)]
return (last - entry) / entry * direction, mfe
def _analyze(prices, ws, K):
mdl, data, n_train = _train_model(prices, ws)
test_data = data[n_train:]
pred_amps = []
actual_amps = []
actual_ranges = []
pnls = []
mfes = []
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
pred_amp_atr = pred_amp / atr
# Actual amplitude
future_end = min(idx + SHIFT - K, len(prices))
actual_future = prices[idx:future_end]
if len(actual_future) < 2:
continue
actual_amp = float(np.max(actual_future) - np.min(actual_future))
actual_amp_atr = actual_amp / atr
# Actual range (LOOKAHEAD)
lookahead_prices = prices[idx:min(idx + LOOKAHEAD, len(prices))]
actual_range = float(np.max(lookahead_prices) - np.min(lookahead_prices))
actual_range_atr = actual_range / atr
# Trailing stop PnL
stop_dist = max(atr * STOP_MULT * STOP_SCALE, prices[idx] * 0.005)
pnl, mfe = _sim_trail(prices, idx, pred_dir, stop_dist)
pred_amps.append(pred_amp_atr)
actual_amps.append(actual_amp_atr)
actual_ranges.append(actual_range_atr)
pnls.append(pnl * 100)
mfes.append(mfe * 100)
if len(pred_amps) < 10:
return None
pred_a = np.array(pred_amps)
actual_a = np.array(actual_amps)
actual_r = np.array(actual_ranges)
pnl_a = np.array(pnls)
mfe_a = np.array(mfes)
with np.errstate(invalid="ignore"):
corr_amp = np.corrcoef(pred_a, actual_a)[0, 1]
corr_range = np.corrcoef(pred_a, actual_r)[0, 1]
if np.isnan(corr_amp):
corr_amp = 0
if np.isnan(corr_range):
corr_range = 0
# Q4/Q1 ratio
pcts = np.percentile(pred_a, [25, 75])
q1 = actual_a[pred_a <= pcts[0]]
q4 = actual_a[pred_a >= pcts[1]]
q4_q1 = float(np.mean(q4) / np.mean(q1)) if len(q1) > 0 and np.mean(q1) > 0 else 0
# Conf >= 1.5 stats
confirm_data = []
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)
if confidence >= 1.5 and confirmed:
stop_dist = max(atr * STOP_MULT * STOP_SCALE, prices[idx] * 0.005)
pnl, mfe = _sim_trail(prices, idx, pred_dir, stop_dist)
confirm_data.append(pnl * 100)
conf_pnl = float(np.mean(confirm_data)) if confirm_data else 0
conf_n = len(confirm_data)
return {
"n": len(pred_amps),
"corr_amp": round(float(corr_amp), 3),
"corr_range": round(float(corr_range), 3),
"q4_q1": round(q4_q1, 2),
"avg_pnl": round(float(np.mean(pnl_a)), 3),
"avg_mfe": round(float(np.mean(mfe_a)), 3),
"wr": round(float(np.sum(pnl_a > 0) / len(pnl_a) * 100), 1),
"pred_amp_mean": round(float(np.mean(pred_a)), 2),
"conf_pnl": round(conf_pnl, 3),
"conf_n": conf_n,
}
def main():
results_dir = Path(__file__).parent / "results"
print("=" * 80)
print("EXP26e: WINDOW SIZE SWEEP — AMPLITUDE PREDICTION")
print("=" * 80)
print(f"Windows: {WINDOW_SIZES}, K: {K_VALUES}, shift={SHIFT}")
print(f"Trailing stop: ATR×{STOP_MULT}×{STOP_SCALE}, lookahead={LOOKAHEAD}\n")
dataset = load_or_fetch("default")
all_results = []
for ticker in ASSETS:
if ticker not in dataset:
print(f" {ticker}: not in dataset, skip")
continue
prices = dataset[ticker]["prices"]
print(f"\n{'═' * 80}")
print(f" {ticker} ({len(prices)} prices)")
print(f"{'═' * 80}")
print(f" {'ws':>4s} {'K':>2s} {'N':>5s} {'Amp r':>6s} {'Rng r':>6s} "
f"{'Q4/Q1':>6s} {'PnL%':>7s} {'MFE%':>7s} {'WR%':>5s} "
f"{'PredAmp':>8s} {'ConfPnL':>8s} {'ConfN':>5s}")
print(f" {'-' * 75}")
best_r = -1
best_cfg = ""
for ws in WINDOW_SIZES:
for K in K_VALUES:
print(f" ws={ws:3d} K={K} ... ", end="", flush=True)
try:
r = _analyze(prices, ws, K)
except Exception as e:
print(f"ERROR: {e}")
continue
if r is None:
print("too few signals")
continue
print(f"N={r['n']:4d} r={r['corr_amp']:+.3f} "
f"Q4/Q1={r['q4_q1']:.2f}x "
f"PnL={r['avg_pnl']:+.3f}% "
f"conf_PnL={r['conf_pnl']:+.3f}% (N={r['conf_n']})")
r["ticker"] = ticker
r["ws"] = ws
r["K"] = K
all_results.append(r)
if r["corr_amp"] > best_r:
best_r = r["corr_amp"]
best_cfg = f"ws={ws}, K={K}"
if best_cfg:
print(f"\n BEST: {best_cfg} → r={best_r:.3f}")
# Cross-asset best configs
print(f"\n{'═' * 80}")
print("BEST CONFIG PER ASSET (by amplitude correlation)")
print(f"{'═' * 80}")
print(f" {'Asset':<10s} {'ws':>4s} {'K':>2s} {'Amp r':>6s} {'Q4/Q1':>6s} "
f"{'PnL%':>7s} {'ConfPnL':>8s} {'ConfN':>5s}")
print(f" {'-' * 55}")
best_per_asset = {}
for ticker in ASSETS:
asset_results = [r for r in all_results if r["ticker"] == ticker]
if not asset_results:
continue
best = max(asset_results, key=lambda x: x["corr_amp"])
best_per_asset[ticker] = best
print(f" {ticker:<10s} {best['ws']:>4d} {best['K']:>2d} "
f"{best['corr_amp']:>+5.3f} {best['q4_q1']:>5.2f}x "
f"{best['avg_pnl']:>+6.3f}% {best['conf_pnl']:>+7.3f}% "
f"{best['conf_n']:>5d}")
# Also show best by PnL with conf filter
print(f"\nBEST CONFIG PER ASSET (by conf-filtered PnL)")
print(f" {'-' * 55}")
for ticker in ASSETS:
asset_results = [r for r in all_results
if r["ticker"] == ticker and r["conf_n"] > 5]
if not asset_results:
continue
best = max(asset_results, key=lambda x: x["conf_pnl"])
print(f" {ticker:<10s} ws={best['ws']:>3d} K={best['K']} "
f"r={best['corr_amp']:+.3f} Q4/Q1={best['q4_q1']:.2f}x "
f"conf_PnL={best['conf_pnl']:+.3f}% (N={best['conf_n']})")
path = save_results({"results": all_results, "best_per_asset": best_per_asset},
results_dir, "exp26e_window_sweep")
print(f"\nSaved: {path}")
if __name__ == "__main__":
main()