Skip to content

"Vibe-Trading: Your Personal Trading Agent"

fix(agent): treat bash-written run-dir OHLC CSVs as observed evidence

Will Liao25eeb291058c
diff --git a/agent/src/agent/grounding.py b/agent/src/agent/grounding.py
index 13db61f80..52026ff40 100644
--- a/agent/src/agent/grounding.py
+++ b/agent/src/agent/grounding.py
@@ -21,6 +21,7 @@ its state machine and final-answer checks remain deterministic and testable.
from __future__ import annotations
import ast
+import csv
import hashlib
import json
import math
@@ -74,6 +75,23 @@ _TIMESTAMP_FIELDS = ("trade_date", "date", "datetime", "timestamp", "time", "ind
_MAX_GENERIC_EVIDENCE = 2_000
_MAX_TRACKED_SYMBOLS = 5_000
+# CSV columns (case-insensitive) accepted from OHLC files the run wrote via
+# bash+yfinance, and their canonical price-field names. Everything else in the
+# file (Volume, Adj Close, etc.) is deliberately ignored so the contradiction
+# check does not gain values it would be willing to accept.
+_CSV_PRICE_COLUMNS = {
+ "open": "open",
+ "high": "high",
+ "low": "low",
+ "close": "close",
+ "price": "price",
+}
+_CSV_DATE_COLUMNS = {"date", "datetime", "trade_date", "timestamp", "index"}
+# Filename -> symbol mapping for run-dir CSVs. The bash workaround writes each
+# series with a filesystem-safe stem: ``BYN_V.csv`` for ``BYN.V``, ``PDI_TO.csv``
+# for ``PDI.TO``, ``GC_F.csv`` for ``GC=F``.
+_CSV_FILENAME_SUFFIX_MAP = (("_V", ".V"), ("_TO", ".TO"), ("_F", "=F"))
+
# Only ``get_market_data`` returns bars whose columns are already the canonical
# OHLC field names. Every other market-sensitive tool nests its quote somewhere,
# and ``_ingest_generic_numeric`` stores that JSON path verbatim — "data.last",
@@ -320,6 +338,30 @@ def _normalize_symbol(value: Any) -> str:
return str(value or "").strip().upper()
+def _symbol_from_csv_filename(stem: str) -> str | None:
+ """Map a run-dir CSV stem back to a canonical project symbol.
+
+ The bash workaround writes filesystem-safe stems: ``BYN_V.csv`` -> ``BYN.V``,
+ ``PDI_TO.csv`` -> ``PDI.TO``, ``GC_F.csv`` -> ``GC=F``. A stem without a
+ recognized suffix (e.g. a bare US name ``AAPL``) maps to None because the
+ project convention requires an explicit venue suffix.
+
+ Args:
+ stem: CSV filename without the ``.csv`` extension.
+
+ Returns:
+ The canonical symbol, or ``None`` when the stem has no recognizable
+ venue suffix.
+ """
+ upper = (stem or "").strip().upper()
+ if not upper:
+ return None
+ for raw, canonical in _CSV_FILENAME_SUFFIX_MAP:
+ if upper.endswith(raw) and len(upper) > len(raw):
+ return upper[: -len(raw)] + canonical
+ return None
+
+
def _query_key(value: Any) -> str:
"""Normalize resolver queries into stable state-machine keys."""
return " ".join(str(value or "").casefold().split())
@@ -347,6 +389,25 @@ def _is_number(value: Any) -> bool:
)
+def _coerce_csv_number(value: Any) -> int | float | None:
+ """Coerce a CSV cell to a finite number, or return None.
+
+ CSV readers return every cell as text (``"0.375"``), so a bare
+ ``_is_number`` check would discard them all. Values that do not parse as a
+ finite number (blank cells, ``-``, ``N/A``) return ``None``.
+ """
+ if _is_number(value):
+ return value
+ if isinstance(value, str):
+ try:
+ parsed = float(value.strip().replace(",", ""))
+ except (TypeError, ValueError):
+ return None
+ if math.isfinite(parsed):
+ return parsed
+ return None
+
+
# "." is deliberately not a separator: a decimal price such as 8.5 would parse
# as month 8 day 5 and match a real trading day.
_YEARLESS_CLAIM_DATE_RE = re.compile(
@@ -607,6 +668,7 @@ class GroundingLedger:
self._evidence: list[EvidenceRecord] = []
self._tool_failures: list[dict[str, Any]] = []
self._validations: list[dict[str, Any]] = []
+ self._ingested_csvs: set[str] = set()
self._identity_required = bool(_ACTIONABLE_MARKET_RE.search(user_message))
self._buffer_output = self._identity_required
# Every instrument this run is entitled to write about: the ones the
@@ -831,6 +893,7 @@ class GroundingLedger:
A deterministic validation result. A record containing only the
answer hash and structured issues is appended to the artifact.
"""
+ self._ingest_run_dir_ohlc_csvs()
issues: list[dict[str, Any]] = []
issues.extend(self._validate_identity(content))
issues.extend(self._validate_unsourced_symbols(content))
@@ -1395,6 +1458,84 @@ class GroundingLedger:
visit(payload, "")
+ def _ingest_run_dir_ohlc_csvs(self) -> None:
+ """Register OHLC rows from CSVs the run wrote via the bash workaround.
+
+ The bash+yfinance escape hatch writes per-symbol OHLC CSVs into the run
+ directory (e.g. ``data/raw/BYN_V.csv``) instead of returning them through
+ ``get_market_data``. Those prices were genuinely observed tool output,
+ but they never entered the ledger, so the final-answer gate rejected
+ every one of them as ``numeric_claim_unavailable``. Scan the run dir for
+ such CSVs and register their open/high/low/close/price rows as observed
+ evidence, keyed to the symbol derived from the filename.
+
+ Only files whose filename maps to a symbol already tracked in this run
+ are accepted, so a stray CSV cannot mint new identity. Rows are bounded
+ by ``_MAX_GENERIC_EVIDENCE`` and each file is ingested at most once.
+ """
+ if not self.run_dir.is_dir():
+ return
+ entitled = self._session_symbols | self.authorized_symbols
+ if not entitled:
+ return
+ room = _MAX_GENERIC_EVIDENCE
+ for path in sorted(self.run_dir.rglob("*.csv")):
+ if room <= 0:
+ return
+ try:
+ identity_key = f"{path.resolve()}:{path.stat().st_mtime_ns}"
+ except (OSError, ValueError):
+ continue
+ if identity_key in self._ingested_csvs:
+ continue
+ self._ingested_csvs.add(identity_key)
+ symbol = _symbol_from_csv_filename(path.stem)
+ if not symbol or symbol not in entitled:
+ continue
+ try:
+ with path.open("r", encoding="utf-8", errors="replace", newline="") as handle:
+ rows = list(csv.DictReader(handle))
+ except (OSError, UnicodeDecodeError, csv.Error):
+ continue
+ for row in rows:
+ if room <= 0:
+ return
+ if not isinstance(row, dict):
+ continue
+ timestamp = next(
+ (
+ str(row[key]).strip()
+ for key in row
+ if str(key).strip().casefold() in _CSV_DATE_COLUMNS
+ and row[key] not in (None, "")
+ ),
+ None,
+ )
+ for key, value in row.items():
+ field_name = _CSV_PRICE_COLUMNS.get(
+ str(key).strip().casefold().replace(" ", "_")
+ )
+ if field_name is None:
+ continue
+ numeric = _coerce_csv_number(value)
+ if numeric is None:
+ continue
+ self._evidence.append(
+ EvidenceRecord(
+ call_id=f"csv:{path.name}",
+ tool="bash",
+ symbol=symbol,
+ source="yfinance",
+ timestamp=timestamp,
+ field=field_name,
+ value=numeric,
+ status="observed",
+ currency=_infer_currency(symbol),
+ venue=_infer_venue(symbol),
+ )
+ )
+ room -= 1
+
def _validate_identity(self, content: str) -> list[dict[str, Any]]:
"""Validate aggregate state and listed/private contradictions."""
issues: list[dict[str, Any]] = []
diff --git a/agent/tests/test_agent_grounding.py b/agent/tests/test_agent_grounding.py
index 8ce663af6..790ebcf16 100644
--- a/agent/tests/test_agent_grounding.py
+++ b/agent/tests/test_agent_grounding.py
@@ -598,6 +598,86 @@ def test_final_numeric_gate_rejects_known_trace_contradiction(tmp_path: Path) ->
assert good.valid is True
+def test_run_dir_ohlc_csv_is_observed_evidence(tmp_path: Path) -> None:
+ """A bash-written OHLC CSV grounds the prices the answer quotes.
+
+ The bash+yfinance workaround writes per-symbol CSVs into the run directory
+ (e.g. ``data/raw/BYN_V.csv``) instead of returning bars through
+ ``get_market_data``. Those prices are real observed output, so the final
+ answer may cite them; a price outside the file must still be rejected.
+ """
+ raw = tmp_path / "data" / "raw"
+ raw.mkdir(parents=True)
+ (raw / "BYN_V.csv").write_text(
+ "Date,Open,High,Low,Close,Adj Close,Volume\n"
+ "2026-08-06,0.35,0.37,0.34,0.36,0.36,500000\n"
+ "2026-08-07,0.36,0.38,0.355,0.375,0.375,600000\n",
+ encoding="utf-8",
+ )
+ ledger = GroundingLedger(
+ run_dir=tmp_path,
+ user_message="请分析 BYN.V 并推荐买入价",
+ )
+
+ inside = ledger.validate_final_answer(
+ "BYN.V(yfinance,CAD)在 2026-08-07 的已观测收盘价为 0.375。"
+ )
+ fabricated = ledger.validate_final_answer(
+ "BYN.V(yfinance,CAD)在 2026-08-07 的已观测收盘价为 0.88。"
+ )
+
+ assert inside.valid is True, inside.issues
+ assert fabricated.valid is False
+ assert any(issue["code"] == "numeric_claim_conflict" for issue in fabricated.issues)
+
+
+def test_run_dir_ohlc_csv_tsx_filename_maps_symbol(tmp_path: Path) -> None:
+ """PDI_TO.csv maps to PDI.TO and grounds its CAD price."""
+ raw = tmp_path / "data" / "raw"
+ raw.mkdir(parents=True)
+ (raw / "PDI_TO.csv").write_text(
+ "Date,Open,High,Low,Close\n"
+ "2026-08-07,10.0,10.5,9.9,10.2\n",
+ encoding="utf-8",
+ )
+ ledger = GroundingLedger(
+ run_dir=tmp_path,
+ user_message="请分析 PDI.TO 并推荐买入价",
+ )
+
+ good = ledger.validate_final_answer(
+ "PDI.TO(yfinance,CAD)在 2026-08-07 的已观测收盘价为 10.2。"
+ )
+
+ assert good.valid is True, good.issues
+
+
+def test_run_dir_ohlc_csv_stray_symbol_is_ignored(tmp_path: Path) -> None:
+ """A CSV for a symbol the run never handled does not mint identity."""
+ raw = tmp_path / "data" / "raw"
+ raw.mkdir(parents=True)
+ (raw / "ZZZ_US.csv").write_text(
+ "Date,Open,High,Low,Close\n"
+ "2026-08-07,100.0,100.0,100.0,100.0\n",
+ encoding="utf-8",
+ )
+ ledger = GroundingLedger(
+ run_dir=tmp_path,
+ user_message="请分析 BYN.V 并推荐买入价",
+ )
+
+ result = ledger.validate_final_answer(
+ "ZZZ.US(yfinance,USD)在 2026-08-07 的已观测收盘价为 100.0。"
+ )
+
+ # The symbol is not entitled, so the price cannot be grounded.
+ assert result.valid is False
+ assert any(
+ issue["code"] in {"numeric_claim_unavailable", "canonical_symbol_not_surfaced"}
+ for issue in result.issues
+ )
+
+
def test_numeric_gate_validates_derived_formula_and_provenance(tmp_path: Path) -> None:
"""A derived entry level must calculate correctly from observed evidence."""
ledger = GroundingLedger(