Skip to content

"Vibe-Trading: Your Personal Trading Agent"

fix(grounding): a metric comes from the head of a field name, and a decimal-comma answer reads its three-digit fractions (#1418, #1426)

Haozhe Wu0e820f43aff4
diff --git a/CHANGELOG.md b/CHANGELOG.md
index db740b753..8ca6fc383 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -87,7 +87,9 @@ This project adheres to [Semantic Versioning](https://semver.org/).
`*_lookback` / `*_obs` / `n_*` / `*_count` / `*_days` / `*_duration` families
no longer ground a percentage ("年化收益 81%" from 81 observations); `var`,
`var_95`, `var_99`, `cvar`, `es` and `expected_shortfall` leaves are tail-risk
- evidence, so a correct VaR is no longer refused.
+ evidence, so a correct VaR is no longer refused. A field's metric comes from
+ the head of its name, so `sharpe_sample_size` and `drawdown_threshold` are
+ no longer a Sharpe ratio or a drawdown.
- **A correction names the prints of the figure's own instrument** (#1433). The
"nearest observed" values come from that symbol (and its table column or
`ref`), not from every field of every symbol in the run.
@@ -96,7 +98,8 @@ This project adheres to [Semantic Versioning](https://semver.org/).
"%", the U+2212 minus sign, a backslash escape ("0\\.888"), an HTML entity
and an ISO code glued to the digits ("CNY0.888") no longer split a price into
unchecked integers; a decimal comma ("0,666 CNY", "12,5 %") is a decimal
- while a valid grouping ("-1,250.00") stays grouped. Fences follow CommonMark,
+ while a valid grouping ("-1,250.00") stays grouped, and an answer that writes
+ a marked decimal comma reads "2,237" and "−5,132%" beside it as decimals too. Fences follow CommonMark,
and an unterminated code fence no longer exempts the rest of the answer.
- **A year is not a price shield.** "$2050", "1999 元" and a 2031 under a close
column are checked; a price placed in a date or code column is checked; a
diff --git a/agent/src/agent/grounding/evidence.py b/agent/src/agent/grounding/evidence.py
index e562adc37..5c6fe8157 100644
--- a/agent/src/agent/grounding/evidence.py
+++ b/agent/src/agent/grounding/evidence.py
@@ -350,6 +350,12 @@ def _is_registered_price_indicator(tool: str, path: str) -> bool:
# as the whole leaf: "var_explained" and "sales_es" are not a VaR.
_EXACT_ONLY_ALIASES = frozenset({"var", "es"})
+# Field-name qualifiers that follow a metric's head and do not change what it
+# measures ("hit_rate_daily", "vol_annualized"), like a numeric parameter.
+_QUALIFIER_SUFFIXES = frozenset(
+ {"daily", "weekly", "monthly", "annual", "annualized", "yearly", "pct", "percent", "bps"}
+)
+
def _metric_kind_for_path(path: str) -> str | None:
"""Map an evidence JSON path to an analysis metric kind.
@@ -364,10 +370,19 @@ def _metric_kind_for_path(path: str) -> str | None:
return kind
# Compound leaves ("strategy_max_drawdown"): scan tokens from the right,
# where English puts the head noun, so "return_vol" is vol, not return.
+ # Only the head of a compound leaf says what it measures (#1426):
+ # "strategy_max_drawdown" is a drawdown, while "sharpe_sample_size" and
+ # "drawdown_threshold" are a size and a threshold. A trailing numeric
+ # parameter or period qualifies the head ("cvar_95", "hit_rate_daily").
tokens = [token for token in re.split(r"[_.]", leaf) if token]
- for size in (2, 1):
- for start in range(len(tokens) - size, -1, -1):
- key = "_".join(tokens[start : start + size])
+ stripped = list(tokens)
+ while stripped and (stripped[-1].isdigit() or stripped[-1] in _QUALIFIER_SUFFIXES):
+ stripped.pop()
+ for candidate in (tokens, stripped):
+ for size in (2, 1):
+ if len(candidate) < size:
+ continue
+ key = "_".join(candidate[-size:])
kind = None if key in _EXACT_ONLY_ALIASES else _ANALYSIS_KIND_ALIASES.get(key)
if kind is not None:
return kind
diff --git a/agent/src/agent/grounding/figures.py b/agent/src/agent/grounding/figures.py
index c78652ae8..3557e8fcf 100644
--- a/agent/src/agent/grounding/figures.py
+++ b/agent/src/agent/grounding/figures.py
@@ -352,8 +352,12 @@ def _numbers(text: str) -> list[_Token]:
A comma is a decimal point when the integer part is exactly "0" ("0,666"),
or when a one- or two-digit fraction carries a percent, pp/bp or currency
- mark ("12,5 %", "3,95 EUR", "€3,95"). A valid grouping stays grouped.
+ mark ("12,5 %", "3,95 EUR", "€3,95"). A document that writes an unambiguous
+ decimal comma anywhere and no unambiguous grouping ("1,234,567",
+ "1,234.56") reads every single-comma number as a decimal, so "2,237" and
+ "−5,132%" beside "1,57%" are 2.237 and −5.132%, not 2237 and −5132%.
"""
+ comma_decimals = _writes_decimal_commas(text)
tokens: list[_Token] = []
cursor = 0
for match in _NUMBER_RE.finditer(text):
@@ -362,13 +366,14 @@ def _numbers(text: str) -> list[_Token]:
raw = match.group(0)
sign = raw[0] if raw[0] in "+-" else ""
body, end = raw[len(sign) :], match.end()
- if body.startswith("0,") and body.count(",") == 1 and "." not in body:
+ if body.count(",") == 1 and "." not in body and (body.startswith("0,") or comma_decimals):
body = body.replace(",", ".")
elif body.isdigit() and text[end : end + 1] == ",":
fraction = _digit_run(text, end + 1)
stop = end + 1 + len(fraction)
if fraction and (
body == "0"
+ or comma_decimals
or (
len(fraction) <= 2
and (
@@ -384,6 +389,34 @@ def _numbers(text: str) -> list[_Token]:
return tokens
+def _writes_decimal_commas(text: str) -> bool:
+ """Whether a document writes decimal commas and never a thousands grouping.
+
+ Evidence for a decimal comma is unambiguous on its own: a "0," integer part,
+ or a one- or two-digit fraction carrying a percent, pp/bp or currency mark
+ ("1,57%", "3,95 EUR"). An unmarked "1,50" could be a list and proves nothing.
+ Evidence for grouping is two or more comma groups or a grouped number with a
+ dot fraction.
+ """
+ decimal, grouped = False, False
+ for match in _NUMBER_RE.finditer(text):
+ body = match.group(0).lstrip("+-")
+ if body.count(",") >= 2 or ("," in body and "." in body):
+ grouped = True
+ elif body.startswith("0,"):
+ decimal = True
+ elif body.isdigit() and text[match.end() : match.end() + 1] == ",":
+ fraction = _digit_run(text, match.end() + 1)
+ stop = match.end() + 1 + len(fraction)
+ if 1 <= len(fraction) <= 2 and (
+ _currency_before(text, match.start())
+ or _currency_after(text, stop)
+ or _percent_mark(text, stop)[0] > 0
+ ):
+ decimal = True
+ 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.
diff --git a/agent/tests/test_grounding_role_hardening.py b/agent/tests/test_grounding_role_hardening.py
index a1a6738db..f1e44e3e0 100644
--- a/agent/tests/test_grounding_role_hardening.py
+++ b/agent/tests/test_grounding_role_hardening.py
@@ -722,3 +722,45 @@ def test_a_count_inside_the_price_range_needs_a_derivation(tmp_path: Path) -> No
assert "observed price range" in posing.issues[0]["message"]
assert factor.valid is True, factor.issues
assert weight.valid is True, weight.issues
+
+
+ ("leaf", "kind"),
+ [
+ ("strategy_max_drawdown", "drawdown"),
+ ("cvar_95", "tail_risk"),
+ ("portfolio_var_95", "tail_risk"),
+ ("hit_rate_daily", "win_rate"),
+ ("rolling_vol_60", "vol"),
+ ("sharpe_sample_size", None),
+ ("drawdown_threshold", None),
+ ("sharpe_ci_upper", None),
+ ("return_var", None),
+ ],
+)
+def test_only_the_head_of_a_compound_leaf_names_its_metric(leaf: str, kind: str | None) -> None:
+ """#1426: a metric word that qualifies another noun does not make the field that metric."""
+ assert _metric_kind_for_path(leaf) == kind
+
+
+def test_the_spanish_var_report_from_1418_grounds_once_its_confidence_is_declared(tmp_path: Path) -> None:
+ ledger = _ledger(
+ tmp_path,
+ (
+ "portfolio_risk_xray",
+ {},
+ {"ok": True, "var_95": -0.0157, "max_drawdown": -0.05132},
+ "risk",
+ ),
+ message="Analiza el riesgo de la cartera",
+ )
+
+ declared = ledger.validate_final_answer(
+ "VaR 95%: 1,57%. Drawdown máximo −5,132%." + _block("95% | count | nivel de confianza")
+ )
+ invented = ledger.validate_final_answer(
+ "VaR 95%: 2,57%. Drawdown máximo −5,132%." + _block("95% | count | nivel de confianza")
+ )
+
+ assert declared.valid is True, declared.issues
+ assert invented.valid is False
diff --git a/agent/tests/test_grounding_shape_hardening.py b/agent/tests/test_grounding_shape_hardening.py
index 345ac2cf3..467ae465e 100644
--- a/agent/tests/test_grounding_shape_hardening.py
+++ b/agent/tests/test_grounding_shape_hardening.py
@@ -663,3 +663,27 @@ def test_an_ordinal_needs_the_space_after_its_punctuation() -> None:
assert _shapes(table.format("| 1 | 0.666 |"))["1"] == "measured"
assert _shapes(table.format("1.| 0.666 |"))["1"] == "measured"
assert _shapes("1. 第一条")["1"] == "exempt"
+
+
+def _measured_values(text: str) -> list[float]:
+ return [f.value for f in scan_figures(text, parse_figures_block(text)) if f.shape != "exempt"]
+
+
+def test_a_decimal_comma_document_reads_three_digit_fractions_as_decimals() -> None:
+ """#1418: "−5,132%" beside "1,57%" is −5.132%, and "2,237" is 2.237."""
+ values = _measured_values("VaR 95%: 1,57%. Drawdown máximo −5,132%. Ratio 2,237 EUR.")
+
+ assert -5.132 in values and 2.237 in values and 1.57 in values
+ assert -5132.0 not in values and 2237.0 not in values
+
+
+ ("text", "grouped"),
+ [
+ ("Revenue 2,237 million, down 1,5% on 1,234,567 units.", 2237.0), # a grouping anywhere wins
+ ("Close 2,237.50 USD, volume 1,500 USD.", 1500.0), # comma-and-dot is grouping
+ ("Revenue 2,237 million.", 2237.0), # no decimal-comma evidence
+ ],
+)
+def test_a_grouping_document_keeps_its_thousands(text: str, grouped: float) -> None:
+ assert grouped in _measured_values(text)