"Vibe-Trading: Your Personal Trading Agent"
Python ai-agentalgorithmic-tradingbacktestingfintechllmmcpmulti-agentpythonquantitative-financetrading
fix(grounding): retain currency identity through scaled amounts and shared units
Haozhe Wu287128ec1882
diff --git a/agent/src/agent/grounding/evidence.py b/agent/src/agent/grounding/evidence.pyindex d49bf9fe9..c0827cf7c 100644--- a/agent/src/agent/grounding/evidence.py+++ b/agent/src/agent/grounding/evidence.py@@ -15,6 +15,7 @@ from dataclasses import dataclass, replacefrom pathlib import Pathfrom typing import Any, Mapping+from src.agent.grounding.figures import _CURRENCY_CODESfrom src.agent.grounding.identity import (_CANONICAL_SYMBOL_RE,_infer_currency,@@ -1227,6 +1228,11 @@ class _EvidenceMixin:source = str(payload.get("source") or tool_name)remaining = _MAX_GENERIC_EVIDENCEtimestamp_fields = (*_TIMESTAMP_FIELDS, "latest_date", "as_of")+ data = payload.get("data")+ metric = data.get("metric") if isinstance(data, dict) else None+ unit = metric.get("unit") if isinstance(metric, dict) else None+ unit = unit.strip().upper() if isinstance(unit, str) else None+ metric_currency = {"RMB": "CNY", "CNH": "CNY"}.get(unit, unit) if unit in _CURRENCY_CODES else Nonedef visit(value: Any, path: str, timestamp: str | None = None) -> None:nonlocal remaining@@ -1244,26 +1250,10 @@ class _EvidenceMixin:value=value,status="observed",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)- )+ metric_currency+ if tool_name == "get_sec_filings"+ and path.startswith("data.metric.points[")+ and path.endswith("].val")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 723a19203..a77e28719 100644--- a/agent/src/agent/grounding/figures.py+++ b/agent/src/agent/grounding/figures.py@@ -85,6 +85,7 @@ _CURRENCY_CODES = frozenset({"USD", "CNY", "CNH", "RMB", "HKD", "JPY", "EUR", "GBP", "KRW", "INR","CAD", "AUD", "SGD", "TWD", "THB", "IRR", "IRT", "USDT", "USDC",+ "CHF", "NZD", "BRL", "ARS", "VND",})@@ -901,13 +902,15 @@ def _currency_code_for_figure(text: str, start: int, end: int) -> str | None: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("원"):+ if head.endswith("₩") or tail.startswith("₩"):+ return "KRW"+ if head.endswith("₹") or tail.startswith("₹"):+ return "INR"+ # Match complete currency units, not the opening of an unrelated word.+ word = _cjk_run(tail)+ if word in {"人民币", "美元", "円"}:+ return {"人民币": "CNY", "美元": "USD", "円": "JPY"}[word]+ if tail.startswith("원") and (len(tail) == 1 or not tail[1].isalpha()):return "KRW"return None@@ -1134,8 +1137,9 @@ def scan_figures(content: str, block: FiguresBlock) -> list[Figure]:cell = next((entry for entry in cells if entry[0] <= start and end <= entry[1]), None)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)+ currency_end = magnitude_suffix(text, token.end)[1]+ currency = _currency_before(text, token.start) or _currency_after(text, currency_end)+ currency_code = _currency_code_for_figure(text, token.start, currency_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).diff --git a/agent/tests/test_grounding_currency_boundaries.py b/agent/tests/test_grounding_currency_boundaries.pynew file mode 100644index 000000000..11075587d--- /dev/null+++ b/agent/tests/test_grounding_currency_boundaries.py@@ -0,0 +1,42 @@+"""Currency identity survives magnitude marks without inventing word matches."""+import json++import pytest++from src.agent.grounding import GroundingLedger+from src.agent.grounding.figures import parse_figures_block, scan_figures++[email protected](('text', 'code'), [+ ('Value 2.5B JPY.', 'JPY'),+ ('Value 2.5亿 CNY.', 'CNY'),+ ('Value CHF 2.5.', 'CHF'),+ ('Value NZD 2.5.', 'NZD'),+ ('Value ₩2.5.', 'KRW'),+ ('Value ₹2.5.', 'INR'),+ ('Value 2.5 美元素描', None),+])+def test_currency_shape_boundaries(text, code):+ [figure] = scan_figures(text, parse_figures_block(text))+ assert figure.currency_code == code++[email protected](('unit', 'claim', 'valid'), [+ ('USD', '2.5B USD', True),+ ('USD', '2.5B JPY', False),+ ('CHF', 'CHF 2,500,000,000', True),+ ('CHF', 'USD 2,500,000,000', False),+ ('THB', 'THB 2,500,000,000', True),+ ('shares', 'USD 2,500,000,000', False),+])+def test_sec_currency_units_and_scaled_claims(tmp_path, unit, claim, valid):+ ledger = GroundingLedger(run_dir=tmp_path, user_message='Analyze HE.US debt')+ ledger.ingest_tool_result(+ tool_name='get_sec_filings', arguments={'ticker': 'HE'}, call_id='sec1', success=True,+ result=json.dumps({'ok': True, 'market': 'US', 'source': 'sec_edgar', 'data': {+ 'ticker': 'HE', 'metric': {'unit': unit, 'points': [{'val': 2500000000}]}}}),+ )+ declared = '2.5B' if '2.5B' in claim else '2500000000'+ answer = f'HE.US debt: {claim}.\n```figures\n{declared} | observed | debt | sec1\n```'+ verdict = ledger.validate_final_answer(answer)+ assert verdict.valid is valid, verdict.issues