"Vibe-Trading: Your Personal Trading Agent"
Python ai-agentalgorithmic-tradingbacktestingfintechllmmcpmulti-agentpythonquantitative-financetrading
fix(grounding): percentage-point figures ground the bare declaration (#2107)
Jackzigen85f567d6cece
diff --git a/CHANGELOG.md b/CHANGELOG.mdindex 3a0981cb0..5348f0c5f 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -37,6 +37,15 @@ This project adheres to [Semantic Versioning](https://semver.org/).### Fixed+- **Percentage-point figures ground against the bare declaration** the+ convention writes (#2107). A CN filing states its moves in `个百分点`; the+ scan marks the prose figure a percent while the model's own block declares+ `1.13` bare, and the gate redacted every such figure even when the document+ held the value. The borrow is one-way and exact: `1.13` grounds+ `1.13个百分点`, while `37%` in the prose still needs a percent declaration.+ `pct` / `ppt` / `ppts` / `百分点` now read as point marks, and a declared+ percent range `20%-30%` becomes two endpoint declarations instead of a+ malformed line plus a bogus `-30%` figure.- **Document figure grounding** accepts document-scoped currency restatementsand magnitude-aware arithmetic, including percentage-point declarations.Ratios, wrong values and wrong currencies remain distinct; undeclareddiff --git a/agent/src/agent/grounding/figures.py b/agent/src/agent/grounding/figures.pyindex 1bb259423..74372ae6f 100644--- a/agent/src/agent/grounding/figures.py+++ b/agent/src/agent/grounding/figures.py@@ -97,7 +97,17 @@ _CURRENCY_CODES = frozenset(_PERCENT_CHARS = "%%"# Glued percentage-point and basis-point marks, and the percent each one is.-_POINT_MARKS = (("个百分点", 1.0), ("bps", 0.01), ("pp", 1.0), ("bp", 0.01))+# Longest first: "个百分点" before "百分点", "ppts" before "pp" and "bp".+_POINT_MARKS = (+ ("个百分点", 1.0),+ ("百分点", 1.0),+ ("ppts", 1.0),+ ("ppt", 1.0),+ ("pct", 1.0),+ ("bps", 0.01),+ ("pp", 1.0),+ ("bp", 0.01),+)# Magnitude marks glued to a figure ("24.6M", "2.4万"): a symbol set like the# currency marks. They scale the comparison with evidence and never decide shape.@@ -153,12 +163,16 @@ class FiguresBlock:spans: tuple[tuple[int, int], ...] = ()def match(- self, value: float, percent: bool, digits: str | None = None+ self, value: float, percent: bool, digits: str | None = None, point_marked: bool = False) -> Declaration | None:"""Return the declaration covering ``value``, or None.Matching is numeric and percent-ness must agree: ``37%`` and ``0.37`` are- different assertions. An exact value (tolerance 1e-9) always wins. Failing+ different assertions. One exception, and it is one-way: a percentage-+ point figure ("1.13个百分点", "3.6pp") carries its unit in words, so the+ convention declares it bare ("1.13"), and a same-valued bare declaration+ may ground it (#2107). A bare figure never borrows a percent+ declaration. An exact value (tolerance 1e-9) always wins. Failingthat, a figure written with decimals ("38,68") covers a declaration holdingthe precise observation ("38.68005857871268") when it is that value correctlyrounded to the digits written: within half a unit of its last decimal, and@@ -171,11 +185,17 @@ class FiguresBlock:percent: Whether the prose figure carries a percent sign.digits: The prose figure's normalized digits ("38.68"), or None torequire an exact match.+ point_marked: Whether the prose figure's mark is a percentage-point+ spelling rather than "%".Returns:The matching declaration (the nearest one when several round to thesame figure), or None."""+ # The bare declaration that may ground a point-marked figure is an+ # exact-value borrow appended after the percent-exact arms, so the+ # rounding arm stays percent-exact and a count declaration cannot+ # drift onto a nearby delta.candidates = [item for item in self.declarations if item.percent == percent]for declaration in candidates:if abs(declaration.value - value) <= max(abs(value) * 1e-9, 1e-9):@@ -189,7 +209,18 @@ class FiguresBlock:if abs(item.value - value) <= half_unit * (1 + 1e-9)and abs(item.value - value) <= abs(item.value) * ROUNDED_BAND]- return min(rounded, key=lambda pair: pair[0])[1] if rounded else None+ if rounded:+ return min(rounded, key=lambda pair: pair[0])[1]+ # #2107: the point-marked borrow. Reached only when the percent-exact+ # arms above found nothing, which for "1.13个百分点" is the normal+ # case — its conventionally bare declaration lives below.+ if point_marked and percent:+ for declaration in self.declarations:+ if not declaration.percent and abs(declaration.value - value) <= max(+ abs(value) * 1e-9, 1e-9+ ):+ return declaration+ return None@dataclass(frozen=True)@@ -219,6 +250,10 @@ class Figure:currency_code: str | None = Nonedigits: str = ""sign: str = ""+ # The trailing mark is a percentage-point spelling ("1.13个百分点", "3.6pp"),+ # not "%": such a figure is a percent (unit 1.0) yet conventionally declared+ # bare ("1.13"), and the gate may bind the two (#2107).+ point_marked: bool = False# The span a redaction replaces: the figure plus its glued currency and# magnitude marks ("HK$1.10", "0.95 元", "24.6M").extent: tuple[int, int] | None = None@@ -489,6 +524,20 @@ def _numbers(text: str, *, decimal_commas: bool | None = None) -> list[_Token]:body, end = f"{body}.{fraction}", stoptokens.append(_Token(match.start(), end, sign, body.replace(",", "")))cursor = end+ # A dash right after a percent mark opens a range ("20%-30%"), it is not+ # the sign of the number that follows (#2107). The endpoint keeps its own+ # sign when written ("20%- -30%" stays a list) and the dash between two+ # plain figures ("10-20") is untouched.+ scrubbed: list[_Token] = []+ for token in tokens:+ if token.sign == "-":+ between = text[max(0, token.start - 3) : token.start]+ m = re.search(r"[%%]\s*$", between)+ if m is not None:+ scrubbed.append(replace(token, sign=""))+ continue+ scrubbed.append(token)+ tokens = scrubbedsigned = [replace(token, sign=text[lead]) if not token.sign and lead is not None else tokenfor token in tokens + protected@@ -562,24 +611,27 @@ def _writes_decimal_commas(text: str) -> bool:return decimal and not grouped-def _percent_mark(text: str, end: int) -> tuple[float, int]:- """The percent a figure's trailing mark denotes, and where the mark ends.+def _percent_mark(text: str, end: int) -> tuple[float, int, bool]:+ """The percent a figure's trailing mark denotes, where the mark ends, and+ whether the mark is a percentage-point spelling rather than ``%``.- A percent sign may follow a space; ``pp`` / ``bp`` / ``bps`` must be glued- and not run into a word ("3.6ppm" is not a percentage point).+ A percent sign may follow a space; ``pp`` / ``bp`` / ``pct`` / the Chinese+ point words must be glued and not run into a word ("3.6ppm" is not a+ percentage point).Returns:- ``(1.0, end)`` for % and pp, ``(0.01, end)`` for bp, ``(0.0, end)``.+ ``(1.0, end, False)`` for %, ``(unit, end, True)`` for a point mark,+ ``(0.0, end, False)`` when there is no mark."""rest = text[end:]spaced = rest.lstrip(" \t")if spaced[:1] and spaced[0] in _PERCENT_CHARS:- return 1.0, end + len(rest) - len(spaced) + 1+ return 1.0, end + len(rest) - len(spaced) + 1, Falsefor mark, unit in _POINT_MARKS:after = rest[len(mark) : len(mark) + 1]if rest[: len(mark)].casefold() == mark and not (after.isascii() and after.isalnum()):- return unit, end + len(mark)- return 0.0, end+ return unit, end + len(mark), True+ return 0.0, end, Falsedef _reading(sign: str, digits: str, unit: float) -> tuple[float, str] | None:@@ -679,7 +731,7 @@ def _parse_value(rest = field[token.end :].strip()if rest[:1] in _MAGNITUDES and not _is_currency_mark(rest):rest = rest[1:].lstrip()- unit, consumed = _percent_mark(rest, 0)+ unit, consumed, _ = _percent_mark(rest, 0)tail = rest[consumed:].strip()if not unit and tail in _MULTIPLE_MARKS:# "5.5x": a multiple, written the way the answer writes it.@@ -698,6 +750,35 @@ def _parse_value(return value, unit > 0, canonical + ("%" if unit > 0 else "")+# A percent range written as one value ("20%-30%"): the dash runs between two+# percent marks. Narrow on purpose — plain numeric or currency ranges keep+# their existing readings.+_PERCENT_RANGE_RE = re.compile(+ r"^(?P<low>[+-]?[\d.,]+)\s*[%%]\s*[-–—~~]\s*(?P<high>[+-]?[\d.,]+)\s*[%%]$"+)+++def _parse_range(+ field: str, decimal_commas: bool | None = None+) -> list[tuple[float, bool, str]]:+ """Both endpoints of a declared percent range, each as ``_parse_value`` reads it.++ Returns:+ Two ``(value, percent, canonical)`` triples, or nothing when the field+ is not exactly ``N% - N%``.+ """+ match = _PERCENT_RANGE_RE.fullmatch(_normalize(field).text.strip())+ if match is None:+ return []+ endpoints = []+ for side in (match.group("low") + "%", match.group("high") + "%"):+ parsed = _parse_value(side, decimal_commas)+ if parsed is None:+ return []+ endpoints.append(parsed)+ return endpoints++def _is_header_or_rule(parts: Sequence[str]) -> bool:"""Whether a block line is a ``value | role`` header or a Markdown separator row."""if len(parts) >= 2 and parts[0].casefold() == "value" and parts[1].casefold() == "role":@@ -744,7 +825,26 @@ def parse_figures_block(content: str) -> FiguresBlock:continueparsed = _parse_value(parts[0], document_reading) if parts else Nonerole = parts[1].casefold() if len(parts) > 1 else ""- if parsed is None or role not in ROLES:+ if parsed is None:+ # "20%-30%" declares both endpoints: one range, two declarations.+ endpoints = _parse_range(parts[0], document_reading) if parts else []+ if not endpoints or role not in ROLES:+ malformed.append((number, line.strip()[:120]))+ continue+ for value, percent, canonical in endpoints:+ declarations.append(+ Declaration(+ index=number,+ value_text=canonical,+ value=value,+ percent=percent,+ role=role,+ note=parts[2] if len(parts) > 2 else "",+ ref=parts[3] if len(parts) > 3 else "",+ )+ )+ continue+ if role not in ROLES:malformed.append((number, line.strip()[:120]))continuevalue, percent, canonical = parsed@@ -1174,7 +1274,7 @@ def scan_figures(content: str, block: FiguresBlock) -> list[Figure]:figures: list[Figure] = []for token in _numbers(text):- unit, unit_end = _percent_mark(text, token.end)+ unit, unit_end, point_marked = _percent_mark(text, token.end)reading = _reading(token.sign, token.digits, unit)if reading is None:continue@@ -1238,6 +1338,7 @@ def scan_figures(content: str, block: FiguresBlock) -> list[Figure]:currency_code=currency_code,digits=token.digits,sign=token.sign,+ point_marked=point_marked,extent=(view.start(prefix_start), view.end(mark_end)),fence=next((info for low, high, info, _ in fences if low <= start and digits_end <= high),diff --git a/agent/src/agent/grounding/policies.py b/agent/src/agent/grounding/policies.pyindex 1fd306b6e..4d76c1916 100644--- a/agent/src/agent/grounding/policies.py+++ b/agent/src/agent/grounding/policies.py@@ -544,7 +544,9 @@ class _PolicyMixin:for figure in figures:if figure.shape not in ("measured", "bare"):continue- declaration = block.match(figure.value, figure.percent, figure.digits)+ declaration = block.match(+ figure.value, figure.percent, figure.digits, figure.point_marked+ )symbol = self._figure_symbol(content,figure,diff --git a/agent/tests/test_grounding_percentage_points.py b/agent/tests/test_grounding_percentage_points.pyindex 28ae83fff..685ca3f30 100644--- a/agent/tests/test_grounding_percentage_points.py+++ b/agent/tests/test_grounding_percentage_points.py@@ -102,3 +102,64 @@ def test_a_declared_delta_passes_in_every_spelling(text: str) -> None:)assert _verdict(declared) is True, text+++# ---------------------------------------------------------------------------+# #2107: the percentage-point unit itself, declared the conventional way.+# A CN filing states its moves in 个百分点; the block convention declares the+# bare number, and the gate used to redact the prose figure for lacking a+# matching percent declaration.+++_BARE_DECLARED = {+ "bare": "1.13",+ "unit word": "1.13个百分点",+ "percent": "1.13%",+ "pct": "1.13 pct",+}++[email protected]("spelling", _BARE_DECLARED.values(), ids=_BARE_DECLARED.keys())+def test_every_conventional_declaration_grounded_the_same_delta(spelling: str) -> None:+ """``1.13`` and ``1.13个百分点`` declare the same figure, one verdict (#2107).++ The delta is written in the answer with its unit word glued, as a CN filing+ writes it, and the declaration spells the same figure each way the+ convention allows. All four are ONE case: declared → passes.+ """+ text = "ROE同比增加1.13个百分点 (2026 Q3 filing)。"+ declared = text + "\n\n```figures\n" + f"{spelling} | cited | 2026 Q3 filing, ROE bridge\n```"++ assert _verdict(declared) is True, spelling+++def test_a_bare_declaration_does_not_ground_a_plain_percent_figure() -> None:+ """The borrow is one-way: ``37%`` in the prose needs a percent declaration.++ ``1.13`` may ground ``1.13个百分点`` because the unit word carries the+ percent-ness. ``37%`` written with a real percent sign cannot borrow the+ count declaration ``37`` — that is the assertion-vs-fraction distinction+ the contract pins (§2).+ """+ text = "市占率 37%。"+ declared = text + "\n\n```figures\n" + "37 | count | 客户数 | c1\n```"++ assert _verdict(declared) is False, "a count declaration must not ground 37%"+++def test_a_declared_percent_range_is_two_endpoints_not_malformed() -> None:+ """``20%-30%`` declares both endpoints; the scan reads no bogus ``-30%`` (#2107).++ A quarterly report's forward guidance is frequently a range. The block+ used to reject the value as malformed and the scan then emitted ``20%``+ and ``-30%`` as two undeclared figures.+ """+ text = "业绩指引:预计年度营收增长 20%-30%。"+ declared = text + "\n\n```figures\n" + "20%-30% | cited | 2026 Q3 filing, guidance\n```"++ block = parse_figures_block(declared)+ figures = scan_figures(text, block)++ assert not block.malformed+ assert [round(item.value, 2) for item in block.declarations] == [20.0, 30.0]+ assert all(figure.sign != "-" for figure in figures if figure.percent)