Skip to content

"Vibe-Trading: Your Personal Trading Agent"

fix(backtest): make the sub-daily PIT guard reason only about clocks

Haozhe Wu16526e114b21
diff --git a/agent/backtest/engines/base.py b/agent/backtest/engines/base.py
index d3a8fb205..94e1ae324 100644
--- a/agent/backtest/engines/base.py
+++ b/agent/backtest/engines/base.py
@@ -33,6 +33,7 @@ from backtest.loaders.rsshub_events import (
)
from backtest.loaders.tushare_fundamentals import (
SUBDAILY_POLICIES,
+ SubdailyPitError,
TushareFundamentalProvider,
enrich_price_frames_with_fundamentals,
)
@@ -426,10 +427,11 @@ def _maybe_enrich_fundamentals(
periods=config.get("fundamental_periods"),
subdaily=subdaily,
)
- except ValueError:
- # A configuration/contract error (an intraday frame under the default
- # reject policy) is the caller's to fix and must not be reworded as a
- # provider failure.
+ except SubdailyPitError:
+ # A contract error (an intraday frame under the default reject policy)
+ # is the caller's to fix and must not be reworded as a provider
+ # failure. Narrow on purpose: a stray ValueError from inside the
+ # enrichment is a failure and keeps the wrapped message.
raise
except Exception as exc:
raise RuntimeError(
diff --git a/agent/backtest/loaders/tushare_fundamentals.py b/agent/backtest/loaders/tushare_fundamentals.py
index 0436de6ae..7be5f027b 100644
--- a/agent/backtest/loaders/tushare_fundamentals.py
+++ b/agent/backtest/loaders/tushare_fundamentals.py
@@ -22,6 +22,14 @@ class SchemaValidationError(DataProviderError):
"""Raised when provider output is missing required columns."""
+class SubdailyPitError(ValueError):
+ """Raised when fundamentals are requested for an intraday price frame.
+
+ A caller-fixable contract error, not a provider failure — engines let it
+ through verbatim instead of rewording it as an enrichment failure.
+ """
+
+
@dataclass(frozen=True)
class ColumnSchema:
"""Machine-readable column metadata for a provider table."""
@@ -277,7 +285,22 @@ def _is_subdaily_index(index: pd.Index) -> bool:
Returns:
``True`` when the frame is finer than one bar per day.
"""
- stamps = pd.to_datetime(index)
+ if isinstance(index, pd.DatetimeIndex):
+ stamps = index
+ elif pd.api.types.is_object_dtype(index) or pd.api.types.is_string_dtype(index):
+ try:
+ stamps = pd.DatetimeIndex(pd.to_datetime(index))
+ except (TypeError, ValueError):
+ # Not a clock at all. The merge below already fails on such an
+ # index exactly as it did before this guard existed; do not
+ # convert that into a sub-daily rejection with a date-parse
+ # message pinned to it.
+ return False
+ else:
+ # A numeric index is not a clock either: ``pd.to_datetime`` reads it
+ # as nanoseconds since the epoch, which puts every row at a distinct
+ # sub-second time and reports every frame as sub-daily.
+ return False
if len(stamps) == 0:
return False
if (stamps != stamps.normalize()).any():
@@ -331,7 +354,7 @@ def enrich_price_frames_with_fundamentals(
if not frame.empty and _is_subdaily_index(frame.index)
]
if subdaily_codes and subdaily == "reject":
- raise ValueError(
+ raise SubdailyPitError(
"fundamental_fields is PIT-safe for daily frames only; "
f"{', '.join(sorted(subdaily_codes)[:5])} carry intraday bars, where an "
"ann_date with no time of day would be visible from the first bar of "
diff --git a/agent/tests/test_tushare_fundamentals_provider.py b/agent/tests/test_tushare_fundamentals_provider.py
index db41a676c..dea48d6d6 100644
--- a/agent/tests/test_tushare_fundamentals_provider.py
+++ b/agent/tests/test_tushare_fundamentals_provider.py
@@ -10,7 +10,9 @@ from backtest.loaders.tushare_fundamentals import (
SchemaValidationError,
TushareFundamentalProvider,
UnknownTableError,
+ _is_subdaily_index,
enrich_price_frames_with_fundamentals,
+ SubdailyPitError,
)
@@ -504,3 +506,71 @@ def test_unknown_subdaily_policy_is_rejected() -> None:
as_of="2024-05-31",
subdaily="whenever",
)
+
+
+ ("index", "expected"),
+ [
+ (pd.date_range("2024-01-01", periods=3), False),
+ (pd.date_range("2024-01-01", periods=3, freq="h"), True),
+ (pd.DatetimeIndex([]), False),
+ (pd.Index(["2024-01-01", "2024-01-02"]), False),
+ (pd.Index(["2024-01-01 09:30", "2024-01-01 10:30"]), True),
+ # A numeric index is not a clock. pd.to_datetime reads it as
+ # nanoseconds since the epoch, which puts every row at a distinct
+ # sub-second time and would reject every such frame as "intraday".
+ (pd.RangeIndex(5), False),
+ (pd.Index([0, 1, 2]), False),
+ # An unparseable index is left to fail where it always failed (the
+ # merge), not turned into a sub-daily rejection carrying a
+ # date-parse message.
+ (pd.Index(["a", "b"]), False),
+ ],
+)
+def test_subdaily_detector_only_reasons_about_clocks(
+ index: pd.Index, expected: bool
+) -> None:
+ assert _is_subdaily_index(index) is expected
+
+
+def test_provider_failures_keep_the_wrapped_message(monkeypatch) -> None:
+ """Only the sub-daily contract error passes through the engine verbatim.
+
+ A stray ValueError from inside enrichment is a provider failure and must
+ keep the "Tushare enrichment failed" wrapper that names it as such.
+ """
+ from backtest.engines import base as base_engine
+
+ def boom(*args: object, **kwargs: object) -> None:
+ raise ValueError("provider returned nonsense")
+
+ monkeypatch.setattr(
+ base_engine, "TushareFundamentalProvider", lambda: object(), raising=False
+ )
+ monkeypatch.setattr(
+ base_engine, "enrich_price_frames_with_fundamentals", boom, raising=False
+ )
+ frame = _bars(pd.to_datetime(["2024-04-25", "2024-04-26"]))
+
+ with pytest.raises(RuntimeError, match="Tushare enrichment failed"):
+ base_engine._maybe_enrich_fundamentals(
+ {"000001.SZ": frame},
+ {"fundamental_fields": {"income": ["total_revenue"]}, "end_date": "2024-04-30"},
+ )
+
+
+def test_subdaily_contract_error_is_not_reworded(monkeypatch) -> None:
+ from backtest.engines import base as base_engine
+
+ monkeypatch.setattr(
+ base_engine,
+ "TushareFundamentalProvider",
+ lambda: TushareFundamentalProvider(api=_AnnouncementApi()),
+ raising=False,
+ )
+
+ with pytest.raises(SubdailyPitError, match="daily frames only"):
+ base_engine._maybe_enrich_fundamentals(
+ {"000001.SZ": _bars(_INTRADAY_INDEX)},
+ {"fundamental_fields": {"income": ["total_revenue"]}, "end_date": "2024-04-30"},
+ )