Skip to content

"Vibe-Trading: Your Personal Trading Agent"

fix(grounding): read a comparison report's arithmetic as it is written

Haozhe Wuc1542cb3f2d1
diff --git a/agent/src/agent/grounding/figures.py b/agent/src/agent/grounding/figures.py
index ece12273c..68da78aae 100644
--- a/agent/src/agent/grounding/figures.py
+++ b/agent/src/agent/grounding/figures.py
@@ -28,6 +28,12 @@ from src.agent.grounding.identity import _CANONICAL_SYMBOL_RE
#: the answer must retain more digits instead of widening its evidence band.
ROUNDED_BAND = 0.005
+#: A declared value written as a fraction of two integers ("1/3").
+_FRACTION_RE = re.compile(r"([1-9]\d{0,2})\s*/\s*([1-9]\d{0,2})")
+
+#: Marks of a multiple a declared value may carry ("5.5x", "3 倍").
+_MULTIPLE_MARKS = frozenset({"x", "X", "×", "倍"})
+
#: The five roles a declaration may carry (spec §2).
ROLES = ("observed", "derived", "proposed", "cited", "count")
@@ -618,6 +624,10 @@ def _parse_value(
exactly one number and its marks.
"""
field = _normalize(text).text.strip()
+ fraction = _FRACTION_RE.fullmatch(field)
+ if fraction is not None:
+ # "1/3" for an equal weight: a value, not two numbers.
+ return int(fraction.group(1)) / int(fraction.group(2)), False, field.replace(" ", "")
tokens = _numbers(field, decimal_commas=decimal_commas)
if len(tokens) != 1:
return None
@@ -626,10 +636,11 @@ def _parse_value(
if rest[:1] in _MAGNITUDES and not _is_currency_mark(rest):
rest = rest[1:].lstrip()
unit, consumed = _percent_mark(rest, 0)
- if not (
- _is_currency_mark(rest[consumed:].strip())
- and _is_currency_mark(field[: token.start].strip())
- ):
+ tail = rest[consumed:].strip()
+ if not unit and tail in _MULTIPLE_MARKS:
+ # "5.5x": a multiple, written the way the answer writes it.
+ tail = ""
+ if not (_is_currency_mark(tail) and _is_currency_mark(field[: token.start].strip())):
return None
reading = _reading(token.sign, token.digits, unit)
if reading is None:
diff --git a/agent/src/agent/grounding/policies.py b/agent/src/agent/grounding/policies.py
index 356d57a4a..b419f670b 100644
--- a/agent/src/agent/grounding/policies.py
+++ b/agent/src/agent/grounding/policies.py
@@ -235,11 +235,19 @@ def _unanchored_term(tree: ast.Expression, observed: Callable[[float], bool]) ->
True when some added or subtracted term is unanchored.
"""
+ exponents = {
+ id(item.right)
+ for item in ast.walk(tree)
+ if isinstance(item, ast.BinOp) and isinstance(item.op, ast.Pow)
+ }
+
def anchored(node: ast.AST) -> bool:
return any(
observed(float(item.value))
for item in ast.walk(node)
- if isinstance(item, ast.Constant) and _is_number(item.value)
+ if isinstance(item, ast.Constant)
+ and _is_number(item.value)
+ and id(item) not in exponents
)
def visit(node: ast.AST, factor: bool) -> bool:
@@ -284,9 +292,16 @@ def _evaluate_formula(expression: str) -> tuple[float, list[float], ast.Expressi
.replace("(", "(")
.replace(")", ")")
.replace(",", "")
- .replace("%", "")
+ .replace("²", "**2")
+ .replace("³", "**3")
+ .replace("^", "**")
.strip()
)
+ # "12.87% − 11.36%" is 0.1287 − 0.1136: an operand written as a percent is
+ # the fraction the evidence holds, and "0.666 × (1 − 3%)" means 0.97.
+ normalized = _PERCENT_OPERAND_RE.sub(
+ lambda match: format(float(match.group(1)) / 100.0, ".12g"), normalized
+ ).replace("%", "").replace("%", "")
if not normalized:
return None
try:
@@ -305,6 +320,12 @@ def _evaluate_formula(expression: str) -> tuple[float, list[float], ast.Expressi
if isinstance(node, ast.UnaryOp) and isinstance(node.op, (ast.UAdd, ast.USub)):
value = visit(node.operand)
return value if isinstance(node.op, ast.UAdd) else -value
+ if isinstance(node, ast.BinOp) and isinstance(node.op, ast.Pow):
+ # A square or a cube (HHI is a sum of squared weights). The
+ # exponent is part of the operator, not an operand.
+ if not _is_small_exponent(node.right):
+ raise ValueError("unsupported exponent")
+ return visit(node.left) ** int(node.right.value)
if isinstance(node, ast.BinOp) and isinstance(
node.op, (ast.Add, ast.Sub, ast.Mult, ast.Div)
):
@@ -330,6 +351,35 @@ def _evaluate_formula(expression: str) -> tuple[float, list[float], ast.Expressi
return value, inputs, tree
+#: A number written with a percent sign inside a formula.
+_PERCENT_OPERAND_RE = re.compile(r"(\d+(?:\.\d+)?)\s*[%%]")
+
+
+def _is_small_exponent(node: ast.AST) -> bool:
+ """Whether a power's exponent is a literal 2 or 3."""
+ return isinstance(node, ast.Constant) and node.value in (2, 3) and not isinstance(node.value, bool)
+
+
+#: A bracketed aside holding a word: "(收益差,约−1.17pp)", "(portfolio)".
+_ANNOTATION_RE = re.compile(r"[((\[][^()()\[\]]*?(?:[\u3400-\u9fff]|[A-Za-z]{2})[^()()\[\]]*[))\]]")
+
+#: A label or unit written against a number: a CJK run, or an ASCII word of
+#: two letters or more ("Sharpe", "RP", "pp"). One letter is kept, so "1e3"
+#: stays a number and "5 x 3" stays unreadable rather than becoming "5 3".
+_LABEL_RE = re.compile(r"[\u3400-\u9fff]+|[A-Za-z]{2,}")
+
+
+def _without_labels(text: str) -> str:
+ """A note with its words removed, so the arithmetic between them can be read.
+
+ "等权Sharpe 0.692 − 风险平价 0.651" is the arithmetic "0.692 − 0.651";
+ an aside in brackets goes whole, because the number inside it
+ ("约−1.17pp") is a restatement of the result, not an operand. Nothing is
+ read from the words themselves.
+ """
+ return _LABEL_RE.sub(" ", _ANNOTATION_RE.sub(" ", text))
+
+
def _formula_in_note(note: str) -> tuple[float, list[float], ast.Expression] | None:
"""Find the derivation a note states.
@@ -351,6 +401,11 @@ def _formula_in_note(note: str) -> tuple[float, list[float], ast.Expression] | N
for separator in (",", ";", ":", "; ", ", "):
parts = [piece for part in parts for piece in part.split(separator)]
candidates.extend(part for part in parts if part.strip())
+ # Only once the note as written fails: its words removed, whole and in parts.
+ unlabelled = _without_labels(note)
+ for separator in ("≈", "≒", "=", "=", "→", "->", ",", ";", ":", "; ", ", "):
+ unlabelled = " \n ".join(unlabelled.split(separator))
+ candidates.extend(part for part in unlabelled.split(" \n ") if part.strip())
for candidate in candidates:
evaluated = _evaluate_formula(candidate)
if evaluated is not None:
diff --git a/agent/src/agent/loop.py b/agent/src/agent/loop.py
index 3fe856b13..bc932af53 100644
--- a/agent/src/agent/loop.py
+++ b/agent/src/agent/loop.py
@@ -914,13 +914,15 @@ def _is_tool_success(result: str) -> bool:
# Provider tool-call markup that a model can emit as plain text on the
# forced-text final iteration, where tool definitions are withheld. Releasing
# it verbatim hands the user mojibake instead of an answer. Both DSML bar
-# spellings are covered: ASCII double bars and fullwidth double bars.
+# spellings are covered: ASCII double bars and fullwidth double bars, opening
+# and closing tags (a draft ending in "</||DSML||invoke>" once reached the
+# grounding gate as three unreadable figures-block lines).
_FORCED_TEXT_TOOL_CALL_RE = re.compile(
r"<\s*/?\s*(?:invoke|parameter|tool_calls|dsml)\b",
re.IGNORECASE,
)
_DSML_BAR_TOOL_CALL_RE = re.compile(
- r"<\s*[|\u2502\uFF5C]{2}\s*(?:dsml|tool_calls|invoke)\b",
+ r"<\s*/?\s*[|\u2502\uFF5C]{2}\s*(?:dsml|tool_calls|invoke)\b",
re.IGNORECASE,
)
diff --git a/agent/tests/test_agent_loop_dsml_tool_calls.py b/agent/tests/test_agent_loop_dsml_tool_calls.py
index b9f810440..52da90c54 100644
--- a/agent/tests/test_agent_loop_dsml_tool_calls.py
+++ b/agent/tests/test_agent_loop_dsml_tool_calls.py
@@ -181,3 +181,23 @@ def test_agent_loop_never_releases_tool_call_syntax_as_a_final_answer(
event_type == "answer" and "<" in str(payload)
for event_type, payload in events
)
+
+
+def test_closing_dsml_tags_alone_are_tool_call_syntax() -> None:
+ """A DeepSeek draft once ended in closing tags only, inside its figures block;
+ the opening-tag pattern missed them and the gate got three unreadable lines."""
+ from src.agent.loop import _looks_like_tool_call_syntax
+
+ tail = "\n".join(
+ [
+ "```figures",
+ "0.3897 | observed | weight | rp",
+ "</||DSML||parameter>",
+ "</||DSML||invoke>",
+ "</||DSML||tool_calls>",
+ ]
+ )
+
+ assert _looks_like_tool_call_syntax("Report.\n\n" + tail)
+ assert _looks_like_tool_call_syntax("done </||DSML||invoke>")
+ assert not _looks_like_tool_call_syntax("| 标的 | 权重 |\n|---|---|\n| 000001.SZ | 38.97% |")
diff --git a/agent/tests/test_grounding_backtest_outputs.py b/agent/tests/test_grounding_backtest_outputs.py
index 1f2d0ce72..50cf83b7c 100644
--- a/agent/tests/test_grounding_backtest_outputs.py
+++ b/agent/tests/test_grounding_backtest_outputs.py
@@ -43,6 +43,7 @@ RP = {
"sortino": 1.1329,
"trade_count": 10,
"total_turnover": 1.366493,
+ "max_consecutive_loss": 2,
}
EW = {
"final_value": 1132804.94,
@@ -527,3 +528,88 @@ def test_a_trade_price_read_back_is_not_a_market_print(two_runs: GroundingLedger
assert result.valid, result.issues
assert not two_runs._price_records()
+
+
+# ---------------------------------------------------------------------------
+# How comparison reports write their arithmetic (same replayed runs)
+# ---------------------------------------------------------------------------
+
+
+ "note",
+ [
+ "等权 Sortino 1.2115 − 风险平价 1.1329",
+ "1.2115 − 1.1329(Sortino 差,约 +0.079)",
+ "Sortino 差 = 等权 1.2115 − 风险平价 1.1329(组合整体)",
+ "1.2115 − 1.1329 Sortino差",
+ ],
+)
+def test_a_labelled_formula_is_read_as_its_arithmetic(two_runs: GroundingLedger, note: str) -> None:
+ """Words glued to operands, or an aside in brackets, used to make the note
+ "not arithmetic"; the words are removed, never interpreted."""
+ result = two_runs.validate_final_answer(
+ _declared("等权 Sortino 高 0.079。", f"0.079 | derived | {note} | rp, ew")
+ )
+
+ assert result.valid, result.issues
+
+
+def test_a_labelled_formula_with_the_wrong_arithmetic_still_fails(two_runs: GroundingLedger) -> None:
+ result = two_runs.validate_final_answer(
+ _declared("等权 Sortino 高 0.12。", "0.12 | derived | 等权 1.2115 − 风险平价 1.1329 | rp, ew")
+ )
+
+ assert [issue["reason"] for issue in result.issues] == ["derivation_result_mismatch"]
+
+
+def test_percent_operands_are_the_fractions_the_evidence_holds(two_runs: GroundingLedger) -> None:
+ """"13.28% − 12.98%" is 0.1328 − 0.1298, anchored on the two total returns."""
+ result = two_runs.validate_final_answer(
+ _declared("等权总收益高 0.30pp。", "0.30pp | derived | 13.28% − 12.98% | rp, ew")
+ )
+
+ assert result.valid, result.issues
+
+
+def test_a_sum_of_squared_weights_is_arithmetic(two_runs: GroundingLedger) -> None:
+ table = two_runs.run_dir / "rp" / "artifacts" / "target_positions.csv"
+ _read(two_runs, table, "read-weights", limit=2)
+
+ anchored = two_runs.validate_final_answer(
+ _declared(
+ "初始 HHI 0.3381。",
+ "0.3381 | derived | 0.389729² + 0.300167² + 0.310103² | rp/artifacts/target_positions.csv",
+ )
+ )
+ # The exponent is not an operand: squaring an invented weight anchors nothing.
+ # The run observed a 2 (max_consecutive_loss), so an exponent that counted
+ # as an operand would anchor the invented 0.4567.
+ invented = two_runs.validate_final_answer(
+ _declared("HHI 0.4135。", "0.4135 | derived | 0.4567² + 0.3002² + 0.3389² | rp")
+ )
+
+ assert anchored.valid, anchored.issues
+ assert [issue["reason"] for issue in invented.issues] == ["additive_operand_not_observed"]
+
+
+def test_a_fraction_or_a_multiple_is_a_readable_declaration(two_runs: GroundingLedger) -> None:
+ """"1/3" and "5.5x" were unreadable lines, and one unreadable line fails the draft."""
+ result = two_runs.validate_final_answer(
+ _declared(
+ "等权每只 1/3,即 0.333;换手是等权的 1.31 倍。",
+ "1/3 | count | 等权权重 | ew",
+ "1.31x | derived | 1.366 / 1.045 | rp, ew",
+ )
+ )
+
+ assert not [issue for issue in result.issues if issue["code"] == "figures_block_malformed"]
+ assert result.valid, result.issues
+
+
+def test_only_a_literal_square_or_cube_is_evaluated() -> None:
+ """``9^9^9`` would take the process down computing a number of 370 million digits."""
+ from src.agent.grounding.policies import _formula_in_note
+
+ assert _formula_in_note("9^9^9") is None
+ assert _formula_in_note("2^10 + 1") is None
+ assert _formula_in_note("0.3^2 + 0.4^2")[0] == pytest.approx(0.25)