"Vibe-Trading: Your Personal Trading Agent"
Python ai-agentalgorithmic-tradingbacktestingfintechllmmcpmulti-agentpythonquantitative-financetrading
fix: fail fast on Tushare fundamental enrichment errors
Haozhe Wu4fd82a095243
diff --git a/agent/backtest/engines/base.py b/agent/backtest/engines/base.pyindex 33f9989cb..e8a785dc6 100644--- a/agent/backtest/engines/base.py+++ b/agent/backtest/engines/base.py@@ -14,6 +14,7 @@ import loggingimport re as _reimport sysfrom abc import ABC, abstractmethod+from collections.abc import Iterablefrom pathlib import Pathfrom typing import Any, Callable, Dict, List, Optional@@ -136,14 +137,29 @@ def _load_optimizer(config: Dict[str, Any]) -> Optional[Callable]:def _normalise_fundamental_fields(config: Dict[str, Any]) -> dict[str, list[str]]:"""Read the optional statement-table field map from backtest config."""- raw_fields = config.get("fundamental_fields") or {}- if not isinstance(raw_fields, dict):+ raw_fields = config.get("fundamental_fields")+ if raw_fields in (None, {}):return {}- return {- str(table): list(fields)- for table, fields in raw_fields.items()- if fields- }+ if not isinstance(raw_fields, dict):+ raise ValueError("fundamental_fields must map table names to field-name lists")++ normalized: dict[str, list[str]] = {}+ for table, fields in raw_fields.items():+ if not isinstance(table, str) or not table.strip():+ raise ValueError("fundamental_fields table names must be non-empty strings")+ if fields is None:+ continue+ if isinstance(fields, str) or not isinstance(fields, Iterable):+ raise ValueError(f"fundamental_fields[{table!r}] must be a list of field names")++ field_list = list(fields)+ if not field_list:+ continue+ invalid = [field for field in field_list if not isinstance(field, str) or not field.strip()]+ if invalid:+ raise ValueError(f"fundamental_fields[{table!r}] contains invalid field names")+ normalized[table.strip()] = field_list+ return normalizeddef _maybe_enrich_fundamentals(@@ -156,16 +172,18 @@ def _maybe_enrich_fundamentals(return data_maptry:+ provider = TushareFundamentalProvider()return enrich_price_frames_with_fundamentals(data_map,- TushareFundamentalProvider(),+ provider,fields_by_table,as_of=config.get("end_date", ""),periods=config.get("fundamental_periods"),)except Exception as exc:- print(f"[WARN] failed to enrich Tushare fundamentals: {exc}")- return data_map+ raise RuntimeError(+ f"fundamental_fields requested but Tushare enrichment failed: {exc}"+ ) from exc# ─── Base Engine ───diff --git a/agent/backtest/runner.py b/agent/backtest/runner.pyindex 67728bd70..e27925bc8 100644--- a/agent/backtest/runner.py+++ b/agent/backtest/runner.py@@ -14,7 +14,7 @@ import loggingimport reimport sysfrom pathlib import Path-from typing import Any, Dict, List, Optional+from typing import Dict, List, Optionalimport pandas as pdfrom pydantic import BaseModel, ConfigDict, model_validator, field_validator@@ -51,6 +51,7 @@ class BacktestConfigSchema(BaseModel):source: str = "tushare"interval: str = "1D"engine: str = "daily"+ fundamental_fields: Optional[Dict[str, List[str]]] = None@field_validator("codes")@classmethod@@ -91,6 +92,21 @@ class BacktestConfigSchema(BaseModel):raise ValueError(f"unsupported source {v!r}, must be one of {_VALID_SOURCES}")return v+ @field_validator("fundamental_fields")+ @classmethod+ def valid_fundamental_fields(+ cls,+ v: Optional[Dict[str, List[str]]],+ ) -> Optional[Dict[str, List[str]]]:+ if v is None:+ return v+ for table, fields in v.items():+ if not table.strip():+ raise ValueError("fundamental_fields table names must be non-empty strings")+ if any(not field.strip() for field in fields):+ raise ValueError("fundamental_fields field names must be non-empty strings")+ return v+@model_validator(mode="after")def start_before_end(self) -> "BacktestConfigSchema":if pd.Timestamp(self.start_date) > pd.Timestamp(self.end_date):@@ -646,6 +662,6 @@ class _AutoLoader:if __name__ == "__main__":if len(sys.argv) < 2:- print(f"Usage: python -m backtest.runner <run_dir>")+ print("Usage: python -m backtest.runner <run_dir>")sys.exit(1)main(Path(sys.argv[1]))diff --git a/agent/tests/test_engine_robustness.py b/agent/tests/test_engine_robustness.pyindex 2759b793c..ea5ed66d5 100644--- a/agent/tests/test_engine_robustness.py+++ b/agent/tests/test_engine_robustness.py@@ -241,6 +241,29 @@ class TestSymbolIsolation:assert metrics["benchmark_ticker"] == "000300.SH"assert metrics["benchmark_return"] == 0.00495+ def test_configured_fundamental_enrichment_failure_is_not_silent(+ self,+ monkeypatch: pytest.MonkeyPatch,+ ) -> None:+ """Explicit statement-field requests should fail rather than degrade silently."""+ dates = pd.bdate_range("2024-04-01", periods=1)+ bars = pd.DataFrame({"close": [10.0]}, index=dates)++ def fake_enrich(*args, **kwargs):+ raise RuntimeError("provider failed")++ monkeypatch.setattr(base_engine, "TushareFundamentalProvider", lambda: object(), raising=False)+ monkeypatch.setattr(base_engine, "enrich_price_frames_with_fundamentals", fake_enrich, raising=False)++ with pytest.raises(RuntimeError, match="fundamental_fields.*provider failed"):+ base_engine._maybe_enrich_fundamentals(+ {"000001.SZ": bars},+ {+ "end_date": "2024-04-30",+ "fundamental_fields": {"income": ["total_revenue"]},+ },+ )+# ---------------------------------------------------------------------------# 3. Config schema validation (pydantic)@@ -258,6 +281,15 @@ class TestBacktestConfigSchema:assert c.interval == "1D"assert c.engine == "daily"+ def test_fundamental_fields_must_be_table_to_field_list_mapping(self) -> None:+ with pytest.raises(ValueError, match="fundamental_fields"):+ BacktestConfigSchema(+ codes=["000001.SZ"],+ start_date="2025-01-01",+ end_date="2025-06-01",+ fundamental_fields={"income": "total_revenue"},+ )+def test_empty_codes_rejected(self) -> None:with pytest.raises(Exception, match="codes must be a non-empty list"):BacktestConfigSchema(