"Vibe-Trading: Your Personal Trading Agent"
Python ai-agentalgorithmic-tradingbacktestingfintechllmmcpmulti-agentpythonquantitative-financetrading
fix(grounding): mask reference levels and currency-prefixed thresholds
William Liaoda4828349f89
diff --git a/agent/src/agent/grounding.py b/agent/src/agent/grounding.pyindex aab8e0975..c8b6d6c5d 100644--- a/agent/src/agent/grounding.py+++ b/agent/src/agent/grounding.py@@ -265,6 +265,32 @@ _INDICATOR_VALUE_RE = re.compile(r"[-+]?\d[\d,]*(?:\.\d+)?",re.IGNORECASE,)+# A currency token may sit between a level marker or comparison operator and+# the number: "收盘 <$2.86", "目标位 C$6.80", "trigger at $119.68". Without+# it, the number survives masking and is compared against observed OHLC as a+# price claim even though it is a prospective level, not an observed quote.+_CURRENCY_TOKEN = r"(?:\$|US\$|C\$|HK\$|CAD|USD|CNY|HKD|¥|¥)?"+# A historical reference names a price the instrument once traded at — an+# all-time high, a 52-week extreme — and the answer is not claiming it as+# today's observed quote. "8/12 高 149.60 为 6/16 ATH 225.64 以来最高" was+# rejected because 225.64 (the June ATH) fell outside this session's observed+# OHLC range. The marker must be adjacent to the number, so a plain field+# reading such as "8/12 高 149.60" stays checked: its 高 carries no historical+# qualifier. "创历史新高" shares the 历史新高 marker and is masked with it; the+# relaxation follows the same trade-off as prospective levels — the historical+# extreme is a reference, not an assertion about the current bar.+_REFERENCE_LEVEL_RE = re.compile(+ r"(?:"+ r"\bATH\b|all[- ]?time\s+(?:high|low)|"+ r"52\s*[- ]?W(?:EEK)?\s*(?:high|low)|52\s*[- ]?W(?:EEK)?\s*高(?:点|位)?|"+ r"52\s*周(?:高|低)(?:点|位)?|"+ r"历史(?:最高|最低|新高|新低|高|低)(?:点|位|价)?|"+ r"上市以来(?:最高|最低)(?:点|位|价)?"+ r")"+ r"\s*(?:of|为|是|约|at)?\s*[::]?\s*\(?"+ r"\s*" + _CURRENCY_TOKEN + r"\s*[-+]?\d[\d,]*(?:\.\d+)?",+ re.IGNORECASE,+)# A trading plan quotes levels it does not claim to have observed. In the# committee report attached to #983, "收盘 ≥6.45 且量 ≥35M手" is an entry# trigger, "年线 4.63 成目标区" is a target zone, and neither asserts anything@@ -286,16 +312,19 @@ _INDICATOR_VALUE_RE = re.compile(_PROSPECTIVE_LEVEL_RE = re.compile(r"(?:"# (a) comparison operator immediately before the number- r"(?:>=|<=|≥|≤|>|<|大于|小于|不低于|不高于|高于|低于)\s*[-+]?\d[\d,]*(?:\.\d+)?"+ r"(?:>=|<=|≥|≤|>|<|大于|小于|不低于|不高于|高于|低于)"+ r"\s*" + _CURRENCY_TOKEN + r"\s*[-+]?\d[\d,]*(?:\.\d+)?"r"|"# (b) a level marker introducing the numberr"(?:目标位|目标区|目标价|均值目标(?:价)?|平均目标(?:价)?|止损位?|止盈位?|触发价|触发位|触发点|上看|下看|"r"支撑(?:阶梯|位|线)?|阻力(?:位|线)?|压力位|压力线|support(?:\s+(?:level|line|zone))?|"r"resistance(?:\s+(?:level|line|zone))?|target\s+(?:price|level|zone)|trigger|stop[-\s]?loss|take[-\s]?profit)"- r"\s*(?:为|是|至|到|on|at|of|=)?\s*[::]?\s*[-+]?\d[\d,]*(?:\.\d+)?"+ r"\s*(?:为|是|至|到|on|at|of|=)?\s*[::]?\s*"+ + _CURRENCY_TOKEN+ + r"\s*[-+]?\d[\d,]*(?:\.\d+)?"r"|"# (c) the number followed by a level marker- r"[-+]?\d[\d,]*(?:\.\d+)?\s*(?:一线|附近)?\s*(?:成为?|作为|是)?\s*"+ r"" + _CURRENCY_TOKEN + r"[-+]?\d[\d,]*(?:\.\d+)?\s*(?:一线|附近)?\s*(?:成为?|作为|是)?\s*"r"(?:目标区|目标位|止损位|止盈位)"r"|"# (d) a conditional opener before the number, digits fencing the reach@@ -2166,6 +2195,7 @@ class GroundingLedger:masked = _LABELLED_SCORE_RE.sub(" ", masked)masked = _INDICATOR_VALUE_RE.sub(" ", masked)masked = _PROSPECTIVE_LEVEL_RE.sub(" ", masked)+ masked = _REFERENCE_LEVEL_RE.sub(" ", masked)without_dates = _QUANTITY_WITH_UNIT_RE.sub(" ", masked)values: list[float] = []for match in _NUMBER_RE.finditer(without_dates):diff --git a/agent/tests/test_agent_grounding.py b/agent/tests/test_agent_grounding.pyindex 270b20827..f53e98781 100644--- a/agent/tests/test_agent_grounding.py+++ b/agent/tests/test_agent_grounding.py@@ -1295,6 +1295,56 @@ def test_plan_level_mask_leaves_observed_quotes_checked(assert GroundingLedger._numbers_without_dates_or_percent(segment) == expected+# A currency token between the anchor and the number used to break every+# prospective branch: "收盘 <$2.86" left 2.86 to be compared against observed+# OHLC, "目标位 $6.80" left 6.8, and "trigger at $119.68" left 119.68. These+# are levels, not observed quotes, so each must mask entirely.+_CURRENCY_PREFIXED_PLAN_LEVELS = [+ "收盘 <$2.86",+ "目标位 $6.80,止损位 C$5.20",+ "trigger at $119.68",+ "支撑位 $190.12",+ "target price of $6.80",+ "收盘 ≥ $135 且低点 > $119.68",+]+++ "segment", _CURRENCY_PREFIXED_PLAN_LEVELS, ids=range(len(_CURRENCY_PREFIXED_PLAN_LEVELS))+)+def test_currency_prefixed_plan_levels_are_not_read_as_observed_prices(segment: str) -> None:+ """A currency-prefixed trigger or target is prospective, not observed."""+ assert GroundingLedger._numbers_without_dates_or_percent(segment) == []+++# A historical reference names a price the instrument once traded at. The+# SPCX.US weekly plan quoted "6/16 ATH 225.64" next to the 8/12 high 149.60;+# 225.64 fell outside the session's observed OHLC range (105.11–149.6) and was+# rejected as a conflict even though it is a reference, not a current quote.+_REFERENCE_LEVEL_SEGMENTS = [+ ("8/12 高 149.60 为 6/16 ATH 225.64 以来最高", [149.60]),+ ("8/12 高 149.60 为 6/16 历史高点 225.64 以来最高", [149.60]),+ ("8/12 高 149.60 为 6/16 all-time high 225.64 以来最高", [149.60]),+ ("52W 高 543.14", []),+ ("52-week low of $190.12", []),+ ("52W low (C$7.27)", []),+ ("历史最低 $60.82", []),+ ("ATH (C$7.31)", []),+]+++ "segment,expected",+ _REFERENCE_LEVEL_SEGMENTS,+ ids=[c[0][:28] for c in _REFERENCE_LEVEL_SEGMENTS],+)+def test_reference_levels_are_not_read_as_observed_price_claims(+ segment: str, expected: list[float],+) -> None:+ """An ATH/52-week/historical extreme is a reference, not a current quote."""+ assert GroundingLedger._numbers_without_dates_or_percent(segment) == expected++def test_plan_level_mask_does_not_shield_a_wrong_quote_end_to_end(tmp_path: Path) -> None:"""The end-to-end gate still rejects a fabricated quote beside a plan level."""ledger = _screened_ledger(tmp_path)@@ -1319,6 +1369,97 @@ def test_plan_level_alone_reaches_a_valid_answer(tmp_path: Path) -> None:assert result.valid is True, result.issues+def _spcx_us_ledger(tmp_path: Path) -> GroundingLedger:+ """A ledger that locked SPCX.US and observed 8/7–8/12 OHLC bars."""+ ledger = GroundingLedger(+ run_dir=tmp_path,+ user_message="以 SPCX.US(纳斯达克,SpaceX 本体)作为美股侧参考",+ )+ query = "SPCX.US"+ ledger.authorize_tool_call(+ "search_symbol",+ {"query": query},+ batch_authorized_symbols=ledger.authorized_symbols,+ call_id="resolve",+ )+ ledger.ingest_tool_result(+ tool_name="search_symbol",+ arguments={"query": query},+ result=_resolver_payload(symbol="SPCX.US", query=query),+ call_id="resolve",+ success=True,+ )+ payload = json.dumps(+ {+ "SPCX.US": [+ {+ "trade_date": "2026-08-07",+ "open": 114.97,+ "high": 133.48,+ "low": 114.53,+ "close": 133.11,+ "volume": 242130700,+ },+ {+ "trade_date": "2026-08-10",+ "open": 134.95,+ "high": 139.26,+ "low": 130.17,+ "close": 138.74,+ "volume": 169934300,+ },+ {+ "trade_date": "2026-08-11",+ "open": 138.66,+ "high": 139.98,+ "low": 130.50,+ "close": 133.29,+ "volume": 108900600,+ },+ {+ "trade_date": "2026-08-12",+ "open": 135.05,+ "high": 149.60,+ "low": 134.01,+ "close": 146.15,+ "volume": 165771792,+ },+ ],+ "_provenance": {+ "SPCX.US": {+ "source": "yahoo",+ "requested_source": "auto",+ "detected_source": "yahoo",+ "fallback_used": False,+ "currency_conversion": "none",+ }+ },+ },+ ensure_ascii=False,+ )+ ledger.ingest_tool_result(+ tool_name="get_market_data",+ arguments={"codes": ["SPCX.US"]},+ result=payload,+ call_id="prices",+ success=True,+ )+ return ledger+++def test_reference_level_and_currency_thresholds_pass_end_to_end(tmp_path: Path) -> None:+ """The SPCX.US verdict prose passes once references and thresholds mask."""+ ledger = _spcx_us_ledger(tmp_path)++ result = ledger.validate_final_answer(+ "SPCX.US 8/10 收 138.74 USD、8/12 高 149.60 USD(source: yahoo)。"+ "8/12 高 149.60 为 6/16 ATH 225.64 以来最高;"+ "8/10 收盘 138.74 ≥ $135 且 ≥ $119.68 触发成立。"+ )++ assert result.valid is True, result.issues++def _shanghai_shortlist() -> str:"""One Shanghai listing as the two sources actually publish it."""return _resolver_payload(