"Vibe-Trading: Your Personal Trading Agent"
Python ai-agentalgorithmic-tradingbacktestingfintechllmmcpmulti-agentpythonquantitative-financetrading
feat(loaders): validate OHLC invariants at the loader boundary (#274)
Lanre Shittu9addc95a4b9c
diff --git a/agent/backtest/loaders/base.py b/agent/backtest/loaders/base.pyindex f65c48f50..9970eccd5 100644--- a/agent/backtest/loaders/base.py+++ b/agent/backtest/loaders/base.py@@ -47,6 +47,59 @@ def validate_date_range(start_date: str, end_date: str) -> None:raise ValueError(f"start_date ({start_date}) > end_date ({end_date})")+def validate_ohlc(frame: pd.DataFrame, *, strategy: str = "drop") -> pd.DataFrame:+ """Drop, flag, or reject bars that violate OHLC invariants.++ Loaders only drop NaN rows, so structurally dirty bars — ``high < low``,+ a non-positive price, or a high/low that fails to bracket open/close —+ flow straight into the backtest and surface downstream as NaN/inf metrics+ that break the strict (``allow_nan=False``) JSON serializers. This is the+ canonical loader-boundary check; call it after the existing ``dropna`` so a+ single sanity pass guards every source.++ Args:+ frame: OHLCV frame with at least ``open``/``high``/``low``/``close``+ columns. NaN handling is left to the caller's ``dropna``.+ strategy: ``"drop"`` (remove offending rows, default), ``"warn"``+ (log and keep), or ``"raise"`` (raise on any violation).++ Returns:+ The frame with invalid rows removed (``"drop"``) or unchanged+ (``"warn"``). A frame that is empty or lacks OHLC columns is returned+ as-is.++ Raises:+ ValueError: ``strategy="raise"`` and at least one bar is invalid.+ """+ required = ("open", "high", "low", "close")+ if frame.empty or not all(col in frame.columns for col in required):+ return frame++ open_, high, low, close = (frame[c] for c in required)+ invalid = (+ (high < low)+ | (high < open_)+ | (high < close)+ | (low > open_)+ | (low > close)+ | (open_ <= 0)+ | (high <= 0)+ | (low <= 0)+ | (close <= 0)+ )+ n_invalid = int(invalid.sum())+ if n_invalid == 0:+ return frame++ if strategy == "raise":+ raise ValueError(f"{n_invalid} bar(s) violate OHLC invariants")+ if strategy == "warn":+ logger.warning("OHLC validation: %d bar(s) violate invariants (kept)", n_invalid)+ return frame+ logger.warning("OHLC validation: dropping %d invalid bar(s)", n_invalid)+ return frame[~invalid]++# ---------------------------------------------------------------------------# Bounded retry / budget helpers (shared by ccxt_loader, okx, and any future# loader calling a flaky external API).diff --git a/agent/backtest/loaders/local_loader.py b/agent/backtest/loaders/local_loader.pyindex 879b4de52..84765e29e 100644--- a/agent/backtest/loaders/local_loader.py+++ b/agent/backtest/loaders/local_loader.py@@ -38,7 +38,7 @@ from typing import Any, Dict, List, Optionalimport pandas as pdimport yaml-from backtest.loaders.base import cached_loader_fetch, validate_date_range+from backtest.loaders.base import cached_loader_fetch, validate_date_range, validate_ohlcfrom backtest.loaders.registry import registerlogger = logging.getLogger(__name__)@@ -104,6 +104,7 @@ def _normalize_columns(for col in ohlcv_cols:df[col] = pd.to_numeric(df[col], errors="coerce")df = df.dropna(subset=["open", "high", "low", "close"])+ df = validate_ohlc(df)for col in ohlcv_cols:df[col] = df[col].astype("float64")diff --git a/agent/backtest/loaders/yfinance_loader.py b/agent/backtest/loaders/yfinance_loader.pyindex 2453db17a..80dd6f605 100644--- a/agent/backtest/loaders/yfinance_loader.py+++ b/agent/backtest/loaders/yfinance_loader.py@@ -8,7 +8,12 @@ from typing import Dict, List, Optional, Unionimport pandas as pdimport yfinance as yf-from backtest.loaders.base import loader_cache_get, loader_cache_put, validate_date_range+from backtest.loaders.base import (+ loader_cache_get,+ loader_cache_put,+ validate_date_range,+ validate_ohlc,+)from backtest.loaders.registry import register_OHLCV_COLUMNS = ["open", "high", "low", "close", "volume"]@@ -182,6 +187,7 @@ def _normalize_frame(frame: pd.DataFrame, requested_interval: str) -> pd.DataFranormalized = normalized.sort_index()normalized["volume"] = normalized["volume"].fillna(0.0)normalized = normalized.dropna(subset=["open", "high", "low", "close"])+ normalized = validate_ohlc(normalized)if requested_interval == "4H" and not normalized.empty:normalized = normalized.resample("4h").agg(diff --git a/agent/backtest/runner.py b/agent/backtest/runner.pyindex 887b892f7..1a7b88dd0 100644--- a/agent/backtest/runner.py+++ b/agent/backtest/runner.py@@ -32,7 +32,7 @@ from backtest.loaders.registry import (get_loader_cls_with_fallback,resolve_loader,)-from backtest.loaders.base import NoAvailableSourceError+from backtest.loaders.base import NoAvailableSourceError, validate_ohlc# Symbol classification lives in ``_market_hooks`` so runner.py and# composite.py share a single source of truth (audit-2026-05-18 B1+C1+C2).# ``_detect_market`` is also re-exported here for back-compat with@@ -494,6 +494,10 @@ def main(run_dir: Path) -> None:source = fb_nameloader = fb_loaderbreak++ # Loader-boundary OHLC sanity for every source, centralized at the one+ # point all fetch paths converge (auto / single / runtime fallback).+ data_map = _sanitize_data_map(data_map)if not data_map:print(json.dumps({"error": "No data fetched"}))sys.exit(1)@@ -655,6 +659,26 @@ def _fetch_auto(codes: List[str], config: dict, interval: str = "1D") -> dict:return merged+def _sanitize_data_map(data_map: dict) -> dict:+ """Drop structurally-invalid OHLC bars from every fetched frame.++ Each loader only drops NaN rows, so a bar that violates the OHLC+ invariants (``high < low``, a non-positive price, or a high/low that fails+ to bracket open/close) can still reach the backtest and surface as NaN/inf+ metrics. Applying :func:`validate_ohlc` here — the single point every+ fetched map converges through — guards every source uniformly (``auto``,+ single-source, runtime fallback, and any future loader), so the per-loader+ checks no longer have to be added one at a time.++ Args:+ data_map: ``code -> DataFrame`` map as returned by a loader fetch.++ Returns:+ The same mapping with each frame's invalid bars removed.+ """+ return {code: validate_ohlc(frame) for code, frame in data_map.items()}++class _AutoLoader:"""Dummy loader for auto mode: returns pre-fetched data maps."""diff --git a/agent/tests/test_ohlc_validation.py b/agent/tests/test_ohlc_validation.pynew file mode 100644index 000000000..9e65eb1cc--- /dev/null+++ b/agent/tests/test_ohlc_validation.py@@ -0,0 +1,139 @@+"""Tests for the shared OHLC invariant validator and its loader wiring."""++from __future__ import annotations++import logging+from pathlib import Path++import pandas as pd+import pytest++import backtest.loaders.local_loader as local_loader+from backtest.loaders.base import validate_ohlc+++def _frame(rows: list[tuple[float, float, float, float, float]]) -> pd.DataFrame:+ """Build an OHLCV frame from (open, high, low, close, volume) rows."""+ index = pd.date_range("2026-01-01", periods=len(rows), freq="D", name="trade_date")+ return pd.DataFrame(+ rows, columns=["open", "high", "low", "close", "volume"], index=index+ )+++def test_validate_ohlc_drops_invariant_violations() -> None:+ """high<low, prices<=0, and high/low not bracketing open/close are dropped."""+ frame = _frame(+ [+ (10.0, 11.0, 9.0, 10.5, 1000.0), # valid+ (10.0, 8.0, 9.0, 10.5, 1000.0), # high < low -> invalid+ (-1.0, 11.0, 9.0, 10.5, 1000.0), # non-positive open -> invalid+ (10.0, 10.5, 9.0, 12.0, 1000.0), # close > high -> invalid+ (10.0, 10.0, 10.0, 10.0, 0.0), # flat doji, zero volume -> valid+ ]+ )++ cleaned = validate_ohlc(frame)++ assert list(cleaned["close"]) == [10.5, 10.0]+ assert len(cleaned) == 2+++def test_validate_ohlc_raise_strategy() -> None:+ """strategy='raise' surfaces the violation instead of silently dropping."""+ frame = _frame([(10.0, 8.0, 9.0, 10.5, 1000.0)])+ with pytest.raises(ValueError):+ validate_ohlc(frame, strategy="raise")+++def test_validate_ohlc_warn_strategy_keeps_rows(+ caplog: pytest.LogCaptureFixture,+) -> None:+ """strategy='warn' logs but keeps the offending rows."""+ frame = _frame([(10.0, 11.0, 9.0, 10.5, 1000.0), (10.0, 8.0, 9.0, 10.5, 1000.0)])+ with caplog.at_level(logging.WARNING, logger="backtest.loaders.base"):+ kept = validate_ohlc(frame, strategy="warn")+ assert len(kept) == 2+ assert any("ohlc" in rec.message.lower() for rec in caplog.records)+++def test_validate_ohlc_passthrough_when_no_ohlc_columns() -> None:+ """A frame without OHLC columns (or empty) is returned unchanged."""+ empty = pd.DataFrame()+ assert validate_ohlc(empty).empty+ other = pd.DataFrame({"value": [1, 2, 3]})+ assert validate_ohlc(other).equals(other)+++def test_local_loader_drops_dirty_bar(+ tmp_path: Path, monkeypatch: pytest.MonkeyPatch+) -> None:+ """A structurally invalid bar in a local file must not reach the backtest."""+ csv_path = tmp_path / "dirty.csv"+ csv_path.write_text(+ "\n".join(+ [+ "Date,Open,High,Low,Close,Volume",+ "2026-01-01,10,11,9,10.5,1000",+ "2026-01-02,10,8,9,10.5,1500", # high < low -> dirty+ "2026-01-03,12,13,11,12.5,1200",+ ]+ ),+ encoding="utf-8",+ )+ config_path = tmp_path / "config.yaml"+ import yaml++ config_path.write_text(+ yaml.safe_dump(+ {+ "sources": [+ {+ "symbol": "AAA.US",+ "type": "csv",+ "path": str(csv_path),+ "columns": {+ "date": "Date",+ "open": "Open",+ "high": "High",+ "low": "Low",+ "close": "Close",+ "volume": "Volume",+ },+ }+ ]+ }+ ),+ encoding="utf-8",+ )+ monkeypatch.setattr(local_loader, "_CONFIG_PATH", config_path)++ frames = local_loader.DataLoader().fetch(["AAA.US"], "2026-01-01", "2026-01-03")++ df = frames["AAA.US"]+ assert list(df["close"]) == [10.5, 12.5] # the dirty 2026-01-02 bar is gone+++def test_sanitize_data_map_guards_every_source() -> None:+ """The runner's central pass drops dirty bars from any loader's frame.++ This is the catch-all boundary: a loader that never calls ``validate_ohlc``+ itself (the large majority) still cannot leak a structurally-invalid bar+ into the backtest, because every fetched map converges through here.+ """+ from backtest.runner import _sanitize_data_map++ data_map = {+ "AAA.US": _frame(+ [+ (10.0, 11.0, 9.0, 10.5, 1000.0), # valid+ (10.0, 8.0, 9.0, 10.5, 1500.0), # high < low -> dropped+ ]+ ),+ "BBB.US": _frame([(12.0, 13.0, 11.0, 12.5, 1200.0)]), # all valid+ }++ cleaned = _sanitize_data_map(data_map)++ assert list(cleaned["AAA.US"]["close"]) == [10.5] # dirty bar gone+ assert list(cleaned["BBB.US"]["close"]) == [12.5] # untouched+ assert set(cleaned) == {"AAA.US", "BBB.US"}