Add trailing stops and parameter sweeps
Trailing stops: strategies can pass trailing_stop_pct to enter_long/enter_short. advance_trailing_stop in app/engine/portfolio.py ratchets the stop with the price (up for longs, down for shorts) and never loosens; the engine persists the ratcheted level and the backtester applies the same logic. Position gains a trailing_stop_pct column (additive migration). momentum exposes it as a param. Parameter sweeps: app/backtest/sweep.py runs a cartesian grid through the same backtester and ranks by return minus max drawdown. POST /api/sweep plus a dashboard Parameter sweep panel.
This commit is contained in:
1 parent
d80e7b155e
commit
9dc00eba95
22 files changed
+575
-7
No files matched your search
@@ -2,5 +2,14 @@ from __future__ import annotations
|
||||
|
||||
from app.backtest.backtester import Backtester
|
||||
from app.backtest.metrics import compute_metrics, max_drawdown_pct, sharpe_ratio
|
||||
from app.backtest.sweep import SweepRow, expand_grid, run_sweep
|
||||
|
||||
__all__ = ["Backtester", "compute_metrics", "max_drawdown_pct", "sharpe_ratio"]
|
||||
__all__ = [
|
||||
"Backtester",
|
||||
"SweepRow",
|
||||
"compute_metrics",
|
||||
"expand_grid",
|
||||
"max_drawdown_pct",
|
||||
"run_sweep",
|
||||
"sharpe_ratio",
|
||||
]
|
||||
@@ -7,6 +7,7 @@ from app.broker.paper import PaperBroker
|
||||
from app.engine.portfolio import (
|
||||
OpenPosition,
|
||||
account_equity,
|
||||
advance_trailing_stop,
|
||||
apply_close,
|
||||
apply_open,
|
||||
order_qty,
|
||||
@@ -91,6 +92,14 @@ class Backtester:
|
||||
for i, candle in enumerate(candles):
|
||||
mark = candle.close
|
||||
if position is not None:
|
||||
if position.trailing_stop_pct > 0:
|
||||
position.stop_loss = advance_trailing_stop(
|
||||
position.side,
|
||||
position.stop_loss,
|
||||
position.trailing_stop_pct,
|
||||
candle.high,
|
||||
candle.low,
|
||||
)
|
||||
hit = risk_exit(
|
||||
position.side,
|
||||
position.stop_loss,
|
||||
@@ -130,6 +139,7 @@ class Backtester:
|
||||
entry_fee=fill.fee,
|
||||
stop_loss=intent.stop_loss,
|
||||
take_profit=intent.take_profit,
|
||||
trailing_stop_pct=intent.trailing_stop_pct,
|
||||
entry_ts=candle.ts,
|
||||
)
|
||||
|
||||
|
||||
@@ -0,0 +1,60 @@
|
||||
from __future__ import annotations
|
||||
|
||||
import itertools
|
||||
from collections.abc import Sequence
|
||||
from dataclasses import dataclass
|
||||
from typing import Any
|
||||
|
||||
from app.backtest.backtester import Backtester
|
||||
from app.engine.strategies import get_strategy
|
||||
from app.engine.strategies.base import Strategy
|
||||
from app.schemas import Candle
|
||||
|
||||
|
||||
@dataclass(slots=True)
|
||||
class SweepRow:
|
||||
params: dict[str, Any]
|
||||
metrics: dict[str, Any]
|
||||
|
||||
|
||||
def expand_grid(grid: dict[str, Sequence[Any]]) -> list[dict[str, Any]]:
|
||||
"""Cartesian product of a param grid into a list of concrete param dicts."""
|
||||
if not grid:
|
||||
return [{}]
|
||||
names = list(grid)
|
||||
return [dict(zip(names, values, strict=True)) for values in itertools.product(*grid.values())]
|
||||
|
||||
|
||||
def _score(metrics: dict[str, Any]) -> float:
|
||||
"""Rank by return, penalising drawdown. Simple, transparent, sortable."""
|
||||
return float(metrics.get("total_return_pct", 0.0)) - float(metrics.get("max_drawdown_pct", 0.0))
|
||||
|
||||
|
||||
def run_sweep(
|
||||
strategy_key: str,
|
||||
base_params: dict[str, Any],
|
||||
grid: dict[str, Sequence[Any]],
|
||||
candles: Sequence[Candle],
|
||||
symbol: str,
|
||||
timeframe: str,
|
||||
*,
|
||||
fee_bps: float = 10.0,
|
||||
slippage_bps: float = 5.0,
|
||||
starting_balance: float = 10_000.0,
|
||||
top_n: int = 20,
|
||||
) -> list[SweepRow]:
|
||||
"""Backtest every combination in ``grid`` (merged over ``base_params``)."""
|
||||
strategy_cls: type[Strategy] = get_strategy(strategy_key)
|
||||
backtester = Backtester(
|
||||
fee_bps=fee_bps, slippage_bps=slippage_bps, starting_balance=starting_balance
|
||||
)
|
||||
|
||||
rows: list[SweepRow] = []
|
||||
for params in expand_grid(grid):
|
||||
merged = {**base_params, **params}
|
||||
strategy = strategy_cls(merged)
|
||||
result = backtester.run(candles, strategy, symbol, timeframe)
|
||||
rows.append(SweepRow(params=merged, metrics=result.metrics.model_dump()))
|
||||
|
||||
rows.sort(key=lambda row: _score(row.metrics), reverse=True)
|
||||
return rows[:top_n]
|
||||
Reference in new issue
Block a user