"Vibe-Trading: Your Personal Trading Agent"
Python ai-agentalgorithmic-tradingbacktestingfintechllmmcpmulti-agentpythonquantitative-financetrading
fix(backtest): say when hold mode drops a requested resize
Haozhe Wue989d537761f
diff --git a/agent/backtest/engines/base.py b/agent/backtest/engines/base.pyindex 9cf4bebe4..5d0ebc54d 100644--- a/agent/backtest/engines/base.py+++ b/agent/backtest/engines/base.py@@ -414,6 +414,15 @@ class BaseEngine(ABC):# insufficient cash can all make the executed book differ from the# optimiser's request.self.actual_position_snapshots: List[tuple[pd.Timestamp, Dict[str, float]]] = []+ # Hold mode executes a target change only when the direction flips or+ # the target reaches zero, so a same-direction resize is dropped. That+ # is a legitimate mode -- it is what "enter once, hold to exit" means --+ # but dropping a request the strategy actually made must not be silent+ # (#918). The previous target is what makes the difference visible:+ # comparing against the CURRENT weight would fire on every bar of a+ # buy-and-hold position, whose weight drifts with price by design.+ self._last_target_weight: Dict[str, float] = {}+ self.dropped_target_adjustments: List[Dict[str, Any]] = []self._bar_idx: int = 0self._active_symbol: str = "" # set by _rebalance/_close_position for subclass use@@ -803,6 +812,31 @@ class BaseEngine(ABC):m["rebalance_turnover_mean"] = rebalance_notes["summary"]["turnover_mean"]m["rebalance_turnover_max"] = rebalance_notes["summary"]["turnover_max"]+ # The notes above count what the STRATEGY asked for. Under+ # position_adjustment="hold" a same-direction resize is not executed,+ # so a run can report rebalances whose weight changes never reached the+ # book. Say which ones, rather than leaving the reader to reconcile a+ # rebalance count against a trade log that does not match it (#918).+ m["position_adjustment"] = self.position_adjustment+ m["dropped_target_adjustment_count"] = len(self.dropped_target_adjustments)+ m["dropped_target_adjustments"] = [+ {+ "timestamp": str(event["timestamp"]),+ "symbol": event["symbol"],+ "previous_target_weight": round(event["previous_target_weight"], 6),+ "requested_target_weight": round(event["requested_target_weight"], 6),+ }+ for event in self.dropped_target_adjustments[:20]+ ]+ if self.dropped_target_adjustments:+ logger.warning(+ "position_adjustment='hold' dropped %d target change(s) across %d "+ "symbol(s); the report's rebalance_count describes requests, not "+ "fills. Set position_adjustment='rebalance' to execute them.",+ len(self.dropped_target_adjustments),+ len({event["symbol"] for event in self.dropped_target_adjustments}),+ )+# Portfolio Studio: risk x-ray over the strategy's average basket.# Short runs and never-invested strategies raise ValueError in the# derivation and simply get no x-ray artifact.@@ -912,6 +946,8 @@ class BaseEngine(ABC):if self.position_adjustment == "rebalance":self._execute_target_rebalance(target_weights, data_map, ts, equity, codes)target_weights = {}+ else:+ self._record_dropped_target_adjustments(target_weights, ts)# b. In legacy hold mode, release capital before opening replacement# positions or increasing other positions. A@@ -1238,6 +1274,61 @@ class BaseEngine(ABC):commission=commission,)+ # A target move smaller than this is optimiser float noise, not a decision.+ _TARGET_CHANGE_EPSILON = 1e-6+ # Detail lines are logged for the first few only; the rest are counted.+ _DROPPED_ADJUSTMENT_LOG_LIMIT = 3++ def _record_dropped_target_adjustments(+ self, target_weights: Dict[str, Optional[float]], ts: pd.Timestamp+ ) -> None:+ """Note every same-direction resize that hold mode is about to drop.++ Only a change in the TARGET counts. A held position's weight drifts+ with price on its own, so comparing the target against the current+ weight would report a buy-and-hold position as a dropped request on+ every bar.++ Args:+ target_weights: This bar's target per symbol; ``None`` means the+ strategy produced no decision and nothing is dropped.+ ts: The decision timestamp, recorded with each dropped request.+ """+ for symbol, target_w in target_weights.items():+ if target_w is None:+ continue+ previous = self._last_target_weight.get(symbol)+ self._last_target_weight[symbol] = target_w+ if previous is None or abs(target_w - previous) <= self._TARGET_CHANGE_EPSILON:+ continue+ position = self.positions.get(symbol)+ if position is None:+ continue+ target_dir = 1 if target_w > 1e-9 else (-1 if target_w < -1e-9 else 0)+ # A flip or an exit IS executed in hold mode; only a same-direction+ # resize is dropped.+ if target_dir == 0 or target_dir != position.direction:+ continue+ self.dropped_target_adjustments.append(+ {+ "timestamp": ts,+ "symbol": symbol,+ "previous_target_weight": previous,+ "requested_target_weight": target_w,+ "direction": position.direction,+ }+ )+ if len(self.dropped_target_adjustments) <= self._DROPPED_ADJUSTMENT_LOG_LIMIT:+ logger.warning(+ "position_adjustment='hold' dropped a resize: %s at %s asked for "+ "weight %.6f (was %.6f) and the position was left unchanged. "+ "Set position_adjustment='rebalance' to execute target changes.",+ symbol,+ ts,+ target_w,+ previous,+ )+def _execute_target_rebalance(self,target_weights: Dict[str, Optional[float]], data_map: Dict[str, pd.DataFrame],diff --git a/agent/src/skills/strategy-generate/SKILL.md b/agent/src/skills/strategy-generate/SKILL.mdindex 465c3fce8..d9baf3c51 100644--- a/agent/src/skills/strategy-generate/SKILL.md+++ b/agent/src/skills/strategy-generate/SKILL.md@@ -142,7 +142,10 @@ Self-check after writing `signal_engine.py`:- `optimizer`: optional, one of `"equal_volatility"` / `"risk_parity"` / `"mean_variance"` / `"max_diversification"` / `"turnover_aware"` / `null` (equal-weight by default)- `optimizer_params`: optimizer parameters, such as `{"lookback": 60}`. `mean_variance` additionally supports `{"risk_free": 0.0}`; `turnover_aware` supports `{"risk_aversion": 1.0, "turnover_penalty": 0.5}` (L1 penalty on weight changes; tune to data frequency)- `engine`: backtest engine, default `"daily"`. For options strategies, set `"options"` (requires `OptionsSignalEngine`)-- `position_adjustment`: use `"rebalance"` for target-weight strategies so every target change is executed using market fills and weighted-average entry accounting; use `"hold"` only when the strategy explicitly intends to preserve a same-direction position until close/reversal+- `position_adjustment`: **always state this explicitly** — the two modes produce different books from the same signals, and neither is right for every strategy.+ - `"rebalance"` executes every target change with market fills and weighted-average entry accounting. It also re-sizes whenever the held weight has drifted from the target, and a strategy restates its target on every bar, so a constant target means a fill on every bar: measured on a 40-bar rising series, a constant 20% target produced **40 fills instead of 1**, with the fees, slippage and transaction taxes that follow. A strategy that rebalances on its own schedule (e.g. `rebalance_freq=20`) will still trade daily here.+ - `"hold"` keeps a same-direction position until it exits or reverses, so the weight drifts with price and a requested resize is **not executed**. Dropped requests are counted in the report as `dropped_target_adjustment_count`, with the first twenty listed, so a rebalance count that does not match the trade log is explained rather than silent.+ - Rule of thumb: `"rebalance"` when the target weight itself carries the strategy (optimizers, risk budgets, continuous scaling); `"hold"` when entries and exits carry it and the weight in between is incidental.- `initial_cash`: default 1,000,000- `commission`: default 0.1%- `validation`: optional statistical validation after backtest completes. Omit to skip. Example:diff --git a/agent/tests/test_dropped_target_adjustments.py b/agent/tests/test_dropped_target_adjustments.pynew file mode 100644index 000000000..ba85646ce--- /dev/null+++ b/agent/tests/test_dropped_target_adjustments.py@@ -0,0 +1,100 @@+"""Hold mode may drop a requested resize, but never silently (#918).++`position_adjustment="hold"` executes a target change only when the direction+flips or the target reaches zero, so a same-direction resize is dropped. That+is the mode's job — "enter once, hold to exit" — but the report used to show a+rebalance count taken from the *requested* targets with nothing saying which of+those requests reached the book.+"""++from __future__ import annotations++import logging++import pandas as pd+import pytest++from backtest.engines.base import BaseEngine+++class _Engine(BaseEngine):+ def can_execute(self, symbol, direction, bar):+ return True++ def round_size(self, raw_size, price):+ return float(int(raw_size))++ def calc_commission(self, size, price, direction, is_open):+ return 0.0++ def apply_slippage(self, price, direction):+ return price * (1 + 0.0005 * direction)+++def _flat_bars(periods: int) -> tuple[pd.DatetimeIndex, pd.DataFrame]:+ dates = pd.bdate_range("2026-01-05", periods=periods)+ bars = pd.DataFrame({"open": [100.0] * periods, "close": [100.0] * periods}, index=dates)+ return dates, bars+++def test_a_dropped_resize_is_recorded_and_warned(caplog: pytest.LogCaptureFixture) -> None:+ """The strategy asked to move 0.20 -> 0.60 -> 0.30 and got none of it."""+ dates, bars = _flat_bars(4)+ close_df = pd.DataFrame({"A": bars["close"]}, index=dates)+ targets = pd.DataFrame({"A": [0.20, 0.60, 0.30, 0.30]}, index=dates)+ engine = _Engine({"initial_cash": 100_000.0})++ with caplog.at_level(logging.WARNING):+ engine._execute_bars(dates, {"A": bars}, close_df, targets, ["A"])++ events = engine.dropped_target_adjustments+ assert [event["symbol"] for event in events] == ["A", "A"]+ assert [event["requested_target_weight"] for event in events] == [0.60, 0.30]+ assert [event["previous_target_weight"] for event in events] == [0.20, 0.60]+ assert any("dropped a resize" in message for message in caplog.messages)+++def test_price_drift_alone_is_not_a_dropped_request() -> None:+ """A buy-and-hold weight drifts by design; reporting it would be noise.++ This is why the check compares against the previous TARGET rather than the+ current weight: on a rising series the held weight leaves 0.20 on its own,+ and comparing against it would flag every bar of an untouched position.+ """+ periods = 40+ dates = pd.bdate_range("2026-01-05", periods=periods)+ prices = [100.0 * (1.01**i) for i in range(periods)]+ bars = pd.DataFrame({"open": prices, "close": prices}, index=dates)+ close_df = pd.DataFrame({"A": bars["close"]}, index=dates)+ targets = pd.DataFrame({"A": [0.20] * periods}, index=dates)+ engine = _Engine({"initial_cash": 1_000_000.0})++ engine._execute_bars(dates, {"A": bars}, close_df, targets, ["A"])++ weights = [snapshot.get("A", 0.0) for _, snapshot in engine.actual_position_snapshots]+ assert weights[-2] > weights[0] # the position really did drift+ assert engine.dropped_target_adjustments == []+++def test_rebalance_mode_drops_nothing() -> None:+ """Nothing is dropped when every target change is executed."""+ dates, bars = _flat_bars(4)+ close_df = pd.DataFrame({"A": bars["close"]}, index=dates)+ targets = pd.DataFrame({"A": [0.20, 0.60, 0.30, 0.30]}, index=dates)+ engine = _Engine({"initial_cash": 100_000.0, "position_adjustment": "rebalance"})++ engine._execute_bars(dates, {"A": bars}, close_df, targets, ["A"])++ assert engine.dropped_target_adjustments == []+++def test_an_exit_or_a_reversal_is_executed_not_dropped() -> None:+ """Hold mode does honour a flip and a flat target, so neither is reported."""+ dates, bars = _flat_bars(4)+ close_df = pd.DataFrame({"A": bars["close"]}, index=dates)+ targets = pd.DataFrame({"A": [0.20, 0.0, -0.20, -0.20]}, index=dates)+ engine = _Engine({"initial_cash": 100_000.0})++ engine._execute_bars(dates, {"A": bars}, close_df, targets, ["A"])++ assert engine.dropped_target_adjustments == []