Skip to content

"Vibe-Trading: Your Personal Trading Agent"

fix(backtest): fold china futures product casing at extraction, not per lookup

Haozhe Wu8a88cc98e1eb
diff --git a/agent/backtest/engines/china_futures.py b/agent/backtest/engines/china_futures.py
index dfa4a255c..2dc5b9b7e 100644
--- a/agent/backtest/engines/china_futures.py
+++ b/agent/backtest/engines/china_futures.py
@@ -109,44 +109,41 @@ _COMMISSION: dict[str, tuple[str, float]] = {
_DEFAULT_COMMISSION: tuple[str, float] = ("fixed", 5.0)
+#: Upper-cased product code -> the spelling the tables above actually use.
+#: CFFEX/ZCE products are keyed uppercase (IF, CF) and SHFE/DCE/INE/GFEX
+#: lowercase (au, rb), but a real ts_code is uppercase on every exchange
+#: (CU2406.SHFE) and ``_is_china_futures`` already routes either casing here.
+#: Folding once at extraction keeps every table lookup below case-blind; no
+#: two products collide when upper-cased (asserted in the tests).
+_CANONICAL_PRODUCT: dict[str, str] = {
+ key.upper(): key
+ for table in (_MULTIPLIER, _MARGIN_RATE, _PRICE_LIMIT, _COMMISSION)
+ for key in table
+}
+
+
def _extract_product(symbol: str) -> str:
"""Extract product code from futures symbol.
+ The returned code is the one the product tables are keyed by, whatever
+ casing the caller used: 'AU2412.SHFE' and 'au2412' both yield 'au'.
+
Examples:
'IF2406.CFFEX' -> 'IF'
'rb2410.SHFE' -> 'rb'
- 'au2412' -> 'au'
+ 'AU2412.SHFE' -> 'au'
Args:
symbol: Futures symbol string.
Returns:
- Product code (e.g. 'IF', 'rb', 'au').
+ Product code as spelled in the tables (e.g. 'IF', 'rb', 'au'), or
+ the raw letters when the product is not listed.
"""
code = symbol.split(".")[0]
m = re.match(r"([A-Za-z]+)", code)
- return m.group(1) if m else code
-
-
-def _ci_lookup(table: dict, product: str, default):
- """Case-insensitive product lookup.
-
- The tables above key CFFEX/ZCE products uppercase (IF, CF) and
- SHFE/DCE/INE/GFEX products lowercase (au, rb) — but this project's
- own documented symbol convention and Tushare's real ts_code values
- (data-routing/SKILL.md: CU2406.SHFE; tushare 日线行情.md: CU1811.SHF)
- use uppercase product codes across every exchange. A caller that
- follows that convention for a SHFE/DCE/INE/GFEX product would
- otherwise miss the table entirely and silently fall back to the
- generic default.
- """
- if product in table:
- return table[product]
- if product.lower() in table:
- return table[product.lower()]
- if product.upper() in table:
- return table[product.upper()]
- return default
+ product = m.group(1) if m else code
+ return _CANONICAL_PRODUCT.get(product.upper(), product)
class ChinaFuturesEngine(FuturesBaseEngine):
@@ -167,7 +164,7 @@ class ChinaFuturesEngine(FuturesBaseEngine):
codes = config.get("codes", [])
if codes:
product = _extract_product(codes[0])
- mr = _ci_lookup(_MARGIN_RATE, product, 0.10)
+ mr = _MARGIN_RATE.get(product, 0.10)
leverage = 1.0 / mr
else:
leverage = 10.0 # ~10% margin default
@@ -195,7 +192,7 @@ class ChinaFuturesEngine(FuturesBaseEngine):
# Price limit, tested at execution time (see _blocked_by_limit).
product = _extract_product(symbol)
- limit = _ci_lookup(_PRICE_LIMIT, product, _DEFAULT_PRICE_LIMIT)
+ limit = _PRICE_LIMIT.get(product, _DEFAULT_PRICE_LIMIT)
pos = self.positions.get(symbol) if direction == 0 else None
if pos is None and direction == 0:
return True
@@ -237,8 +234,8 @@ class ChinaFuturesEngine(FuturesBaseEngine):
Commission in RMB.
"""
product = _extract_product(symbol)
- mode, value = _ci_lookup(_COMMISSION, product, _DEFAULT_COMMISSION)
- cm = _ci_lookup(_MULTIPLIER, product, 10)
+ mode, value = _COMMISSION.get(product, _DEFAULT_COMMISSION)
+ cm = _MULTIPLIER.get(product, 10)
if mode == "rate":
return size * price * cm * value
return size * value
@@ -250,7 +247,7 @@ class ChinaFuturesEngine(FuturesBaseEngine):
def get_contract_multiplier(self, symbol: str) -> float:
"""Look up contract multiplier from product code."""
product = _extract_product(symbol)
- return float(_ci_lookup(_MULTIPLIER, product, 10))
+ return float(_MULTIPLIER.get(product, 10))
def get_margin_rate(self, symbol: str) -> float:
"""Look up exchange margin rate for a product.
@@ -262,7 +259,7 @@ class ChinaFuturesEngine(FuturesBaseEngine):
Margin rate (e.g. 0.10 for 10%).
"""
product = _extract_product(symbol)
- return _ci_lookup(_MARGIN_RATE, product, 0.10)
+ return _MARGIN_RATE.get(product, 0.10)
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_engine.py b/agent/tests/test_china_futures_engine.py
index 81c8683be..baf454996 100644
--- a/agent/tests/test_china_futures_engine.py
+++ b/agent/tests/test_china_futures_engine.py
@@ -250,6 +250,44 @@ class TestMarginRate:
assert engine.get_margin_rate("XX9999.SHFE") == 0.10
+# ---------------------------------------------------------------------------
+# Product-key casing: every table lookup keys off _extract_product, so the
+# fold lives there and these tests guard the invariant that makes it safe
+# ---------------------------------------------------------------------------
+
+
+class TestProductKeyCasing:
+ def test_extract_folds_to_the_table_spelling(self) -> None:
+ """A symbol reaches the tables in their own spelling, either casing in."""
+ assert _extract_product("AU2412.SHFE") == "au"
+ assert _extract_product("au2412.SHFE") == "au"
+ assert _extract_product("if2406.CFFEX") == "IF"
+ assert _extract_product("IF2406.CFFEX") == "IF"
+
+ def test_unlisted_product_keeps_its_own_letters(self) -> None:
+ """An unknown product still falls through to the generic defaults."""
+ assert _extract_product("XX9999.SHFE") == "XX"
+
+ def test_no_product_collides_when_case_folded(self) -> None:
+ """Folding is only safe while no two keys in a table share an
+ upper-cased spelling; a future 'ao' beside an existing 'AO' would
+ silently merge two different products into one."""
+ for table in (_MULTIPLIER, _MARGIN_RATE, _PRICE_LIMIT, _COMMISSION):
+ folded: dict[str, str] = {}
+ for key in table:
+ first = folded.setdefault(key.upper(), key)
+ assert first == key, f"{first!r} and {key!r} fold together"
+
+ def test_tables_agree_on_how_a_product_is_spelled(self) -> None:
+ """One product, one spelling across all four tables — otherwise the
+ canonical map would send a lookup to the wrong casing."""
+ spelling: dict[str, str] = {}
+ for table in (_MULTIPLIER, _MARGIN_RATE, _PRICE_LIMIT, _COMMISSION):
+ for key in table:
+ first = spelling.setdefault(key.upper(), key)
+ assert first == key, f"product spelled {first!r} and {key!r}"
+
+
# ---------------------------------------------------------------------------
# Case-insensitive product lookup (this project's documented symbol
# convention, and Tushare's real ts_code values, use uppercase product