Skip to content

"Vibe-Trading: Your Personal Trading Agent"

fix(backtest): stop fundamental PIT enrichment leaking into intraday bars

Haozhe Wu260b1ddbc3c5
diff --git a/agent/backtest/engines/base.py b/agent/backtest/engines/base.py
index 0821272dd..d3a8fb205 100644
--- a/agent/backtest/engines/base.py
+++ b/agent/backtest/engines/base.py
@@ -32,6 +32,7 @@ from backtest.loaders.rsshub_events import (
feed_specs_from_config,
)
from backtest.loaders.tushare_fundamentals import (
+ SUBDAILY_POLICIES,
TushareFundamentalProvider,
enrich_price_frames_with_fundamentals,
)
@@ -409,6 +410,12 @@ def _maybe_enrich_fundamentals(
if not fields_by_table:
return data_map
+ subdaily = str(config.get("fundamental_subdaily", "reject")).strip().lower()
+ if subdaily not in SUBDAILY_POLICIES:
+ raise ValueError(
+ f"fundamental_subdaily must be one of {SUBDAILY_POLICIES}, got {subdaily!r}"
+ )
+
try:
provider = TushareFundamentalProvider()
return enrich_price_frames_with_fundamentals(
@@ -417,7 +424,13 @@ def _maybe_enrich_fundamentals(
fields_by_table,
as_of=config.get("end_date", ""),
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.
+ raise
except Exception as exc:
raise RuntimeError(
f"fundamental_fields requested but Tushare enrichment failed: {exc}"
diff --git a/agent/backtest/loaders/tushare_fundamentals.py b/agent/backtest/loaders/tushare_fundamentals.py
index 7d183d7e1..0436de6ae 100644
--- a/agent/backtest/loaders/tushare_fundamentals.py
+++ b/agent/backtest/loaders/tushare_fundamentals.py
@@ -261,6 +261,30 @@ def _parse_tushare_date(value: str | pd.Timestamp) -> pd.Timestamp:
return pd.to_datetime(text).normalize()
+SUBDAILY_POLICIES = ("reject", "next_day")
+
+
+def _is_subdaily_index(index: pd.Index) -> bool:
+ """Report whether a price frame's index carries intraday bars.
+
+ A frame is sub-daily when any timestamp has a time-of-day component, or
+ when one calendar day holds more than one bar. Either alone is enough:
+ a 1h frame that happens to start at midnight still repeats the day.
+
+ Args:
+ index: A price frame's index.
+
+ Returns:
+ ``True`` when the frame is finer than one bar per day.
+ """
+ stamps = pd.to_datetime(index)
+ if len(stamps) == 0:
+ return False
+ if (stamps != stamps.normalize()).any():
+ return True
+ return bool(stamps.normalize().duplicated().any())
+
+
def enrich_price_frames_with_fundamentals(
data_map: dict[str, pd.DataFrame],
provider: TushareFundamentalProvider,
@@ -268,9 +292,20 @@ def enrich_price_frames_with_fundamentals(
*,
as_of: str | pd.Timestamp,
periods: Iterable[str] | None = None,
+ subdaily: str = "reject",
) -> dict[str, pd.DataFrame]:
"""Attach PIT-safe fundamental snapshots to daily price frames.
+ Sub-daily frames (``subdaily``): Tushare's ``ann_date`` / ``f_ann_date``
+ is a date with no time of day, and CN filings typically land after the
+ close, so a day-granular visibility rule applied to intraday bars makes
+ a filing visible from the first bar of its own announcement day — a real
+ lookahead below 1D. Daily runs are unaffected because a signal on day D
+ fills at D+1's open at the earliest. ``"reject"`` (the default) raises
+ rather than enriching an intraday frame; ``"next_day"`` opts in to
+ intraday enrichment with the conservative convention that a filing
+ announced on D is visible from the first bar of D+1.
+
Fundamental columns are prefixed with their table name, for example
``income_total_revenue`` and ``fina_indicator_roe``. Each row becomes
visible only on or after its announcement/disclosure date.
@@ -283,9 +318,28 @@ def enrich_price_frames_with_fundamentals(
currently visible. Same-period restatements (same ``end_date``, later
pit date) do update the visible values.
"""
+ if subdaily not in SUBDAILY_POLICIES:
+ raise ValueError(
+ f"subdaily must be one of {SUBDAILY_POLICIES}, got {subdaily!r}"
+ )
if not data_map or not fields_by_table:
return data_map
+ subdaily_codes = [
+ code
+ for code, frame in data_map.items()
+ if not frame.empty and _is_subdaily_index(frame.index)
+ ]
+ if subdaily_codes and subdaily == "reject":
+ raise ValueError(
+ "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 "
+ "its own announcement day. Run the backtest daily, or set "
+ "fundamental_subdaily='next_day' to accept the conservative "
+ "first-bar-of-the-next-day convention."
+ )
+
enriched = {code: frame.copy() for code, frame in data_map.items()}
codes = list(enriched)
@@ -358,6 +412,14 @@ def enrich_price_frames_with_fundamentals(
columns={column: f"{table}_{column}" for column in value_columns}
)
+ if code in subdaily_codes:
+ # ``next_day``: an announcement dated D becomes visible one
+ # calendar day later, i.e. from the first bar of D+1. The bar
+ # index is normalized to midnight below, so shifting the pit
+ # date by one day is exactly that boundary.
+ right = right.copy()
+ right["_pit_date"] = right["_pit_date"] + pd.Timedelta(days=1)
+
left = frame.copy()
original_index = left.index
left["_trade_date"] = pd.to_datetime(left.index).normalize()
diff --git a/agent/tests/test_tushare_fundamentals_provider.py b/agent/tests/test_tushare_fundamentals_provider.py
index d4fa1de4f..db41a676c 100644
--- a/agent/tests/test_tushare_fundamentals_provider.py
+++ b/agent/tests/test_tushare_fundamentals_provider.py
@@ -374,3 +374,133 @@ def test_t3_enrich_same_period_restatement_updates_value() -> None:
assert result.loc[d, "income_revenue"] == 95.0, (
f"{d.date()}: expected restated revenue=95, got {result.loc[d, 'income_revenue']}"
)
+
+
+# ---------------------------------------------------------------------------
+# #1387: PIT visibility on sub-daily frames
+# ---------------------------------------------------------------------------
+
+
+class _AnnouncementApi:
+ """One filing announced on 2024-04-26, the day the intraday bars cover."""
+
+ def income(self, **kwargs: object) -> pd.DataFrame:
+ return pd.DataFrame(
+ [
+ {
+ "ts_code": kwargs["ts_code"],
+ "end_date": "20240331",
+ "ann_date": "20240426",
+ "f_ann_date": "20240426",
+ "total_revenue": 120.0,
+ }
+ ]
+ )
+
+
+def _bars(index: pd.DatetimeIndex) -> pd.DataFrame:
+ return pd.DataFrame(
+ {
+ "open": 10.0,
+ "high": 10.5,
+ "low": 9.5,
+ "close": 10.2,
+ "volume": 1000,
+ },
+ index=index,
+ )
+
+
+_INTRADAY_INDEX = pd.to_datetime(
+ [
+ "2024-04-26 09:30",
+ "2024-04-26 10:30",
+ "2024-04-26 15:00",
+ "2024-04-29 09:30",
+ "2024-04-29 10:30",
+ ]
+)
+
+
+def test_subdaily_frames_are_rejected_by_default() -> None:
+ """An ann_date has no time of day, so a day-granular rule leaks intraday.
+
+ Before this guard the 09:30 bar of the announcement day already carried
+ the filing — a lookahead of a full session, on filings that in CN
+ typically land after the close.
+ """
+ provider = TushareFundamentalProvider(api=_AnnouncementApi())
+
+ with pytest.raises(ValueError, match="daily frames only"):
+ enrich_price_frames_with_fundamentals(
+ {"000001.SZ": _bars(_INTRADAY_INDEX)},
+ provider,
+ {"income": ["total_revenue"]},
+ as_of="2024-05-31",
+ )
+
+
+def test_subdaily_next_day_policy_hides_the_announcement_day() -> None:
+ provider = TushareFundamentalProvider(api=_AnnouncementApi())
+
+ result = enrich_price_frames_with_fundamentals(
+ {"000001.SZ": _bars(_INTRADAY_INDEX)},
+ provider,
+ {"income": ["total_revenue"]},
+ as_of="2024-05-31",
+ subdaily="next_day",
+ )["000001.SZ"]
+
+ announcement_day = result.loc["2024-04-26", "income_total_revenue"]
+ assert announcement_day.isna().all(), announcement_day.tolist()
+ # …and the very next bar, on D+1, does carry it: the guard must not turn
+ # into "intraday never sees fundamentals".
+ assert result.loc[pd.Timestamp("2024-04-29 09:30"), "income_total_revenue"] == 120.0
+
+
+def test_daily_frames_keep_same_day_visibility() -> None:
+ """The sub-daily guard must not move the daily contract.
+
+ A daily signal on day D fills at D+1's open at the earliest, so same-day
+ visibility on a daily bar is correct and stays.
+ """
+ provider = TushareFundamentalProvider(api=_AnnouncementApi())
+ daily = pd.to_datetime(["2024-04-25", "2024-04-26", "2024-04-29"])
+
+ result = enrich_price_frames_with_fundamentals(
+ {"000001.SZ": _bars(daily)},
+ provider,
+ {"income": ["total_revenue"]},
+ as_of="2024-05-31",
+ )["000001.SZ"]
+
+ assert pd.isna(result.loc[pd.Timestamp("2024-04-25"), "income_total_revenue"])
+ assert result.loc[pd.Timestamp("2024-04-26"), "income_total_revenue"] == 120.0
+
+
+def test_daily_index_written_with_midnight_times_is_not_flagged_subdaily() -> None:
+ """A daily frame whose stamps carry 00:00 is still daily."""
+ provider = TushareFundamentalProvider(api=_AnnouncementApi())
+ midnight = pd.to_datetime(["2024-04-25 00:00", "2024-04-26 00:00"])
+
+ result = enrich_price_frames_with_fundamentals(
+ {"000001.SZ": _bars(midnight)},
+ provider,
+ {"income": ["total_revenue"]},
+ as_of="2024-05-31",
+ )["000001.SZ"]
+
+ assert result.loc[pd.Timestamp("2024-04-26"), "income_total_revenue"] == 120.0
+
+
+def test_unknown_subdaily_policy_is_rejected() -> None:
+ provider = TushareFundamentalProvider(api=_AnnouncementApi())
+
+ with pytest.raises(ValueError, match="subdaily must be one of"):
+ enrich_price_frames_with_fundamentals(
+ {"000001.SZ": _bars(_INTRADAY_INDEX)},
+ provider,
+ {"income": ["total_revenue"]},
+ as_of="2024-05-31",
+ subdaily="whenever",
+ )