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
@@ -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:
|
||||
|
||||
Reference in new issue
Block a user