fix: Sharpe ratio — daily returns вместо trade count + memory leak fix
Sharpe считался через sqrt(trades_per_year), что завышало метрику в ~2x. Исправлено на daily returns + sqrt(252) во всех бэктест скриптах. Утечка памяти: добавлен del tensors в model.train() и evaluate.py. Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
This commit is contained in:
+293
@@ -0,0 +1,293 @@
|
||||
"""Walk-forward backtest for RemizovNet on 4H timeframe.
|
||||
|
||||
Tests ETH-USD and BTC-USD with the same parameters as live config.
|
||||
"""
|
||||
import sys
|
||||
sys.path.insert(0, "src")
|
||||
|
||||
import numpy as np
|
||||
import torch
|
||||
|
||||
from remizov_trader.core import model as model_mod, signals, risk
|
||||
from remizov_trader.config import ModelConfig, RiskConfig
|
||||
|
||||
# Config
|
||||
MODEL_CFG = ModelConfig(
|
||||
window_size=64, n_steps=20, total_time=0.5,
|
||||
shift=7, epochs=200, finetune_epochs=50, lr=0.003,
|
||||
)
|
||||
RISK_CFG = RiskConfig(
|
||||
per_trade=0.05, max_position_pct=0.25,
|
||||
max_open_positions=1, leverage=1,
|
||||
)
|
||||
|
||||
K = 2
|
||||
CORR_THRESH = 0.5
|
||||
INITIAL_CAPITAL = 10_000.0
|
||||
TRAILING_STOP = True
|
||||
TRAIN_RATIO = 0.3 # train on first 30%, test on rest
|
||||
|
||||
|
||||
def run_backtest(ticker: str, prices: np.ndarray, dates: list):
|
||||
"""Walk-forward backtest."""
|
||||
ws = MODEL_CFG.window_size
|
||||
shift = MODEL_CFG.shift
|
||||
|
||||
# Prepare all windows
|
||||
data = signals.prepare_windows(prices, ws, shift)
|
||||
if len(data) < 30:
|
||||
print(f" Not enough windows: {len(data)}")
|
||||
return None
|
||||
|
||||
# Train/test split
|
||||
n_train = max(int(len(data) * TRAIN_RATIO), 20)
|
||||
train_data = data[:n_train]
|
||||
test_data = data[n_train:]
|
||||
|
||||
print(f" Windows: {len(data)} total, {n_train} train, {len(test_data)} test")
|
||||
print(f" Price range: {prices.min():.2f} - {prices.max():.2f}")
|
||||
|
||||
# Train model
|
||||
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])
|
||||
loss = model_mod.train(mdl, windows, targets, MODEL_CFG.epochs, MODEL_CFG.lr)
|
||||
print(f" Train loss: {loss:.6f}")
|
||||
|
||||
# Simulate trading on test data
|
||||
equity = INITIAL_CAPITAL
|
||||
peak_equity = equity
|
||||
trades = []
|
||||
position = None # {direction, entry_price, stop_price, stop_dist, best_price, pos_size, pos_value, entry_idx, k_used}
|
||||
equity_curve = [equity]
|
||||
|
||||
for i, d in enumerate(test_data):
|
||||
price_idx = d["price_idx"]
|
||||
current_price = float(prices[price_idx])
|
||||
|
||||
# Check open position
|
||||
if position is not None:
|
||||
p = position
|
||||
last_price = current_price
|
||||
|
||||
# Trailing stop
|
||||
if TRAILING_STOP:
|
||||
p["best_price"], p["stop_price"] = risk.update_trailing_stop(
|
||||
last_price, p["best_price"], p["stop_price"],
|
||||
p["stop_dist"], p["direction"],
|
||||
)
|
||||
|
||||
stopped = risk.is_stopped(last_price, p["stop_price"], p["direction"])
|
||||
bars_held = price_idx - p["entry_bar"]
|
||||
max_hold = shift - p["k_used"]
|
||||
time_exit = bars_held >= max_hold
|
||||
|
||||
if stopped or time_exit:
|
||||
exit_price = p["stop_price"] if stopped else last_price
|
||||
reason = "stop" if stopped else "time"
|
||||
pnl_net, pnl_pct = 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)
|
||||
trades.append({
|
||||
"direction": p["direction"],
|
||||
"entry_price": p["entry_price"],
|
||||
"exit_price": exit_price,
|
||||
"pnl_net": pnl_net,
|
||||
"pnl_pct": pnl_pct,
|
||||
"reason": reason,
|
||||
"equity_at_entry": p["equity_at_entry"],
|
||||
})
|
||||
position = None
|
||||
|
||||
# New signal (if no position)
|
||||
if position is None and price_idx >= ws + K:
|
||||
# Get signal window
|
||||
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:
|
||||
equity_curve.append(equity)
|
||||
continue
|
||||
norm_input = (w - mu) / std
|
||||
|
||||
pred = model_mod.predict(mdl, norm_input)
|
||||
pred_new = pred[-shift:]
|
||||
|
||||
# Shape confirmation
|
||||
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:
|
||||
entry_price = current_price
|
||||
|
||||
# Regime adaptive
|
||||
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, entry_price * 0.005)
|
||||
stop_price = entry_price - direction * stop_dist
|
||||
|
||||
pos_size, pos_value = risk.calculate_position(
|
||||
equity, entry_price, stop_dist, RISK_CFG,
|
||||
)
|
||||
|
||||
position = {
|
||||
"direction": direction,
|
||||
"entry_price": entry_price,
|
||||
"stop_price": stop_price,
|
||||
"stop_dist": stop_dist,
|
||||
"best_price": entry_price,
|
||||
"pos_size": pos_size,
|
||||
"pos_value": pos_value,
|
||||
"entry_bar": price_idx,
|
||||
"k_used": k_adj,
|
||||
"equity_at_entry": equity,
|
||||
}
|
||||
|
||||
equity_curve.append(equity)
|
||||
|
||||
# Close any remaining position at last price
|
||||
if position is not None:
|
||||
last_price = float(prices[-1])
|
||||
pnl_net, pnl_pct = risk.calculate_pnl(
|
||||
position["entry_price"], last_price, position["direction"],
|
||||
position["pos_size"], position["pos_value"],
|
||||
)
|
||||
equity += pnl_net
|
||||
trades.append({
|
||||
"direction": position["direction"],
|
||||
"entry_price": position["entry_price"],
|
||||
"exit_price": last_price,
|
||||
"pnl_net": pnl_net,
|
||||
"pnl_pct": pnl_pct,
|
||||
"reason": "end",
|
||||
"equity_at_entry": position["equity_at_entry"],
|
||||
})
|
||||
equity_curve.append(equity)
|
||||
|
||||
# Calculate metrics
|
||||
if not trades:
|
||||
print(" No trades!")
|
||||
return None
|
||||
|
||||
pnls = [t["pnl_net"] for t in trades]
|
||||
wins = [t for t in trades if t["pnl_net"] > 0]
|
||||
losses = [t for t in trades if t["pnl_net"] <= 0]
|
||||
wr = len(wins) / len(trades) * 100
|
||||
|
||||
total_pnl = equity - INITIAL_CAPITAL
|
||||
total_ret = total_pnl / INITIAL_CAPITAL * 100
|
||||
|
||||
# Actual test period in bars (not windows)
|
||||
first_bar = test_data[0]["price_idx"]
|
||||
last_bar = test_data[-1]["price_idx"]
|
||||
n_bars_actual = last_bar - first_bar
|
||||
# 4h bars: 6 per day, ~2190 per year
|
||||
bars_per_year = 365.25 * 6
|
||||
years = n_bars_actual / bars_per_year
|
||||
|
||||
# Sharpe ratio (daily returns, proper annualization)
|
||||
if len(pnls) > 1 and years > 0:
|
||||
n_days = max(n_bars_actual // 6, 1)
|
||||
daily_pnl = np.zeros(n_days)
|
||||
for t in trades:
|
||||
day = min((t.get("bar", t.get("entry_idx", first_bar)) - first_bar) // 6, n_days - 1)
|
||||
daily_pnl[day] += t["pnl_net"]
|
||||
daily_ret = daily_pnl / INITIAL_CAPITAL
|
||||
sharpe = float(np.mean(daily_ret) / np.std(daily_ret) * np.sqrt(252)) if np.std(daily_ret) > 0 else 0
|
||||
else:
|
||||
sharpe = 0
|
||||
|
||||
# Max drawdown
|
||||
eq = np.array(equity_curve)
|
||||
peak = np.maximum.accumulate(eq)
|
||||
dd = (peak - eq) / peak
|
||||
max_dd = dd.max() * 100
|
||||
|
||||
# Monthly PnL
|
||||
months = years * 12
|
||||
monthly_pnl = total_pnl / months if months > 0 else 0
|
||||
|
||||
result = {
|
||||
"ticker": ticker,
|
||||
"trades": len(trades),
|
||||
"wins": len(wins),
|
||||
"losses": len(losses),
|
||||
"wr": wr,
|
||||
"total_pnl": total_pnl,
|
||||
"total_ret": total_ret,
|
||||
"sharpe": sharpe,
|
||||
"max_dd": max_dd,
|
||||
"monthly_pnl": monthly_pnl,
|
||||
"months": months,
|
||||
"avg_pnl": np.mean(pnls),
|
||||
"avg_win": np.mean([t["pnl_net"] for t in wins]) if wins else 0,
|
||||
"avg_loss": np.mean([t["pnl_net"] for t in losses]) if losses else 0,
|
||||
}
|
||||
|
||||
return result
|
||||
|
||||
|
||||
def print_result(r):
|
||||
if r is None:
|
||||
return
|
||||
print(f"\n{'='*60}")
|
||||
print(f" {r['ticker']} — 4H BACKTEST")
|
||||
print(f"{'='*60}")
|
||||
print(f" Period: ~{r['months']:.1f} months")
|
||||
print(f" Trades: {r['trades']} (W:{r['wins']} L:{r['losses']} WR:{r['wr']:.1f}%)")
|
||||
print(f" Total PnL: ${r['total_pnl']:+,.2f} ({r['total_ret']:+.1f}%)")
|
||||
print(f" Sharpe: {r['sharpe']:.2f}")
|
||||
print(f" Max DD: {r['max_dd']:.1f}%")
|
||||
print(f" Monthly: ${r['monthly_pnl']:+,.2f}/mo")
|
||||
print(f" Avg trade: ${r['avg_pnl']:+,.2f}")
|
||||
print(f" Avg win: ${r['avg_win']:+,.2f} | Avg loss: ${r['avg_loss']:+,.2f}")
|
||||
print(f"{'='*60}")
|
||||
|
||||
|
||||
def main():
|
||||
# Bybit USDC pairs with native 4h candles
|
||||
assets = [
|
||||
("ETH/USDC", "ETH-USD"),
|
||||
("BTC/USDC", "BTC-USD"),
|
||||
("SOL/USDC", "SOL-USD"),
|
||||
]
|
||||
results = []
|
||||
|
||||
for symbol, ticker in assets:
|
||||
print(f"\n--- {symbol} ---")
|
||||
print(f" Fetching 4H data from Bybit...")
|
||||
prices, dates = signals.fetch_prices_ccxt(symbol, "4h", "max")
|
||||
if prices is None:
|
||||
print(f" No data for {symbol}")
|
||||
continue
|
||||
prices_4h = prices
|
||||
dates_4h = dates
|
||||
print(f" Got {len(prices_4h)} 4h bars")
|
||||
|
||||
r = run_backtest(symbol, prices_4h, dates_4h)
|
||||
if r:
|
||||
results.append(r)
|
||||
print_result(r)
|
||||
|
||||
if results:
|
||||
print(f"\n\n{'='*60}")
|
||||
print(f" SUMMARY — 4H BACKTEST")
|
||||
print(f"{'='*60}")
|
||||
print(f" {'Asset':<12s} {'Sharpe':>8s} {'Return':>10s} {'Trades':>8s} {'WR':>6s} {'MaxDD':>8s}")
|
||||
print(f" {'-'*52}")
|
||||
for r in sorted(results, key=lambda x: x["sharpe"], reverse=True):
|
||||
print(f" {r['ticker']:<12s} {r['sharpe']:>8.2f} {r['total_ret']:>+9.1f}% "
|
||||
f"{r['trades']:>8d} {r['wr']:>5.1f}% {r['max_dd']:>7.1f}%")
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
Reference in New Issue
Block a user