Skip to content

"Vibe-Trading: Your Personal Trading Agent"

fix(fundamentals): dedup restated rows and prevent period regression in PIT snapshots

klmtseng4e7ddc5e4af0
diff --git a/agent/backtest/loaders/tushare_fundamentals.py b/agent/backtest/loaders/tushare_fundamentals.py
index 2e18d4d9d..7d183d7e1 100644
--- a/agent/backtest/loaders/tushare_fundamentals.py
+++ b/agent/backtest/loaders/tushare_fundamentals.py
@@ -142,7 +142,57 @@ class TushareFundamentalProvider:
periods: Iterable[str] | None = None,
fields: Iterable[str] | None = None,
) -> pd.DataFrame:
- """Query a fundamental table and filter out rows unpublished by ``as_of``."""
+ """Query a fundamental table and filter out rows unpublished by ``as_of``.
+
+ After the PIT cut, rows are deduplicated so that each ``(ts_code,
+ end_date)`` pair keeps only the entry with the latest effective pit
+ date (``f_ann_date`` when present and non-null, falling back to
+ ``ann_date``). Ties on the same pit date preserve the last row in
+ input order, which matches the natural Tushare ordering where
+ restatements appear after originals.
+ """
+ result = self._query_pit_cut(table, codes, as_of=as_of, periods=periods, fields=fields)
+ if result.empty:
+ return result
+
+ schema = self.describe_table(table)
+ pit_column = schema.point_in_time_column
+ if pit_column not in result.columns or result[pit_column].isna().all():
+ pit_column = "ann_date"
+
+ pit_values = result[pit_column]
+ if pit_column != "ann_date" and "ann_date" in result.columns:
+ pit_values = pit_values.where(pit_values.notna(), result["ann_date"])
+ result = result.copy()
+ result["_eff_pit_date"] = pit_values.map(_parse_tushare_date)
+
+ # Keep the row with the latest effective pit date per (ts_code, end_date).
+ # stable sort + keep='last' means that within ties the last row in
+ # input order wins, which is what we want for restatements appended
+ # after the original.
+ result = result.sort_values("_eff_pit_date", kind="stable")
+ result = result.drop_duplicates(subset=["ts_code", "end_date"], keep="last")
+ result = result.drop(columns=["_eff_pit_date"])
+
+ output_columns = self._output_columns(schema, result, fields)
+ result = result.loc[:, output_columns].sort_values(["ts_code", "end_date"]).reset_index(drop=True)
+ return result
+
+ def _query_pit_cut(
+ self,
+ table: str,
+ codes: Iterable[str],
+ *,
+ as_of: str | pd.Timestamp,
+ periods: Iterable[str] | None = None,
+ fields: Iterable[str] | None = None,
+ ) -> pd.DataFrame:
+ """Return all rows visible by ``as_of`` without deduplication.
+
+ This is the raw PIT cut used internally by
+ :func:`enrich_price_frames_with_fundamentals` so that per-trading-day
+ visibility can be evaluated before deduplication is applied.
+ """
schema = self.describe_table(table)
requested_periods = set(periods or [])
frames: list[pd.DataFrame] = []
@@ -176,7 +226,7 @@ class TushareFundamentalProvider:
result = result[pit_dates <= as_of_date]
output_columns = self._output_columns(schema, result, fields)
- result = result.loc[:, output_columns].sort_values(["ts_code", "end_date"]).reset_index(drop=True)
+ result = result.loc[:, output_columns].reset_index(drop=True)
return result
def _validate_schema(self, schema: TableSchema, frame: pd.DataFrame) -> None:
@@ -224,6 +274,14 @@ def enrich_price_frames_with_fundamentals(
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.
+
+ Restatement handling: when a later disclosure covers an *older* reporting
+ period than the most-recently-seen period, the snapshot does **not**
+ regress to that older period. Specifically, the effective announcement
+ timeline is built by scanning rows in ascending pit-date order and only
+ accepting a row when its ``end_date`` is >= the ``end_date`` that is
+ currently visible. Same-period restatements (same ``end_date``, later
+ pit date) do update the visible values.
"""
if not data_map or not fields_by_table:
return data_map
@@ -233,7 +291,9 @@ def enrich_price_frames_with_fundamentals(
for table, fields in fields_by_table.items():
field_list = list(fields or [])
- fundamentals = provider.query_fundamentals(
+ # Use the raw PIT cut (no dedup) so that per-day visibility can be
+ # evaluated correctly before same-period deduplication is applied.
+ fundamentals = provider._query_pit_cut(
table,
codes,
as_of=as_of,
@@ -257,12 +317,44 @@ def enrich_price_frames_with_fundamentals(
if pit_column != "ann_date" and "ann_date" in rows.columns:
pit_values = pit_values.where(pit_values.notna(), rows["ann_date"])
rows["_pit_date"] = pit_values.map(_parse_tushare_date)
- rows = rows.dropna(subset=["_pit_date"]).sort_values("_pit_date")
+ rows["_end_date_parsed"] = rows["end_date"].map(_parse_tushare_date)
+ rows = rows.dropna(subset=["_pit_date", "_end_date_parsed"]).sort_values(
+ ["_pit_date", "_end_date_parsed"], kind="stable"
+ )
if rows.empty:
continue
- value_columns = [column for column in rows.columns if column not in {"ts_code", "_pit_date"}]
- right = rows[["_pit_date", *value_columns]].rename(
+ # Build effective timeline: scan in ascending pit-date order and
+ # only include a row when its end_date >= the currently-visible
+ # end_date. This prevents an old-period restatement (announced
+ # later) from regressing the snapshot to an earlier period.
+ # Same-period restatements (same end_date, later pit_date) pass
+ # the check and are appended as additional timeline entries;
+ # merge_asof will then naturally surface the later restatement for
+ # trade dates on or after its pit_date while keeping the original
+ # visible for earlier dates.
+ timeline_rows: list[pd.Series] = []
+ current_end_date: pd.Timestamp | None = None
+ for _, row in rows.iterrows():
+ row_end_date: pd.Timestamp = row["_end_date_parsed"]
+ if current_end_date is None or row_end_date >= current_end_date:
+ timeline_rows.append(row)
+ current_end_date = row_end_date
+ # Rows where row_end_date < current_end_date are silently
+ # dropped — they represent old-period restatements that must
+ # not regress the visible snapshot.
+
+ if not timeline_rows:
+ continue
+
+ timeline = pd.DataFrame(timeline_rows).drop(columns=["_end_date_parsed"])
+
+ value_columns = [
+ column
+ for column in timeline.columns
+ if column not in {"ts_code", "_pit_date"}
+ ]
+ right = timeline[["_pit_date", *value_columns]].rename(
columns={column: f"{table}_{column}" for column in value_columns}
)
diff --git a/agent/tests/test_tushare_fundamentals_provider.py b/agent/tests/test_tushare_fundamentals_provider.py
index 6fd43b59d..d4fa1de4f 100644
--- a/agent/tests/test_tushare_fundamentals_provider.py
+++ b/agent/tests/test_tushare_fundamentals_provider.py
@@ -194,3 +194,183 @@ def test_enrich_price_frames_with_fundamentals_respects_point_in_time_dates() ->
assert result.loc[pd.Timestamp("2024-04-03"), "income_total_revenue"] == 80.0
assert result.loc[pd.Timestamp("2024-05-07"), "income_total_revenue"] == 120.0
assert result.loc[pd.Timestamp("2024-05-07"), "income_end_date"] == "20240331"
+
+
+# ---------------------------------------------------------------------------
+# Issue #771 fixtures: FY2023 original + restatement + Q1 2024
+# ---------------------------------------------------------------------------
+
+
+def _issue771_api_data(ts_code: str) -> list[dict]:
+ """Return the three-row fixture described in issue #771."""
+ return [
+ # FY2023 original: announced and disclosed 2024-01-30, revenue=100
+ {
+ "ts_code": ts_code,
+ "ann_date": "20240130",
+ "f_ann_date": "20240130",
+ "end_date": "20231231",
+ "revenue": 100.0,
+ },
+ # FY2023 restatement: original announcement still 2024-01-30,
+ # but the actual disclosure (f_ann_date) is 2024-05-15, revenue=95
+ {
+ "ts_code": ts_code,
+ "ann_date": "20240130",
+ "f_ann_date": "20240515",
+ "end_date": "20231231",
+ "revenue": 95.0,
+ },
+ # Q1 2024: announced and disclosed 2024-04-30, revenue=30
+ {
+ "ts_code": ts_code,
+ "ann_date": "20240430",
+ "f_ann_date": "20240430",
+ "end_date": "20240331",
+ "revenue": 30.0,
+ },
+ ]
+
+
+class _Issue771Api:
+ """Fake Tushare API returning the three-row issue #771 fixture."""
+
+ def income(self, **kwargs: object) -> pd.DataFrame:
+ return pd.DataFrame(_issue771_api_data(str(kwargs["ts_code"])))
+
+
+def test_t1_query_fundamentals_deduplicates_restated_rows() -> None:
+ """T1: query_fundamentals with as_of after all disclosures keeps only the
+ latest revision for each (ts_code, end_date) pair."""
+ provider = TushareFundamentalProvider(api=_Issue771Api())
+
+ result = provider.query_fundamentals(
+ "income",
+ ["000001.SZ"],
+ as_of="20240601",
+ fields=["revenue"],
+ )
+
+ # No (ts_code, end_date) duplicates
+ assert not result.duplicated(subset=["ts_code", "end_date"]).any(), (
+ "query_fundamentals must not return duplicate (ts_code, end_date) rows"
+ )
+ # FY2023 must survive but carry the restated revenue=95
+ fy2023 = result[result["end_date"] == "20231231"]
+ assert len(fy2023) == 1, "FY2023 should appear exactly once after dedup"
+ assert fy2023.iloc[0]["revenue"] == 95.0, (
+ "FY2023 must keep the restatement value (rev=95, f_ann_date=20240515)"
+ )
+ # Q1 must also be present
+ q1 = result[result["end_date"] == "20240331"]
+ assert len(q1) == 1
+ assert q1.iloc[0]["revenue"] == 30.0
+
+
+def test_t2_enrich_no_period_regression() -> None:
+ """T2: enrich must not regress to an older period when a late restatement
+ arrives for that period after a newer period's filing is already visible.
+
+ Timeline:
+ 2024-01-30 FY2023 original published (rev=100, visible from 01-30)
+ 2024-04-30 Q1 2024 published (rev=30, visible from 04-30)
+ 2024-05-15 FY2023 restatement (end_date < current visible end_date
+ => must NOT roll back to FY2023)
+
+ Expected observations on each trade date:
+ 04-25..04-29 income_end_date=20231231, income_revenue=100
+ 04-30..05-14 income_end_date=20240331, income_revenue=30
+ 05-15..05-20 income_end_date=20240331, income_revenue=30 (no regression)
+ """
+ provider = TushareFundamentalProvider(api=_Issue771Api())
+ trade_dates = pd.bdate_range("2024-04-25", "2024-05-20")
+ bars = pd.DataFrame({"close": 10.0}, index=trade_dates)
+
+ enriched = enrich_price_frames_with_fundamentals(
+ {"000001.SZ": bars},
+ provider,
+ {"income": ["revenue"]},
+ as_of="20240601",
+ )
+ result = enriched["000001.SZ"]
+
+ # Before Q1 is published: see FY2023 original
+ for d in pd.bdate_range("2024-04-25", "2024-04-29"):
+ assert result.loc[d, "income_end_date"] == "20231231", (
+ f"{d.date()}: expected FY2023 end_date, got {result.loc[d, 'income_end_date']}"
+ )
+ assert result.loc[d, "income_revenue"] == 100.0, (
+ f"{d.date()}: expected revenue=100, got {result.loc[d, 'income_revenue']}"
+ )
+
+ # After Q1 published, before restatement: see Q1
+ for d in pd.bdate_range("2024-04-30", "2024-05-14"):
+ assert result.loc[d, "income_end_date"] == "20240331", (
+ f"{d.date()}: expected Q1 end_date, got {result.loc[d, 'income_end_date']}"
+ )
+ assert result.loc[d, "income_revenue"] == 30.0, (
+ f"{d.date()}: expected revenue=30, got {result.loc[d, 'income_revenue']}"
+ )
+
+ # After FY2023 restatement: must NOT regress to FY2023
+ for d in pd.bdate_range("2024-05-15", "2024-05-20"):
+ assert result.loc[d, "income_end_date"] == "20240331", (
+ f"{d.date()}: snapshot regressed to {result.loc[d, 'income_end_date']} "
+ f"(expected Q1 20240331 to remain visible)"
+ )
+ assert result.loc[d, "income_revenue"] == 30.0, (
+ f"{d.date()}: expected revenue=30, got {result.loc[d, 'income_revenue']}"
+ )
+
+
+def test_t3_enrich_same_period_restatement_updates_value() -> None:
+ """T3: when only same-period original+restatement exist (no newer period),
+ the restatement must update the visible value from its pit_date onward
+ while the original value remains visible before the restatement date."""
+
+ class _SamePeriodApi:
+ def income(self, **kwargs: object) -> pd.DataFrame:
+ return pd.DataFrame(
+ [
+ # FY2023 original
+ {
+ "ts_code": kwargs["ts_code"],
+ "ann_date": "20240130",
+ "f_ann_date": "20240130",
+ "end_date": "20231231",
+ "revenue": 100.0,
+ },
+ # FY2023 restatement, disclosed 2024-05-15
+ {
+ "ts_code": kwargs["ts_code"],
+ "ann_date": "20240130",
+ "f_ann_date": "20240515",
+ "end_date": "20231231",
+ "revenue": 95.0,
+ },
+ ]
+ )
+
+ provider = TushareFundamentalProvider(api=_SamePeriodApi())
+ trade_dates = pd.bdate_range("2024-01-30", "2024-05-20")
+ bars = pd.DataFrame({"close": 10.0}, index=trade_dates)
+
+ enriched = enrich_price_frames_with_fundamentals(
+ {"000001.SZ": bars},
+ provider,
+ {"income": ["revenue"]},
+ as_of="20240601",
+ )
+ result = enriched["000001.SZ"]
+
+ # Before restatement: original value
+ for d in pd.bdate_range("2024-01-30", "2024-05-14"):
+ assert result.loc[d, "income_revenue"] == 100.0, (
+ f"{d.date()}: expected original revenue=100, got {result.loc[d, 'income_revenue']}"
+ )
+
+ # From restatement date onward: updated value
+ for d in pd.bdate_range("2024-05-15", "2024-05-20"):
+ assert result.loc[d, "income_revenue"] == 95.0, (
+ f"{d.date()}: expected restated revenue=95, got {result.loc[d, 'income_revenue']}"
+ )