"Vibe-Trading: Your Personal Trading Agent"
Python ai-agentalgorithmic-tradingbacktestingfintechllmmcpmulti-agentpythonquantitative-financetrading
fix(backtest): enforce A-share and India rules through composite state
Yufeng He8ffdfc7a4ad7
diff --git a/agent/backtest/engines/china_a.py b/agent/backtest/engines/china_a.pyindex 0b5f73cb5..7d10e4239 100644--- a/agent/backtest/engines/china_a.py+++ b/agent/backtest/engines/china_a.py@@ -48,24 +48,7 @@ class ChinaAEngine(BaseEngine):Returns:True if the trade is allowed."""- # 1. No short selling- if direction == -1:- return False-- # 2. T+1: can't sell shares bought today- if direction == 0:- pos = self.positions.get(symbol)- if pos is not None:- bar_date = _bar_date(bar)- entry_date = pos.entry_time.date() if hasattr(pos.entry_time, "date") else None- if bar_date is not None and entry_date is not None and bar_date == entry_date:- return False-- # 3. Price limits, tested at execution time (see _blocked_by_limit).- if _blocked_by_limit(self, symbol, direction, bar, _price_limit(symbol)):- return False-- return True+ return china_a_can_execute(self, self, symbol, direction, bar)def round_size(self, raw_size: float, price: float) -> float:"""Round down to 100-share lots."""@@ -190,3 +173,32 @@ def _price_limit(symbol: str) -> float:return 0.30# Main board: ±10%return 0.10+++def china_a_can_execute(state, rules, symbol: str, direction: int, bar: pd.Series) -> bool:+ """A-share execution rules read against ``state`` with params from ``rules``.++ Composite runs pass the composite engine as ``state`` (it owns the shared+ positions and the close panel) and the A-share sub-engine as ``rules``;+ a single-market run passes the same engine for both. Reading through the+ state side is what lets the composite enforce T+1 and the limit bands+ instead of evaluating them against a stateless rule book (#1292).+ """+ # 1. No short selling+ if direction == -1:+ return False++ # 2. T+1: can't sell shares bought today+ if direction == 0:+ pos = state.positions.get(symbol)+ if pos is not None:+ bar_date = _bar_date(bar)+ entry_date = pos.entry_time.date() if hasattr(pos.entry_time, "date") else None+ if bar_date is not None and entry_date is not None and bar_date == entry_date:+ return False++ # 3. Price limits, tested at execution time (see _blocked_by_limit).+ if _blocked_by_limit(state, symbol, direction, bar, _price_limit(symbol)):+ return False++ return Truediff --git a/agent/backtest/engines/composite.py b/agent/backtest/engines/composite.pyindex 6046bc2e3..d18346678 100644--- a/agent/backtest/engines/composite.py+++ b/agent/backtest/engines/composite.py@@ -167,15 +167,14 @@ class CompositeEngine(BaseEngine):# ── Stateless method dispatch ──def can_execute(self, symbol: str, direction: int, bar: pd.Series) -> bool:- """Market-rule check with settlement interceptors for A-shares and HOSE."""+ """Market-rule check with state/rules split helpers for HOSE, A-share, India."""market = self._symbol_market.get(symbol, "a_share")- # HOSE: both the T+2 hold and the ±7% band read run state — positions- # and the fill ledger for the hold, the close panel for the reference- # price — that a stateless rule book does not have. Delegating them- # would pass every sell and skip every band check, so the rules are- # evaluated against this engine's state using the Vietnam engine's own- # implementation, with the sub-engine supplying only the parameters.+ # HOSE, A-share and India all read run state a stateless rule book+ # does not have: positions for T+1/T+2 and the close panel for the+ # band reference price. Each market's module-level helper takes the+ # composite as the state side and the sub-engine as the parameter+ # side, so the shared state is what the rules are evaluated against.if market == "vietnam_equity":sub = self._rule_engines.get("vietnam_equity")if sub is not None:@@ -183,20 +182,19 @@ class CompositeEngine(BaseEngine):return hose_can_execute(self, sub, symbol, direction, bar)- # T+1: intercept here because sub-engine has no access to shared positions- if market == "a_share" and direction == 0:- pos = self.positions.get(symbol)- if pos is not None:- bar_date = None- if hasattr(bar, "name") and hasattr(bar.name, "date"):- bar_date = bar.name.date()- entry_date = (- pos.entry_time.date()- if hasattr(pos.entry_time, "date")- else None- )- if bar_date and entry_date and bar_date == entry_date:- return False+ if market == "a_share":+ sub = self._rule_engines.get("a_share")+ if sub is not None:+ from backtest.engines.china_a import china_a_can_execute++ return china_a_can_execute(self, sub, symbol, direction, bar)++ if market == "india_equity":+ sub = self._rule_engines.get("india_equity")+ if sub is not None:+ from backtest.engines.india_equity import india_can_execute++ return india_can_execute(self, sub, symbol, direction, bar)# Delegate remaining checks (price limits, short-sell block, etc.)return self._rule_for(symbol).can_execute(symbol, direction, bar)diff --git a/agent/backtest/engines/india_equity.py b/agent/backtest/engines/india_equity.pyindex fd50f8814..bdebdba9f 100644--- a/agent/backtest/engines/india_equity.py+++ b/agent/backtest/engines/india_equity.py@@ -73,26 +73,7 @@ class IndiaEquityEngine(BaseEngine):Returns:True if the trade is allowed."""- # 1. Short selling: blocked unless explicitly modelling intraday (MIS).- if direction == -1 and not self.allow_short:- return False-- # 2. T+1: can't sell shares bought today (delivery).- if direction == 0:- pos = self.positions.get(symbol)- if pos is not None:- bar_date = _bar_date(bar)- entry_date = pos.entry_time.date() if hasattr(pos.entry_time, "date") else None- if bar_date is not None and entry_date is not None and bar_date == entry_date:- return False-- # 3. Circuit bands, tested at execution time (see _blocked_by_limit).- if self.price_limit and _blocked_by_limit(- self, symbol, direction, bar, float(self.price_limit)- ):- return False-- return True+ return india_can_execute(self, self, symbol, direction, bar)def round_size(self, raw_size: float, price: float) -> float:"""Cash equity trades in 1-share lots."""@@ -139,3 +120,35 @@ def _bar_date(bar: pd.Series):if hasattr(bar, "name") and hasattr(bar.name, "date"):return bar.name.date()return None+++def india_can_execute(state, rules, symbol: str, direction: int, bar: pd.Series) -> bool:+ """India delivery rules read against ``state`` with params from ``rules``.++ Composite runs pass the composite engine as ``state`` (shared positions+ and close panel) and the India sub-engine as ``rules`` (``allow_short``,+ ``price_limit``, slippage); a single-market run passes the same engine+ for both. Without this the composite evaluated T+1 against the+ sub-engine's always-empty positions and let same-day sells through+ (#1292).+ """+ # 1. Short selling: blocked unless explicitly modelling intraday (MIS).+ if direction == -1 and not rules.allow_short:+ return False++ # 2. T+1: can't sell shares bought today (delivery).+ if direction == 0:+ pos = state.positions.get(symbol)+ if pos is not None:+ bar_date = _bar_date(bar)+ entry_date = pos.entry_time.date() if hasattr(pos.entry_time, "date") else None+ if bar_date is not None and entry_date is not None and bar_date == entry_date:+ return False++ # 3. Circuit bands, tested at execution time (see _blocked_by_limit).+ if rules.price_limit and _blocked_by_limit(+ state, symbol, direction, bar, float(rules.price_limit)+ ):+ return False++ return Truediff --git a/agent/tests/test_composite_market_rules.py b/agent/tests/test_composite_market_rules.pynew file mode 100644index 000000000..ebf651fe6--- /dev/null+++ b/agent/tests/test_composite_market_rules.py@@ -0,0 +1,99 @@+"""Composite enforcement of A-share and India rules (#1292).++Sub-engines in a composite run are stateless rule books: their ``positions``+dict is always empty and they own no close panel. India T+1 therefore never+fired (the check read the empty dict), and price-limit bands failed open on+every bar (no loader emits ``pre_close``/``pct_chg``, and the panel fallback+lives only on the running engine). The rules now evaluate against the+composite's state through module-level helpers, with the sub-engine supplying+only market parameters.+"""++from __future__ import annotations++import numpy as np+import pandas as pd++from backtest.engines.china_a import ChinaAEngine+from backtest.engines.composite import CompositeEngine+from backtest.models import Position++CODES = ["600000.SH", "RELIANCE.NS"]+++def _composite(**overrides) -> CompositeEngine:+ config = {"initial_cash": 1_000_000, "codes": CODES, **overrides}+ return CompositeEngine(config, CODES)+++def _bar(open_: float, close: float, day: str) -> pd.Series:+ return pd.Series(+ {"open": open_, "high": max(open_, close), "low": min(open_, close), "close": close},+ name=pd.Timestamp(day),+ )+++def _hold(engine: CompositeEngine, symbol: str, entry_day: str) -> None:+ engine.positions[symbol] = Position(+ symbol=symbol,+ direction=1,+ entry_price=100.0,+ entry_time=pd.Timestamp(entry_day),+ size=100.0,+ leverage=1.0,+ )+++def _panel(engine: CompositeEngine, prev_close: float, bar_idx: int = 1) -> None:+ engine._close_arr = np.array([[prev_close, prev_close]])+ engine._code_to_col = {code: i for i, code in enumerate(CODES)}+ engine._bar_idx = bar_idx+++class TestIndiaT1InComposite:+ def test_same_day_sell_is_blocked(self) -> None:+ engine = _composite()+ engine._active_symbol = "RELIANCE.NS"+ _hold(engine, "RELIANCE.NS", entry_day="2026-03-03")+ _panel(engine, 100.0)+ # Open sits well inside the ±20% band, so only T+1 can block this.+ assert engine.can_execute("RELIANCE.NS", 0, _bar(101.0, 101.0, "2026-03-03")) is False++ def test_older_position_may_sell(self) -> None:+ engine = _composite()+ engine._active_symbol = "RELIANCE.NS"+ _hold(engine, "RELIANCE.NS", entry_day="2026-03-02")+ _panel(engine, 100.0)+ assert engine.can_execute("RELIANCE.NS", 0, _bar(101.0, 101.0, "2026-03-03")) is True+++class TestLimitBandInComposite:+ def test_limit_up_open_is_not_fillable(self) -> None:+ engine = _composite()+ engine._active_symbol = "600000.SH"+ _panel(engine, 90.0) # previous close 90 -> upper band 99.0 at ±10%+ # Open prints at the locked upper band; a buy fill would book above it.+ assert engine.can_execute("600000.SH", 1, _bar(99.2, 99.0, "2026-03-03")) is False++ def test_open_inside_band_is_fillable(self) -> None:+ engine = _composite()+ engine._active_symbol = "600000.SH"+ _panel(engine, 90.0)+ assert engine.can_execute("600000.SH", 1, _bar(95.0, 94.5, "2026-03-03")) is True+++class TestSingleMarketUnchanged:+ def test_china_a_single_market_still_blocks_same_day_sell(self) -> None:+ engine = ChinaAEngine({"initial_cash": 100_000})+ engine.positions["600000.SH"] = Position(+ symbol="600000.SH",+ direction=1,+ entry_price=100.0,+ entry_time=pd.Timestamp("2026-03-03"),+ size=100.0,+ leverage=1.0,+ )+ engine._close_arr = np.array([[90.0]])+ engine._code_to_col = {"600000.SH": 0}+ engine._bar_idx = 1+ assert engine.can_execute("600000.SH", 0, _bar(95.0, 95.0, "2026-03-03")) is False