"Vibe-Trading: Your Personal Trading Agent"
Python ai-agentalgorithmic-tradingbacktestingfintechllmmcpmulti-agentpythonquantitative-financetrading
feat(backtest): report which China-futures products were priced on a default
Haozhe Wu306aca2c1351
diff --git a/agent/backtest/engines/base.py b/agent/backtest/engines/base.pyindex 94e1ae324..3c6589d48 100644--- a/agent/backtest/engines/base.py+++ b/agent/backtest/engines/base.py@@ -779,6 +779,20 @@ class BaseEngine(ABC):"unfilled_plan_rejections_by_symbol": by_symbol,}+ def _engine_diagnostics(self) -> Dict[str, Any]:+ """Per-engine facts about how this run was priced.++ Default empty. An engine overrides this to state something the metrics+ cannot be derived from — currently ChinaFuturesEngine reporting which+ products it priced on a generic default instead of a table entry+ (#1393), where the alternative is a number that looks like data.++ Returns:+ Extra keys merged into the metrics dict; empty when there is+ nothing to declare.+ """+ return {}+def _on_plan_rejected(self, symbol: str, reason: str, timestamp: pd.Timestamp) -> None:"""Observe a silently rejected opening-order plan.@@ -1005,6 +1019,7 @@ class BaseEngine(ABC):m["total_return"] - benchmark_metadata["benchmark_return"], 6)m.update(self._plan_rejection_metrics())+ m.update(self._engine_diagnostics())if self.rebalance_mask is not None:m["rebalance_mask"] = self.rebalance_maskm["rebalance_bars_executed"] = self.rebalance_bars_executeddiff --git a/agent/backtest/engines/china_futures.py b/agent/backtest/engines/china_futures.pyindex 2dc5b9b7e..9e7c8c2be 100644--- a/agent/backtest/engines/china_futures.py+++ b/agent/backtest/engines/china_futures.py@@ -12,13 +12,19 @@ Market rules (exchange-level, CFFEX / SHFE / DCE / ZCE / INE / GFEX):from __future__ import annotations+import loggingimport re+from typing import Any, Dict, Hashable, Mapping, TypeVarimport pandas as pdfrom backtest.engines.china_a import _blocked_by_limitfrom backtest.engines.futures_base import FuturesBaseEngine+logger = logging.getLogger(__name__)++_T = TypeVar("_T")+# ── Contract multiplier lookup ──@@ -107,6 +113,8 @@ _COMMISSION: dict[str, tuple[str, float]] = {"v": ("fixed", 1.0), "SA": ("fixed", 3.5), "FG": ("fixed", 3.0),}_DEFAULT_COMMISSION: tuple[str, float] = ("fixed", 5.0)+_DEFAULT_MULTIPLIER = 10+_DEFAULT_MARGIN_RATE = 0.10#: Upper-cased product code -> the spelling the tables above actually use.@@ -155,7 +163,14 @@ class ChinaFuturesEngine(FuturesBaseEngine):- commission_override: override commission for all products"""+ #: (product, field) -> the generic constant this run was priced on. A+ #: product missing from a table does not fail, it silently takes a default+ #: (#1393), so the run has to say which numbers were assumed rather than+ #: looked up. Recording, not changing: every number stays what it was.+ _pricing_defaults: Dict[tuple[str, str], Any]+def __init__(self, config: dict):+ self._pricing_defaults = {}# Derive leverage from margin rate of first code, or use config overridemargin_override = config.get("margin_rate_override")if margin_override:@@ -164,7 +179,7 @@ class ChinaFuturesEngine(FuturesBaseEngine):codes = config.get("codes", [])if codes:product = _extract_product(codes[0])- mr = _MARGIN_RATE.get(product, 0.10)+ mr = self._priced(_MARGIN_RATE, product, _DEFAULT_MARGIN_RATE, "margin_rate")leverage = 1.0 / mrelse:leverage = 10.0 # ~10% margin default@@ -176,6 +191,56 @@ class ChinaFuturesEngine(FuturesBaseEngine):self._margin_rate_override = margin_override if margin_override else Noneself._commission_override = config.get("commission_override")+ def _priced(+ self,+ table: Mapping[str, _T],+ product: str,+ default: _T,+ field: str,+ ) -> _T:+ """Look a product up, recording the miss when it falls back.++ A product absent from one of the tables is priced on a generic+ constant that looks exactly like data in the output. This returns the+ same value the plain ``table.get(product, default)`` returned before+ and additionally remembers the miss, so the run can state which of its+ numbers were assumed.++ Args:+ table: One of the product tables in this module.+ product: Product code as ``_extract_product`` spells it.+ default: The generic constant used when the product is absent.+ field: Name of the field, as reported in ``pricing_assumptions``.++ Returns:+ The table entry, or ``default`` when the product is not listed.+ """+ if product in table:+ return table[product]+ key = (product, field)+ if key not in self._pricing_defaults:+ self._pricing_defaults[key] = default+ logger.warning(+ "China futures product %r has no %s entry; pricing it on the "+ "generic default %r. The backtest reports this under "+ "pricing_assumptions.",+ product,+ field,+ default,+ )+ return default++ def _engine_diagnostics(self) -> Dict[str, Any]:+ """Report every table lookup this run priced on a generic default."""+ if not self._pricing_defaults:+ return {}+ return {+ "pricing_assumptions": [+ {"product": product, "field": field, "value": value}+ for (product, field), value in sorted(self._pricing_defaults.items())+ ]+ }+def can_execute(self, symbol: str, direction: int, bar: pd.Series) -> bool:"""China futures: T+0, both directions, price-limit enforced.@@ -192,7 +257,7 @@ class ChinaFuturesEngine(FuturesBaseEngine):# Price limit, tested at execution time (see _blocked_by_limit).product = _extract_product(symbol)- limit = _PRICE_LIMIT.get(product, _DEFAULT_PRICE_LIMIT)+ limit = self._priced(_PRICE_LIMIT, product, _DEFAULT_PRICE_LIMIT, "price_limit")pos = self.positions.get(symbol) if direction == 0 else Noneif pos is None and direction == 0:return True@@ -234,8 +299,12 @@ class ChinaFuturesEngine(FuturesBaseEngine):Commission in RMB."""product = _extract_product(symbol)- mode, value = _COMMISSION.get(product, _DEFAULT_COMMISSION)- cm = _MULTIPLIER.get(product, 10)+ mode, value = self._priced(+ _COMMISSION, product, _DEFAULT_COMMISSION, "commission"+ )+ cm = self._priced(+ _MULTIPLIER, product, _DEFAULT_MULTIPLIER, "contract_multiplier"+ )if mode == "rate":return size * price * cm * valuereturn size * value@@ -247,7 +316,9 @@ class ChinaFuturesEngine(FuturesBaseEngine):def get_contract_multiplier(self, symbol: str) -> float:"""Look up contract multiplier from product code."""product = _extract_product(symbol)- return float(_MULTIPLIER.get(product, 10))+ return float(+ self._priced(_MULTIPLIER, product, _DEFAULT_MULTIPLIER, "contract_multiplier")+ )def get_margin_rate(self, symbol: str) -> float:"""Look up exchange margin rate for a product.@@ -259,7 +330,7 @@ class ChinaFuturesEngine(FuturesBaseEngine):Margin rate (e.g. 0.10 for 10%)."""product = _extract_product(symbol)- return _MARGIN_RATE.get(product, 0.10)+ return self._priced(_MARGIN_RATE, product, _DEFAULT_MARGIN_RATE, "margin_rate")def _leverage_for_symbol(self, symbol: str) -> float:"""Derive leverage from this contract's own margin requirement."""diff --git a/agent/tests/test_china_futures_pricing_assumptions.py b/agent/tests/test_china_futures_pricing_assumptions.pynew file mode 100644index 000000000..c49696aaa--- /dev/null+++ b/agent/tests/test_china_futures_pricing_assumptions.py@@ -0,0 +1,172 @@+"""A China-futures run must say which numbers it assumed (#1393).++``china_futures.py`` keeps four product tables of different sizes. A product+listed in one and absent from another does not fail the run -- it silently+takes a generic constant (margin 0.10, commission ``("fixed", 5.0)``,+multiplier 10, price limit 0.05) that is indistinguishable from a real table+entry in the output. ``pg`` is the case #1389's own test used to prove its fix:+its multiplier is now correct and its margin rate is still the default, so the+same contract is half-looked-up and half-assumed.++The direction agreed on #1393 is to make the default observable rather than to+fill the tables, because filling them leaves the *next* added product silently+defaulting. Numbers are unchanged; the run now states which of them were+assumed.++The sharp case is ``rb``: its real margin rate IS 0.10, the same number as the+default. A report that cannot tell "looked up 0.10" from "assumed 0.10" would+be worthless, so that discrimination is asserted directly.+"""++from __future__ import annotations++import logging++import pytest++from backtest.engines.china_futures import (+ _COMMISSION,+ _DEFAULT_COMMISSION,+ _DEFAULT_MARGIN_RATE,+ _DEFAULT_MULTIPLIER,+ _MARGIN_RATE,+ _MULTIPLIER,+ ChinaFuturesEngine,+)+++def _engine(*codes: str) -> ChinaFuturesEngine:+ return ChinaFuturesEngine({"codes": list(codes), "initial_capital": 1_000_000})+++def _assumptions(engine: ChinaFuturesEngine) -> dict[tuple[str, str], object]:+ reported = engine._engine_diagnostics().get("pricing_assumptions", [])+ return {(row["product"], row["field"]): row["value"] for row in reported}+++class TestPricingAssumptionsAreReported:+ def test_a_product_missing_from_a_table_is_reported(self) -> None:+ engine = _engine("pg2412.DCE")+ engine.get_margin_rate("pg2412.DCE")+ engine.calc_commission_for_symbol("pg2412.DCE", 1, 4000.0, True)++ assumed = _assumptions(engine)+ assert assumed[("pg", "margin_rate")] == _DEFAULT_MARGIN_RATE+ assert assumed[("pg", "commission")] == _DEFAULT_COMMISSION++ def test_the_value_the_run_used_is_unchanged(self) -> None:+ """Observability only: every number stays exactly what it was."""+ engine = _engine("pg2412.DCE")+ assert engine.get_margin_rate("pg2412.DCE") == _DEFAULT_MARGIN_RATE+ assert engine.get_contract_multiplier("pg2412.DCE") == float(+ _MULTIPLIER["pg"]+ )+ assert engine.calc_commission_for_symbol("pg2412.DCE", 2, 4000.0, True) == 10.0++ def test_a_real_entry_equal_to_the_default_is_not_reported(self) -> None:+ """``rb``'s looked-up margin is 0.10 -- the default's own value."""+ assert _MARGIN_RATE["rb"] == _DEFAULT_MARGIN_RATE+ engine = _engine("rb2410.SHFE")+ assert engine.get_margin_rate("rb2410.SHFE") == _DEFAULT_MARGIN_RATE++ assert ("rb", "margin_rate") not in _assumptions(engine)++ def test_a_fully_covered_run_declares_nothing(self) -> None:+ engine = _engine("IF2406.CFFEX")+ engine.get_margin_rate("IF2406.CFFEX")+ engine.get_contract_multiplier("IF2406.CFFEX")+ engine.calc_commission_for_symbol("IF2406.CFFEX", 1, 3800.0, True)++ assert engine._engine_diagnostics() == {}++ def test_pg_is_the_half_real_contract_the_issue_names(self) -> None:+ """#1389 fixed pg's multiplier; its margin rate is still assumed."""+ assert "pg" in _MULTIPLIER and _MULTIPLIER["pg"] != _DEFAULT_MULTIPLIER+ assert "pg" not in _MARGIN_RATE+ assert "pg" not in _COMMISSION++ engine = _engine("pg2412.DCE")+ engine.get_contract_multiplier("pg2412.DCE")+ engine.get_margin_rate("pg2412.DCE")++ assumed = _assumptions(engine)+ assert ("pg", "contract_multiplier") not in assumed+ assert ("pg", "margin_rate") in assumed++ def test_the_warning_fires_once_per_field_not_once_per_bar(+ self, caplog: pytest.LogCaptureFixture+ ) -> None:+ engine = _engine("pg2412.DCE")+ with caplog.at_level(logging.WARNING, logger="backtest.engines.china_futures"):+ for _ in range(50):+ engine.get_margin_rate("pg2412.DCE")++ margin_warnings = [+ record+ for record in caplog.records+ if "margin_rate" in record.getMessage()+ ]+ assert len(margin_warnings) == 1+ assert "pg" in margin_warnings[0].getMessage()++ def test_leverage_derived_at_construction_is_also_reported(self) -> None:+ """__init__ prices leverage off codes[0] before any bar is seen."""+ engine = _engine("pg2412.DCE")++ assert ("pg", "margin_rate") in _assumptions(engine)+ assert engine._leverage_for_symbol("pg2412.DCE") == 1.0 / _DEFAULT_MARGIN_RATE+++class TestDiagnosticsSeam:+ def test_base_engine_declares_nothing_by_default(self) -> None:+ from backtest.engines.china_a import ChinaAEngine++ assert ChinaAEngine({"initial_capital": 1_000_000})._engine_diagnostics() == {}++ def test_the_report_reaches_the_run_metrics_not_just_the_hook(+ self, tmp_path+ ) -> None:+ """A hook nobody merges into the result is the failure this guards."""+ import numpy as np+ import pandas as pd++ index = pd.date_range("2026-01-01", periods=60, freq="D")+ prices = np.linspace(4000.0, 4400.0, 60)+ frame = pd.DataFrame(+ {+ "open": prices,+ "high": prices * 1.01,+ "low": prices * 0.99,+ "close": prices,+ "volume": 1e5,+ "pre_settle": np.r_[prices[0], prices[:-1]],+ },+ index=index,+ )++ class _Loader:+ def fetch(self, *args, **kwargs):+ return {"pg2412.DCE": frame}++ class _Signals:+ def generate(self, data_map):+ return {"pg2412.DCE": pd.Series(1.0, index=index)}++ config = {+ "codes": ["pg2412.DCE"],+ "initial_capital": 1_000_000,+ "start_date": "2026-01-01",+ "end_date": "2026-03-01",+ }+ result = ChinaFuturesEngine(config).run_backtest(+ config, _Loader(), _Signals(), tmp_path+ )++ metrics = result.get("metrics", result)+ reported = {+ (row["product"], row["field"]) for row in metrics["pricing_assumptions"]+ }+ assert ("pg", "margin_rate") in reported+ assert ("pg", "commission") in reported+ # pg's multiplier is a real table entry (#1389), so it is not assumed.+ assert ("pg", "contract_multiplier") not in reported