Files
remizov-trader/experiments/exp12_leverage/run.py
T
anorandClaude Opus 4.6 ee6b633c23 feat: включить 2x плечо + exp12 leverage backtest
Exp12: протестировано 1x/2x/3x/5x на 7 боевых парах.
2x оптимален: PnL ×3-4, DD ~14% (< CB 20%).
Sharpe стабилен при любом плече.

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-03-09 19:53:15 +10:00

238 lines
8.6 KiB
Python

"""Exp12: Leverage impact on current production assets.
Tests leverage 1x, 2x, 3x, 5x on all 7 production pairs
with their actual timeframes (ETH/SOL 2H, rest 4H).
"""
import copy
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
MODEL_CFG = ModelConfig(
window_size=64, n_steps=20, total_time=0.5,
shift=7, epochs=200, finetune_epochs=50, lr=0.003,
)
K = 2
CORR_THRESH = 0.5
INITIAL_CAPITAL = 10_000.0
TRAILING_STOP = True
TRAIN_RATIO = 0.3
LEVERAGES = [1, 2, 3, 5]
# Production assets with their timeframes
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, leverage, tf="4h"):
"""Backtest with specified leverage."""
risk_cfg = RiskConfig(per_trade=0.05, max_position_pct=0.40,
max_open_positions=1, leverage=leverage)
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,
"leverage": leverage,
"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 per asset
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 leverage in LEVERAGES:
print(f"\n{'='*60}")
print(f"LEVERAGE: {leverage}x")
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, leverage, 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["final_equity"] = r["final_equity"]
m["leverage"] = leverage
key = f"{ticker}_{leverage}x"
all_results[key] = m
print(f" {ticker}: Sharpe={m['sharpe']:.2f} PnL=${m['total_pnl']:+,.0f} "
f"DD={m['max_drawdown']:.1f}% WR={m['wr']:.0f}%")
except Exception as e:
print(f" {ticker}: ERROR: {e}")
traceback.print_exc()
# Summary table
print(f"\n{'='*80}")
print("EXP12 SUMMARY — Leverage Impact on Production Assets")
print(f"{'='*80}")
print(f" {'Asset':<10s} {'TF':>3s} | {'1x Sharpe':>9s} {'2x':>9s} {'3x':>9s} {'5x':>9s} | "
f"{'1x DD%':>7s} {'2x':>7s} {'3x':>7s} {'5x':>7s}")
print(f" {'-'*76}")
for symbol, ticker, tf in ASSETS:
sharpes = []
dds = []
for lev in LEVERAGES:
key = f"{ticker}_{lev}x"
m = all_results.get(key, {})
sharpes.append(f"{m.get('sharpe', 0):>9.2f}" if m else f"{'N/A':>9s}")
dds.append(f"{m.get('max_drawdown', 0):>6.1f}%" if m else f"{'N/A':>7s}")
print(f" {ticker:<10s} {tf:>3s} | {' '.join(sharpes)} | {' '.join(dds)}")
# PnL table
print(f"\n {'Asset':<10s} {'TF':>3s} | {'1x PnL':>12s} {'2x':>12s} {'3x':>12s} {'5x':>12s}")
print(f" {'-'*60}")
for symbol, ticker, tf in ASSETS:
pnls = []
for lev in LEVERAGES:
key = f"{ticker}_{lev}x"
m = all_results.get(key, {})
pnls.append(f"${m.get('total_pnl', 0):>+10,.0f}" if m else f"{'N/A':>12s}")
print(f" {ticker:<10s} {tf:>3s} | {' '.join(pnls)}")
# Save
path = save_results(all_results, results_dir, "exp12_leverage")
print(f"\nSaved: {path}")
if __name__ == "__main__":
main()