Skip to content

"Vibe-Trading: Your Personal Trading Agent"

feat(backtest): report the plans the engine wanted but could not take

Haozhe Wufb515aa7dacb
diff --git a/agent/backtest/engines/base.py b/agent/backtest/engines/base.py
index 316cb1f16..c7f5db20c 100644
--- a/agent/backtest/engines/base.py
+++ b/agent/backtest/engines/base.py
@@ -15,6 +15,7 @@ import math
import re as _re
import sys
from abc import ABC, abstractmethod
+from collections import Counter
from collections.abc import Iterable
from dataclasses import dataclass, replace
from pathlib import Path
@@ -501,6 +502,12 @@ class BaseEngine(ABC):
# 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]] = []
+ # Opening plans the engine wanted but could not take, keyed
+ # (symbol, reason). A sleeve whose target notional rounds below one
+ # lot trades zero times while the run reports a normal result
+ # (#1235); counting the causes is what makes that visible in the
+ # metrics instead of only to a subclass that overrode the hook.
+ self.plan_rejections: Counter = Counter()
self._bar_idx: int = 0
self._active_symbol: str = "" # set by _rebalance/_close_position for subclass use
@@ -689,6 +696,43 @@ class BaseEngine(ABC):
"""Allow engines to update risk state/evidence after a committed delta fill."""
return None
+ #: Rejection causes that mean the engine WANTED a position and could not
+ #: take it. ``no_target_weight`` and ``already_held`` are excluded: they
+ #: mean nothing was wanted, which is not a finding.
+ UNFILLED_PLAN_REASONS = (
+ "no_data",
+ "no_bar",
+ "execution_blocked",
+ "invalid_price",
+ "zero_size",
+ )
+
+ def _plan_rejection_metrics(self) -> Dict[str, Any]:
+ """Summarise opening plans the engine wanted but could not take.
+
+ A rejected plan is invisible in the result otherwise: the run reports a
+ normal equity curve over the symbols that did fill, so a sleeve whose
+ target notional never clears one lot silently drops out of the book and
+ the configuration is graded as if it had never contained that sleeve
+ (#1235). Only the causes that mean "wanted but unfillable" are counted.
+
+ Returns:
+ ``unfilled_plan_rejections`` (total) and
+ ``unfilled_plan_rejections_by_symbol`` (``{symbol: {reason: n}}``),
+ the latter empty when nothing was rejected.
+ """
+ by_symbol: Dict[str, Dict[str, int]] = {}
+ total = 0
+ for (symbol, reason), count in self.plan_rejections.items():
+ if reason not in self.UNFILLED_PLAN_REASONS:
+ continue
+ by_symbol.setdefault(symbol, {})[reason] = count
+ total += count
+ return {
+ "unfilled_plan_rejections": total,
+ "unfilled_plan_rejections_by_symbol": by_symbol,
+ }
+
def _on_plan_rejected(self, symbol: str, reason: str, timestamp: pd.Timestamp) -> None:
"""Observe a silently rejected opening-order plan.
@@ -706,7 +750,7 @@ class BaseEngine(ABC):
``execution_blocked``, ``invalid_price`` or ``zero_size``.
timestamp: Decision bar timestamp.
"""
- return None
+ self.plan_rejections[(symbol, reason)] += 1
def execution_open(self, bar: pd.Series) -> float:
"""Return the normal market-fill price for a bar."""
@@ -902,6 +946,7 @@ class BaseEngine(ABC):
m["excess_return"] = round(
m["total_return"] - benchmark_metadata["benchmark_return"], 6
)
+ m.update(self._plan_rejection_metrics())
m["by_symbol"] = by_symbol_stats(self.trades)
m["by_exit_reason"] = by_exit_reason_stats(self.trades)
diff --git a/agent/tests/test_plan_rejected.py b/agent/tests/test_plan_rejected.py
index 08663401a..eefbc6daa 100644
--- a/agent/tests/test_plan_rejected.py
+++ b/agent/tests/test_plan_rejected.py
@@ -201,3 +201,103 @@ def _run_fill_and_reject_scenario(engine):
# no_data and no_bar via direct calls.
engine._plan_open_order("B", 0.5, None, _TS, 1_000.0)
engine._plan_open_order("B", 0.5, frame, pd.Timestamp("2026-01-03"), 1_000.0)
+
+
+# ---------------------------------------------------------------------------
+# Default surfacing: a rejection nobody subclassed for still reaches the run
+# ---------------------------------------------------------------------------
+
+
+class _PlainEngine(BaseEngine):
+ """No _on_plan_rejected override, and a lot rule that truncates to zero."""
+
+ def __init__(self, *, truncate: bool = False):
+ super().__init__(
+ {"initial_cash": 1_000.0, "leverage": 1.0, "position_adjustment": "rebalance"}
+ )
+ self.execute_ok = True
+ self._truncate = truncate
+
+ def can_execute(self, symbol, direction, bar):
+ return self.execute_ok
+
+ def round_size(self, raw_size, price):
+ return 0.0 if self._truncate else round(max(raw_size, 0.0), 6)
+
+ def calc_commission(self, size, price, direction, is_open):
+ return 0.0
+
+ def apply_slippage(self, price, direction):
+ return price
+
+
+def test_wanted_but_unfillable_plans_are_counted_by_default():
+ """A plain engine records the causes without any subclass override."""
+ engine = _PlainEngine(truncate=True)
+ assert engine._plan_open_order("A", 0.5, None, _TS, 1_000.0) is None # no_data
+ assert (
+ engine._plan_open_order("A", 0.5, _frame(), pd.Timestamp("2026-01-03"), 1_000.0)
+ is None
+ ) # no_bar
+ assert (
+ engine._plan_open_order("A", 0.5, _frame(open_price=0.0), _TS, 1_000.0) is None
+ ) # invalid_price
+ assert engine._plan_open_order("A", 0.5, _frame(), _TS, 1_000.0) is None # zero_size
+ engine.execute_ok = False
+ assert (
+ engine._plan_open_order("A", 0.5, _frame(), _TS, 1_000.0) is None
+ ) # execution_blocked
+ # Benign causes must not be counted as findings.
+ assert engine._plan_open_order("A", 0.0, _frame(), _TS, 1_000.0) is None
+
+ metrics = engine._plan_rejection_metrics()
+ assert metrics["unfilled_plan_rejections"] == 5
+ assert metrics["unfilled_plan_rejections_by_symbol"] == {
+ "A": {
+ "no_data": 1,
+ "no_bar": 1,
+ "invalid_price": 1,
+ "zero_size": 1,
+ "execution_blocked": 1,
+ }
+ }
+ assert set(metrics["unfilled_plan_rejections_by_symbol"]["A"]) == set(
+ BaseEngine.UNFILLED_PLAN_REASONS
+ )
+
+
+def test_a_clean_run_reports_zero_unfilled_plans():
+ engine = _PlainEngine()
+ assert engine._plan_open_order("A", 0.5, _frame(), _TS, 1_000.0) is not None
+ metrics = engine._plan_rejection_metrics()
+ assert metrics["unfilled_plan_rejections"] == 0
+ assert metrics["unfilled_plan_rejections_by_symbol"] == {}
+
+
+def test_lot_truncated_sleeve_is_named_in_the_metrics():
+ """#1235's motivating case: the sleeve that never fills must be nameable."""
+ engine = _PlainEngine(truncate=True)
+ for _ in range(3):
+ engine._plan_open_order("ES", 0.0005, _frame(), _TS, 1_000.0)
+
+ metrics = engine._plan_rejection_metrics()
+ assert metrics["unfilled_plan_rejections"] == 3
+ assert metrics["unfilled_plan_rejections_by_symbol"] == {"ES": {"zero_size": 3}}
+
+
+def test_an_overriding_subclass_still_gets_the_default_counting():
+ """A subclass that calls super() keeps both the hook and the metrics."""
+
+ class _Both(_PlainEngine):
+ def __init__(self):
+ super().__init__(truncate=True)
+ self.seen = []
+
+ def _on_plan_rejected(self, symbol, reason, timestamp):
+ self.seen.append((symbol, reason))
+ super()._on_plan_rejected(symbol, reason, timestamp)
+
+ engine = _Both()
+ engine._plan_open_order("A", 0.5, _frame(), _TS, 1_000.0)
+ assert engine.seen == [("A", "zero_size")]
+ assert engine._plan_rejection_metrics()["unfilled_plan_rejections"] == 1