Skip to content

"Vibe-Trading: Your Personal Trading Agent"

feat(loaders): free baostock fallback for val:* when tushare is unavailable (#1799)

Jackzigen2b2b5e01c9e3
diff --git a/agent/backtest/loaders/valuation_loader.py b/agent/backtest/loaders/valuation_loader.py
index 5526465a9..384b4d2da 100644
--- a/agent/backtest/loaders/valuation_loader.py
+++ b/agent/backtest/loaders/valuation_loader.py
@@ -37,6 +37,12 @@ logger = logging.getLogger(__name__)
#: percent units (股息率TTM, %); consumers z-score it, which is scale-invariant.
VALUATION_FIELDS: tuple[str, ...] = ("pe", "pe_ttm", "pb", "ps_ttm", "dv_ttm")
+#: Fields the free baostock fallback can serve, mapped to their
+#: ``query_history_k_data_plus`` column names (#1789 follow-up #3).
+#: ``pe`` (dynamic) and ``dv_ttm`` have no baostock counterpart and stay NaN
+#: when the fallback is the only source.
+BAOSTOCK_VALUATION_FIELDS: dict[str, str] = {"pe_ttm": "peTTM", "pb": "pbMRQ", "ps_ttm": "psTTM"}
+
#: A-share exchange suffixes covered by ``daily_basic``.
_CN_EQUITY_SUFFIXES = (".SH", ".SZ", ".BJ")
@@ -91,6 +97,135 @@ def _build_api() -> Any:
return ts.pro_api(token)
+def _resolve_tushare_api(api: Any | None) -> Any | None:
+ """Return an injectable API unchanged; build from token or None.
+
+ A missing token returns None (the free baostock fallback serves those
+ fields) instead of raising, and a tushare import/config failure also
+ returns None so a broken tushare install degrades rather than kills the
+ valuation panel.
+ """
+ if api is not None:
+ return api
+ try:
+ return _build_api()
+ except Exception as exc: # noqa: BLE001 - missing token falls back, never raises
+ logger.info("tushare unavailable for val:* (%s); trying baostock fallback", exc)
+ return None
+
+
+def _baostock_available() -> bool:
+ """True if the baostock package is importable."""
+ try:
+ import baostock # noqa: F401
+
+ return True
+ except ImportError:
+ return False
+
+
+def _to_baostock_code(code: str) -> str | None:
+ """Map a panel symbol to baostock's ``sh.``/``sz.`` code, if A-share."""
+ lower = code.lower()
+ if lower.startswith(("sh.", "sz.")):
+ return lower
+ if code.upper().endswith((".SH", ".SZ")):
+ symbol, _, suffix = code.upper().rpartition(".")
+ return f"{suffix.lower()}.{symbol}"
+ return None
+
+
+def _load_baostock_valuation(
+ cn_symbols: Sequence[str],
+ fields: Sequence[str],
+ start: str,
+ end: str,
+ index: pd.DatetimeIndex,
+) -> dict[str, pd.DataFrame]:
+ """Serve ``val:*`` fields from free, no-auth baostock daily bars.
+
+ Fallback for users without a TUSHARE_TOKEN (#1789 follow-up #3):
+ ``query_history_k_data_plus`` exposes per-day valuation columns
+ (``peTTM``/``pbMRQ``/``psTTM``) on the same daily bars the OHLCV loader
+ already uses. Fields without a baostock counterpart (``pe`` dynamic,
+ ``dv_ttm``) are returned as NaN frames rather than fabricated, and a
+ baostock outage degrades to NaN frames instead of raising.
+
+ Args:
+ cn_symbols: CN A-share symbols to fetch.
+ fields: Requested field names (``val:`` prefix stripped).
+ start: Start date (YYYY-MM-DD).
+ end: End date (YYYY-MM-DD).
+ index: Price-panel index to align to.
+
+ Returns:
+ ``field -> dates x symbols`` frames aligned to ``index``/``cn_symbols``.
+ """
+ from backtest.loaders.baostock_loader import _baostock_socket_guard, _read_timeout
+
+ wanted = [field for field in fields if field in BAOSTOCK_VALUATION_FIELDS]
+ nan_frames = {
+ field: pd.DataFrame(float("nan"), index=index, columns=list(cn_symbols))
+ for field in fields
+ }
+ if not wanted:
+ return nan_frames
+
+ import baostock as bs
+
+ columns = "date," + ",".join(BAOSTOCK_VALUATION_FIELDS[field] for field in wanted)
+ series_by_field: dict[str, dict[str, pd.Series]] = {field: {} for field in wanted}
+ with _baostock_socket_guard(_read_timeout()) as acquired:
+ if not acquired:
+ return nan_frames
+ lg = bs.login()
+ if lg.error_code != "0":
+ logger.warning("baostock login failed: %s; valuation fallback stays NaN", lg.error_msg)
+ return nan_frames
+ try:
+ for code in cn_symbols:
+ bs_code = _to_baostock_code(code)
+ if bs_code is None:
+ continue
+ try:
+ rs = bs.query_history_k_data_plus(
+ bs_code,
+ columns,
+ start_date=start,
+ end_date=end,
+ frequency="d",
+ )
+ except Exception as exc: # noqa: BLE001 - one bad fetch must not raise
+ logger.warning("baostock valuation fetch failed for %s: %s", code, exc)
+ continue
+ if rs.error_code != "0":
+ logger.warning("baostock valuation query failed for %s: %s", code, rs.error_msg)
+ continue
+ rows = []
+ while rs.next():
+ rows.append(rs.get_row_data())
+ if not rows:
+ continue
+ frame = pd.DataFrame(rows, columns=columns.split(","))
+ frame["date"] = pd.to_datetime(frame["date"], errors="coerce")
+ frame = frame.dropna(subset=["date"]).set_index("date").sort_index()
+ for field in wanted:
+ source_column = BAOSTOCK_VALUATION_FIELDS[field]
+ if source_column in frame.columns:
+ series_by_field[field][code] = pd.to_numeric(
+ frame[source_column], errors="coerce"
+ )
+ finally:
+ bs.logout()
+
+ for field in wanted:
+ per_code = series_by_field[field]
+ if per_code:
+ frame = pd.DataFrame(per_code).reindex(index=index, columns=list(cn_symbols))
+ nan_frames[field] = frame
+ return nan_frames
+
+
def load_valuation_panel(
*,
symbols: Sequence[str],
@@ -114,11 +249,12 @@ def load_valuation_panel(
Returns:
``field -> dates x symbols`` frames aligned to ``index``/``symbols``.
Every validated field is present; symbols or dates ``daily_basic`` did
- not serve are NaN.
+ not serve are NaN, and fields tushare could not serve (no token, or
+ no data returned) are retried against the free baostock fallback
+ (:func:`_load_baostock_valuation`) before degrading to NaN.
Raises:
ValueError: If a field is outside :data:`VALUATION_FIELDS`.
- RuntimeError: If no API is injected and ``TUSHARE_TOKEN`` is missing.
"""
checked = validate_valuation_fields(fields)
if not checked:
@@ -132,35 +268,50 @@ def load_valuation_panel(
cn_symbols = [code for code in symbols if _is_cn_equity(code)]
if not cn_symbols:
return {field: _nan_frame() for field in checked}
- if api is None:
- api = _build_api()
+
+ api = _resolve_tushare_api(api)
sd = start.replace("-", "")
ed = end.replace("-", "")
series_by_field: dict[str, dict[str, pd.Series]] = {field: {} for field in checked}
- for code in cn_symbols:
- try:
- basic = _call_with_backoff(
- api.daily_basic,
- ts_code=code,
- start_date=sd,
- end_date=ed,
- fields="ts_code,trade_date," + ",".join(checked),
- )
- except Exception as exc: # noqa: BLE001 - one bad fetch must not raise
- logger.warning("daily_basic valuation fetch failed for %s: %s", code, exc)
- continue
- if basic is None or basic.empty:
- logger.warning("daily_basic returned empty valuation data for %s", code)
- continue
- basic = basic.copy()
- basic["trade_date"] = pd.to_datetime(basic["trade_date"], errors="coerce")
- basic = basic.dropna(subset=["trade_date"]).set_index("trade_date").sort_index()
- for field in checked:
- if field in basic.columns:
- series_by_field[field][code] = pd.to_numeric(
- basic[field], errors="coerce"
+ if api is not None:
+ for code in cn_symbols:
+ try:
+ basic = _call_with_backoff(
+ api.daily_basic,
+ ts_code=code,
+ start_date=sd,
+ end_date=ed,
+ fields="ts_code,trade_date," + ",".join(checked),
)
+ except Exception as exc: # noqa: BLE001 - one bad fetch must not raise
+ logger.warning("daily_basic valuation fetch failed for %s: %s", code, exc)
+ continue
+ if basic is None or basic.empty:
+ logger.warning("daily_basic returned empty valuation data for %s", code)
+ continue
+ basic = basic.copy()
+ basic["trade_date"] = pd.to_datetime(basic["trade_date"], errors="coerce")
+ basic = basic.dropna(subset=["trade_date"]).set_index("trade_date").sort_index()
+ for field in checked:
+ if field in basic.columns:
+ series_by_field[field][code] = pd.to_numeric(
+ basic[field], errors="coerce"
+ )
+
+ tushare_served = {field for field, per_code in series_by_field.items() if per_code}
+ fallback_fields = [field for field in checked if field not in tushare_served]
+ if fallback_fields and _baostock_available():
+ logger.info(
+ "val:%s not served by tushare; trying the free baostock fallback",
+ fallback_fields,
+ )
+ fallback = _load_baostock_valuation(cn_symbols, fallback_fields, start, end, index)
+ for field, frame in fallback.items():
+ if frame.notna().any().any():
+ series_by_field[field] = {
+ code: frame[code] for code in frame.columns if frame[code].notna().any()
+ }
return {field: _nan_frame(per_code) for field, per_code in series_by_field.items()}
diff --git a/agent/tests/factors/test_fundamental_valuation_samples.py b/agent/tests/factors/test_fundamental_valuation_samples.py
index 41da12e84..8f466daf8 100644
--- a/agent/tests/factors/test_fundamental_valuation_samples.py
+++ b/agent/tests/factors/test_fundamental_valuation_samples.py
@@ -24,6 +24,7 @@ import pandas as pd
import pytest
from backtest import runner
+from backtest.loaders import valuation_loader
from src.factors.registry import AlphaMeta, Registry
_DATES = pd.to_datetime(["2024-01-01", "2024-01-02"])
@@ -339,6 +340,7 @@ def test_missing_token_degrades_to_nan_frames(
) -> None:
"""No TUSHARE_TOKEN: the run survives on NaN frames instead of crashing."""
monkeypatch.setenv("TUSHARE_TOKEN", "")
+ monkeypatch.setattr(valuation_loader, "_baostock_available", lambda: False)
index = pd.to_datetime(["2024-01-02", "2024-01-03", "2024-01-04"])
panel = {"close": pd.DataFrame({"000001.SZ": [10.1, 10.3, 10.4]}, index=index)}
diff --git a/agent/tests/factors/test_valuation_baostock_fallback.py b/agent/tests/factors/test_valuation_baostock_fallback.py
new file mode 100644
index 000000000..72346eb0d
--- /dev/null
+++ b/agent/tests/factors/test_valuation_baostock_fallback.py
@@ -0,0 +1,192 @@
+"""Free baostock fallback for ``val:*`` fields (#1789 follow-up #3).
+
+Users without a TUSHARE_TOKEN used to get an all-NaN valuation panel (and
+before that, a crash). This suite pins the new degradation ladder:
+
+1. no token + baostock installed -> fields are served from baostock daily
+ bars (``peTTM``/``pbMRQ``/``psTTM``);
+2. a tushare outage on specific fields falls back to baostock too;
+3. no token + baostock missing -> NaN frames, run survives;
+4. fields baostock cannot serve (``pe`` dynamic, ``dv_ttm``) stay NaN instead
+ of being fabricated from a proxy;
+5. a baostock outage degrades to NaN frames instead of raising.
+
+All baostock IO is faked via ``sys.modules`` test doubles -- no network.
+"""
+
+from __future__ import annotations
+
+import sys
+from contextlib import contextmanager
+from types import SimpleNamespace
+from typing import Any
+
+import numpy as np
+import pandas as pd
+import pytest
+
+from backtest.loaders import valuation_loader
+from backtest.loaders.valuation_loader import (
+ BAOSTOCK_VALUATION_FIELDS,
+ load_valuation_panel,
+)
+
+_DATES = pd.to_datetime(["2024-01-02", "2024-01-03", "2024-01-04"])
+
+
+class _FakeResultData:
+ def __init__(self, rows: list[list[str]]):
+ self._rows = rows
+ self.error_code = "0"
+ self.error_msg = ""
+
+ def next(self) -> bool:
+ return bool(self._rows)
+
+ def get_row_data(self) -> list[str]:
+ return self._rows.pop(0)
+
+
+class _FakeBaostock:
+ """Minimal ``query_history_k_data_plus`` double backed by canned rows.
+
+ Canned rows are per-column dicts (``{"date": ..., "pbMRQ": ...}``) so the
+ double serves whatever subset of columns the loader asks for.
+ """
+
+ def __init__(self, rows_by_code: dict[str, list[dict[str, str]]]):
+ self.rows_by_code = rows_by_code
+ self.queries: list[str] = []
+
+ def login(self) -> SimpleNamespace:
+ return SimpleNamespace(error_code="0", error_msg="success")
+
+ def logout(self) -> SimpleNamespace:
+ return SimpleNamespace(error_code="0", error_msg="success")
+
+ def query_history_k_data_plus(self, code: str, fields: str, **kwargs: Any) -> _FakeResultData:
+ self.queries.append(code)
+ wanted = fields.split(",")
+ rows = [
+ [row.get(column, "") for column in wanted]
+ for row in self.rows_by_code.get(code, [])
+ ]
+ return _FakeResultData(rows)
+
+
+@contextmanager
+def _fake_guard(timeout: float):
+ yield True
+
+
+def _install_fake_baostock(monkeypatch: pytest.MonkeyPatch, fake: Any) -> None:
+ from backtest.loaders import baostock_loader
+
+ monkeypatch.setitem(sys.modules, "baostock", fake)
+ monkeypatch.setattr(valuation_loader, "_baostock_available", lambda: True)
+ monkeypatch.setattr(baostock_loader, "_baostock_socket_guard", _fake_guard)
+
+
+def test_no_token_serves_val_fields_from_baostock(monkeypatch: pytest.MonkeyPatch) -> None:
+ """Without a token, pe_ttm/pb/ps_ttm come from baostock daily bars."""
+ monkeypatch.setenv("TUSHARE_TOKEN", "")
+ rows = {
+ "sz.000001": [
+ {"date": "2024-01-02", "peTTM": "5.5", "pbMRQ": "0.8", "psTTM": "1.9"},
+ {"date": "2024-01-03", "peTTM": "5.6", "pbMRQ": "0.81", "psTTM": "1.91"},
+ {"date": "2024-01-04", "peTTM": "5.7", "pbMRQ": "0.82", "psTTM": "1.92"},
+ ]
+ }
+ fake = _FakeBaostock(rows)
+ _install_fake_baostock(monkeypatch, fake)
+
+ panels = load_valuation_panel(
+ symbols=["000001.SZ"],
+ fields=["pe_ttm", "pb", "ps_ttm"],
+ start="2024-01-02",
+ end="2024-01-04",
+ index=_DATES,
+ )
+
+ assert fake.queries == ["sz.000001"]
+ np.testing.assert_allclose(panels["pe_ttm"]["000001.SZ"].to_numpy(), [5.5, 5.6, 5.7])
+ np.testing.assert_allclose(panels["pb"]["000001.SZ"].to_numpy(), [0.8, 0.81, 0.82])
+ np.testing.assert_allclose(panels["ps_ttm"]["000001.SZ"].to_numpy(), [1.9, 1.91, 1.92])
+
+
+def test_tushare_failure_falls_back_to_baostock(monkeypatch: pytest.MonkeyPatch) -> None:
+ """A tushare API whose daily_basic always fails degrades to baostock."""
+ rows = {
+ "sh.600000": [
+ {"date": "2024-01-02", "peTTM": "4.1", "pbMRQ": "0.5", "psTTM": "1.2"},
+ {"date": "2024-01-03", "peTTM": "4.2", "pbMRQ": "0.51", "psTTM": "1.21"},
+ ]
+ }
+ fake = _FakeBaostock(rows)
+ _install_fake_baostock(monkeypatch, fake)
+
+ class _BrokenApi:
+ def daily_basic(self, **kwargs: Any):
+ raise RuntimeError("server exploded")
+
+ panels = load_valuation_panel(
+ symbols=["600000.SH"],
+ fields=["pb"],
+ start="2024-01-02",
+ end="2024-01-04",
+ index=_DATES,
+ api=_BrokenApi(),
+ )
+
+ assert fake.queries == ["sh.600000"]
+ np.testing.assert_allclose(
+ panels["pb"]["600000.SH"].to_numpy(), [0.5, 0.51, np.nan]
+ )
+
+
+def test_no_token_and_no_baostock_still_nan(monkeypatch: pytest.MonkeyPatch) -> None:
+ """No token and no baostock: NaN frames, no exception."""
+ monkeypatch.setenv("TUSHARE_TOKEN", "")
+ monkeypatch.setattr(valuation_loader, "_baostock_available", lambda: False)
+
+ panels = load_valuation_panel(
+ symbols=["000001.SZ"],
+ fields=["pb"],
+ start="2024-01-02",
+ end="2024-01-04",
+ index=_DATES,
+ )
+
+ assert panels["pb"].isna().all().all()
+ assert list(panels["pb"].index) == list(_DATES)
+
+
+def test_unserved_fields_stay_nan_not_proxied() -> None:
+ """pe/dv_ttm have no baostock counterpart and must stay NaN, not proxy."""
+ assert "pe" not in BAOSTOCK_VALUATION_FIELDS
+ assert "dv_ttm" not in BAOSTOCK_VALUATION_FIELDS
+ assert set(BAOSTOCK_VALUATION_FIELDS) == {"pe_ttm", "pb", "ps_ttm"}
+
+
+def test_baostock_outage_degrades_to_nan(monkeypatch: pytest.MonkeyPatch) -> None:
+ """baostock login failure yields NaN frames instead of raising."""
+ monkeypatch.setenv("TUSHARE_TOKEN", "")
+
+ class _DeadBaostock:
+ def login(self) -> SimpleNamespace:
+ return SimpleNamespace(error_code="10001", error_msg="network error")
+
+ def logout(self) -> SimpleNamespace:
+ return SimpleNamespace(error_code="0", error_msg="")
+
+ _install_fake_baostock(monkeypatch, _DeadBaostock())
+
+ panels = load_valuation_panel(
+ symbols=["000001.SZ"],
+ fields=["pb"],
+ start="2024-01-02",
+ end="2024-01-04",
+ index=_DATES,
+ )
+
+ assert panels["pb"].isna().all().all()