Skip to content

"Vibe-Trading: Your Personal Trading Agent"

fix(margin-trading): extract 6-digit code for prefix-style A-share symbols in _extract_code (#930)

Santh2e21ad98ff2a
diff --git a/agent/src/tools/margin_trading_tool.py b/agent/src/tools/margin_trading_tool.py
index 464fa8dc2..f806bf9a0 100644
--- a/agent/src/tools/margin_trading_tool.py
+++ b/agent/src/tools/margin_trading_tool.py
@@ -62,14 +62,13 @@ def _extract_code(symbol: str) -> str | None:
if not symbol:
return None
token = symbol.strip().upper()
- if "." in token:
- token = token.rpartition(".")[0]
- for prefix in ("SH", "SZ", "BJ"):
- if token.startswith(prefix):
- token = token[len(prefix) :]
- token = token.strip()
- if len(token) == 6 and token.isdigit():
- return token
+ parts = [p.strip() for p in token.split(".") if p.strip()]
+ for part in parts:
+ for prefix in ("SH", "SZ", "BJ"):
+ if part.startswith(prefix):
+ part = part[len(prefix):]
+ if len(part) == 6 and part.isdigit():
+ return part
return None
diff --git a/agent/tests/test_margin_trading_prefix_symbol.py b/agent/tests/test_margin_trading_prefix_symbol.py
new file mode 100644
index 000000000..e2c565163
--- /dev/null
+++ b/agent/tests/test_margin_trading_prefix_symbol.py
@@ -0,0 +1,20 @@
+"""Regression test for _extract_code handling prefix-style A-share symbols in margin_trading_tool.
+
+Locks out a bug where _extract_code returned None for prefix-style symbols like
+"sh.600519" or "sz.000001" because token.rpartition(".")[0] extracted the prefix part before the dot.
+"""
+
+from src.tools.margin_trading_tool import _extract_code
+
+
+def test_extract_code_supports_prefix_style_symbols():
+ """Prove that _extract_code extracts bare 6-digit codes from both suffix and prefix style A-share symbols."""
+ # Suffix style
+ assert _extract_code("600519.SH") == "600519"
+ assert _extract_code("000001.SZ") == "000001"
+ assert _extract_code("600519") == "600519"
+
+ # Prefix style (previously returned None on un-fixed code)
+ assert _extract_code("sh.600519") == "600519"
+ assert _extract_code("sz.000001") == "000001"
+ assert _extract_code("SH.600519") == "600519"