Skip to content

"Vibe-Trading: Your Personal Trading Agent"

fix(grounding): year-less dates are structure, and magnitude marks scale the comparison

Haozhe Wu76e01ceee786
diff --git a/agent/src/agent/grounding/figures.py b/agent/src/agent/grounding/figures.py
index e0d35b987..4d7b0da05 100644
--- a/agent/src/agent/grounding/figures.py
+++ b/agent/src/agent/grounding/figures.py
@@ -31,7 +31,9 @@ _NUMBER_RE = re.compile(
# SHAPE 2 — a calendar date or a bare year: structure, never a measurement
# (spec §3). A year-less "08-10" is two bare integers and needs no mask.
_DATE_RE = re.compile(
- r"(?:19|20)\d{2}\s*[-/年]\s*\d{1,2}\s*[-/月]\s*\d{1,2}\s*[日号]?"
+ r"(?P<full>(?:19|20)\d{2}\s*[-/年]\s*\d{1,2}\s*[-/月]\s*\d{1,2}\s*[日号]?)"
+ # A year-less MM-DD / MM/DD; see _short_date_is_structural.
+ r"|(?P<short>(?<![\d.])(?:0[1-9]|1[0-2])[-/](?:0[1-9]|[12]\d|3[01])(?!\d|\.\d))"
r"|\d{1,2}\s*月\s*\d{1,2}\s*[日号]"
r"|(?:19|20)\d{2}\s*年"
r"|(?:19|20)\d{2}"
@@ -57,6 +59,10 @@ _CURRENCY_CODES = frozenset(
_PERCENT_CHARS = "%%"
+# 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.
+_MAGNITUDES = {"K": 1e3, "M": 1e6, "B": 1e9, "千": 1e3, "万": 1e4, "亿": 1e8}
+
# A CJK currency word is at most three characters (人民币); bounding the run
# keeps 元宵/元件, inside longer CJK runs, from reading as money.
_MAX_CURRENCY_WORD = 3
@@ -120,6 +126,7 @@ class Figure:
column: str | None = None
date: str | None = None
symbol: str | None = None
+ scale: float = 1.0
@dataclass(frozen=True)
@@ -202,6 +209,8 @@ def _parse_value(text: str) -> tuple[float, bool] | None:
if percent:
raw = raw[:-1]
raw = raw.strip("".join(_CURRENCY_CHARS))
+ if raw and raw[-1] in _MAGNITUDES:
+ raw = raw[:-1]
if not raw:
return None
try:
@@ -374,6 +383,28 @@ def _currency_after(text: str, end: int) -> bool:
return code.upper() in _CURRENCY_CODES
+def magnitude_suffix(text: str, end: int) -> tuple[float, int]:
+ """The magnitude mark glued to the right of a figure, if any.
+
+ ``K`` / ``M`` / ``B`` count only when no further letter follows, so "5MB"
+ and "3Mn" are not millions.
+
+ Args:
+ text: The document.
+ end: Where the figure's digits end.
+
+ Returns:
+ ``(multiplier, end past the mark)``, or ``(1.0, end)`` without one.
+ """
+ mark = text[end : end + 1]
+ if not mark or mark not in _MAGNITUDES:
+ return 1.0, end
+ after = text[end + 1 : end + 2]
+ if mark.isascii() and after.isascii() and after.isalpha():
+ return 1.0, end
+ return _MAGNITUDES[mark], end + 1
+
+
def currency_prefix_start(text: str, start: int) -> int:
"""Where a currency symbol attached to the left of a figure ("$1.10") begins."""
head = text[:start]
@@ -463,6 +494,28 @@ def _within(span: tuple[int, int], spans: Sequence[tuple[int, int]]) -> bool:
return any(start <= span[0] and span[1] <= end for start, end in spans)
+def _short_date_is_structural(content: str, match: re.Match[str], full_dates: Sequence[re.Match[str]]) -> bool:
+ """Whether a year-less ``MM-DD`` is a date rather than an integer range.
+
+ Zero padding ("09-14") is how dates are written and ranges are not. An
+ unpadded one ("10-14") counts only when a full date opens the same table
+ cell or line ("2026-10-11 / 10-14"), because "| 11-12 |" may be a price range.
+
+ Args:
+ content: The candidate answer.
+ match: A ``_DATE_RE`` match of the ``short`` branch.
+ full_dates: Every match of the ``full`` branch.
+
+ Returns:
+ True when the digits are structure.
+ """
+ month, day = match.group("short")[:2], match.group("short")[3:]
+ if month.startswith("0") or day.startswith("0"):
+ return True
+ segment = max(content.rfind("\n", 0, match.start()), content.rfind("|", 0, match.start())) + 1
+ return any(segment <= full.start() and full.end() <= match.start() for full in full_dates)
+
+
def scan_figures(content: str, block: FiguresBlock) -> list[Figure]:
"""Locate and classify every number in the prose of a draft (spec §3).
@@ -487,7 +540,14 @@ def scan_figures(content: str, block: FiguresBlock) -> list[Figure]:
exempt: list[tuple[int, int]] = [
(start, end) for start, end, _, _ in _fenced_blocks(content)
]
- for pattern in (_DATE_RE, _CANONICAL_SYMBOL_RE, _ORDINAL_RE):
+ dates = list(_DATE_RE.finditer(content))
+ full_dates = [match for match in dates if match.group("full")]
+ exempt.extend(
+ (match.start(), match.end())
+ for match in dates
+ if not match.group("short") or _short_date_is_structural(content, match, full_dates)
+ )
+ for pattern in (_CANONICAL_SYMBOL_RE, _ORDINAL_RE):
exempt.extend((match.start(), match.end()) for match in pattern.finditer(content))
cell_at: list[tuple[int, int, TableRow, int]] = []
@@ -533,6 +593,7 @@ def scan_figures(content: str, block: FiguresBlock) -> list[Figure]:
date_value = row.cells[row.date_column][0] or None
if row.symbol_column is not None and row.symbol_column < len(row.cells):
symbol_value = row.cells[row.symbol_column][0] or None
+ scale = 1.0 if percent else magnitude_suffix(content, match.end())[0]
figures.append(
Figure(
text=content[start:end],
@@ -545,6 +606,7 @@ def scan_figures(content: str, block: FiguresBlock) -> list[Figure]:
column=column,
date=date_value,
symbol=symbol_value,
+ scale=scale,
)
)
return figures
diff --git a/agent/src/agent/grounding/policies.py b/agent/src/agent/grounding/policies.py
index e596e8335..16055ba08 100644
--- a/agent/src/agent/grounding/policies.py
+++ b/agent/src/agent/grounding/policies.py
@@ -520,6 +520,8 @@ class _PolicyMixin:
"""
if _close_any(figure.value, direct):
return True
+ if figure.scale != 1.0 and _close_any(figure.value * figure.scale, direct):
+ return True
candidates = {abs(figure.value), abs(figure.value) / 100.0}
magnitudes = [abs(target) for target in scaled]
return any(_close_any(candidate, magnitudes) for candidate in candidates)
diff --git a/agent/src/agent/grounding/release.py b/agent/src/agent/grounding/release.py
index 9e06c3890..65c12ccdd 100644
--- a/agent/src/agent/grounding/release.py
+++ b/agent/src/agent/grounding/release.py
@@ -17,6 +17,7 @@ from src.agent.grounding.figures import (
_lines_with_offsets,
currency_prefix_start,
currency_suffix_end,
+ magnitude_suffix,
parse_figures_block,
scan_figures,
)
@@ -659,7 +660,7 @@ class _ReleaseMixin:
continue
removed.append(text[start:end])
start = max(cursor, currency_prefix_start(text, start))
- end = currency_suffix_end(text, end)
+ end = currency_suffix_end(text, magnitude_suffix(text, end)[1])
marker = self._marker_for(text, start)
if marker is _REDACTION_MARKER_ZH:
# "建议买入价 0.95 元" → "建议买入价(略※)": flush against the word,
diff --git a/agent/tests/test_grounding_figures_contract.py b/agent/tests/test_grounding_figures_contract.py
index d0e24e723..1d3e90f0c 100644
--- a/agent/tests/test_grounding_figures_contract.py
+++ b/agent/tests/test_grounding_figures_contract.py
@@ -135,6 +135,7 @@ def test_the_block_parses_the_spec_example() -> None:
"0.666 | OBSERVED | close | c1", # role case
"¥0.666 | observed | close | c1", # currency mark on the value
"1,234.50 | observed | close | c1", # grouped thousands
+ "0.235M | observed | volume | c1", # magnitude mark on the value
],
)
def test_the_parser_is_lenient_about_form(line: str) -> None:
@@ -274,6 +275,10 @@ def _shapes(text: str) -> dict[str, str]:
"The 2026-09-09 close", # ISO date, English prose
"On 2024 levels", # bare year, English prose
"3. First conclusion", # ordered-list marker, English
+ "2026-09-11 / 09-14 两次盘中低点", # zero-padded MM-DD after a full date
+ "09-14 收盘", # zero-padded MM-DD alone
+ "2026-10-11 / 10-14 两次盘中低点", # unpadded MM-DD opened by a full date
+ "| 价位 | 含义 |\n|---|---|\n| 近端支撑 | 2026-09-11 / 09-14 盘中低点 |", # real run
],
)
def test_structural_shapes_need_no_declaration(text: str) -> None:
@@ -294,6 +299,8 @@ def test_structural_shapes_need_no_declaration(text: str) -> None:
"The close was 0.666", # decimal, English prose
"Down 37% from the high", # percent, English prose
"revenue of 400.5 billion", # decimal, English prose
+ "| 区间 |\n|---|\n| 11-12 |", # unpadded MM-DD shape may be a price range
+ "| 日期 | 区间 |\n|---|---|\n| 2026-09-09 | 11-12 |", # a date in ANOTHER cell
],
)
def test_measurement_shapes_must_be_declared(text: str) -> None:
@@ -314,6 +321,7 @@ def test_measurement_shapes_must_be_declared(text: str) -> None:
"共 16 个交易日", # count noun
"a 52-week high", # window, English prose
"over 3 sessions", # horizon, English prose
+ "a 6M holding horizon", # magnitude mark does not make a measurement
],
)
def test_bare_integers_are_not_checked(text: str) -> None:
@@ -716,3 +724,38 @@ def test_the_chinese_prompt_example_passes_the_gate_it_describes(tmp_path: Path)
)
def test_streaming_holds_back_the_figures_fence_and_nothing_else(text: str, safe: int) -> None:
assert GroundingLedger.streamable_length(text) == safe
+
+
+def test_a_magnitude_mark_scales_the_comparison_not_the_shape(tmp_path: Path) -> None:
+ """A real run quoted volume as "24.6M" and had every one cut.
+
+ The row's volume is 234567. "0.235M" and "23.46万" are that print; "0.300M"
+ is not, and is refused like any other invented figure.
+ """
+ ledger = _ledger(tmp_path)
+
+ in_millions = ledger.validate_final_answer(
+ HDR + " 成交量 0.235M 手。" + _block(HDR_ROW, "0.235M | observed | volume 2026-09-09 | 159516.SZ")
+ )
+ in_wan = ledger.validate_final_answer(
+ HDR + " 成交量 23.46万 手。" + _block(HDR_ROW, "23.46 | observed | volume 2026-09-09 | c1")
+ )
+ invented = ledger.validate_final_answer(
+ HDR + " 成交量 0.300M 手。" + _block(HDR_ROW, "0.300M | observed | volume | 159516.SZ")
+ )
+
+ assert in_millions.valid, in_millions.issues
+ assert in_wan.valid, in_wan.issues
+ assert [issue["value"] for issue in invented.issues] == ["0.300"]
+
+
+def test_a_cut_figure_takes_its_magnitude_mark_with_it(tmp_path: Path) -> None:
+ """A real release read "(omitted※)M → (omitted※)M" before this."""
+ ledger = _ledger(tmp_path)
+ draft = HDR + " 成交量 0.300M 手。"
+
+ released = ledger.redacted_release(draft, ledger.validate_final_answer(draft))
+
+ assert released is not None
+ assert "0.300" not in released
+ assert "M" not in released