"Vibe-Trading: Your Personal Trading Agent"
Python ai-agentalgorithmic-tradingbacktestingfintechllmmcpmulti-agentpythonquantitative-financetrading
Fixed source data
Will Liaoe42c44217075
diff --git a/agent/src/agent/grounding.py b/agent/src/agent/grounding.pyindex 1e6e378df..11ef38651 100644--- a/agent/src/agent/grounding.py+++ b/agent/src/agent/grounding.py@@ -409,12 +409,53 @@ def _price_field_for_path(path: str) -> str | None:return _GENERIC_PRICE_FIELD_ALIASES.get(leaf)+# Trading-plan file stems encode the ticker with ``.``, ``_``, or ``-``+# standing in for the dot: ``als.to-trading-plan...``, ``tf_to-trading-plan...``+# (base has no hyphen), ``btcx-b-to-trading-plan...`` (base is itself+# hyphenated) and ``gldc_v-Weekly...``. The stem's leading token is the+# ticker and it is always terminated by the ``-Weekly`` / ``-trading-plan``+# descriptor, so English prose ending in ``-to`` (``ready-to-go``,+# ``go_to school``) can never be misread as a ticker.+_TRADING_PLAN_TICKER_RE = re.compile(+ r"(?<![A-Za-z0-9])([A-Z0-9][A-Z0-9.\-]*?)[._-](TO|V)"+ r"(?=[\-_ ]Weekly|[\-_ ]trading[\-_ ]plan)",+ re.IGNORECASE,+)+++def _is_path_like(text: str) -> bool:+ """Return whether *text* looks like it contains a file path."""+ return "/" in text or "\\" in text+++def _trading_plan_tickers(text: str) -> set[str]:+ """Expand trading-plan file stems to canonical symbols.++ ``als.to-trading-plan...``, ``tf_to-trading-plan...``,+ ``btcx-b-to-trading-plan...`` and ``gldc_v-Weekly...`` all yield the+ canonical ticker (``ALS.TO``, ``TF.TO``, ``BTCX-B.TO``, ``GLDC.V``).+ Guarded to path-like text and the ``-Weekly``/``-trading-plan`` descriptor+ so English prose ending in ``-to`` is never read as a ticker.+ """+ blob = text or ""+ if not _is_path_like(blob):+ return set()+ found: set[str] = set()+ for match in _TRADING_PLAN_TICKER_RE.finditer(blob):+ base = match.group(1).upper()+ suffix = match.group(2).upper()+ found.add(f"{base}.{suffix}")+ return found++def _scan_symbols(text: str) -> set[str]:"""Return the canonical symbols written anywhere in a blob of text."""- return {+ found = {_normalize_symbol(match.group(0))for match in _CANONICAL_SYMBOL_RE.finditer(text or "")}+ found.update(_trading_plan_tickers(text))+ return founddef _infer_venue(symbol: str) -> str | None:@@ -937,8 +978,7 @@ class GroundingLedger:def _seed_symbols(self, text: str, *, source: str) -> None:"""Lock exact symbols explicitly supplied by a user."""- for match in _CANONICAL_SYMBOL_RE.finditer(text or ""):- symbol = _normalize_symbol(match.group(0))+ for symbol in sorted(_scan_symbols(text)):key = f"explicit:{symbol}"existing = self._identities.get(key)version = existing.version + 1 if existing else 1@@ -1028,6 +1068,35 @@ class GroundingLedger:chosen = self._choose_candidate(query, candidates)if chosen is None:+ # A loose/bare search that came back ambiguous must not demote an+ # already-locked identity. When the candidate list contains the+ # symbol of an existing lock (bare "GLDC" returning GLDC.V among+ # other global GLDC-* instruments while GLDC.V is already locked),+ # the shortlist is answered by that lock: record it as superseded+ # so the aggregate stays "locked" and already-authorized market+ # tools are not blocked for the rest of the run.+ locked_matches = sorted(+ {+ record.symbol+ for record in self._identities.values()+ if record.status == "locked"+ and record.symbol+ and any(+ _normalize_symbol(candidate.get("symbol")) == record.symbol+ for candidate in candidates+ )+ }+ )+ if len(locked_matches) == 1:+ self._supersede_shortlists(locked_matches[0])+ self._identities[key] = IdentityRecord(+ query=query,+ status="superseded",+ source_tool_call_id=call_id,+ candidates=candidates,+ version=version,+ )+ returnself._identities[key] = IdentityRecord(query=query,status="ambiguous",diff --git a/agent/tests/test_agent_grounding.py b/agent/tests/test_agent_grounding.pyindex 3a9a164c1..374ed204b 100644--- a/agent/tests/test_agent_grounding.py+++ b/agent/tests/test_agent_grounding.py@@ -518,6 +518,143 @@ def test_canadian_symbols_are_canonical_and_venue_currency_aware() -> None:assert _infer_currency("SHOP.V") == "CAD"+def test_underscore_ticker_in_plan_path_seeds_locked_identity(+ tmp_path: Path,+) -> None:+ """A plan-file path like gldc_v-Weekly-...md must lock GLDC.V."""+ ledger = GroundingLedger(+ run_dir=tmp_path,+ user_message=(+ "Please update C:\\vibe-trading\\vibe-trading-history\\TSX\\2026\\08\\"+ "gldc_v-Weekly-2026-08-03.md"+ ),+ )++ assert ledger.authorized_symbols == {"GLDC.V"}+ authorization = ledger.authorize_tool_call(+ "get_market_data",+ {"codes": ["GLDC.V"]},+ batch_authorized_symbols=ledger.authorized_symbols,+ call_id="prices",+ )+ assert authorization.allowed is True+++def test_trading_plan_ticker_scan_and_prose_guard() -> None:+ """Trading-plan stems scan to canonical symbols; prose is not misread."""+ from src.agent.grounding import _scan_symbols++ # Underscore separator.+ assert _scan_symbols(+ "C:\\vibe-trading\\vibe-trading-history\\TSX\\2026\\07\\"+ "tf_to-trading-plan-2026-07-16-to-24.md"+ ) == {"TF.TO"}+ assert "GLDC.V" in _scan_symbols(+ "C:\\vibe-trading\\vibe-trading-history\\TSX\\2026\\08\\"+ "gldc_v-Weekly-2026-08-03.md"+ )+ assert "SGML.V" in _scan_symbols(+ "C:\\vibe-trading\\vibe-trading-history\\TSX\\2026\\08\\"+ "SGML_V-Weekly-2026-08-03.md"+ )+ # Hyphen separator, including a base that is itself hyphenated (BTCX-B).+ assert _scan_symbols(+ "C:\\vibe-trading\\vibe-trading-history\\TSX\\2026\\07\\"+ "btcx-b-to-trading-plan-2026-07-13-to-17.md"+ ) == {"BTCX-B.TO"}+ assert _scan_symbols(+ "C:\\vibe-trading\\vibe-trading-history\\TSX\\2026\\07\\"+ "aapl-to-trading-plan-2026-07-06-to-10.md"+ ) == {"AAPL.TO"}+ assert "HIVE.TO" in _scan_symbols(+ "C:\\vibe-trading\\vibe-trading-history\\TSX\\2026\\06\\"+ "hive-to-trading-plan-2026-july-to-august.md"+ )+ # Dot separator (also handled by the canonical regex) stays consistent.+ assert "BTCX-B.TO" in _scan_symbols(+ "C:\\vibe-trading\\vibe-trading-history\\TSX\\2026\\07\\"+ "btcx-b.to-trading-plan-2026-07-20-to-24.md"+ )+ # English prose ending in -to/-v must not become phantom tickers, even+ # when the message carries a path elsewhere (no -Weekly/-trading-plan+ # descriptor follows the suffix).+ assert (+ _scan_symbols("go_to school ready_to-go back_to basics C:\\x\\note.md")+ == set()+ )+++def test_locked_symbol_survives_a_later_bare_ambiguous_search(+ tmp_path: Path,+) -> None:+ """Bare 'GLDC' ambiguity must not demote an already-locked GLDC.V."""+ ledger = GroundingLedger(+ run_dir=tmp_path,+ user_message="请分析 GLDC.V 的当前价格",+ )+ candidates = [+ {"symbol": "GLDCO2.SW", "name": "UBSETF Carbon Compens Gold ETF", "source": "yahoo"},+ {"symbol": "GLDCX", "name": "Gabelli Gold Fund Class C", "source": "yahoo"},+ {"symbol": "GLDC.V", "name": "CASSIAR GOLD CORP", "source": "yahoo"},+ {"symbol": "GLDC.BA", "name": "SPDR GOLD TRUST GDR", "source": "yahoo"},+ ]+ ledger.ingest_tool_result(+ tool_name="search_symbol",+ arguments={"query": "GLDC"},+ result=_resolver_payload(candidates=candidates, query="GLDC"),+ call_id="bare-search",+ success=True,+ )++ assert ledger.identity_status == "locked"+ assert ledger.authorized_symbols == {"GLDC.V"}+ authorization = ledger.authorize_tool_call(+ "get_market_data",+ {"codes": ["GLDC.V"]},+ batch_authorized_symbols=ledger.authorized_symbols,+ batch_identity_status=ledger.identity_status,+ call_id="prices",+ )+ assert authorization.allowed is True+++def test_plan_path_symbol_survives_bare_search_end_to_end(+ tmp_path: Path,+) -> None:+ """End-to-end: a gldc_v plan path locks GLDC.V; bare GLDC can't demote it."""+ ledger = GroundingLedger(+ run_dir=tmp_path,+ user_message=(+ "Please update C:\\vibe-trading\\vibe-trading-history\\TSX\\2026\\08\\"+ "gldc_v-Weekly-2026-08-03.md"+ ),+ )+ assert ledger.authorized_symbols == {"GLDC.V"}+ candidates = [+ {"symbol": "GLDCO2.SW", "name": "UBSETF Carbon Compens Gold ETF", "source": "yahoo"},+ {"symbol": "GLDCX", "name": "Gabelli Gold Fund Class C", "source": "yahoo"},+ {"symbol": "GLDC.V", "name": "CASSIAR GOLD CORP", "source": "yahoo"},+ {"symbol": "GLDC.BA", "name": "SPDR GOLD TRUST GDR", "source": "yahoo"},+ ]+ ledger.ingest_tool_result(+ tool_name="search_symbol",+ arguments={"query": "GLDC"},+ result=_resolver_payload(candidates=candidates, query="GLDC"),+ call_id="bare-search",+ success=True,+ )++ assert ledger.identity_status == "locked"+ authorization = ledger.authorize_tool_call(+ "get_market_data",+ {"codes": ["GLDC.V"]},+ batch_authorized_symbols=ledger.authorized_symbols,+ batch_identity_status=ledger.identity_status,+ call_id="prices",+ )+ assert authorization.allowed is True++def test_listed_identity_blocks_private_company_workflow(tmp_path: Path,) -> None: