"Vibe-Trading: Your Personal Trading Agent"
Python ai-agentalgorithmic-tradingbacktestingfintechllmmcpmulti-agentpythonquantitative-financetrading
fix(portfolio): read Futu market-prefixed codes in the risk x-ray and holdings merge
Rudy Celekli2ff0cc447b09
diff --git a/agent/src/portfolio/service.py b/agent/src/portfolio/service.pyindex b52a99d0f..10711a376 100644--- a/agent/src/portfolio/service.py+++ b/agent/src/portfolio/service.py@@ -48,6 +48,25 @@ _RISK_XRAY_MAX_SYMBOLS = 50PORTFOLIO_VALUATION_VERSION = 3_LOADER_MARKET_SUFFIXES = frozenset({"US", "HK", "SZ", "SH", "BJ", "KS", "KQ", "NS", "BO", "TO", "V"})_NON_EQUITY_ASSET_TYPES = frozenset({"crypto", "stablecoin", "cash"})+# Futu reports codes market-first (``HK.00700``, ``US.AAPL``); the rest of the+# portfolio layer and the loaders use the suffix form (``00700.HK``).+_PREFIX_MARKETS = ("US", "HK", "SH", "SZ", "BJ")+++def _suffix_form(symbol: str) -> str:+ """Rewrite a market-prefixed code (``HK.00700``) to suffix form (``00700.HK``).++ Args:+ symbol: Upper-cased connector symbol.++ Returns:+ The suffix-form symbol, or ``symbol`` unchanged when it carries no+ market prefix.+ """+ prefix, dot, code = symbol.partition(".")+ if dot and prefix in _PREFIX_MARKETS and code:+ return f"{code}.{prefix}"+ return symbol_AUTH_REQUIRED_MARKERS = (@@ -753,7 +772,7 @@ class PortfolioService:"""if position.get("instrument_id_kind") or position.get("source_kind") == "extraetf":return None # An ISIN or exported pair is not an observed listing/venue.- symbol = str(position.get("symbol") or "").strip().upper()+ symbol = _suffix_form(str(position.get("symbol") or "").strip().upper())if not symbol:return Nonehead, _, suffix = symbol.rpartition(".")@@ -820,7 +839,7 @@ class PortfolioService:"""grouped: dict[str, dict[str, Any]] = {}for row in positions:- symbol = str(row.get("symbol") or "").upper()+ symbol = _suffix_form(str(row.get("symbol") or "").upper())currency = str(row.get("currency") or "").upper()market = str(row.get("market") or "").upper()if symbol.endswith(".US"):diff --git a/agent/tests/test_portfolio_futu_prefixed_codes.py b/agent/tests/test_portfolio_futu_prefixed_codes.pynew file mode 100644index 000000000..ba4622b93--- /dev/null+++ b/agent/tests/test_portfolio_futu_prefixed_codes.py@@ -0,0 +1,45 @@+"""Futu's market-prefixed codes must reach the risk x-ray and merge across brokers."""++from __future__ import annotations++from src.portfolio.normalization import normalize_position+from src.portfolio.service import PortfolioService+++def _futu(code: str, market: str, currency: str) -> dict:+ position = normalize_position(+ "futu",+ {"code": code, "qty": 10, "market_val": 1000, "average_cost": 90,+ "market": market, "currency": currency},+ )+ position.update(priced=True, market_value_usd=1000, broker="futu")+ return position+++def test_futu_prefixed_codes_are_risk_xray_symbols() -> None:+ args = PortfolioService._risk_xray_args(+ [_futu("HK.00700", "HK", "HKD"), _futu("US.AAPL", "US", "USD")]+ )+ assert sorted(args["symbols"]) == ["00700.HK", "AAPL.US"]+++def test_futu_and_suffix_form_holdings_merge() -> None:+ longbridge = {"symbol": "700.HK", "currency": "HKD", "market": "HK", "broker": "longbridge",+ "asset_type": "stock", "market_value_usd": 500}+ ibkr = {"symbol": "AAPL", "currency": "USD", "market": "US", "broker": "ibkr",+ "asset_type": "stock", "market_value_usd": 300}+ rows = PortfolioService._combine_holdings(+ [_futu("HK.00700", "HK", "HKD"), longbridge, _futu("US.AAPL", "US", "USD"), ibkr]+ )+ by_id = {row["canonical_id"]: row for row in rows}+ assert set(by_id) == {"HK:700", "US:AAPL"}+ assert by_id["HK:700"]["duplicate_across_brokers"] is True+ assert by_id["HK:700"]["brokers"] == ["futu", "longbridge"]+ assert by_id["US:AAPL"]["brokers"] == ["futu", "ibkr"]++++def test_suffix_form_symbols_still_route_to_the_risk_xray() -> None:+ position = {"symbol": "700.HK", "currency": "HKD", "market": "HK", "priced": True,+ "market_value_usd": 1000, "asset_type": "stock"}+ assert PortfolioService._risk_xray_symbol(position) == "700.HK"