"Vibe-Trading: Your Personal Trading Agent"
Python ai-agentalgorithmic-tradingbacktestingfintechllmmcpmulti-agentpythonquantitative-financetrading
Merge remote-tracking branch 'upstream/main'
William Liao912e5fa19fee
diff --cc agent/src/agent/grounding.pyindex 173665ef7,59efd4b6e..d207ab8ad--- a/agent/src/agent/grounding.py+++ b/agent/src/agent/grounding.py@@@ -205,13 -219,32 +219,35 @@@ _DATE_RE = re.compile(r"\b(?:19|20)\d{2# A year-less "8/5" is how a trading day is written in running prose, and it# contributed 8 and 5 as candidate prices (#983). The month and day ranges are# bounded, and both sides are fenced off from a longer slash run, so the window-# enumeration "20/50/200-day" cannot be mistaken for a date.+# enumeration "20/50/200-day" cannot be mistaken for a date. Reports also write- # the same day as "08-10(一)" or "08-10盘中", so the dash form is masked with- # the same bounds and fencing; a dash is never part of a longer digit run.++# the same day as "08-10(一)" or "08-10盘中"; that dash form is masked by++# ``_DASH_DATE_RE`` below, where a zero-padded month or a weekday/session++# marker is required so a quoted price range like "8-10 元" stays checkable._SHORT_DATE_RE = re.compile(r"(?<![\d/])(?:0?[1-9]|1[0-2])/(?:0?[1-9]|[12]\d|3[01])(?![\d/])"- r"|(?<![\d-])(?:0?[1-9]|1[0-2])-(?:0?[1-9]|[12]\d|3[01])(?![\d-])")+ # A report writes a trading day as "08-10(一)" or "08-10盘中", and the dash form+ # leaked 8 and 10 as candidate prices exactly as "8/5" once did. The dash is+ # NOT symmetric with the slash, though: it also separates a range, and "目标价+ # 10-20 元" must stay checkable. So the two halves are split -- a zero-padded+ # month (01-09) is a formatting intent no price range imitates, while 10/11/12+ # have to carry a weekday or session marker to read as a date.+ _DASH_DATE_RE = re.compile(+ r"(?<![\d/-])(?:"+ r"0[1-9]-(?:0[1-9]|[12]\d|3[01])"+ r"|1[0-2]-(?:0[1-9]|[12]\d|3[01])"+ r"(?=\s*(?:[((]\s*(?:周|星期)?[一二三四五六日天]\s*[))]"+ r"|盘中|盘后|盘前|收盘|开盘|最低|最高"+ r"|\s*(?:close|open|intraday|low|high)\b))"+ r")(?![\d/-])",+ re.IGNORECASE,+ )+ # A level stated as a RANGE has the same shape: the separator touches the+ # second number, so masking "目标价 10" left "-20" behind and a negative price+ # matches no OHLC window at all -- a guaranteed rejection of a correct draft.+ # The tail is optional, so a single-value level is unaffected.+ _RANGE_TAIL = r"(?:\s*[-–—~~至到]\s*[-+]?\d[\d,]*(?:\.\d+)?)?"+# A percentage range masks only its upper bound through the "%" tail check# below, because the sign touches the second number: "1–2%" left 1 behind# (#983). Mask the span as a whole.@@@ -390,31 -450,6 +453,8 @@@ _PROSPECTIVE_LEVEL_RE = re.compile# parentheses are deliberately not separators: an explicit derivation such as# "(8.5 - 7.9) / 2" must stay in one segment for the formula check._CLAUSE_SEPARATOR_RE = re.compile(r"[,,;;。、\n()【】]")++- # An order-level claim names a resting or desired order, not an observed- # quote: "两档 GTC (100 @ $3.50 / 100 @ $4.00) 均未触发 (周高 $3.42 < $3.50)"- # asserts nothing about what the instrument traded at - the limit prices are- # prospective levels (like targets/stops) and the share counts are quantities.- # Without this mask the gate reported 100, 3.5 and 4.0 as price claims- # conflicting with the observed OHLC range and rejected a correct draft.- # The @-price branch requires a leading quantity so a bare "@" (rare in- # trading reports) stays checked; the keyword branch covers labelled- # resting orders (挂单/限价单/委托/订单/GTC). Suggested entry prices such- # as "建议买入价" are deliberately NOT masked - the numeric gate must still- # validate them against observed evidence.- _ORDER_LEVEL_RE = re.compile(- r"(?:"- # (a) quantity (optional unit) @ price: "100 @ $3.50", "100 股 @ 4.00"- r"(?:\d[\d,]*(?:\.\d+)?)\s*(?:股|手|张|份|shares?|units?)?\s*@\s*"- + _CURRENCY_TOKEN + r"\s*[-+]?\d[\d,]*(?:\.\d+)?"- r"|"- # (b) order keyword + price: 挂单/限价单/限价/委托/订单/买入价/卖出价/GTC- r"(?:挂单|限价单|委托|订单|GTC(?:单)?)\s*(?:为|是|至|到|on|at|=)?\s*[::]?\s*(?!\s*[-+]?\d[\d,]*(?:\.\d+)?(?:\s*(?:股|手|张|份|shares?|units?))?\s*@)\s*"- + _CURRENCY_TOKEN + r"\s*[-+]?\d[\d,]*(?:\.\d+)?"- r")",- re.IGNORECASE,- )# The ASCII comma both separates clauses and groups thousands, and the clause# split ran first: "收盘价 ¥1,309.22" became a clause ending in "¥1", whose 1 was# compared against the observed 1300.01–1363.35 range and rejected as a@@@ -619,18 -653,19 +659,28 @@@ def _coerce_csv_number(value: Any) -> i# "." is deliberately not a separator: a decimal price such as 8.5 would parse# as month 8 day 5 and match a real trading day.+ # A report writes the day as a table cell -- "08-10(一)", "08-10(周一)盘中",+ # "08-10盘中" -- and the weekday or session suffix made the cell match no+ # evidence row at all, so every price in that row came back+ # "numeric_claim_unavailable" even though the run had fetched the bar.+ _TRADING_DAY_SUFFIX = (+ r"(?:\s*[((]\s*(?:周|星期)?[一二三四五六日天]\s*[))])?"+ r"\s*(?:盘中|盘后|盘前|收盘|开盘|早盘|尾盘)?"+ )_YEARLESS_CLAIM_DATE_RE = re.compile(- r"^(0?[1-9]|1[0-2])\s*[-/月]\s*(0?[1-9]|[12]\d|3[01])\s*[日号]?$"+ r"^(0?[1-9]|1[0-2])\s*[-/月]\s*(0?[1-9]|[12]\d|3[01])\s*[日号]?"+ + _TRADING_DAY_SUFFIX+ + r"$")+# Two-digit day alternatives are tried before a bare digit so an+# unanchored prefix match consumes the full day ("10" of "08-10(一)")+# instead of stopping at "1".+_ISO_CLAIM_DATE_PREFIX_RE = re.compile(+ r"^\s*((?:19|20)\d{2})\s*[-/]\s*(0?[1-9]|1[0-2])\s*[-/]\s*([12]\d|3[01]|0?[1-9])"+)+_YEARLESS_CLAIM_DATE_PREFIX_RE = re.compile(+ r"^\s*(0?[1-9]|1[0-2])\s*[-/月]\s*([12]\d|3[01]|0?[1-9])"+)_ISO_TIMESTAMP_RE = re.compile(r"^(\d{4})-(\d{1,2})-(\d{1,2})")diff --cc agent/tests/test_agent_grounding.pyindex e66825370,2f216f653..da36d6e60--- a/agent/tests/test_agent_grounding.py+++ b/agent/tests/test_agent_grounding.py@@@ -2215,55 -2162,113 +2245,167 @@@ def test_in_text_decimal_survives_list_assert result.valid is True, (draft, result.issues)+def test_order_level_prices_are_not_observed_quotes(tmp_path: Path) -> None:+ """GTC order limits (100 @ $3.50) are prospective, not observed prices.++ Regression for the RXRX run: the draft "两档 GTC (100 @ $3.50 / 100 @ $4.00)+ 均未触发 (周高 $3.42 < $3.50)" was rejected with numeric_claim_conflict for+ 100, 3.5 and 4.0 against the observed OHLC range. Order levels are levels,+ like targets/stops, and share counts are quantities - neither is a claim+ about an observed quote.+ """+ raw = tmp_path / "data" / "raw"+ raw.mkdir(parents=True)+ (raw / "RXRX_US.csv").write_text(+ "Date,Open,High,Low,Close\n"+ "2026-08-07,3.25,3.26,3.18,3.20\n"+ "2026-08-08,3.10,3.42,3.05,3.35\n",+ encoding="utf-8",+ )+ ledger = GroundingLedger(+ run_dir=tmp_path,+ user_message="请分析 RXRX.US 并更新周报",+ )+ ledger.ingest_tool_result(+ tool_name="search_symbol",+ arguments={"query": "RXRX"},+ result=json.dumps({+ "ok": True,+ "data": {+ "candidates": [+ {"symbol": "RXRX.US", "name": "Recursion Pharmaceuticals", "market": "us",+ "type": "equity", "exchange": "NMS", "source": "yahoo"},+ ]+ },+ }),+ call_id="lock1",+ success=True,+ )++ answer = (+ "RXRX.US(yahoo,USD)本周高 $3.42。订单: 两档 GTC (100 @ $3.50 / 100 @ $4.00) "+ "均未触发 (周高 $3.42 < $3.50) — 价格推断未成交。"+ )+ result = ledger.validate_final_answer(answer)+ assert result.valid is True, result.issues++ # A genuinely fabricated close is still rejected.+ fabricated = ledger.validate_final_answer(+ "RXRX.US(yahoo,USD)本周高 $3.42。另: 收盘 2.50 已确认。"+ )+ assert fabricated.valid is False+ assert any(+ issue["code"] == "numeric_claim_conflict" for issue in fabricated.issues+ )+++++ def test_dash_form_trading_day_is_a_date_but_a_price_range_is_not() -> None:+ """A report writes the day as "08-10(一)"; a target still writes "10-20 元".++ The dash carries both meanings, so the mask splits them: a zero-padded+ month reads as a date on its own, October through December need a weekday+ or session marker, and a range with neither stays checkable.+ """+ extract = GroundingLedger._numbers_without_dates_or_percent++ assert extract("08-10(一) 收盘 8.20 CNY") == [8.2]+ assert extract("08-10盘中最低 8.20 CNY") == [8.2]+ assert extract("08-10 close 8.20 USD") == [8.2]+ assert extract("10-20(周一)盘中 8.20 CNY") == [8.2]++ # No date marker and no zero-padded month: an ordinary quoted range, and+ # masking it would stop checking a claim the ledger exists to check.+ assert extract("区间 8-10 元") == [8.0, 10.0]+ assert extract("跌 12-25 元") == [12.0, 25.0]+++ def test_a_level_stated_as_a_range_masks_both_bounds(tmp_path: Path) -> None:+ """Masking only the lower bound left a negative upper bound behind.++ The separator touches the second number, so "目标价 10-20 元" used to+ reduce to "-20" — and a negative price is outside every OHLC window, which+ made a correct draft impossible to pass rather than merely unchecked.+ """+ extract = GroundingLedger._numbers_without_dates_or_percent++ for draft in ("目标价 10-20 元", "支撑位 8-10 元", "阻力位 12.0~13.5", "52周高 15.0-16.0"):+ assert extract(draft) == [], draft++ # A single-value level is unchanged, and an observed quote beside a ranged+ # level is still extracted and checked.+ assert extract("止损位 7.5 元") == []+ assert extract("目标价 10-20 元,现价 8.20 CNY") == [8.2]++ ledger = _screened_ledger(tmp_path)+ result = ledger.validate_final_answer(+ "000543.SZ 收盘价 8.20 CNY,目标价 10-20 元(source: tencent)"+ )+ assert result.valid is True, result.issues+++ def test_an_order_line_is_an_instruction_not_an_observation(tmp_path: Path) -> None:+ """"100 @ $3.50" states where a limit sits; 100 was never a price at all.++ A GTC summary in a weekly update was read as two observed quotes and+ rejected against the session's range, which is the same category error the+ target/stop masks already prevent.+ """+ extract = GroundingLedger._numbers_without_dates_or_percent++ for draft in (+ "GTC 100 @ $3.50",+ "buy 100 @ $3.50 GTC",+ "挂单 100 股 @ 4.00",+ "限价单 100 @ 3.50",+ "委托价 3.50",+ ):+ assert extract(draft) == [], draft++ # 买入价/卖出价 stay OUT of the label set: in running prose they name the+ # price a report says it observed, and masking them let an ungrounded+ # quote through the gate.+ assert extract("买入价 0.881") == [0.881]++ # There is no bare "@ <price>" branch either. Dates are masked before this+ # runs, so an observed close written "2026-08-10 @ 8.20" would reach the+ # order mask as "@ 8.20" and stop being checked at all.+ assert extract("收盘 2026-08-10 @ 8.20") == [8.2]++ # An observed quote standing beside an order line is still checked, and a+ # bare handle carries no price to mask.+ assert extract("现价 8.20 CNY,挂单 100 @ 8.50") == [8.2]+ assert extract("联系 @user 获取") == []++ ledger = _screened_ledger(tmp_path)+ result = ledger.validate_final_answer(+ "000543.SZ 收盘价 8.20 CNY,挂单 100 股 @ 12.00(source: tencent)"+ )+ assert result.valid is True, result.issues+++ def test_a_report_style_date_cell_still_matches_its_evidence_row() -> None:+ """"08-10(一)" and "08-10盘中" are the same trading day as "08-10".++ A weekday or session suffix made the cell match no evidence row, so every+ price in that row was reported numeric_claim_unavailable even though the+ run had fetched the bar.+ """+ from src.agent.grounding import _timestamp_matches_claim_date++ stamp = "2026-08-10T15:00:00Z"+ for claim in ("08-10", "8-10", "08-10(一)", "08-10(周一)", "08-10(周一)盘中", "08-10盘中", "08-10收盘"):+ assert _timestamp_matches_claim_date(stamp, claim) is True, claim++ # The suffix is decoration, not a wildcard — a different day still misses.+ assert _timestamp_matches_claim_date(stamp, "08-11(一)") is False+++ def test_a_us_csv_stem_resolves_to_its_venue_suffix() -> None:+ """``INTC_US.csv`` is ``INTC.US``; without the row it was no evidence at all."""+ from src.agent.grounding import _symbol_from_csv_filename++ assert _symbol_from_csv_filename("INTC_US") == "INTC.US"+ assert _symbol_from_csv_filename("BYN_V") == "BYN.V"+ assert _symbol_from_csv_filename("GC_F") == "GC=F"+ # A bare name has no venue suffix and must stay unresolvable.+ assert _symbol_from_csv_filename("AAPL") is None