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
@@ -25,6 +25,8 @@ from app.schemas import (
|
||||
StrategyConfigIn,
|
||||
StrategyConfigOut,
|
||||
StrategyOut,
|
||||
SweepRequest,
|
||||
SweepResult,
|
||||
)
|
||||
|
||||
router = APIRouter(prefix="/api")
|
||||
@@ -139,6 +141,18 @@ def delete_preset(config_id: int, runtime: GuardedRuntimeDep) -> dict[str, bool]
|
||||
return {"deleted": True}
|
||||
|
||||
|
||||
@router.post("/sweep", response_model=SweepResult)
|
||||
async def run_sweep_endpoint(payload: SweepRequest, runtime: GuardedRuntimeDep) -> SweepResult:
|
||||
try:
|
||||
return await runtime.run_sweep(payload)
|
||||
except KeyError as exc:
|
||||
raise HTTPException(status_code=404, detail=str(exc)) from exc
|
||||
except ValueError as exc:
|
||||
raise HTTPException(status_code=400, detail=str(exc)) from exc
|
||||
except httpx.HTTPError as exc:
|
||||
raise HTTPException(status_code=502, detail=f"market data error: {exc}") from exc
|
||||
|
||||
|
||||
def _position_out(position: Position, price: float | None) -> PositionOut:
|
||||
out = PositionOut.model_validate(position)
|
||||
if position.status == PositionStatus.OPEN and price is not None:
|
||||
|
||||
@@ -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]
|
||||
@@ -18,6 +18,7 @@ _settings = get_settings()
|
||||
# added here as (table, column, DDL type) tuples.
|
||||
_ADDITIVE_COLUMNS: list[tuple[str, str, str]] = [
|
||||
("strategy_configs", "name", "VARCHAR(80) DEFAULT ''"),
|
||||
("positions", "trailing_stop_pct", "FLOAT DEFAULT 0"),
|
||||
]
|
||||
|
||||
|
||||
|
||||
@@ -10,6 +10,7 @@ from app.broker.base import Broker
|
||||
from app.config import Settings
|
||||
from app.engine.portfolio import (
|
||||
account_equity,
|
||||
advance_trailing_stop,
|
||||
apply_close,
|
||||
apply_open,
|
||||
order_qty,
|
||||
@@ -202,6 +203,7 @@ class TradingEngine:
|
||||
size=intent.size if intent.size is not None else 1.0,
|
||||
stop_loss=intent.stop_loss,
|
||||
take_profit=intent.take_profit,
|
||||
trailing_stop_pct=intent.trailing_stop_pct,
|
||||
reason=intent.reason or intent.action,
|
||||
)
|
||||
|
||||
@@ -213,6 +215,7 @@ class TradingEngine:
|
||||
stop_loss: float | None,
|
||||
take_profit: float | None,
|
||||
reason: str,
|
||||
trailing_stop_pct: float = 0.0,
|
||||
qty_override: float | None = None,
|
||||
) -> None:
|
||||
price = self.last_price
|
||||
@@ -250,6 +253,7 @@ class TradingEngine:
|
||||
entry_fee=fill.fee,
|
||||
stop_loss=stop_loss,
|
||||
take_profit=take_profit,
|
||||
trailing_stop_pct=trailing_stop_pct,
|
||||
)
|
||||
self.store.record_order(
|
||||
position_id=self.position.id,
|
||||
@@ -317,6 +321,21 @@ class TradingEngine:
|
||||
position = self.position
|
||||
if position is None:
|
||||
return
|
||||
|
||||
# Ratchet a trailing stop before testing levels, so a bar that both
|
||||
# advances the trail and reverses is handled consistently.
|
||||
if position.trailing_stop_pct and position.trailing_stop_pct > 0:
|
||||
advanced = advance_trailing_stop(
|
||||
position.side,
|
||||
position.stop_loss,
|
||||
position.trailing_stop_pct,
|
||||
candle.high,
|
||||
candle.low,
|
||||
)
|
||||
if advanced is not None and advanced != position.stop_loss:
|
||||
position.stop_loss = advanced
|
||||
self.store.update_stop_loss(position.id, advanced)
|
||||
|
||||
hit = risk_exit(
|
||||
position.side,
|
||||
position.stop_loss,
|
||||
|
||||
@@ -18,9 +18,33 @@ class OpenPosition:
|
||||
entry_fee: float = 0.0
|
||||
stop_loss: float | None = None
|
||||
take_profit: float | None = None
|
||||
# Distance to trail the stop below the high (long) / above the low (short),
|
||||
# as a fraction of price (0.02 = 2%). 0 disables trailing.
|
||||
trailing_stop_pct: float = 0.0
|
||||
entry_ts: int = 0
|
||||
|
||||
|
||||
def advance_trailing_stop(
|
||||
side: PositionSide,
|
||||
stop_loss: float | None,
|
||||
trailing_stop_pct: float,
|
||||
high: float,
|
||||
low: float,
|
||||
) -> float | None:
|
||||
"""Ratchet a trailing stop toward the price; never loosens.
|
||||
|
||||
For a long the stop trails ``pct`` below the running high; for a short it
|
||||
trails ``pct`` above the running low. Returns the (possibly unchanged) stop.
|
||||
"""
|
||||
if trailing_stop_pct <= 0:
|
||||
return stop_loss
|
||||
if side == PositionSide.LONG:
|
||||
candidate = high * (1 - trailing_stop_pct)
|
||||
return candidate if stop_loss is None else max(stop_loss, candidate)
|
||||
candidate = low * (1 + trailing_stop_pct)
|
||||
return candidate if stop_loss is None else min(stop_loss, candidate)
|
||||
|
||||
|
||||
def apply_open(cash: float, side: PositionSide, qty: float, price: float, fee: float) -> float:
|
||||
"""Cash after opening a position (buying long / selling short)."""
|
||||
notional = qty * price
|
||||
|
||||
@@ -26,6 +26,7 @@ class Intent:
|
||||
size: float | None = None
|
||||
stop_loss: float | None = None
|
||||
take_profit: float | None = None
|
||||
trailing_stop_pct: float = 0.0
|
||||
reason: str = ""
|
||||
|
||||
|
||||
@@ -121,18 +122,24 @@ class StrategyContext:
|
||||
size: float | None = None,
|
||||
stop_loss: float | None = None,
|
||||
take_profit: float | None = None,
|
||||
trailing_stop_pct: float = 0.0,
|
||||
reason: str = "",
|
||||
) -> None:
|
||||
self._intents.append(Intent("enter_long", size, stop_loss, take_profit, reason))
|
||||
self._intents.append(
|
||||
Intent("enter_long", size, stop_loss, take_profit, trailing_stop_pct, reason)
|
||||
)
|
||||
|
||||
def enter_short(
|
||||
self,
|
||||
size: float | None = None,
|
||||
stop_loss: float | None = None,
|
||||
take_profit: float | None = None,
|
||||
trailing_stop_pct: float = 0.0,
|
||||
reason: str = "",
|
||||
) -> None:
|
||||
self._intents.append(Intent("enter_short", size, stop_loss, take_profit, reason))
|
||||
self._intents.append(
|
||||
Intent("enter_short", size, stop_loss, take_profit, trailing_stop_pct, reason)
|
||||
)
|
||||
|
||||
def close(self, reason: str = "") -> None:
|
||||
self._intents.append(Intent("close", reason=reason))
|
||||
|
||||
@@ -21,19 +21,22 @@ class Momentum(Strategy):
|
||||
"entry_threshold": 0.01,
|
||||
"atr_period": 14,
|
||||
"atr_stop_mult": 2.0,
|
||||
"trailing_stop_pct": 0.0,
|
||||
"size": 1.0,
|
||||
}
|
||||
param_help: ClassVar[dict] = {
|
||||
"period": "ROC lookback in bars",
|
||||
"entry_threshold": "Minimum ROC to enter (0.01 = 1%)",
|
||||
"atr_period": "ATR lookback for the stop",
|
||||
"atr_period": "ATR lookback for the initial stop",
|
||||
"atr_stop_mult": "Stop distance in ATRs (0 disables)",
|
||||
"trailing_stop_pct": "Trailing stop distance as a fraction of price (0 disables)",
|
||||
"size": "Fraction of equity per trade",
|
||||
}
|
||||
param_bounds: ClassVar[dict] = {
|
||||
"period": (2, 200),
|
||||
"entry_threshold": (0.0, 1.0),
|
||||
"atr_stop_mult": (0.0, 10.0),
|
||||
"trailing_stop_pct": (0.0, 0.5),
|
||||
"size": (0.01, 1.0),
|
||||
}
|
||||
|
||||
@@ -52,6 +55,7 @@ class Momentum(Strategy):
|
||||
ctx.enter_long(
|
||||
size=float(self.params["size"]),
|
||||
stop_loss=stop,
|
||||
trailing_stop_pct=float(self.params["trailing_stop_pct"]),
|
||||
reason=f"ROC {value:.2%} above threshold",
|
||||
)
|
||||
elif ctx.side == PositionSide.LONG and value < 0:
|
||||
|
||||
@@ -67,6 +67,7 @@ class Position(Base):
|
||||
)
|
||||
stop_loss: Mapped[float | None] = mapped_column(Float, nullable=True)
|
||||
take_profit: Mapped[float | None] = mapped_column(Float, nullable=True)
|
||||
trailing_stop_pct: Mapped[float] = mapped_column(Float, default=0.0)
|
||||
entry_fee: Mapped[float] = mapped_column(Float, default=0.0)
|
||||
exit_price: Mapped[float | None] = mapped_column(Float, nullable=True)
|
||||
exit_fee: Mapped[float] = mapped_column(Float, default=0.0)
|
||||
|
||||
+44
-2
@@ -6,7 +6,7 @@ from collections.abc import Callable
|
||||
from contextlib import suppress
|
||||
from typing import Any
|
||||
|
||||
from app.backtest import Backtester
|
||||
from app.backtest import Backtester, run_sweep
|
||||
from app.broker import build_broker
|
||||
from app.broker.base import Broker
|
||||
from app.config import Settings
|
||||
@@ -15,7 +15,14 @@ from app.engine.strategies import get_strategy
|
||||
from app.market import build_market_data
|
||||
from app.market.base import MarketData
|
||||
from app.notify import Notifier, build_notifier
|
||||
from app.schemas import BacktestRequest, BacktestResult, StatusOut
|
||||
from app.schemas import (
|
||||
BacktestRequest,
|
||||
BacktestResult,
|
||||
StatusOut,
|
||||
SweepRequest,
|
||||
SweepResult,
|
||||
SweepRowOut,
|
||||
)
|
||||
from app.store import Store
|
||||
|
||||
logger = logging.getLogger(__name__)
|
||||
@@ -139,6 +146,41 @@ class Runtime:
|
||||
)
|
||||
return backtester.run(candles, strategy, symbol, timeframe)
|
||||
|
||||
async def run_sweep(self, request: SweepRequest) -> SweepResult:
|
||||
symbol = request.symbol or self.settings.symbol
|
||||
timeframe = request.timeframe or self.settings.timeframe
|
||||
strategy_cls = get_strategy(request.strategy_key)
|
||||
|
||||
feed = self._feed_factory(self.settings)
|
||||
try:
|
||||
candles = await feed.fetch_candles(symbol, timeframe, request.limit)
|
||||
finally:
|
||||
await feed.close()
|
||||
|
||||
rows = run_sweep(
|
||||
request.strategy_key,
|
||||
request.base_params,
|
||||
request.grid,
|
||||
candles,
|
||||
symbol,
|
||||
timeframe,
|
||||
fee_bps=self.settings.fee_bps,
|
||||
slippage_bps=self.settings.slippage_bps,
|
||||
starting_balance=request.starting_balance or self.settings.starting_balance,
|
||||
top_n=request.top_n,
|
||||
)
|
||||
combinations = 1
|
||||
for values in request.grid.values():
|
||||
combinations *= max(1, len(values))
|
||||
return SweepResult(
|
||||
strategy_key=request.strategy_key,
|
||||
strategy_name=strategy_cls.name or request.strategy_key,
|
||||
symbol=symbol,
|
||||
timeframe=timeframe,
|
||||
combinations=combinations,
|
||||
rows=[SweepRowOut(params=row.params, metrics=row.metrics) for row in rows],
|
||||
)
|
||||
|
||||
async def shutdown(self) -> None:
|
||||
if self.engine is not None:
|
||||
await self.engine.shutdown()
|
||||
|
||||
@@ -206,3 +206,30 @@ class BacktestResult(BaseModel):
|
||||
equity_curve: list[BacktestPointOut]
|
||||
trades: list[BacktestTradeOut]
|
||||
error: str | None = None
|
||||
|
||||
|
||||
class SweepRequest(BaseModel):
|
||||
strategy_key: str
|
||||
base_params: dict[str, Any] = Field(default_factory=dict)
|
||||
# param name -> list of candidate values (cartesian product)
|
||||
grid: dict[str, list[Any]] = Field(default_factory=dict)
|
||||
symbol: str | None = None
|
||||
timeframe: str | None = None
|
||||
limit: int = Field(default=500, ge=20, le=1000)
|
||||
starting_balance: float | None = None
|
||||
top_n: int = Field(default=20, ge=1, le=100)
|
||||
|
||||
|
||||
class SweepRowOut(BaseModel):
|
||||
params: dict[str, Any]
|
||||
metrics: BacktestMetricsOut
|
||||
|
||||
|
||||
class SweepResult(BaseModel):
|
||||
strategy_key: str
|
||||
strategy_name: str
|
||||
symbol: str
|
||||
timeframe: str
|
||||
combinations: int
|
||||
rows: list[SweepRowOut]
|
||||
error: str | None = None
|
||||
@@ -33,6 +33,7 @@ class Store:
|
||||
entry_fee: float,
|
||||
stop_loss: float | None = None,
|
||||
take_profit: float | None = None,
|
||||
trailing_stop_pct: float = 0.0,
|
||||
) -> Position:
|
||||
with self._session_factory() as session:
|
||||
position = Position(
|
||||
@@ -44,6 +45,7 @@ class Store:
|
||||
entry_fee=entry_fee,
|
||||
stop_loss=stop_loss,
|
||||
take_profit=take_profit,
|
||||
trailing_stop_pct=trailing_stop_pct,
|
||||
status=PositionStatus.OPEN,
|
||||
)
|
||||
session.add(position)
|
||||
@@ -88,6 +90,14 @@ class Store:
|
||||
session.commit()
|
||||
return len(positions)
|
||||
|
||||
def update_stop_loss(self, position_id: int, stop_loss: float) -> None:
|
||||
with self._session_factory() as session:
|
||||
position = session.get(Position, position_id)
|
||||
if position is None:
|
||||
return
|
||||
position.stop_loss = stop_loss
|
||||
session.commit()
|
||||
|
||||
def open_position_for(self, strategy_key: str) -> Position | None:
|
||||
with self._session_factory() as session:
|
||||
return session.scalars(
|
||||
|
||||
Reference in new issue
Block a user