"Vibe-Trading: Your Personal Trading Agent"
Python ai-agentalgorithmic-tradingbacktestingfintechllmmcpmulti-agentpythonquantitative-financetrading
Enforce currency identity in financial figure grounding
Josh Felland956ece87e489
diff --git a/agent/src/agent/grounding/evidence.py b/agent/src/agent/grounding/evidence.pyindex a5a509d65..d49bf9fe9 100644--- a/agent/src/agent/grounding/evidence.py+++ b/agent/src/agent/grounding/evidence.py@@ -668,7 +668,14 @@ def _is_price_kind(record: EvidenceRecord) -> bool:amount/turnover leaves."""return (- record.field in _PRICE_FIELDS+ (+ record.tool == "get_sec_filings"+ and record.source == "sec_edgar"+ and record.field.startswith("data.metric.points[")+ and record.field.endswith("].val")+ and record.currency is not None+ )+ or record.field in _PRICE_FIELDSor _price_field_for_path(record.field) is not Noneor _is_registered_price_indicator(record.tool, record.field)or _leaf_name(record.field) in _AMOUNT_FIELDS@@ -1236,7 +1243,29 @@ class _EvidenceMixin:field=path or "value",value=value,status="observed",- currency=_infer_currency(symbol or ""),+ currency=(+ (+ payload["data"]["metric"]["unit"].upper()+ if (+ isinstance(payload["data"]["metric"].get("unit"), str)+ and payload["data"]["metric"]["unit"].upper()+ in {+ "USD", "JPY", "EUR", "GBP", "CNY",+ "CAD", "AUD", "HKD", "KRW", "INR",+ "SGD", "TWD", "CHF", "NZD",+ }+ )+ else None+ )+ if (+ tool_name == "get_sec_filings"+ and path.startswith("data.metric.points[")+ and path.endswith("].val")+ and isinstance(payload.get("data"), dict)+ and isinstance(payload["data"].get("metric"), dict)+ )+ else _infer_currency(symbol or "")+ ),venue=_infer_venue(symbol or ""),))diff --git a/agent/src/agent/grounding/figures.py b/agent/src/agent/grounding/figures.pyindex dda43eb05..723a19203 100644--- a/agent/src/agent/grounding/figures.py+++ b/agent/src/agent/grounding/figures.py@@ -209,6 +209,8 @@ class Figure:scale: float = 1.0# A currency mark or ISO code touches the digits ("$2050", "0.95 元").currency: bool = False+ # Unambiguous ISO currency identity; None for ambiguous or absent markers.+ currency_code: str | None = Nonedigits: str = ""sign: str = ""# The span a redaction replaces: the figure plus its glued currency and@@ -874,6 +876,43 @@ def _currency_after(text: str, end: int) -> bool:return code.upper() in _CURRENCY_CODES+def _currency_code_for_figure(text: str, start: int, end: int) -> str | None:+ """Identify an unambiguous currency immediately adjacent to a number."""+ head = text[:start].rstrip()+ tail = text[end:].lstrip()++ # Explicit ISO currency codes take precedence.+ prefix = _code_before(head)+ if prefix:+ return {"CNH": "CNY", "RMB": "CNY"}.get(prefix, prefix)++ suffix = ""+ for char in tail:+ if not char.isascii() or not char.isalpha():+ break+ suffix += char++ if suffix.upper() in _CURRENCY_CODES:+ code = suffix.upper()+ return {"CNH": "CNY", "RMB": "CNY"}.get(code, code)++ # Only unambiguous symbols and words can establish currency identity.+ if head.endswith("€") or tail.startswith("€"):+ return "EUR"+ if head.endswith("£") or tail.startswith("£"):+ return "GBP"+ if tail.startswith("人民币"):+ return "CNY"+ if tail.startswith("美元"):+ return "USD"+ if tail.startswith("円"):+ return "JPY"+ if tail.startswith("원"):+ return "KRW"++ return None++def magnitude_suffix(text: str, end: int) -> tuple[float, int]:"""The magnitude mark glued to the right of a figure, if any.@@ -1096,6 +1135,7 @@ def scan_figures(content: str, block: FiguresBlock) -> list[Figure]:row, position = (cell[2], cell[3]) if cell else (None, None)structural = row is not None and position in (row.date_column, row.symbol_column)currency = _currency_before(text, token.start) or _currency_after(text, token.end)+ currency_code = _currency_code_for_figure(text, token.start, token.end)marked = percent or currency or "." in token.digits or token.grouped# A cell that also holds a word is prose set in a table: its plain# integer is a count or a horizon, as it would be in a sentence (#1471).@@ -1139,6 +1179,7 @@ def scan_figures(content: str, block: FiguresBlock) -> list[Figure]:symbol=symbol_value,scale=1.0 if percent else magnitude_suffix(text, token.end)[0],currency=currency,+ currency_code=currency_code,digits=token.digits,sign=token.sign,extent=(view.start(_currency_prefix_start(text, token.start)), view.end(mark_end)),diff --git a/agent/src/agent/grounding/policies.py b/agent/src/agent/grounding/policies.pyindex 2a9fa82f9..1a3b77b1b 100644--- a/agent/src/agent/grounding/policies.py+++ b/agent/src/agent/grounding/policies.py@@ -1374,12 +1374,19 @@ class _PolicyMixin:*,column: str | None = None,date: str | None = None,+ currency_code: str | None = None,) -> list[float]:"""Observed price values a figure may be compared against."""- return [- float(record.value)- for record in self._price_candidates(symbol, records, column=column, date=date)- ]+ candidates = self._price_candidates(+ symbol, records, column=column, date=date+ )+ if currency_code is not None:+ candidates = [+ record+ for record in candidates+ if record.currency == currency_code+ ]+ return [float(record.value) for record in candidates]def _price_candidates(self,@@ -1412,7 +1419,13 @@ class _PolicyMixin:]return [record for record in candidates if record.value is not None]- def _row_pool(self, symbol: str | None, *, money_only: bool = False) -> list[float]:+ def _row_pool(+ self,+ symbol: str | None,+ *,+ money_only: bool = False,+ currency_code: str | None = None,+ ) -> list[float]:"""Numbers a market-data row carried (volume, amount, turnover, …).Only ``get_market_data`` and run-dir CSV rows count, so a generic tool's@@ -1427,6 +1440,7 @@ class _PolicyMixin:and record.tool in {"get_market_data", "bash"}and (not symbol or record.symbol == symbol)and (not money_only or _is_price_kind(record))+ and (currency_code is None or record.currency == currency_code)]@staticmethod@@ -1661,6 +1675,12 @@ class _PolicyMixin:field_ref_candidates=unknown_scope_candidates,)]+ if figure.currency_code is not None:+ scoped_records = [+ record+ for record in scoped_records+ if record.currency == figure.currency_code+ ]values = [float(record.value) for record in scoped_records] + metric_valuesmoney = figure.currency and not figure.percent# A call- or tool-scoped ref pools every field that call returned,@@ -1743,6 +1763,12 @@ class _PolicyMixin:candidates = self._price_candidates(symbol, records, column=figure.column, date=figure.date)+ if figure.currency_code is not None:+ candidates = [+ record+ for record in candidates+ if record.currency == figure.currency_code+ ]prices = [float(record.value) for record in candidates]if figure.percent:# A percent is a ratio; no price or volume may answer it.@@ -1751,7 +1777,11 @@ class _PolicyMixin:elif figure.column:direct, scaled = prices, []elif figure.currency:- direct, scaled = prices + self._row_pool(symbol, money_only=True), []+ direct, scaled = prices + self._row_pool(+ symbol,+ money_only=True,+ currency_code=figure.currency_code,+ ), []else:direct, scaled = prices + self._row_pool(symbol), self._metric_pool(symbol)# An undeclared tail-risk figure is matched against every tail-risk@@ -1842,6 +1872,7 @@ class _PolicyMixin:records: Sequence[EvidenceRecord],*,money: bool = False,+ currency_code: str | None = None,percent: bool = False,scalar_parameters: Sequence[float] = (),) -> tuple[float, list[float], bool] | str | None:@@ -1903,7 +1934,11 @@ class _PolicyMixin:if not unattributed:# A money-marked result is derived from money: an RSI or a volume# is not a price to take a discount of.- anchors = self._price_pool(symbol, records) + self._row_pool(symbol, money_only=money)+ anchors = self._price_pool(+ symbol, records, currency_code=currency_code+ ) + self._row_pool(+ symbol, money_only=money, currency_code=currency_code+ )if not money:anchors += self._metric_pool(symbol)# Arithmetic across two runs needs both runs' values: a field ref that@@ -1934,7 +1969,9 @@ class _PolicyMixin:anchors.extend(float(record.value)for record in scoped[0]- if (not money or _is_price_kind(record)) and not (unattributed and record.symbol)+ if (not money or _is_price_kind(record))+ and (currency_code is None or record.currency == currency_code)+ and not (unattributed and record.symbol))if not money and not unattributed:anchors.extend(scoped[1])@@ -2090,7 +2127,8 @@ class _PolicyMixin:) -> list[dict[str, Any]]:"""A derived figure must be the arithmetic its note states."""derivation = self._derivation(- declaration, symbol, records, money=figure.currency, percent=figure.percent,+ declaration, symbol, records, money=figure.currency,+ currency_code=figure.currency_code, percent=figure.percent,scalar_parameters=scalar_parameters,)if isinstance(derivation, str):@@ -2184,12 +2222,19 @@ class _PolicyMixin:)]derivation = self._derivation(- declaration, symbol, records, money=figure.currency, percent=figure.percent,+ declaration, symbol, records, money=figure.currency,+ currency_code=figure.currency_code, percent=figure.percent,scalar_parameters=scalar_parameters,)if not isinstance(derivation, str) and self._result_matches(figure, derivation[0]):return []candidates = self._price_candidates(symbol, records)+ if figure.currency_code is not None:+ candidates = [+ record+ for record in candidates+ if record.currency == figure.currency_code+ ]prices = [float(record.value) for record in candidates]if not prices:return [diff --git a/agent/tests/test_agent_output_discipline.py b/agent/tests/test_agent_output_discipline.pyindex d36ccebcf..513033593 100644--- a/agent/tests/test_agent_output_discipline.py+++ b/agent/tests/test_agent_output_discipline.py@@ -205,6 +205,22 @@ class TestPrincipleOneReachesEveryTool:assert result.valid is Falseassert [issue["code"] for issue in result.issues] == ["numeric_claim_conflict"]+ def test_unreferenced_currency_must_match_evidence(+ self, tmp_path: Path+ ) -> None:+ """A USD market price cannot support an identical JPY claim."""+ ledger = _ledger(+ tmp_path,+ tool="get_stock_profile",+ result=_PROFILE_QUOTE,+ )++ result = ledger.validate_final_answer(+ "AAPL.US 收盘价 212.5 JPY。"+ )++ assert result.valid is False, result.issues+def test_a_non_price_field_does_not_become_price_evidence(self, tmp_path: Path) -> None:"""The P/E in the same payload must not license quoting 31.4 as a price."""ledger = _ledger(tmp_path, tool="get_stock_profile", result=_PROFILE_QUOTE)@@ -386,6 +402,212 @@ class TestTheGateDoesNotKillCorrectAnswers:assert result.valid is True, result.issues++ def test_sec_xbrl_usd_debt_is_grounded_by_exact_reference(+ self, tmp_path: Path+ ) -> None:+ """A genuine SEC USD metric should support a referenced dollar claim."""+ ledger = GroundingLedger(+ run_dir=tmp_path,+ user_message="Analyze HE.US debt from its June 2026 filing.",+ )+ ledger.ingest_tool_result(+ tool_name="get_sec_filings",+ arguments={"ticker": "HE", "metric": "LongTermDebt"},+ result=json.dumps(+ {+ "ok": True,+ "market": "US",+ "source": "sec_edgar",+ "data": {+ "ticker": "HE",+ "metric": {+ "concept": "LongTermDebt",+ "unit": "USD",+ "points": [+ {+ "end": "2026-06-30",+ "val": 2500000000,+ "form": "10-Q",+ "accession": "0000354707-26-000054",+ }+ ],+ },+ },+ }+ ),+ call_id="sec1",+ success=True,+ )++ answer = (+ "HE.US reported $2,500,000,000 in long-term debt."+ "\n\n```figures\n"+ "2,500,000,000 | observed | data.metric.points[0].val | sec1\n"+ "```"+ )+ result = ledger.validate_final_answer(answer)++ assert result.valid is True, result.issues++ @pytest.mark.parametrize(+ ("unit", "claimed_amount", "expected_valid"),+ [+ ("USD", 3500000000, False),+ ("shares", 2500000000, False),+ ],+ )+ def test_sec_xbrl_rejects_invalid_monetary_claims(+ self, tmp_path: Path, unit: str,+ claimed_amount: int, expected_valid: bool+ ) -> None:+ """Incorrect values and nonmonetary units cannot support USD claims."""+ ledger = GroundingLedger(+ run_dir=tmp_path,+ user_message="Analyze HE.US financial statements.",+ )+ ledger.ingest_tool_result(+ tool_name="get_sec_filings",+ arguments={"ticker": "HE", "metric": "LongTermDebt"},+ result=json.dumps(+ {+ "ok": True,+ "market": "US",+ "source": "sec_edgar",+ "data": {+ "ticker": "HE",+ "metric": {+ "concept": "LongTermDebt",+ "unit": unit,+ "points": [+ {+ "end": "2026-06-30",+ "val": 2500000000,+ "form": "10-Q",+ }+ ],+ },+ },+ }+ ),+ call_id="sec1",+ success=True,+ )++ answer = (+ f"HE.US reported ${claimed_amount:,} in long-term debt."+ "\n\n```figures\n"+ f"{claimed_amount:,} | observed | data.metric.points[0].val | sec1\n"+ "```"+ )+ result = ledger.validate_final_answer(answer)++ assert result.valid is expected_valid, result.issues++ @pytest.mark.parametrize(+ ("source_currency", "claimed_currency", "expected_valid"),+ [+ ("USD", "USD", True),+ ("JPY", "JPY", True),+ ("EUR", "EUR", True),+ ("USD", "JPY", False),+ ("JPY", "USD", False),+ ("EUR", "USD", False),+ ],+ )+ def test_sec_xbrl_currency_must_match_evidence(+ self,+ tmp_path: Path,+ source_currency: str,+ claimed_currency: str,+ expected_valid: bool,+ ) -> None:+ """SEC financial claims must preserve the source currency."""+ ledger = GroundingLedger(+ run_dir=tmp_path,+ user_message="Analyze HE.US financial statements.",+ )+ ledger.ingest_tool_result(+ tool_name="get_sec_filings",+ arguments={"ticker": "HE", "metric": "LongTermDebt"},+ result=json.dumps(+ {+ "ok": True,+ "market": "US",+ "source": "sec_edgar",+ "data": {+ "ticker": "HE",+ "metric": {+ "concept": "LongTermDebt",+ "unit": source_currency,+ "points": [+ {+ "end": "2026-06-30",+ "val": 2500000000,+ "form": "10-Q",+ }+ ],+ },+ },+ }+ ),+ call_id="sec1",+ success=True,+ )++ answer = (+ f"HE.US reported {claimed_currency} 2,500,000,000 in long-term debt."+ "\n\n```figures\n"+ "2,500,000,000 | observed | data.metric.points[0].val | sec1\n"+ "```"+ )+ result = ledger.validate_final_answer(answer)++ assert result.valid is expected_valid, result.issues++ def test_sec_xbrl_rejects_wrong_source_reference(+ self, tmp_path: Path+ ) -> None:+ """A real SEC figure cannot be attributed to a different call."""+ ledger = GroundingLedger(+ run_dir=tmp_path,+ user_message="Analyze HE.US debt.",+ )+ ledger.ingest_tool_result(+ tool_name="get_sec_filings",+ arguments={"ticker": "HE", "metric": "LongTermDebt"},+ result=json.dumps(+ {+ "ok": True,+ "market": "US",+ "source": "sec_edgar",+ "data": {+ "ticker": "HE",+ "metric": {+ "concept": "LongTermDebt",+ "unit": "USD",+ "points": [+ {"end": "2026-06-30", "val": 2500000000}+ ],+ },+ },+ }+ ),+ call_id="sec1",+ success=True,+ )++ answer = (+ "HE.US reported $2,500,000,000 in long-term debt."+ "\n\n```figures\n"+ "2,500,000,000 | observed | data.metric.points[0].val | wrong_call\n"+ "```"+ )+ result = ledger.validate_final_answer(answer)++ assert result.valid is False, result.issues++def test_the_root_allowance_does_not_licence_an_untouched_ticker(self, tmp_path: Path) -> None:diff --git a/agent/tests/test_grounding_figures_contract.py b/agent/tests/test_grounding_figures_contract.pyindex 87680d7f7..0de8cbf89 100644--- a/agent/tests/test_grounding_figures_contract.py+++ b/agent/tests/test_grounding_figures_contract.py@@ -463,6 +463,29 @@ def test_derived_passes_on_its_own_arithmetic_and_fails_without_it(assert [i["reason"] for i in unanchored.issues] == ["formula_not_anchored"]+def test_derived_currency_must_match_evidence(tmp_path: Path) -> None:+ ledger = _ledger(tmp_path)++ formula = "0.666 × 0.97"+ row = f"0.646 | derived | {formula} | c1"++ matching = ledger.validate_final_answer(+ HDR+ + declared_parameter("97%")+ + " 第一档 0.646 CNY。"+ + _block(HDR_ROW, row)+ )+ mismatched = ledger.validate_final_answer(+ HDR+ + declared_parameter("97%")+ + " 第一档 0.646 USD。"+ + _block(HDR_ROW, row)+ )++ assert matching.valid is True, matching.issues+ assert mismatched.valid is False, mismatched.issues++def test_derived_covers_only_the_value_it_declares(tmp_path: Path) -> None:"""§4: the exemption is the declaration, and a declaration names one value."""ledger = _ledger(tmp_path)@@ -507,6 +530,22 @@ def test_proposed_outside_the_range_passes_with_a_derivation(tmp_path: Path) ->assert result.valid is True, result.issues+def test_proposed_currency_must_match_evidence(tmp_path: Path) -> None:+ ledger = _ledger(tmp_path)++ matching = ledger.validate_final_answer(+ HDR + " 建议买入价 0.65 CNY。"+ + _block(HDR_ROW, "0.65 | proposed | entry")+ )+ mismatched = ledger.validate_final_answer(+ HDR + " 建议买入价 0.65 USD。"+ + _block(HDR_ROW, "0.65 | proposed | entry")+ )++ assert matching.valid is True, matching.issues+ assert mismatched.valid is False, mismatched.issues++def test_cited_needs_a_source_and_may_not_pose_as_a_print(tmp_path: Path) -> None:ledger = _ledger(tmp_path)diff --git a/agent/tests/test_grounding_shape_hardening.py b/agent/tests/test_grounding_shape_hardening.pyindex 20f5341eb..3d9cd5b8d 100644--- a/agent/tests/test_grounding_shape_hardening.py+++ b/agent/tests/test_grounding_shape_hardening.py@@ -174,6 +174,29 @@ def test_an_iso_code_glued_to_digits_is_a_currency_mark(tmp_path: Path) -> None:assert _shapes("见 XUSD100 与 SMA20") == {}+ ("text", "expected"),+ [+ ("Cost USD100", "USD"),+ ("Cost 100 JPY", "JPY"),+ ("Cost 100 EUR", "EUR"),+ ("Cost €100", "EUR"),+ ("Cost £100", "GBP"),+ ("Cost 100 CNY", "CNY"),+ ("Cost 100 人民币", "CNY"),+ ("Cost ¥100", None),+ ("Cost $100", None),+ ("Cost 100 shares", None),+ ],+)+def test_currency_identity_is_preserved(+ text: str, expected: str | None+) -> None:+ [figure] = _figures(text)++ assert figure.currency_code == expected++# ---------------------------------------------------------------------------# A2 — a decimal comma (#1418)# ---------------------------------------------------------------------------