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>
382 lines
13 KiB
Python
382 lines
13 KiB
Python
"""Portfolio backtest: 3 assets × 33% each, event-driven retrain.
|
||
|
||
Tests ETH/USDC + SOL/USDC + BTC/USDC simultaneously.
|
||
"""
|
||
import copy
|
||
import json
|
||
import sys
|
||
from datetime import datetime
|
||
from pathlib import Path
|
||
|
||
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
|
||
|
||
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
|
||
TRAILING_STOP = True
|
||
TRAIN_RATIO = 0.3
|
||
TOTAL_CAPITAL = 10_000.0
|
||
|
||
|
||
def get_atr_regime(prices, idx):
|
||
atr14 = risk.compute_atr(prices, idx, period=14)
|
||
atr50 = risk.compute_atr(prices, idx, period=50)
|
||
ratio = atr14 / atr50 if atr50 > 0 else 1.0
|
||
if ratio < 0.7:
|
||
return "low"
|
||
if ratio > 1.5:
|
||
return "high"
|
||
return "normal"
|
||
|
||
|
||
def should_retrain(consecutive_losses, current_regime, last_regime):
|
||
if consecutive_losses >= 3:
|
||
return True
|
||
if last_regime and current_regime != last_regime:
|
||
return True
|
||
return False
|
||
|
||
|
||
def do_finetune(model, all_data, price_idx, cfg):
|
||
train_windows = [d for d in all_data if d["price_idx"] <= price_idx]
|
||
if len(train_windows) < 20:
|
||
return model
|
||
recent = train_windows[-200:]
|
||
windows = np.array([d["norm_input"] for d in recent])
|
||
targets = np.array([d["norm_target"] for d in recent])
|
||
new_model = copy.deepcopy(model)
|
||
model_mod.train(new_model, windows, targets, 20, cfg.lr * 0.3)
|
||
return new_model
|
||
|
||
|
||
def run_single_asset(symbol, prices, all_data, test_data, initial_model,
|
||
asset_capital, risk_cfg):
|
||
"""Run backtest for single asset. Returns trades list and final equity."""
|
||
ws = MODEL_CFG.window_size
|
||
shift = MODEL_CFG.shift
|
||
mdl = copy.deepcopy(initial_model)
|
||
|
||
equity = asset_capital
|
||
trades = []
|
||
position = None
|
||
equity_curve = [equity]
|
||
consecutive_losses = 0
|
||
last_regime = None
|
||
retrains = 0
|
||
|
||
for i, d in enumerate(test_data):
|
||
price_idx = d["price_idx"]
|
||
current_price = float(prices[price_idx])
|
||
|
||
# Check position
|
||
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"]
|
||
time_exit = bars_held >= (shift - p["k_used"])
|
||
|
||
if stopped or time_exit:
|
||
exit_price = p["stop_price"] if stopped else current_price
|
||
pnl_net, pnl_pct = risk.calculate_pnl(
|
||
p["entry_price"], exit_price, p["direction"],
|
||
p["pos_size"], p["pos_value"],
|
||
)
|
||
equity += pnl_net
|
||
if pnl_net > 0:
|
||
consecutive_losses = 0
|
||
else:
|
||
consecutive_losses += 1
|
||
trades.append({
|
||
"pnl_net": pnl_net,
|
||
"equity_at_entry": p["equity_at_entry"],
|
||
"bar": price_idx,
|
||
})
|
||
position = None
|
||
|
||
# Retrain check
|
||
if position is None:
|
||
regime = get_atr_regime(prices, price_idx)
|
||
if should_retrain(consecutive_losses, regime, last_regime):
|
||
mdl = do_finetune(mdl, all_data, price_idx, MODEL_CFG)
|
||
retrains += 1
|
||
consecutive_losses = 0
|
||
last_regime = regime
|
||
|
||
# Signal
|
||
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:
|
||
equity_curve.append(equity)
|
||
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)
|
||
stop_price = current_price - direction * stop_dist
|
||
pos_size, pos_value = risk.calculate_position(
|
||
equity, current_price, stop_dist, risk_cfg,
|
||
)
|
||
position = {
|
||
"direction": direction,
|
||
"entry_price": current_price,
|
||
"stop_price": stop_price,
|
||
"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,
|
||
}
|
||
equity_curve.append(equity)
|
||
|
||
# Close remaining
|
||
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({
|
||
"pnl_net": pnl_net,
|
||
"equity_at_entry": position["equity_at_entry"],
|
||
"bar": len(prices) - 1,
|
||
})
|
||
equity_curve.append(equity)
|
||
|
||
return {
|
||
"equity": equity,
|
||
"trades": trades,
|
||
"equity_curve": equity_curve,
|
||
"retrains": retrains,
|
||
}
|
||
|
||
|
||
def compute_metrics(trades, initial_capital, years):
|
||
if not 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]
|
||
total_pnl = sum(pnls)
|
||
total_ret = total_pnl / initial_capital * 100
|
||
wr = len(wins) / len(trades) * 100
|
||
|
||
if len(pnls) > 1 and years > 0:
|
||
# Daily returns Sharpe (proper annualization)
|
||
bars_per_day = 6 # 4h bars
|
||
if trades[0].get("bar") is not None:
|
||
first_bar = min(t["bar"] for t in trades)
|
||
last_bar = max(t["bar"] for t in trades)
|
||
n_days = max((last_bar - first_bar) // bars_per_day, 1)
|
||
daily_pnl = np.zeros(n_days)
|
||
for t in trades:
|
||
day = min((t["bar"] - first_bar) // bars_per_day, 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
|
||
else:
|
||
sharpe = 0
|
||
|
||
months = years * 12
|
||
return {
|
||
"trades": len(trades),
|
||
"wins": len(wins),
|
||
"losses": len(losses),
|
||
"wr": wr,
|
||
"total_pnl": total_pnl,
|
||
"total_ret": total_ret,
|
||
"sharpe": sharpe,
|
||
"monthly_pnl": total_pnl / months if months > 0 else 0,
|
||
"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,
|
||
}
|
||
|
||
|
||
def main():
|
||
assets = [
|
||
("ETH/USDC", "ETH-USD"),
|
||
("SOL/USDC", "SOL-USD"),
|
||
("BTC/USDC", "BTC-USD"),
|
||
]
|
||
|
||
n_assets = len(assets)
|
||
per_asset_capital = TOTAL_CAPITAL / n_assets
|
||
risk_cfg = RiskConfig(
|
||
per_trade=0.05, max_position_pct=0.25,
|
||
max_open_positions=1, leverage=1,
|
||
)
|
||
|
||
print(f"Portfolio: ${TOTAL_CAPITAL:,.0f} / {n_assets} assets = ${per_asset_capital:,.0f} each")
|
||
print(f"Risk: {risk_cfg.per_trade*100:.0f}% per trade, {risk_cfg.max_position_pct*100:.0f}% max position")
|
||
print()
|
||
|
||
# Fetch all data
|
||
asset_data = {}
|
||
for symbol, ticker in assets:
|
||
print(f"Fetching {symbol}...", end="", flush=True)
|
||
prices, dates = signals.fetch_prices_ccxt(symbol, "4h", "max")
|
||
if prices is None:
|
||
print(" NO DATA")
|
||
continue
|
||
|
||
all_data = signals.prepare_windows(prices, MODEL_CFG.window_size, MODEL_CFG.shift)
|
||
n_train = max(int(len(all_data) * TRAIN_RATIO), 20)
|
||
train_data = all_data[:n_train]
|
||
test_data = all_data[n_train:]
|
||
|
||
# Train initial 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)
|
||
|
||
asset_data[symbol] = {
|
||
"ticker": ticker,
|
||
"prices": prices,
|
||
"all_data": all_data,
|
||
"test_data": test_data,
|
||
"model": mdl,
|
||
"n_bars": len(prices),
|
||
}
|
||
print(f" {len(prices)} bars, {len(test_data)} test windows, loss={loss:.4f}")
|
||
|
||
# Run individual backtests
|
||
print(f"\n{'='*70}")
|
||
print(f" INDIVIDUAL RESULTS (${per_asset_capital:,.0f} per asset, event-driven retrain)")
|
||
print(f"{'='*70}")
|
||
|
||
results = {}
|
||
all_trades = []
|
||
total_final_equity = 0
|
||
years = None
|
||
|
||
for symbol, ticker in assets:
|
||
if symbol not in asset_data:
|
||
continue
|
||
d = asset_data[symbol]
|
||
r = run_single_asset(
|
||
symbol, d["prices"], d["all_data"], d["test_data"],
|
||
d["model"], per_asset_capital, risk_cfg,
|
||
)
|
||
|
||
first_bar = d["test_data"][0]["price_idx"]
|
||
last_bar = d["test_data"][-1]["price_idx"]
|
||
y = (last_bar - first_bar) / (365.25 * 6)
|
||
if years is None:
|
||
years = y
|
||
|
||
m = compute_metrics(r["trades"], per_asset_capital, y)
|
||
if m is None:
|
||
continue
|
||
|
||
results[symbol] = {**m, "retrains": r["retrains"], "final_equity": r["equity"]}
|
||
all_trades.extend(r["trades"])
|
||
total_final_equity += r["equity"]
|
||
|
||
print(f"\n {symbol}:")
|
||
print(f" Sharpe: {m['sharpe']:.2f} | Return: {m['total_ret']:+.1f}% | "
|
||
f"Trades: {m['trades']} | WR: {m['wr']:.1f}%")
|
||
print(f" PnL: ${m['total_pnl']:+,.2f} | Monthly: ${m['monthly_pnl']:+,.0f}/mo | "
|
||
f"Retrains: {r['retrains']}")
|
||
|
||
# Portfolio summary
|
||
portfolio_pnl = total_final_equity - TOTAL_CAPITAL
|
||
portfolio_ret = portfolio_pnl / TOTAL_CAPITAL * 100
|
||
months = years * 12 if years else 1
|
||
portfolio_monthly = portfolio_pnl / months
|
||
|
||
# Portfolio Sharpe (from combined trades)
|
||
if len(all_trades) > 1 and years:
|
||
returns = np.array([t["pnl_net"] / t["equity_at_entry"] for t in all_trades])
|
||
tpy = len(all_trades) / years
|
||
portfolio_sharpe = (np.mean(returns) / np.std(returns) * np.sqrt(tpy)) if np.std(returns) > 0 else 0
|
||
else:
|
||
portfolio_sharpe = 0
|
||
|
||
wins = [t for t in all_trades if t["pnl_net"] > 0]
|
||
|
||
print(f"\n{'='*70}")
|
||
print(f" PORTFOLIO SUMMARY — 3 assets × 33%")
|
||
print(f"{'='*70}")
|
||
print(f" Period: {months:.1f} months ({years:.1f} years)")
|
||
print(f" Initial: ${TOTAL_CAPITAL:,.0f}")
|
||
print(f" Final: ${total_final_equity:,.2f}")
|
||
print(f" PnL: ${portfolio_pnl:+,.2f} ({portfolio_ret:+.1f}%)")
|
||
print(f" Monthly: ${portfolio_monthly:+,.0f}/mo")
|
||
print(f" Sharpe: {portfolio_sharpe:.2f}")
|
||
print(f" Trades: {len(all_trades)} (W:{len(wins)} L:{len(all_trades)-len(wins)} "
|
||
f"WR:{len(wins)/len(all_trades)*100:.1f}%)")
|
||
print(f"{'='*70}")
|
||
|
||
# Annualized
|
||
annual_ret = portfolio_ret / years if years else 0
|
||
annual_pnl = portfolio_pnl / years if years else 0
|
||
print(f"\n Annualized: ${annual_pnl:+,.0f}/year ({annual_ret:+.1f}%/year)")
|
||
|
||
# Per $114 capital (actual deposit)
|
||
scale = 114.0 / TOTAL_CAPITAL
|
||
print(f"\n На твой депозит $114:")
|
||
print(f" PnL за период: ${portfolio_pnl * scale:+,.2f}")
|
||
print(f" PnL в месяц: ${portfolio_monthly * scale:+,.2f}/mo")
|
||
print(f" PnL в год: ${annual_pnl * scale:+,.2f}/year")
|
||
|
||
# Save
|
||
log_dir = Path("data/backtest_logs")
|
||
log_dir.mkdir(parents=True, exist_ok=True)
|
||
ts = datetime.now().strftime("%Y%m%d_%H%M%S")
|
||
log_path = log_dir / f"portfolio_3assets_{ts}.json"
|
||
log_data = {
|
||
"timestamp": ts,
|
||
"total_capital": TOTAL_CAPITAL,
|
||
"per_asset_capital": per_asset_capital,
|
||
"assets": list(results.keys()),
|
||
"period_months": months,
|
||
"portfolio": {
|
||
"sharpe": portfolio_sharpe,
|
||
"total_pnl": portfolio_pnl,
|
||
"total_ret": portfolio_ret,
|
||
"monthly_pnl": portfolio_monthly,
|
||
"total_trades": len(all_trades),
|
||
"wr": len(wins) / len(all_trades) * 100,
|
||
},
|
||
"per_asset": {k: {kk: vv for kk, vv in v.items()}
|
||
for k, v in results.items()},
|
||
}
|
||
log_path.write_text(json.dumps(log_data, indent=2, default=str))
|
||
print(f"\n Results saved: {log_path}")
|
||
|
||
|
||
if __name__ == "__main__":
|
||
main()
|