Skip to content

"Vibe-Trading: Your Personal Trading Agent"

fix(correlation): normalize suffixed HK codes so the duplicate guard fires

cgycoreycbb25e4b7377
diff --git a/agent/backtest/correlation.py b/agent/backtest/correlation.py
index 5bd38eb6f..ae162ad81 100644
--- a/agent/backtest/correlation.py
+++ b/agent/backtest/correlation.py
@@ -120,6 +120,12 @@ def _normalize_symbol(code: str, market: str) -> str:
return f"{cleaned[:-4]}-USDT"
return cleaned
if re.search(r"\.(US|HK|SH|SZ|BJ|KS|KQ|NS|BO|TO|V|BA|L|VN|FX)$", cleaned):
+ # HK codes are zero-padded to four digits on the bare path below; the
+ # suffixed spelling must land on the same key, or the duplicate-asset
+ # guard misses one instrument written as `700` and `700.HK`.
+ hk = re.fullmatch(r"(\d{1,5})\.HK", cleaned)
+ if market == "hk_equity" and hk:
+ return f"{hk.group(1).zfill(4)}.HK"
return cleaned
upper = cleaned.upper()
if market == "us_equity":
diff --git a/agent/tests/test_analysis_reliability.py b/agent/tests/test_analysis_reliability.py
index e05131d62..fa7fe3df0 100644
--- a/agent/tests/test_analysis_reliability.py
+++ b/agent/tests/test_analysis_reliability.py
@@ -98,6 +98,29 @@ def test_duplicate_aliases_rejected_before_any_fetch(monkeypatch):
assert correlation._normalize_symbol("eur/usd", "forex") == "EURUSD=X"
+ "pair", [("700", "700.HK"), ("9988", "9988.HK"), ("00700", "00700.HK")]
+)
+def test_hk_spellings_of_one_instrument_are_rejected_as_duplicates(pair, monkeypatch):
+ """A bare HK code and its suffixed spelling must normalize to one key.
+
+ The bare path zero-pads to four digits while the suffixed spelling passed
+ through unchanged, so the duplicate guard missed the same instrument written
+ both ways and the endpoint returned a self-correlation, presented as a
+ cross-asset relationship.
+ """
+ fetch = Mock()
+ monkeypatch.setattr(correlation, "_fetch_price_series", fetch)
+ left, right = pair
+ market = correlation.infer_market(left)
+ assert correlation._normalize_symbol(left, market) == correlation._normalize_symbol(
+ right, market
+ )
+ with pytest.raises(ValueError, match="distinct"):
+ correlation.compute_correlation_analysis(list(pair))
+ fetch.assert_not_called()
+
+
def test_readiness_snapshots_and_single_asset_validation():
client = TestClient(api_server.app, client=("127.0.0.1", 50000))
assert client.get("/alpha/readiness").json()["universes"]["btc-usdt"]["ready"] is False