feat: exp13 window_size — оптимальные окна для всех пар

Результаты: 2H пары (ETH/SOL) лучше при ws=128,
BTC при ws=48, остальные оптимальны при ws=64.
ETH ws=128 2x: Sharpe 3.59, DD 8.2% — лучший risk-adjusted.

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
This commit is contained in:
anor
2026-03-09 22:06:18 +10:00
co-authored by Claude Opus 4.6
parent 5fe877913b
commit efb6efe824
3 changed files with 950 additions and 0 deletions
+326
View File
@@ -0,0 +1,326 @@
"""Exp13: Window size impact on signal quality.
Tests window_size = 32, 48, 64, 96, 128 on production pairs.
Start with ETH (2H) and DOGE (4H) as representatives.
"""
import json
import sys
import traceback
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.config import ModelConfig, RiskConfig
from common.metrics import compute_metrics, save_results, print_metrics
RISK_CFG = RiskConfig(per_trade=0.05, max_position_pct=0.40,
max_open_positions=1, leverage=1)
K = 2
CORR_THRESH = 0.5
INITIAL_CAPITAL = 10_000.0
TRAILING_STOP = True
TRAIN_RATIO = 0.3
WINDOW_SIZES = [32, 48, 64, 96, 128]
ASSETS = [
("ETH/USDC", "ETH-USD", "2h"),
("SOL/USDC", "SOL-USD", "2h"),
("BTC/USDC", "BTC-USD", "4h"),
("DOGE/USDC", "DOGE-USD", "4h"),
("ADA/USDC", "ADA-USD", "4h"),
("XRP/USDC", "XRP-USD", "4h"),
("DOT/USDC", "DOT-USD", "4h"),
]
def run_backtest(ticker, prices, dates, window_size, tf="4h"):
"""Backtest with specified window size."""
model_cfg = ModelConfig(
window_size=window_size, n_steps=20, total_time=0.5,
shift=7, epochs=200, finetune_epochs=50, lr=0.003,
)
ws = model_cfg.window_size
shift = model_cfg.shift
data = signals.prepare_windows(prices, ws, shift)
if len(data) < 30:
return None
n_train = max(int(len(data) * TRAIN_RATIO), 20)
train_data = data[:n_train]
test_data = data[n_train:]
torch.manual_seed(42)
np.random.seed(42)
mdl = model_mod.create_model(model_cfg)
windows = np.array([d["norm_input"] for d in train_data])
targets = np.array([d["norm_target"] for d in train_data])
model_mod.train(mdl, windows, targets, model_cfg.epochs, model_cfg.lr)
equity = INITIAL_CAPITAL
peak_equity = INITIAL_CAPITAL
max_drawdown = 0.0
trades = []
position = None
for d in test_data:
price_idx = d["price_idx"]
current_price = float(prices[price_idx])
if position is not None:
p = position
if TRAILING_STOP:
p["best_price"], p["stop_price"] = risk.update_trailing_stop(
current_price, p["best_price"], p["stop_price"],
p["stop_dist"], p["direction"])
stopped = risk.is_stopped(current_price, p["stop_price"], p["direction"])
bars_held = price_idx - p["entry_bar"]
if stopped or bars_held >= (shift - p["k_used"]):
exit_price = p["stop_price"] if stopped else current_price
pnl_net, _ = risk.calculate_pnl(
p["entry_price"], exit_price, p["direction"],
p["pos_size"], p["pos_value"])
equity += pnl_net
peak_equity = max(peak_equity, equity)
dd = (peak_equity - equity) / peak_equity if peak_equity > 0 else 0
max_drawdown = max(max_drawdown, dd)
trades.append({"pnl_net": pnl_net, "equity_at_entry": p["equity_at_entry"]})
position = None
if position is None and price_idx >= ws + K:
w = prices[price_idx - ws - K:price_idx - K].copy()
confirm = prices[price_idx - K:price_idx].copy()
mu, std = w.mean(), w.std()
if std < 1e-10:
continue
norm_input = (w - mu) / std
pred = model_mod.predict(mdl, norm_input)
pred_new = pred[-shift:]
corr, confirmed = signals.check_shape_confirmation(
pred_new, confirm, mu, std, K, CORR_THRESH)
if confirmed:
direction = signals.get_direction(pred_new, K)
if direction is not None:
k_adj, stop_mult = risk.regime_adaptive_params(prices, price_idx, K)
atr = risk.compute_atr(prices, price_idx)
stop_dist = max(atr * stop_mult, current_price * 0.005)
pos_size, pos_value = risk.calculate_position(
equity, current_price, stop_dist, RISK_CFG)
position = {
"direction": direction, "entry_price": current_price,
"stop_price": current_price - direction * stop_dist,
"stop_dist": stop_dist, "best_price": current_price,
"pos_size": pos_size, "pos_value": pos_value,
"entry_bar": price_idx, "k_used": k_adj,
"equity_at_entry": equity,
}
if position:
last_price = float(prices[-1])
pnl_net, _ = risk.calculate_pnl(
position["entry_price"], last_price, position["direction"],
position["pos_size"], position["pos_value"])
equity += pnl_net
peak_equity = max(peak_equity, equity)
dd = (peak_equity - equity) / peak_equity if peak_equity > 0 else 0
max_drawdown = max(max_drawdown, dd)
trades.append({"pnl_net": pnl_net, "equity_at_entry": position["equity_at_entry"]})
first_bar = test_data[0]["price_idx"]
last_bar = test_data[-1]["price_idx"]
tf_hours = {"1h": 1, "2h": 2, "4h": 4, "6h": 6, "12h": 12, "1d": 24}
bars_per_day = 24 / tf_hours.get(tf, 4)
years = (last_bar - first_bar) / (365.25 * bars_per_day)
return {
"ticker": ticker,
"window_size": window_size,
"trades": trades,
"years": years,
"max_drawdown": round(max_drawdown * 100, 1),
"final_equity": round(equity, 2),
}
def main():
results_dir = Path(__file__).parent / "results"
all_results = {}
# Fetch data once
price_cache = {}
for symbol, ticker, tf in ASSETS:
print(f"Fetching {ticker} ({tf})...", end=" ", flush=True)
try:
prices, dates = signals.fetch_prices_ccxt(symbol, tf, "max")
if prices is not None:
price_cache[ticker] = (prices, dates, tf)
print(f"{len(prices)} bars")
else:
print("SKIP: no data")
except Exception as e:
print(f"ERROR: {e}")
# Run backtests
for ws in WINDOW_SIZES:
print(f"\n{'='*60}")
print(f"WINDOW SIZE: {ws}")
print(f"{'='*60}")
for symbol, ticker, tf in ASSETS:
if ticker not in price_cache:
continue
prices, dates, _ = price_cache[ticker]
try:
r = run_backtest(ticker, prices, dates, ws, tf)
if not r or not r["trades"]:
print(f" {ticker}: no trades")
continue
m = compute_metrics(r["trades"], INITIAL_CAPITAL, r["years"])
m["max_drawdown"] = r["max_drawdown"]
m["window_size"] = ws
m["years"] = round(r["years"], 2)
key = f"{ticker}_ws{ws}"
all_results[key] = m
print(f" {ticker}: Sharpe={m['sharpe']:.2f} PnL=${m['total_pnl']:+,.0f} "
f"WR={m['wr']:.0f}% trades={m['trades']} DD={m['max_drawdown']:.1f}%")
except Exception as e:
print(f" {ticker}: ERROR: {e}")
traceback.print_exc()
# Summary table
print(f"\n{'='*70}")
print("EXP13 SUMMARY — Window Size Impact")
print(f"{'='*70}")
print(f" {'Asset':<10s} {'TF':>3s} | {'ws=32':>8s} {'ws=48':>8s} {'ws=64':>8s} {'ws=96':>8s} {'ws=128':>8s}")
print(f" {'-'*55}")
for label, metric in [("Sharpe", "sharpe"), ("WR%", "wr"),
("Trades", "trades"), ("DD%", "max_drawdown")]:
print(f"\n {label}:")
for symbol, ticker, tf in ASSETS:
vals = []
for ws in WINDOW_SIZES:
key = f"{ticker}_ws{ws}"
m = all_results.get(key, {})
v = m.get(metric, 0)
if metric == "sharpe":
vals.append(f"{v:>8.2f}")
elif metric == "wr":
vals.append(f"{v:>7.1f}%")
elif metric == "trades":
vals.append(f"{v:>8d}")
elif metric == "max_drawdown":
vals.append(f"{v:>7.1f}%")
print(f" {ticker:<10s} {tf:>3s} | {' '.join(vals)}")
# Best window per asset
print(f"\n{'='*90}")
print("BEST WINDOW PER ASSET")
print(f"{'='*90}")
print(f" {'Asset':<10s} {'TF':>3s} | {'Best WS':>7s} {'Sharpe':>8s} {'WR%':>7s} "
f"{'Trades':>7s} {'PnL':>12s} {'Ret%':>8s} {'DD%':>7s} "
f"{'Mo.PnL':>10s} {'Mo.Ret%':>8s}")
print(f" {'-'*85}")
for symbol, ticker, tf in ASSETS:
best_ws = None
best_sharpe = -999
for ws in WINDOW_SIZES:
key = f"{ticker}_ws{ws}"
m = all_results.get(key, {})
if m.get("sharpe", 0) > best_sharpe:
best_sharpe = m["sharpe"]
best_ws = ws
if best_ws is None:
continue
key = f"{ticker}_ws{best_ws}"
m = all_results[key]
# Monthly profit: total_pnl / (years * 12)
years = 0
for ws_check in WINDOW_SIZES:
k2 = f"{ticker}_ws{ws_check}"
if k2 in all_results and "years" in all_results[k2]:
years = all_results[k2]["years"]
break
# Fallback: estimate from trades count
if years == 0:
tf_hours = {"1h": 1, "2h": 2, "4h": 4, "6h": 6, "12h": 12, "1d": 24}
bars_per_day = 24 / tf_hours.get(tf, 4)
years = m["trades"] * 7 / (365.25 * bars_per_day) # rough
months = years * 12
monthly_pnl = m["total_pnl"] / months if months > 0 else 0
monthly_ret = m["total_ret"] / months if months > 0 else 0
cur_ws_key = f"{ticker}_ws64"
cur_sharpe = all_results.get(cur_ws_key, {}).get("sharpe", 0)
delta = f" ({best_sharpe - cur_sharpe:+.2f} vs 64)" if best_ws != 64 else " (current)"
print(f" {ticker:<10s} {tf:>3s} | {best_ws:>5d} {m['sharpe']:>7.2f} {m['wr']:>6.1f}% "
f"{m['trades']:>7d} ${m['total_pnl']:>+10,.0f} {m['total_ret']:>+7.1f}% "
f"{m['max_drawdown']:>6.1f}% "
f"${monthly_pnl:>+8,.0f} {monthly_ret:>+7.2f}%"
f"{delta}")
# Full ranking table
print(f"\n{'='*100}")
print("FULL RANKING (all asset×window combinations, sorted by Sharpe)")
print(f"{'='*100}")
print(f" {'#':>3s} {'Asset':<10s} {'TF':>3s} {'WS':>4s} | {'Sharpe':>7s} {'WR%':>7s} "
f"{'Trades':>7s} {'PnL':>12s} {'Ret%':>8s} {'DD%':>7s} "
f"{'Mo.PnL':>10s} {'Mo.Ret%':>8s}")
print(f" {'-'*90}")
# Collect all with years info
ranking = []
for symbol, ticker, tf in ASSETS:
for ws in WINDOW_SIZES:
key = f"{ticker}_ws{ws}"
m = all_results.get(key)
if not m:
continue
tf_hours = {"1h": 1, "2h": 2, "4h": 4, "6h": 6, "12h": 12, "1d": 24}
bars_per_day = 24 / tf_hours.get(tf, 4)
# Get years from run result
years = m.get("years", 0)
if years == 0:
years = m["trades"] * 7 / (365.25 * bars_per_day)
months = years * 12
monthly_pnl = m["total_pnl"] / months if months > 0 else 0
monthly_ret = m["total_ret"] / months if months > 0 else 0
ranking.append({
"ticker": ticker, "tf": tf, "ws": ws,
"sharpe": m["sharpe"], "wr": m["wr"], "trades": m["trades"],
"total_pnl": m["total_pnl"], "total_ret": m["total_ret"],
"max_drawdown": m["max_drawdown"],
"monthly_pnl": monthly_pnl, "monthly_ret": monthly_ret,
})
ranking.sort(key=lambda x: x["sharpe"], reverse=True)
for i, r in enumerate(ranking, 1):
marker = " ◄" if r["ws"] == 64 else ""
print(f" {i:>3d} {r['ticker']:<10s} {r['tf']:>3s} {r['ws']:>4d} | "
f"{r['sharpe']:>7.2f} {r['wr']:>6.1f}% {r['trades']:>7d} "
f"${r['total_pnl']:>+10,.0f} {r['total_ret']:>+7.1f}% "
f"{r['max_drawdown']:>6.1f}% "
f"${r['monthly_pnl']:>+8,.0f} {r['monthly_ret']:>+7.2f}%{marker}")
# Save
path = save_results(all_results, results_dir, "exp13_window_size")
print(f"\nSaved: {path}")
if __name__ == "__main__":
main()