"Vibe-Trading: Your Personal Trading Agent"
Python ai-agentalgorithmic-tradingbacktestingfintechllmmcpmulti-agentpythonquantitative-financetrading
fix: harden backtest engine with data validation and error isolation
warren6182772ecb688a4
diff --git a/agent/backtest/engines/base.py b/agent/backtest/engines/base.pyindex 92127d75d..8eb6c1f2d 100644--- a/agent/backtest/engines/base.py+++ b/agent/backtest/engines/base.py@@ -10,6 +10,7 @@ from __future__ import annotationsimport importlibimport json+import loggingimport sysfrom abc import ABC, abstractmethodfrom pathlib import Path@@ -18,6 +19,8 @@ from typing import Any, Callable, Dict, List, Optionalimport numpy as npimport pandas as pd+logger = logging.getLogger(__name__)+from backtest.metrics import (by_exit_reason_stats,by_symbol_stats,@@ -57,7 +60,18 @@ def _align(close = pd.DataFrame(index=dates, columns=codes, dtype=float)for c in codes:close[c] = data_map[c]["close"].reindex(dates)- close = close.ffill().bfill()++ # ffill with limit to avoid masking long suspensions (e.g. 3-week halt)+ close = close.ffill(limit=5)++ # Drop symbols that are entirely NaN (no data overlap with date range)+ all_nan_cols = [c for c in codes if close[c].isna().all()]+ if all_nan_cols:+ logger.warning("Symbols dropped (no usable price data): %s", all_nan_cols)+ codes = [c for c in codes if c not in all_nan_cols]+ if not codes:+ raise ValueError(f"All symbols have no data in the requested date range")+ close = close[codes]pos = pd.DataFrame(0.0, index=dates, columns=codes)for c in codes:@@ -255,6 +269,9 @@ class BaseEngine(ABC):data_map, signal_map, valid_codes, optimizer=opt_fn,)+ # Sync codes after _align may have dropped all-NaN symbols+ valid_codes = [c for c in valid_codes if c in target_pos.columns]+# 4. Bar-by-bar executionself._execute_bars(dates, data_map, close_df, target_pos, valid_codes)@@ -314,8 +331,11 @@ class BaseEngine(ABC):# b. Rebalance each symbol to target weightequity = self._calc_equity(close_df, ts)for c in codes:- target_w = float(target_pos.at[ts, c]) if ts in target_pos.index else 0.0- self._rebalance(c, target_w, data_map.get(c), ts, equity)+ try:+ target_w = float(target_pos.at[ts, c]) if ts in target_pos.index else 0.0+ self._rebalance(c, target_w, data_map.get(c), ts, equity)+ except Exception as exc:+ logger.warning("Rebalance failed for %s at %s: %s", c, ts, exc)# c. Record equity snapshotsnap_equity = self._calc_equity(close_df, ts)diff --git a/agent/backtest/loaders/akshare_loader.py b/agent/backtest/loaders/akshare_loader.pyindex 9edf78e8f..a6436e2eb 100644--- a/agent/backtest/loaders/akshare_loader.py+++ b/agent/backtest/loaders/akshare_loader.py@@ -11,6 +11,7 @@ from typing import Dict, List, Optionalimport pandas as pd+from backtest.loaders.base import validate_date_rangefrom backtest.loaders.registry import registerlogger = logging.getLogger(__name__)@@ -78,6 +79,8 @@ class DataLoader:Returns:Mapping symbol -> OHLCV DataFrame."""+ validate_date_range(start_date, end_date)+result: Dict[str, pd.DataFrame] = {}for code in codes:try:diff --git a/agent/backtest/loaders/base.py b/agent/backtest/loaders/base.pyindex a68501a5e..ab04deb07 100644--- a/agent/backtest/loaders/base.py+++ b/agent/backtest/loaders/base.py@@ -11,6 +11,25 @@ class NoAvailableSourceError(Exception):"""Raised when no data source is available for a given market."""+def validate_date_range(start_date: str, end_date: str) -> None:+ """Validate that start_date <= end_date.++ Args:+ start_date: Start date string (YYYY-MM-DD).+ end_date: End date string (YYYY-MM-DD).++ Raises:+ ValueError: If dates are invalid or start > end.+ """+ try:+ start = pd.Timestamp(start_date)+ end = pd.Timestamp(end_date)+ except Exception as exc:+ raise ValueError(f"Invalid date format: start={start_date!r}, end={end_date!r}") from exc+ if start > end:+ raise ValueError(f"start_date ({start_date}) > end_date ({end_date})")++@runtime_checkableclass DataLoaderProtocol(Protocol):"""Interface that every data source loader must satisfy."""diff --git a/agent/backtest/loaders/ccxt_loader.py b/agent/backtest/loaders/ccxt_loader.pyindex 68ac891e5..ab7052e45 100644--- a/agent/backtest/loaders/ccxt_loader.py+++ b/agent/backtest/loaders/ccxt_loader.py@@ -13,6 +13,7 @@ from typing import Dict, List, Optionalimport pandas as pd+from backtest.loaders.base import validate_date_rangefrom backtest.loaders.registry import registerlogger = logging.getLogger(__name__)@@ -73,6 +74,8 @@ class DataLoader:Returns:Mapping symbol -> OHLCV DataFrame."""+ validate_date_range(start_date, end_date)+exchange = self._get_exchange()timeframe = _INTERVAL_MAP.get(interval, "1d")since_ms = int(pd.Timestamp(start_date).timestamp() * 1000)diff --git a/agent/backtest/loaders/okx.py b/agent/backtest/loaders/okx.pyindex c54931ad5..750b69421 100644--- a/agent/backtest/loaders/okx.py+++ b/agent/backtest/loaders/okx.py@@ -10,6 +10,7 @@ from typing import Dict, List, Optionalimport pandas as pdimport requests+from backtest.loaders.base import validate_date_rangefrom backtest.loaders.registry import registerBASE_URL = "https://www.okx.com/api/v5"@@ -52,6 +53,8 @@ class DataLoader:Returns:Mapping symbol -> DataFrame."""+ validate_date_range(start_date, end_date)+if fields:print(f"[WARN] OKX ignores extra fields: {fields}")diff --git a/agent/backtest/loaders/tushare.py b/agent/backtest/loaders/tushare.pyindex 155e48122..b2fc5d20d 100644--- a/agent/backtest/loaders/tushare.py+++ b/agent/backtest/loaders/tushare.py@@ -9,6 +9,7 @@ from typing import Dict, List, Optionalimport pandas as pd+from backtest.loaders.base import validate_date_rangefrom backtest.loaders.registry import register@@ -51,6 +52,8 @@ class DataLoader:Returns:Mapping code -> OHLCV DataFrame."""+ validate_date_range(start_date, end_date)+if interval != "1D":return self._fetch_minutes(codes, start_date, end_date, interval)diff --git a/agent/backtest/loaders/yfinance_loader.py b/agent/backtest/loaders/yfinance_loader.pyindex 54028c3b1..952ff593f 100644--- a/agent/backtest/loaders/yfinance_loader.py+++ b/agent/backtest/loaders/yfinance_loader.py@@ -8,6 +8,7 @@ from typing import Dict, List, Optional, Unionimport pandas as pdimport yfinance as yf+from backtest.loaders.base import validate_date_rangefrom backtest.loaders.registry import register_OHLCV_COLUMNS = ["open", "high", "low", "close", "volume"]@@ -230,6 +231,7 @@ class DataLoader:del fieldsif not codes:return {}+ validate_date_range(start_date, end_date)requested_interval = str(interval or "1D").strip()yf_interval = _to_yfinance_interval(requested_interval)diff --git a/agent/backtest/runner.py b/agent/backtest/runner.pyindex 7f3a045c6..0ee52971e 100644--- a/agent/backtest/runner.py+++ b/agent/backtest/runner.py@@ -13,7 +13,10 @@ import loggingimport reimport sysfrom pathlib import Path-from typing import Dict, List+from typing import Any, Dict, List, Optional++import pandas as pd+from pydantic import BaseModel, ConfigDict, model_validator, field_validatortry:from dotenv import load_dotenv@@ -30,6 +33,70 @@ from backtest.loaders.base import NoAvailableSourceErrorlogger = logging.getLogger(__name__)+_VALID_INTERVALS = {"1m", "5m", "15m", "30m", "1H", "4H", "1D"}+_VALID_ENGINES = {"daily", "options"}+_VALID_SOURCES = {"tushare", "okx", "yfinance", "akshare", "ccxt", "auto"}+++class BacktestConfigSchema(BaseModel):+ """Validates backtest config.json before execution."""++ model_config = ConfigDict(extra="allow")++ codes: List[str]+ start_date: str+ end_date: str+ source: str = "tushare"+ interval: str = "1D"+ engine: str = "daily"++ @field_validator("codes")+ @classmethod+ def codes_not_empty(cls, v: List[str]) -> List[str]:+ if not v:+ raise ValueError("codes must be a non-empty list")+ if any(not c.strip() for c in v):+ raise ValueError("codes must not contain empty strings")+ return v++ @field_validator("start_date", "end_date")+ @classmethod+ def valid_date(cls, v: str) -> str:+ try:+ pd.Timestamp(v)+ except Exception:+ raise ValueError(f"invalid date format: {v!r} (expected YYYY-MM-DD)")+ return v++ @field_validator("interval")+ @classmethod+ def valid_interval(cls, v: str) -> str:+ if v not in _VALID_INTERVALS:+ raise ValueError(f"unsupported interval {v!r}, must be one of {_VALID_INTERVALS}")+ return v++ @field_validator("engine")+ @classmethod+ def valid_engine(cls, v: str) -> str:+ if v not in _VALID_ENGINES:+ raise ValueError(f"unsupported engine {v!r}, must be one of {_VALID_ENGINES}")+ return v++ @field_validator("source")+ @classmethod+ def valid_source(cls, v: str) -> str:+ if v not in _VALID_SOURCES:+ raise ValueError(f"unsupported source {v!r}, must be one of {_VALID_SOURCES}")+ return v++ @model_validator(mode="after")+ def start_before_end(self) -> "BacktestConfigSchema":+ if pd.Timestamp(self.start_date) > pd.Timestamp(self.end_date):+ raise ValueError(+ f"start_date ({self.start_date}) must be <= end_date ({self.end_date})"+ )+ return self+def _load_module_from_file(file_path: Path, module_name: str):"""Load a Python module from a file path via importlib.@@ -192,7 +259,17 @@ def main(run_dir: Path) -> None:print(json.dumps({"error": "config.json not found"}))sys.exit(1)- config = json.loads(config_path.read_text(encoding="utf-8"))+ raw_config = json.loads(config_path.read_text(encoding="utf-8"))++ # Validate config schema+ try:+ BacktestConfigSchema(**raw_config)+ except Exception as exc:+ errors = str(exc)+ print(json.dumps({"error": f"Invalid config: {errors}"}))+ sys.exit(1)++ config = raw_configsource = config.get("source", "tushare")codes = config.get("codes", [])diff --git a/agent/tests/test_engine_robustness.py b/agent/tests/test_engine_robustness.pynew file mode 100644index 000000000..66397ce70--- /dev/null+++ b/agent/tests/test_engine_robustness.py@@ -0,0 +1,344 @@+"""E2E tests for engine robustness fixes:++1. ffill(limit=5) — long suspensions stay NaN instead of using stale prices+2. All-NaN symbol detection — symbols with no data are dropped with warning+3. Single symbol exception isolation — one symbol crash doesn't kill the backtest+4. Config schema validation — invalid config gets clear pydantic error+5. Date range validation — start > end raises ValueError in all loaders+"""++from __future__ import annotations++import json+import tempfile+from pathlib import Path+from typing import Dict+from unittest.mock import patch++import numpy as np+import pandas as pd+import pytest++from backtest.engines.base import _align+from backtest.engines.china_a import ChinaAEngine+from backtest.loaders.base import validate_date_range+from backtest.runner import BacktestConfigSchema+++# ---------------------------------------------------------------------------+# 1. ffill(limit=5) — long gaps stay NaN+# ---------------------------------------------------------------------------+++class TestFfillLimit:+ def test_short_gap_filled(self) -> None:+ """Gaps <= 5 bars should be forward-filled."""+ dates = pd.bdate_range("2025-01-01", periods=10)+ close = [100, 101, np.nan, np.nan, np.nan, 105, 106, 107, 108, 109]+ df = pd.DataFrame({"close": close, "open": close}, index=dates)+ sig = pd.Series(1.0, index=dates)++ _, close_df, _, _ = _align({"A": df}, {"A": sig}, ["A"])+ # 3-bar gap should be filled — no NaN in close+ assert close_df["A"].isna().sum() == 0++ def test_long_gap_not_filled(self) -> None:+ """Gaps > 5 bars should remain NaN (not masked by stale price)."""+ dates = pd.bdate_range("2025-01-01", periods=15)+ close = [100.0] + [np.nan] * 8 + [110.0] * 6+ df = pd.DataFrame({"close": close, "open": close}, index=dates)+ sig = pd.Series(1.0, index=dates)++ _, close_df, _, _ = _align({"A": df}, {"A": sig}, ["A"])+ # 8-bar gap: ffill covers first 5, remaining 3 should be NaN+ nan_count = close_df["A"].isna().sum()+ assert nan_count == 3, f"Expected 3 NaN bars after ffill limit=5, got {nan_count}"++ def test_all_nan_symbol_dropped(self) -> None:+ """Symbol with entirely NaN data should be dropped from alignment."""+ dates = pd.bdate_range("2025-01-01", periods=10)+ df_good = pd.DataFrame(+ {"close": np.linspace(100, 110, 10), "open": np.linspace(100, 110, 10)},+ index=dates,+ )+ df_bad = pd.DataFrame(+ {"close": [np.nan] * 10, "open": [np.nan] * 10},+ index=dates,+ )+ data_map = {"GOOD": df_good, "BAD": df_bad}+ signal_map = {+ "GOOD": pd.Series(1.0, index=dates),+ "BAD": pd.Series(1.0, index=dates),+ }++ _, close_df, pos_df, _ = _align(data_map, signal_map, ["GOOD", "BAD"])+ assert "BAD" not in close_df.columns, "All-NaN symbol should be dropped"+ assert "GOOD" in close_df.columns+ assert "BAD" not in pos_df.columns++ def test_all_symbols_nan_raises(self) -> None:+ """If ALL symbols are NaN, _align should raise ValueError."""+ dates = pd.bdate_range("2025-01-01", periods=5)+ df = pd.DataFrame({"close": [np.nan] * 5, "open": [np.nan] * 5}, index=dates)+ data_map = {"X": df}+ signal_map = {"X": pd.Series(1.0, index=dates)}++ with pytest.raises(ValueError, match="All symbols have no data"):+ _align(data_map, signal_map, ["X"])+++# ---------------------------------------------------------------------------+# 2. Single symbol exception isolation+# ---------------------------------------------------------------------------+++class TestSymbolIsolation:+ def test_one_symbol_error_doesnt_crash_backtest(self) -> None:+ """If rebalance fails for one symbol, other symbols still execute."""+ dates = pd.bdate_range("2025-01-01", periods=10)+ df_good = pd.DataFrame(+ {+ "close": np.linspace(10, 20, 10),+ "open": np.linspace(10, 20, 10),+ "high": np.linspace(10, 21, 10),+ "low": np.linspace(9, 19, 10),+ "volume": [1000] * 10,+ },+ index=dates,+ )+ df_bad = df_good.copy()+ data_map: Dict[str, pd.DataFrame] = {"GOOD": df_good, "BAD": df_bad}++ sig = pd.Series(0.0, index=dates)+ sig.iloc[2:] = 1.0+ signal_map = {"GOOD": sig.copy(), "BAD": sig.copy()}+ valid_codes = ["GOOD", "BAD"]++ _, close_df, target_pos, _ = _align(data_map, signal_map, valid_codes)++ engine = ChinaAEngine({"initial_cash": 1_000_000})++ # Patch _rebalance to throw for BAD only+ original_rebalance = ChinaAEngine._rebalance++ def _exploding_rebalance(self, symbol, target_weight, df, ts, equity):+ if symbol == "BAD":+ raise RuntimeError("Simulated failure for BAD")+ return original_rebalance(self, symbol, target_weight, df, ts, equity)++ with patch.object(ChinaAEngine, "_rebalance", _exploding_rebalance):+ # Should NOT raise — exception is caught internally+ engine._execute_bars(dates, data_map, close_df, target_pos, valid_codes)++ # GOOD should have traded despite BAD exploding+ assert len(engine.trades) > 0+ assert all(t.symbol == "GOOD" for t in engine.trades)+++# ---------------------------------------------------------------------------+# 3. Config schema validation (pydantic)+# ---------------------------------------------------------------------------+++class TestBacktestConfigSchema:+ def test_valid_config(self) -> None:+ c = BacktestConfigSchema(+ codes=["AAPL.US"],+ start_date="2025-01-01",+ end_date="2025-06-01",+ )+ assert c.codes == ["AAPL.US"]+ assert c.interval == "1D"+ assert c.engine == "daily"++ def test_empty_codes_rejected(self) -> None:+ with pytest.raises(Exception, match="codes must be a non-empty list"):+ BacktestConfigSchema(+ codes=[], start_date="2025-01-01", end_date="2025-06-01"+ )++ def test_empty_string_code_rejected(self) -> None:+ with pytest.raises(Exception, match="codes must not contain empty strings"):+ BacktestConfigSchema(+ codes=["AAPL.US", ""], start_date="2025-01-01", end_date="2025-06-01"+ )++ def test_reversed_dates_rejected(self) -> None:+ with pytest.raises(Exception, match="start_date.*must be <= end_date"):+ BacktestConfigSchema(+ codes=["AAPL.US"],+ start_date="2025-06-01",+ end_date="2025-01-01",+ )++ def test_invalid_date_format_rejected(self) -> None:+ with pytest.raises(Exception, match="invalid date format"):+ BacktestConfigSchema(+ codes=["AAPL.US"],+ start_date="not-a-date",+ end_date="2025-06-01",+ )++ def test_invalid_interval_rejected(self) -> None:+ with pytest.raises(Exception, match="unsupported interval"):+ BacktestConfigSchema(+ codes=["AAPL.US"],+ start_date="2025-01-01",+ end_date="2025-06-01",+ interval="3D",+ )++ def test_invalid_engine_rejected(self) -> None:+ with pytest.raises(Exception, match="unsupported engine"):+ BacktestConfigSchema(+ codes=["AAPL.US"],+ start_date="2025-01-01",+ end_date="2025-06-01",+ engine="invalid",+ )++ def test_invalid_source_rejected(self) -> None:+ with pytest.raises(Exception, match="unsupported source"):+ BacktestConfigSchema(+ codes=["AAPL.US"],+ start_date="2025-01-01",+ end_date="2025-06-01",+ source="bloomberg",+ )++ def test_extra_fields_allowed(self) -> None:+ """Config may contain engine-specific fields not in the schema."""+ c = BacktestConfigSchema(+ codes=["AAPL.US"],+ start_date="2025-01-01",+ end_date="2025-06-01",+ initial_cash=500_000,+ custom_field="whatever",+ )+ assert c.codes == ["AAPL.US"]++ def test_same_start_end_allowed(self) -> None:+ """start_date == end_date is valid (single-day backtest)."""+ c = BacktestConfigSchema(+ codes=["AAPL.US"],+ start_date="2025-03-15",+ end_date="2025-03-15",+ )+ assert c.start_date == c.end_date+++# ---------------------------------------------------------------------------+# 4. Date range validation in loaders+# ---------------------------------------------------------------------------+++class TestDateRangeValidation:+ def test_valid_range(self) -> None:+ validate_date_range("2025-01-01", "2025-06-01")++ def test_same_date_valid(self) -> None:+ validate_date_range("2025-03-15", "2025-03-15")++ def test_reversed_dates_raise(self) -> None:+ with pytest.raises(ValueError, match="start_date.*>.*end_date"):+ validate_date_range("2025-06-01", "2025-01-01")++ def test_invalid_date_format_raises(self) -> None:+ with pytest.raises(ValueError, match="Invalid date format"):+ validate_date_range("not-a-date", "2025-06-01")++ def test_yfinance_loader_validates_dates(self) -> None:+ """yfinance loader should raise on reversed dates before fetching."""+ from backtest.loaders.yfinance_loader import DataLoader++ loader = DataLoader()+ with pytest.raises(ValueError):+ loader.fetch(["AAPL"], "2025-06-01", "2025-01-01")++ def test_okx_loader_validates_dates(self) -> None:+ """OKX loader should raise on reversed dates before fetching."""+ from backtest.loaders.okx import DataLoader++ loader = DataLoader()+ with pytest.raises(ValueError):+ loader.fetch(["BTC-USDT"], "2025-06-01", "2025-01-01")++ def test_ccxt_loader_validates_dates(self) -> None:+ """CCXT loader should raise on reversed dates before fetching."""+ from backtest.loaders.ccxt_loader import DataLoader++ loader = DataLoader()+ with pytest.raises(ValueError):+ loader.fetch(["BTC-USDT"], "2025-06-01", "2025-01-01")++ def test_akshare_loader_validates_dates(self) -> None:+ """AKShare loader should raise on reversed dates before fetching."""+ from backtest.loaders.akshare_loader import DataLoader++ loader = DataLoader()+ with pytest.raises(ValueError):+ loader.fetch(["000001.SZ"], "2025-06-01", "2025-01-01")++ def test_tushare_loader_validates_dates(self) -> None:+ """Tushare loader should raise on reversed dates before fetching."""+ from backtest.loaders.tushare import DataLoader++ # Tushare requires TUSHARE_TOKEN at init; skip if unavailable+ import os+ if not os.getenv("TUSHARE_TOKEN"):+ pytest.skip("TUSHARE_TOKEN not set")+ loader = DataLoader()+ with pytest.raises(ValueError):+ loader.fetch(["000001.SZ"], "2025-06-01", "2025-01-01")+++# ---------------------------------------------------------------------------+# 5. Integration: full backtest with bad data doesn't crash+# ---------------------------------------------------------------------------+++class TestFullBacktestRobustness:+ def test_backtest_with_suspension_gap(self) -> None:+ """A stock suspended for >5 bars should not produce fake flat equity."""+ dates = pd.bdate_range("2025-01-01", periods=20)+ # Normal stock+ df_normal = pd.DataFrame(+ {+ "close": np.linspace(100, 120, 20),+ "open": np.linspace(100, 120, 20),+ "high": np.linspace(101, 121, 20),+ "low": np.linspace(99, 119, 20),+ "volume": [10000] * 20,+ },+ index=dates,+ )+ # Suspended stock: data only at start and end+ close_suspended = [50.0] * 3 + [np.nan] * 14 + [60.0] * 3+ df_suspended = pd.DataFrame(+ {+ "close": close_suspended,+ "open": close_suspended,+ "high": close_suspended,+ "low": close_suspended,+ "volume": [1000] * 3 + [0] * 14 + [1000] * 3,+ },+ index=dates,+ )+ data_map = {"NORMAL": df_normal, "SUSPENDED": df_suspended}++ sig = pd.Series(1.0, index=dates)+ signal_map = {"NORMAL": sig.copy(), "SUSPENDED": sig.copy()}+ valid_codes = ["NORMAL", "SUSPENDED"]++ _, close_df, target_pos, _ = _align(data_map, signal_map, valid_codes)++ # The 14-bar gap should not be fully filled+ suspended_nan_count = close_df["SUSPENDED"].isna().sum()+ assert suspended_nan_count >= 9, (+ f"14-bar gap with ffill(limit=5) should leave >=9 NaN, got {suspended_nan_count}"+ )++ # Engine should still complete without crashing+ engine = ChinaAEngine({"initial_cash": 1_000_000})+ engine._execute_bars(dates, data_map, close_df, target_pos, valid_codes)+ assert len(engine.equity_snapshots) == 20