Skip to content

"Vibe-Trading: Your Personal Trading Agent"

fix(grounding): kind-scope analysis metric evidence and gate window claims (#1336)

cgycorey4b3fd8f6823c
diff --git a/agent/src/agent/grounding.py b/agent/src/agent/grounding.py
index eefa00c7e..95eb7bf58 100644
--- a/agent/src/agent/grounding.py
+++ b/agent/src/agent/grounding.py
@@ -43,12 +43,17 @@ GROUNDING_ARTIFACT = "grounding_evidence.json"
_RESOLVER_TOOL = "search_symbol"
-# Tools whose successful completion grounds backtest/analysis metric claims
-# (#1336). A deduplicated ("skipped") call also counts: the loop only skips a
-# call that already completed successfully, and its result lives in the run.
+# Tools whose successful completion can ground backtest/analysis metric claims
+# (#1336). Success alone is not authority: only results that actually carried
+# metric output (parsed from the result or its run-dir artifacts) raise
+# ``analysis_claim_unavailable``. A deduplicated ("skipped") call is never a
+# completion.
_ANALYSIS_TOOLS = frozenset(
{"backtest", "factor_analysis", "run_shadow_backtest", "quantlib_call"}
)
+# Tools whose run produces the equity/regime windows behind a categorical
+# "all N-month windows were profitable" statement.
+_ANALYSIS_WINDOW_TOOLS = frozenset({"backtest", "run_shadow_backtest"})
_PRIVATE_COMPANY_SKILL_NAMES = {
"private-company",
"private-company-analysis",
@@ -243,7 +248,8 @@ _ANALYSIS_METRIC_RE = re.compile(
r"\bsharpe(?: ratio)?\b|\bwin rate\b|\bhit rate\b|"
r"\bprob(?:ability)?\.?\s+of\b|\bvolatility\b|\bdrawdown\b|"
r"\bannualiz\w*\b|\bwindow(?:s)?\b|\bregime(?:s)?\b|"
- r"夏普|回撤|波动率|胜率|命中率|概率|年化|回测|窗口)",
+ r"\b(?:annual|cumulative|total)\s+return\b|"
+ r"夏普|回撤|波动率|胜率|命中率|概率|年化|回测|窗口|收益(?:率)?|回报(?:率)?)",
re.IGNORECASE,
)
# Measurement-shaped numbers for analysis claims: keeps the % sign and sign
@@ -263,6 +269,75 @@ _FORECAST_FRAME_RE = re.compile(
r"(?:\b(?:forecast|expected|projected|predicted)\b|预计|预期|预测|估计|展望)",
re.IGNORECASE,
)
+
+# Metric family for a claim/evidence leaf, so a figure is only grounded by
+# evidence of its own kind: an observed price must never stand in for an
+# invented volatility (#1336).
+_ANALYSIS_KIND_ALIASES = {
+ "annualized_vol": "vol",
+ "annualized_volatility": "vol",
+ "volatility": "vol",
+ "return_vol": "vol",
+ "return_volatility": "vol",
+ "vol": "vol",
+ "max_drawdown": "drawdown",
+ "maxdd": "drawdown",
+ "drawdown": "drawdown",
+ "sharpe": "sharpe",
+ "sharpe_ratio": "sharpe",
+ "win_rate": "win_rate",
+ "hit_rate": "win_rate",
+ "hitrate": "win_rate",
+ "probability": "probability",
+ "prob": "probability",
+ "total_return": "return",
+ "annual_return": "return",
+ "cumulative_return": "return",
+ "benchmark_return": "return",
+ "excess_return": "return",
+ "annualized_return": "return",
+ "return": "return",
+ "returns": "return",
+ "ic_positive_ratio": "win_rate",
+}
+
+# Order matters: 最大回撤 is drawdown before 收益/return, and 年化波动率 is vol
+# before the generic return branch.
+_ANALYSIS_KIND_PATTERNS: tuple[tuple[re.Pattern[str], str], ...] = (
+ (re.compile(r"(?:回撤|drawdown|maxdd|最大亏损)", re.IGNORECASE), "drawdown"),
+ (
+ re.compile(
+ r"(?:波动率|波动性|volatility|annualized\s*vol|return\s*vol|年化波动)",
+ re.IGNORECASE,
+ ),
+ "vol",
+ ),
+ (re.compile(r"(?:夏普|sharpe)", re.IGNORECASE), "sharpe"),
+ (re.compile(r"(?:胜率|命中率|win\s*rate|hit\s*rate)", re.IGNORECASE), "win_rate"),
+ (re.compile(r"(?:概率|probability|prob)", re.IGNORECASE), "probability"),
+ (re.compile(r"(?:收益|回报|收益率|回报率|\breturns?\b)", re.IGNORECASE), "return"),
+)
+
+# Definitional prose ("夏普比率大于 1.0 通常被认为较好") states a convention,
+# not a measurement this session produced (#1336: preserve explicitly labelled
+# definitions). The bare 通常 alone is deliberately not enough — "通常实现
+# 18.2% 年化" is a measured claim.
+_DEFINITION_FRAME_RE = re.compile(
+ r"(?:通常(?:认为|被?认为|说来|指|用于)|一般认为|定义为|是指|惯例|"
+ r"conventionally|typically\s+(?:considered|regarded|seen)|"
+ r"generally\s+(?:accepted|considered|regarded)|by\s+convention)",
+ re.IGNORECASE,
+)
+
+# A categorical "all N-month windows were profitable" claim carries only an
+# integer window length, which _MEASURE_NUMBER_RE deliberately ignores; it is a
+# measured fact about the run and needs a window-producing analysis result.
+_CATEGORICAL_WINDOW_RE = re.compile(
+ r"(?:所有|全部|每个|任何|each|every|all)[\s\S]{0,40}?"
+ r"(?:窗口|区间|windows?|periods?)[\s\S]{0,30}?"
+ r"(?:正收益|均为正|都为正|盈利|上涨|positive|profitable)",
+ re.IGNORECASE,
+)
_DERIVATION_RE = re.compile(
r"(?:\bderived\b|\bcalculated\b|\bformula\b|\bbased on\b|计算|推导|公式|基于)",
re.IGNORECASE,
@@ -884,6 +959,24 @@ def _price_field_for_path(path: str) -> str | None:
return _GENERIC_PRICE_FIELD_ALIASES.get(leaf)
+def _metric_kind_for_path(path: str) -> str | None:
+ """Map an evidence JSON path to an analysis metric kind."""
+ leaf = re.sub(r"\[\d+\]$", "", str(path or "").rsplit(".", 1)[-1])
+ leaf = leaf.strip().casefold()
+ kind = _ANALYSIS_KIND_ALIASES.get(leaf)
+ if kind is not None:
+ return kind
+ return _metric_kind_for_text(path)
+
+
+def _metric_kind_for_text(text: str) -> str | None:
+ """Return the analysis metric kind named in a claim or header."""
+ for pattern, kind in _ANALYSIS_KIND_PATTERNS:
+ if pattern.search(text):
+ return kind
+ return None
+
+
def _scan_symbols(text: str) -> set[str]:
"""Return the canonical symbols written anywhere in a blob of text."""
return {
@@ -1085,6 +1178,7 @@ class GroundingLedger:
self._evidence: list[EvidenceRecord] = []
self._tool_failures: list[dict[str, Any]] = []
self._analysis_completed: list[dict[str, Any]] = []
+ self._analysis_metrics: list[dict[str, Any]] = []
self._validations: list[dict[str, Any]] = []
self._recovery_rounds = 0
self._symbol_resolution_attempts = 0
@@ -1376,9 +1470,7 @@ class GroundingLedger:
self._track_session_symbols(arguments, result)
if tool_name in _ANALYSIS_TOOLS:
- self._analysis_completed.append(
- {"call_id": call_id, "tool": tool_name, "recorded_at": _utc_now()}
- )
+ self._ingest_analysis_result(tool_name, arguments, payload, call_id)
if tool_name == _RESOLVER_TOOL:
self._ingest_resolution(arguments, payload, call_id)
elif tool_name == "get_market_data":
@@ -1387,6 +1479,190 @@ class GroundingLedger:
self._ingest_generic_numeric(tool_name, arguments, payload, call_id)
self.persist()
+ def _ingest_analysis_result(
+ self,
+ tool_name: str,
+ arguments: Mapping[str, Any],
+ payload: dict[str, Any] | None,
+ call_id: str,
+ ) -> None:
+ """Record metric numbers a completed analysis result actually produced.
+
+ Success of the call envelope is not enough: ``backtest`` reports ok for
+ any runner exit, and a deduplicated ("skipped") call carries no new
+ result at all (#1336). Only results that yielded at least one
+ recognisable metric figure count as completed analysis.
+ """
+ if payload is None or payload.get("skipped"):
+ return
+ if tool_name == "backtest":
+ if str(payload.get("status") or "").casefold() != "ok" and payload.get(
+ "exit_code"
+ ) not in (0, "0"):
+ return
+ recorded = self._record_backtest_metrics(arguments, payload, call_id)
+ elif tool_name == "factor_analysis":
+ if str(payload.get("status") or "").casefold() != "ok":
+ return
+ recorded = self._record_leaf_metrics(payload, call_id, tool_name, "")
+ elif tool_name == "run_shadow_backtest":
+ if str(payload.get("status") or "").casefold() != "ok":
+ return
+ combined = payload.get("combined")
+ if not isinstance(combined, dict):
+ # A combined dict containing only {"error": ...} is no analysis.
+ return
+ recorded = self._record_leaf_metrics(combined, call_id, tool_name, "combined")
+ elif tool_name == "quantlib_call":
+ if payload.get("ok") is not True or str(
+ arguments.get("action") or ""
+ ).casefold() != "call":
+ return
+ function = str(arguments.get("function") or "")
+ recorded = self._record_leaf_metrics(
+ payload.get("result"), call_id, tool_name, function
+ )
+ else:
+ return
+ if recorded:
+ self._analysis_completed.append(
+ {"call_id": call_id, "tool": tool_name, "recorded_at": _utc_now()}
+ )
+
+ def _record_leaf_metrics(
+ self,
+ value: Any,
+ call_id: str,
+ tool_name: str,
+ field_prefix: str,
+ ) -> int:
+ """Record nested numeric leaves whose key names a metric kind."""
+ recorded = 0
+
+ def visit(item: Any, path: str) -> None:
+ nonlocal recorded
+ if _is_number(item):
+ kind = _metric_kind_for_path(path)
+ if kind is None:
+ return
+ self._analysis_metrics.append(
+ {
+ "metric": kind,
+ "value": float(item),
+ "tool": tool_name,
+ "call_id": call_id,
+ "field": path,
+ }
+ )
+ recorded += 1
+ return
+ if isinstance(item, dict):
+ for key, child in item.items():
+ visit(child, f"{path}.{key}" if path else str(key))
+ elif isinstance(item, list):
+ for index, child in enumerate(item):
+ visit(child, f"{path}[{index}]")
+
+ visit(value, field_prefix or "")
+ return recorded
+
+ def _record_backtest_metrics(
+ self,
+ arguments: Mapping[str, Any],
+ payload: dict[str, Any],
+ call_id: str,
+ ) -> int:
+ """Parse metric figures from a successful backtest's run-dir artifacts."""
+ root = self.run_dir.resolve()
+ candidates: list[Path] = []
+ raw_dir = arguments.get("run_dir") or payload.get("run_dir")
+ if raw_dir:
+ candidate = Path(str(raw_dir))
+ if not candidate.is_absolute():
+ candidate = self.run_dir / candidate
+ try:
+ resolved = candidate.resolve()
+ if resolved == root or resolved.is_relative_to(root):
+ candidates.append(resolved)
+ except OSError:
+ pass
+ # The loop archives a detached backtest's artifacts into the active run
+ # dir right after it succeeds, so that copy is the second candidate.
+ candidates.append(root)
+ artifacts = payload.get("artifacts")
+ if isinstance(artifacts, dict):
+ for path_value in artifacts.values():
+ if not isinstance(path_value, str):
+ continue
+ try:
+ resolved = Path(path_value).resolve()
+ if resolved.is_relative_to(root):
+ candidates.append(resolved)
+ except OSError:
+ continue
+ files: list[Path] = []
+ seen_dirs: set[Path] = set()
+ for candidate in candidates:
+ if candidate.is_file():
+ files.append(candidate)
+ continue
+ if candidate in seen_dirs:
+ continue
+ seen_dirs.add(candidate)
+ for dir_path in (candidate, candidate / "artifacts"):
+ for name in ("metrics.csv", "metrics.json"):
+ target = dir_path / name
+ if target.is_file():
+ files.append(target)
+ recorded = 0
+ seen_files: set[Path] = set()
+ for file_path in files:
+ if file_path in seen_files:
+ continue
+ seen_files.add(file_path)
+ recorded += self._record_metrics_file(file_path, call_id)
+ return recorded
+
+ def _record_metrics_file(self, path: Path, call_id: str) -> int:
+ """Record metric figures from one metrics.csv/metrics.json artifact."""
+ try:
+ text = path.read_text(encoding="utf-8")
+ except (OSError, UnicodeDecodeError):
+ return 0
+ if path.suffix == ".json":
+ try:
+ data = json.loads(text)
+ except json.JSONDecodeError:
+ return 0
+ if not isinstance(data, dict):
+ return 0
+ return self._record_leaf_metrics(data, call_id, "backtest", "")
+ try:
+ rows = list(csv.reader(text.splitlines()))
+ except csv.Error:
+ return 0
+ if len(rows) < 2:
+ return 0
+ header = [cell.strip().casefold() for cell in rows[0]]
+ recorded = 0
+ for index, raw in enumerate(rows[1]):
+ if index >= len(header):
+ break
+ kind = _ANALYSIS_KIND_ALIASES.get(header[index])
+ value = _coerce_csv_number(raw)
+ if kind is not None and value is not None:
+ self._analysis_metrics.append(
+ {
+ "metric": kind,
+ "value": float(value),
+ "tool": "backtest",
+ "call_id": call_id,
+ "field": header[index],
+ }
+ )
+ recorded += 1
+ return recorded
+
def validate_final_answer(self, content: str) -> ValidationResult:
"""Validate identity assertions and numeric price claims.
@@ -1630,6 +1906,8 @@ class GroundingLedger:
"session_symbol_roots": sorted(self._session_symbol_roots),
"evidence": [asdict(record) for record in self._evidence],
"tool_failures": list(self._tool_failures),
+ "analysis_completed": list(self._analysis_completed),
+ "analysis_evidence": list(self._analysis_metrics),
"validations": list(self._validations),
}
temp.write_text(
@@ -2343,62 +2621,111 @@ class GroundingLedger:
return issues
def _validate_analysis_claims(self, content: str) -> list[dict[str, Any]]:
- """Reject backtest/analysis metrics with no supporting tool result.
+ """Reject backtest/analysis metrics with no kind-scoped evidence.
#1336: after failed or deduplicated market-data calls the model may
still present return-volatility / drawdown / probability figures as
- measured facts. Two support paths make a metric figure legitimate:
-
- * a completed analysis tool (``_analysis_completed``) — the backtest
- family, whose metric numbers live in run-dir files and therefore
- never enter ``_evidence``; and
- * value-level match against observed evidence — any successful tool's
- numeric output (e.g. ``portfolio_risk_xray``) is flattened into
- ``_evidence``, so a figure the run actually observed is accepted.
-
- A figure with neither origin has no source but model memory. This is
- the same shape as ``_compare_price_claim``: value in the observed
- corpus → pass; value absent → reject. Note that a hand-maintained
- analysis-tool list is deliberately avoided (see the test that replaced
- the nine-tool price list with a uniqueness check).
+ measured facts. A metric figure is legitimate only when the run's
+ evidence contains the same *kind* of figure — recorded from a
+ completed analysis result (backtest artifacts, factor/shadow/quantlib
+ output) or from any successful tool's numeric output (e.g.
+ ``portfolio_risk_xray``, flattened into ``_evidence``). Kind scoping
+ is what keeps an observed price from standing in for an invented
+ volatility figure. Definitional prose ("夏普比率大于 1.0 通常被认为
+ 较好"), explicitly forward-looking forecasts, and categorical
+ historical-window facts without any window-producing analysis are
+ handled separately here.
Args:
content: Candidate assistant answer.
Returns:
- One issue per metric-bearing clause or table row.
+ One issue per metric-bearing clause or table cell.
"""
- if self._analysis_completed:
- return []
issues: list[dict[str, Any]] = []
lines = content.splitlines()
- table_mode = any(
- line.count("|") >= 2 and _ANALYSIS_METRIC_RE.search(line)
- for line in lines
- )
- for line in lines:
- is_table_line = table_mode and line.count("|") >= 2
- # A pipe table whose header names metrics: every numeric cell row
- # is a metric claim, even though the marker lives on the header
- # line rather than the data row.
- segments = [line] if is_table_line else _split_clauses(line)
- for segment in segments:
- masked = _LOCALIZED_DATE_RE.sub(" ", segment)
- masked = _DATE_RE.sub(" ", masked)
- masked = _SHORT_DATE_RE.sub(" ", masked)
- masked = _DASH_DATE_RE.sub(" ", masked)
- values = [
- match.group(0).replace(" ", "").replace(",", "")
- for match in _MEASURE_NUMBER_RE.finditer(masked)
- ]
+ consumed: set[int] = set()
+ for header, rows, row_indices in self._pipe_tables(lines):
+ consumed.update(row_indices)
+ columns = [
+ (cell, _metric_kind_for_text(cell), bool(_FORECAST_FRAME_RE.search(cell)))
+ for cell in header
+ ]
+ if not any(kind for _, kind, _ in columns):
+ continue
+ for row in rows:
+ cells = row + [""] * (len(columns) - len(row))
+ for (cell_text, kind, header_forecast), cell in zip(columns, cells):
+ if kind is None or header_forecast:
+ continue
+ values = self._measure_numbers(cell)
+ if not values:
+ continue
+ # A forecast annotation inside the cell ("预计 12.4%")
+ # exempts only that cell, never its neighbours.
+ if _FORECAST_FRAME_RE.search(cell) or _DEFINITION_FRAME_RE.search(
+ cell
+ ):
+ continue
+ unsupported = [
+ value
+ for value in values
+ if not self._analysis_value_observed(value, kind)
+ ]
+ if not unsupported:
+ continue
+ issues.append(
+ {
+ "code": "analysis_claim_unavailable",
+ "claim": f"{cell_text}: {cell}"[:200],
+ "value": unsupported[0],
+ "kind": kind,
+ "message": (
+ "No supporting analysis evidence (a completed "
+ "backtest result or observed risk metric) exists "
+ "for this figure. Mark the analysis as incomplete "
+ "and omit these figures."
+ ),
+ }
+ )
+ for index, line in enumerate(lines):
+ if index in consumed:
+ continue
+ for segment in _split_clauses(line):
+ if _CATEGORICAL_WINDOW_RE.search(segment) and _NUMBER_RE.search(segment):
+ if not any(
+ entry.get("tool") in _ANALYSIS_WINDOW_TOOLS
+ for entry in self._analysis_completed
+ ):
+ match = _NUMBER_RE.search(segment)
+ issues.append(
+ {
+ "code": "analysis_claim_unavailable",
+ "claim": segment.strip()[:200],
+ "value": match.group(0) if match else None,
+ "message": (
+ "No backtest completed in this session, yet the "
+ "answer states a categorical historical-window "
+ "fact. Mark the analysis as incomplete and omit "
+ "this claim."
+ ),
+ }
+ )
+ continue
+ if _DEFINITION_FRAME_RE.search(segment):
+ continue
+ values = self._measure_numbers(segment)
if not values:
continue
- if not is_table_line and not _ANALYSIS_METRIC_RE.search(segment):
+ if not _ANALYSIS_METRIC_RE.search(segment):
continue
if _FORECAST_FRAME_RE.search(segment):
continue
+ kind = _metric_kind_for_text(segment)
unsupported = [
- value for value in values if not self._analysis_value_observed(value)
+ value
+ for value in values
+ if not self._analysis_value_observed(value, kind)
]
if not unsupported:
continue
@@ -2407,39 +2734,91 @@ class GroundingLedger:
"code": "analysis_claim_unavailable",
"claim": segment.strip()[:200],
"value": unsupported[0],
+ "kind": kind,
"message": (
- "No backtest or analysis tool completed successfully "
- "in this session, yet the answer states analysis "
- "figures. Mark the analysis as incomplete and omit "
+ "No supporting analysis evidence (a completed "
+ "backtest result or observed risk metric) exists for "
+ "this figure. Mark the analysis as incomplete and omit "
"these figures."
),
}
)
return issues
- def _analysis_value_observed(self, raw: str) -> bool:
- """Return True when a claim measurement matches observed evidence.
+ @staticmethod
+ def _measure_numbers(text: str) -> list[str]:
+ """Extract measurement-shaped numbers (decimal or percent) from a claim."""
+ masked = _LOCALIZED_DATE_RE.sub(" ", text)
+ masked = _DATE_RE.sub(" ", masked)
+ masked = _SHORT_DATE_RE.sub(" ", masked)
+ masked = _DASH_DATE_RE.sub(" ", masked)
+ return [
+ match.group(0).replace(" ", "").replace(",", "")
+ for match in _MEASURE_NUMBER_RE.finditer(masked)
+ ]
+
+ @staticmethod
+ def _pipe_tables(
+ lines: Sequence[str],
+ ) -> list[tuple[list[str], list[list[str]], list[int]]]:
+ """Yield (header cells, row cells, row line indices) per pipe table."""
+ tables: list[tuple[list[str], list[list[str]], list[int]]] = []
+ index = 0
+ while index < len(lines):
+ if lines[index].count("|") < 2:
+ index += 1
+ continue
+ block_start = index
+ block: list[str] = []
+ while index < len(lines) and lines[index].count("|") >= 2:
+ block.append(lines[index])
+ index += 1
+ rows: list[list[str]] = []
+ row_indices: list[int] = []
+ for offset, block_line in enumerate(block[1:], start=1):
+ cells = GroundingLedger._table_cells(block_line)
+ if not cells or all(
+ _TABLE_SEPARATOR_RE.fullmatch(cell.strip()) for cell in cells
+ ):
+ continue
+ rows.append(cells)
+ row_indices.append(block_start + offset)
+ tables.append((GroundingLedger._table_cells(block[0]), rows, row_indices))
+ return tables
+
+ def _analysis_value_observed(self, raw: str, kind: str | None) -> bool:
+ """Return True when a claim measurement matches kind-scoped evidence.
Tools disagree on scale: ``compute_risk_xray`` returns fractions
(annualized_vol 0.182, max_drawdown -0.094) while answers quote
percents (18.2%, -9.4%). Try both the value and its percent scaling
- so an observed 0.182 grounds an 18.2% claim and vice versa.
+ so an observed 0.182 grounds an 18.2% claim and vice versa. Drawdown
+ sign conventions disagree too (positive vs negative fraction), so
+ magnitude is compared for that kind. Only evidence of the claim's own
+ kind counts: an observed price never grounds a volatility figure.
"""
try:
value = float(raw.replace("%", "").replace("%", "").replace(",", ""))
except ValueError:
return True
- observed = [
- float(record.value)
- for record in self._evidence
- if record.value is not None and record.status == "observed"
- ]
+ observed: list[float] = []
+ for record in self._analysis_metrics:
+ if record.get("metric") == kind and record.get("value") is not None:
+ observed.append(float(record["value"]))
+ for record in self._evidence:
+ if record.status != "observed" or record.value is None:
+ continue
+ if _metric_kind_for_path(record.field) != kind:
+ continue
+ observed.append(float(record.value))
candidates = {value, value / 100.0}
- return any(
- abs(candidate - item) <= max(abs(item) * 0.005, 1e-9)
- for candidate in candidates
- for item in observed
- )
+ if kind == "drawdown":
+ candidates |= {abs(value), abs(value) / 100.0}
+
+ def close(candidate: float, item: float) -> bool:
+ return abs(candidate - item) <= max(abs(item) * 0.005, 1e-9)
+
+ return any(close(candidate, item) for candidate in candidates for item in observed)
def _validate_price_claims(self, content: str) -> list[dict[str, Any]]:
"""Check Markdown OHLC tables and price prose against observed records.
diff --git a/agent/tests/test_agent_grounding.py b/agent/tests/test_agent_grounding.py
index 2a2005430..fd27d4456 100644
--- a/agent/tests/test_agent_grounding.py
+++ b/agent/tests/test_agent_grounding.py
@@ -2843,26 +2843,38 @@ def test_backtest_metrics_rejected_when_no_analysis_result(
def test_backtest_metrics_accepted_after_successful_backtest(
tmp_path: Path,
) -> None:
- """#1336: a genuinely completed backtest grounds the same figures."""
+ """#1336: a genuinely completed backtest grounds metrics its artifact holds."""
+ run_dir = tmp_path / "runs" / "compare"
+ (run_dir / "artifacts").mkdir(parents=True)
+ (run_dir / "artifacts" / "metrics.csv").write_text(
+ "total_return,sharpe,max_drawdown\n0.124,1.21,-0.081\n",
+ encoding="utf-8",
+ )
ledger = GroundingLedger(
run_dir=tmp_path,
user_message="比较几支标的并回测不同市场状态",
)
ledger.ingest_tool_result(
tool_name="backtest",
- arguments={"run_dir": "runs/compare"},
- result=(
- '{"exit_code": 0, "stdout": "ok", "stderr": "", "artifacts": '
- '["metrics.csv"], "run_dir": "runs/compare"}'
+ arguments={"run_dir": str(run_dir)},
+ result=json.dumps(
+ {
+ "status": "ok",
+ "exit_code": 0,
+ "run_dir": str(run_dir),
+ "artifacts": {
+ "metrics.csv": str(run_dir / "artifacts" / "metrics.csv")
+ },
+ }
),
call_id="bt-ok",
success=True,
)
good = ledger.validate_final_answer(
- "| 策略 | Return vol | MaxDD | Prob. of hitting target |\n"
+ "| 策略 | 年化收益 | 夏普比率 | MaxDD |\n"
"|---|---:|---:|---:|\n"
- "| M1 | 12.4% | -8.1% | 55% |"
+ "| M1 | 12.4% | 1.21 | -8.1% |"
)
assert good.valid is True, good.issues
@@ -2961,3 +2973,143 @@ def test_forecast_probability_is_not_a_measured_claim(tmp_path: Path) -> None:
)
assert good.valid is True, good.issues
+
+
+def test_valid_price_does_not_launder_unsupported_analysis_metric(
+ tmp_path: Path,
+) -> None:
+ """A valid quote must not make an invented backtest metric acceptable."""
+ ledger = GroundingLedger(
+ run_dir=tmp_path,
+ user_message="AAPL.US 现价多少",
+ )
+ ledger.ingest_tool_result(
+ tool_name="get_market_data",
+ arguments={"codes": ["AAPL.US"]},
+ result=json.dumps(
+ {"AAPL.US": [{"trade_date": "2026-09-02", "close": 18.2}]}
+ ),
+ call_id="quote",
+ success=True,
+ )
+
+ result = ledger.validate_final_answer(
+ "AAPL.US 收盘价 18.2 USD。历史回测年化波动率 18.2%。"
+ )
+
+ assert result.valid is False, result.issues
+ assert any(issue["code"] == "analysis_claim_unavailable" for issue in result.issues)
+
+
+def test_successful_backtest_only_supports_metrics_in_its_artifact(
+ tmp_path: Path,
+) -> None:
+ """One successful result must not authorize unrelated invented metrics."""
+ metrics = tmp_path / "artifacts" / "metrics.csv"
+ metrics.parent.mkdir()
+ metrics.write_text("annual_return,sharpe\n0.182,1.21\n", encoding="utf-8")
+ ledger = GroundingLedger(
+ run_dir=tmp_path,
+ user_message="回测策略",
+ )
+ ledger.ingest_tool_result(
+ tool_name="backtest",
+ arguments={"run_dir": str(tmp_path)},
+ result=json.dumps(
+ {
+ "status": "ok",
+ "run_dir": str(tmp_path),
+ "artifacts": {"metrics": str(metrics)},
+ }
+ ),
+ call_id="backtest",
+ success=True,
+ )
+
+ result = ledger.validate_final_answer(
+ "策略年化收益 18.2%,夏普比率 1.21,最大回撤 -9.4%。"
+ )
+
+ assert result.valid is False, result.issues
+ assert any(issue.get("value") == "-9.4%" for issue in result.issues)
+
+
+def test_skipped_analysis_result_does_not_authorize_metrics(tmp_path: Path) -> None:
+ """A skipped/deduplicated call is not a completed analysis."""
+ ledger = GroundingLedger(run_dir=tmp_path, user_message="回测策略")
+ ledger.ingest_tool_result(
+ tool_name="backtest",
+ arguments={"run_dir": str(tmp_path)},
+ result=json.dumps({"skipped": True, "reason": "already completed"}),
+ call_id="backtest-skipped",
+ success=True,
+ )
+
+ result = ledger.validate_final_answer("回测年化收益 18.2%,最大回撤 -9.4%。")
+
+ assert result.valid is False, result.issues
+
+
+def test_integer_historical_window_claim_is_rejected(tmp_path: Path) -> None:
+ """Categorical claims about all historical windows need evidence too."""
+ ledger = GroundingLedger(run_dir=tmp_path, user_message="分析策略")
+
+ result = ledger.validate_final_answer("所有历史 12 个月窗口均实现正收益。")
+
+ assert result.valid is False, result.issues
+ assert any(issue["code"] == "analysis_claim_unavailable" for issue in result.issues)
+
+
+def test_analysis_definition_is_not_rejected(tmp_path: Path) -> None:
+ """A threshold definition is not a measured result from this session."""
+ ledger = GroundingLedger(run_dir=tmp_path, user_message="什么是夏普比率?")
+
+ result = ledger.validate_final_answer("夏普比率大于 1.0 通常被认为较好。")
+
+ assert result.valid is True, result.issues
+
+
+def test_forecast_table_cell_does_not_exempt_measured_cell(
+ tmp_path: Path,
+) -> None:
+ """A forecast column must not hide an unsupported historical metric cell."""
+ ledger = GroundingLedger(run_dir=tmp_path, user_message="比较两种策略")
+
+ result = ledger.validate_final_answer(
+ "| 策略 | 预计收益 | 历史最大回撤 |\n"
+ "|---|---:|---:|\n"
+ "| M1 | 预计 12.4% | -8.1% |"
+ )
+
+ assert result.valid is False, result.issues
+ assert any(issue["code"] == "analysis_claim_unavailable" for issue in result.issues)
+
+
+def test_analysis_completion_is_persisted_with_metric_provenance(
+ tmp_path: Path,
+) -> None:
+ """The grounding artifact records why an analysis figure was accepted."""
+ metrics = tmp_path / "artifacts" / "metrics.csv"
+ metrics.parent.mkdir()
+ metrics.write_text("annual_return\n0.182\n", encoding="utf-8")
+ ledger = GroundingLedger(run_dir=tmp_path, user_message="回测策略")
+ ledger.ingest_tool_result(
+ tool_name="backtest",
+ arguments={"run_dir": str(tmp_path)},
+ result=json.dumps(
+ {
+ "status": "ok",
+ "run_dir": str(tmp_path),
+ "artifacts": {"metrics": str(metrics)},
+ }
+ ),
+ call_id="backtest",
+ success=True,
+ )
+
+ artifact = json.loads(
+ (tmp_path / "artifacts" / "grounding_evidence.json").read_text(encoding="utf-8")
+ )
+
+ assert artifact["analysis_evidence"]
+ assert artifact["analysis_evidence"][0]["metric"] == "return"