- tests/test_core.py: 50 тестов (risk, state, reconciliation) - tests/test_executor.py: 21 тест (SHORT skip, cooldown, CB, reconcile, update_stops, balance sync) - backtest_prod.py: LONG_ONLY=True по умолчанию (шорты на споте невозможны), NEAR cd=3 Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
308 lines
11 KiB
Python
308 lines
11 KiB
Python
"""Walk-forward backtest with exact production config parameters.
|
|
|
|
Tests UNI, ATOM, NEAR with per-asset params from config.yaml.
|
|
"""
|
|
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
|
|
|
|
RISK_CFG = RiskConfig(
|
|
per_trade=0.05, max_position_pct=0.40,
|
|
max_open_positions=3, leverage=1,
|
|
)
|
|
|
|
INITIAL_CAPITAL = 254.0 # actual prod capital
|
|
TRAILING_STOP = True
|
|
TRAIN_RATIO = 0.3
|
|
LONG_ONLY = True # spot mode: can't short
|
|
|
|
# Per-asset configs from production config.yaml
|
|
ASSETS = [
|
|
{
|
|
"symbol": "UNI/USDC", "ticker": "UNI-USD",
|
|
"window_size": 64, "K": 2, "shift": 14,
|
|
"epochs": 300, "lr": 0.005,
|
|
"stop_mult": 1.25, "stop_scale": 0.75,
|
|
"cooldown_bars": 3, "shape_confirm": False,
|
|
"corr_thresh": 0.5, "weight": 0.34,
|
|
},
|
|
{
|
|
"symbol": "ATOM/USDC", "ticker": "ATOM-USD",
|
|
"window_size": 64, "K": 3, "shift": 14,
|
|
"epochs": 300, "lr": 0.005,
|
|
"stop_mult": 0.75, "stop_scale": 1.0,
|
|
"cooldown_bars": 3, "shape_confirm": False,
|
|
"corr_thresh": 0.5, "weight": 0.33,
|
|
},
|
|
{
|
|
"symbol": "NEAR/USDC", "ticker": "NEAR-USD",
|
|
"window_size": 64, "K": 2, "shift": 16,
|
|
"epochs": 300, "lr": 0.01,
|
|
"stop_mult": 1.0, "stop_scale": 1.0,
|
|
"cooldown_bars": 3, # updated from WF results (was -1)
|
|
"shape_confirm": False,
|
|
"corr_thresh": 0.5, "weight": 0.33,
|
|
},
|
|
]
|
|
|
|
|
|
def run_backtest(asset: dict, prices: np.ndarray):
|
|
"""Walk-forward backtest with exact prod params."""
|
|
ws = asset["window_size"]
|
|
shift = asset["shift"]
|
|
K = asset["K"]
|
|
corr_thresh = asset["corr_thresh"]
|
|
shape_confirm = asset["shape_confirm"]
|
|
stop_mult_base = asset["stop_mult"]
|
|
stop_scale = asset["stop_scale"]
|
|
cooldown_bars = asset["cooldown_bars"]
|
|
if cooldown_bars == -1:
|
|
cooldown_bars = shift
|
|
|
|
model_cfg = ModelConfig(
|
|
window_size=ws, n_steps=20, total_time=0.5,
|
|
shift=shift, epochs=asset["epochs"],
|
|
finetune_epochs=50, lr=asset["lr"],
|
|
)
|
|
|
|
data = signals.prepare_windows(prices, ws, shift)
|
|
if len(data) < 30:
|
|
print(f" Not enough windows: {len(data)}")
|
|
return None
|
|
|
|
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")
|
|
|
|
# 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])
|
|
loss = model_mod.train(mdl, windows, targets, model_cfg.epochs, model_cfg.lr)
|
|
print(f" Train loss: {loss:.6f}")
|
|
|
|
# Simulate
|
|
capital = INITIAL_CAPITAL * asset["weight"]
|
|
equity = capital
|
|
trades = []
|
|
position = None
|
|
equity_curve = [equity]
|
|
cooldown_until = 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
|
|
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
|
|
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"],
|
|
"entry_idx": p["entry_bar"],
|
|
})
|
|
position = None
|
|
if stopped:
|
|
cooldown_until = price_idx + cooldown_bars
|
|
|
|
# New signal
|
|
if position is None and price_idx >= ws + K and price_idx >= cooldown_until:
|
|
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 (prod: disabled for all 3 assets)
|
|
if shape_confirm:
|
|
corr, confirmed = signals.check_shape_confirmation(
|
|
pred_new, confirm, mu, std, K, corr_thresh,
|
|
)
|
|
else:
|
|
confirmed = True
|
|
|
|
if confirmed:
|
|
direction = signals.get_direction(pred_new, K)
|
|
if direction is not None and not (LONG_ONLY and direction == -1):
|
|
entry_price = current_price
|
|
atr = risk.compute_atr(prices, price_idx)
|
|
stop_dist = max(atr * stop_mult_base * stop_scale,
|
|
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,
|
|
"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({
|
|
"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"],
|
|
"entry_idx": position["entry_bar"],
|
|
})
|
|
equity_curve.append(equity)
|
|
|
|
if not trades:
|
|
print(" No trades!")
|
|
return None
|
|
|
|
# Metrics
|
|
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 = equity - capital
|
|
total_ret = total_pnl / capital * 100
|
|
|
|
first_bar = test_data[0]["price_idx"]
|
|
last_bar = test_data[-1]["price_idx"]
|
|
n_bars = last_bar - first_bar
|
|
years = n_bars / (365.25 * 6)
|
|
|
|
# Sharpe
|
|
if len(pnls) > 1 and years > 0:
|
|
n_days = max(n_bars // 6, 1)
|
|
daily_pnl = np.zeros(n_days)
|
|
for t in trades:
|
|
day = min((t.get("entry_idx", first_bar) - first_bar) // 6, n_days - 1)
|
|
daily_pnl[day] += t["pnl_net"]
|
|
daily_ret = daily_pnl / 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 DD
|
|
eq = np.array(equity_curve)
|
|
peak = np.maximum.accumulate(eq)
|
|
dd = (peak - eq) / peak
|
|
max_dd = dd.max() * 100
|
|
|
|
months = years * 12
|
|
|
|
return {
|
|
"ticker": asset["ticker"],
|
|
"trades": len(trades), "wins": len(wins), "losses": len(losses),
|
|
"wr": len(wins) / len(trades) * 100,
|
|
"total_pnl": total_pnl, "total_ret": total_ret,
|
|
"sharpe": sharpe, "max_dd": max_dd,
|
|
"monthly_pnl": total_pnl / months if months > 0 else 0,
|
|
"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,
|
|
"capital": capital,
|
|
}
|
|
|
|
|
|
def main():
|
|
results = []
|
|
for asset in ASSETS:
|
|
print(f"\n--- {asset['symbol']} ({asset['ticker']}) ---")
|
|
print(f" Params: K={asset['K']} shift={asset['shift']} "
|
|
f"stop_mult={asset['stop_mult']} stop_scale={asset['stop_scale']} "
|
|
f"cooldown={asset['cooldown_bars']} lr={asset['lr']}")
|
|
print(f" Fetching 4H data...")
|
|
prices, dates = signals.fetch_prices_ccxt(asset["symbol"], "4h", "max")
|
|
if prices is None:
|
|
print(f" No data")
|
|
continue
|
|
print(f" Got {len(prices)} bars")
|
|
|
|
r = run_backtest(asset, prices)
|
|
if r:
|
|
results.append(r)
|
|
print(f"\n{'='*60}")
|
|
print(f" {r['ticker']} — PROD PARAMS BACKTEST")
|
|
print(f"{'='*60}")
|
|
print(f" Period: ~{r['months']:.1f} months | Capital: ${r['capital']:.0f}")
|
|
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 win: ${r['avg_win']:+,.2f} | Avg loss: ${r['avg_loss']:+,.2f}")
|
|
print(f"{'='*60}")
|
|
|
|
if results:
|
|
total_pnl = sum(r["total_pnl"] for r in results)
|
|
total_cap = sum(r["capital"] for r in results)
|
|
print(f"\n\n{'='*60}")
|
|
mode_str = "LONG ONLY" if LONG_ONLY else "LONG+SHORT"
|
|
print(f" PORTFOLIO — PROD PARAMS ({mode_str}) | ${INITIAL_CAPITAL:.0f} capital")
|
|
print(f"{'='*60}")
|
|
print(f" {'Asset':<12s} {'Sharpe':>8s} {'Return':>10s} {'PnL':>10s} {'Trades':>7s} {'WR':>6s} {'MaxDD':>7s}")
|
|
print(f" {'-'*60}")
|
|
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['total_pnl']:>+9.2f} {r['trades']:>7d} {r['wr']:>5.1f}% {r['max_dd']:>6.1f}%")
|
|
print(f" {'TOTAL':<12s} {'':>8s} {total_pnl/total_cap*100:>+9.1f}% "
|
|
f"${total_pnl:>+9.2f}")
|
|
|
|
|
|
if __name__ == "__main__":
|
|
main()
|