Skip to content

"Vibe-Trading: Your Personal Trading Agent"

feat: wire tushare fundamentals into filters

MrBob94d0589638b1
diff --git a/agent/backtest/engines/base.py b/agent/backtest/engines/base.py
index feea449be..33f9989cb 100644
--- a/agent/backtest/engines/base.py
+++ b/agent/backtest/engines/base.py
@@ -11,16 +11,18 @@ from __future__ import annotations
import importlib
import json
import logging
+import re as _re
import sys
from abc import ABC, abstractmethod
from pathlib import Path
from typing import Any, Callable, Dict, List, Optional
-import numpy as np
import pandas as pd
-logger = logging.getLogger(__name__)
-
+from backtest.loaders.tushare_fundamentals import (
+ TushareFundamentalProvider,
+ enrich_price_frames_with_fundamentals,
+)
from backtest.metrics import (
by_exit_reason_stats,
by_symbol_stats,
@@ -28,10 +30,10 @@ from backtest.metrics import (
)
from backtest.models import EquitySnapshot, Position, TradeRecord
+logger = logging.getLogger(__name__)
-# ─── Market detection (lightweight, for signal alignment only) ───
-import re as _re
+# ─── Market detection (lightweight, for signal alignment only) ───
_CRYPTO_RE = _re.compile(r"^[A-Z]+-USDT$|^[A-Z]+/USDT$", _re.I)
_FOREX_RE = _re.compile(r"^[A-Z]{3}/[A-Z]{3}$|^[A-Z]{6}\.FX$")
@@ -89,7 +91,7 @@ def _align(
logger.warning("Symbols dropped (no usable price data): %s", all_nan_cols)
codes = [c for c in codes if c not in all_nan_cols]
if not codes:
- raise ValueError(f"All symbols have no data in the requested date range")
+ raise ValueError("All symbols have no data in the requested date range")
close = close[codes]
pos = pd.DataFrame(0.0, index=dates, columns=codes)
@@ -132,6 +134,40 @@ def _load_optimizer(config: Dict[str, Any]) -> Optional[Callable]:
return None
+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):
+ return {}
+ return {
+ str(table): list(fields)
+ for table, fields in raw_fields.items()
+ if fields
+ }
+
+
+def _maybe_enrich_fundamentals(
+ data_map: Dict[str, pd.DataFrame],
+ config: Dict[str, Any],
+) -> Dict[str, pd.DataFrame]:
+ """Attach configured Tushare statement fields before signal generation."""
+ fields_by_table = _normalise_fundamental_fields(config)
+ if not fields_by_table:
+ return data_map
+
+ try:
+ return enrich_price_frames_with_fundamentals(
+ data_map,
+ TushareFundamentalProvider(),
+ 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
+
+
# ─── Base Engine ───
@@ -277,6 +313,7 @@ class BaseEngine(ABC):
if not data_map:
print(json.dumps({"error": "No data fetched"}))
sys.exit(1)
+ data_map = _maybe_enrich_fundamentals(data_map, config)
# 2. Generate signals
signal_map = signal_engine.generate(data_map)
@@ -303,6 +340,7 @@ class BaseEngine(ABC):
index=[s.timestamp for s in self.equity_snapshots],
)
bench_ret = ret_df.mean(axis=1) if ret_df.shape[1] > 0 else pd.Series(0.0, index=dates)
+ benchmark_metadata = {}
# ── External benchmark fetch ──────────────────────────────────────────
bench_ticker = config.get("benchmark")
@@ -318,15 +356,17 @@ class BaseEngine(ABC):
)
if bench_result is not None:
bench_ret = bench_result.ret_series.reindex(dates).fillna(0.0)
- bench_equity = self.initial_capital * (1 + bench_ret).cumprod()
- m["benchmark_ticker"] = bench_result.ticker
- m["benchmark_return"] = bench_result.total_ret
+ benchmark_metadata = {
+ "benchmark_ticker": bench_result.ticker,
+ "benchmark_return": bench_result.total_ret,
+ }
# ── External benchmark fetch ──────────────────────────────────────────
bench_equity = self.initial_capital * (1 + bench_ret).cumprod()
# 6. Metrics
m = calc_metrics(equity_series, self.trades, self.initial_capital, bars_per_year, bench_ret)
+ m.update(benchmark_metadata)
m["by_symbol"] = by_symbol_stats(self.trades)
m["by_exit_reason"] = by_exit_reason_stats(self.trades)
diff --git a/agent/backtest/loaders/tushare_fundamentals.py b/agent/backtest/loaders/tushare_fundamentals.py
index 35946b174..75c111c5c 100644
--- a/agent/backtest/loaders/tushare_fundamentals.py
+++ b/agent/backtest/loaders/tushare_fundamentals.py
@@ -208,3 +208,79 @@ def _parse_tushare_date(value: str | pd.Timestamp) -> pd.Timestamp:
if len(text) == 8 and text.isdigit():
return pd.to_datetime(text, format="%Y%m%d")
return pd.to_datetime(text).normalize()
+
+
+def enrich_price_frames_with_fundamentals(
+ data_map: dict[str, pd.DataFrame],
+ provider: TushareFundamentalProvider,
+ fields_by_table: dict[str, Iterable[str]],
+ *,
+ as_of: str | pd.Timestamp,
+ periods: Iterable[str] | None = None,
+) -> dict[str, pd.DataFrame]:
+ """Attach PIT-safe fundamental snapshots to daily price frames.
+
+ 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.
+ """
+ if not data_map or not fields_by_table:
+ return data_map
+
+ enriched = {code: frame.copy() for code, frame in data_map.items()}
+ codes = list(enriched)
+
+ for table, fields in fields_by_table.items():
+ field_list = list(fields or [])
+ fundamentals = provider.query_fundamentals(
+ table,
+ codes,
+ as_of=as_of,
+ periods=periods,
+ fields=field_list,
+ )
+ if fundamentals.empty:
+ continue
+
+ schema = provider.describe_table(table)
+ pit_column = schema.point_in_time_column
+ if pit_column not in fundamentals.columns or fundamentals[pit_column].isna().all():
+ pit_column = "ann_date"
+
+ for code, frame in enriched.items():
+ rows = fundamentals[fundamentals["ts_code"] == code].copy()
+ if rows.empty or frame.empty:
+ continue
+
+ pit_values = rows[pit_column]
+ 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")
+ 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(
+ columns={column: f"{table}_{column}" for column in value_columns}
+ )
+
+ left = frame.copy()
+ original_index = left.index
+ left["_trade_date"] = pd.to_datetime(left.index).normalize()
+ left["_original_order"] = range(len(left))
+
+ merged = pd.merge_asof(
+ left.sort_values("_trade_date"),
+ right.sort_values("_pit_date"),
+ left_on="_trade_date",
+ right_on="_pit_date",
+ direction="backward",
+ )
+ merged = merged.sort_values("_original_order").drop(
+ columns=["_trade_date", "_original_order", "_pit_date"]
+ )
+ merged.index = original_index
+ enriched[code] = merged
+
+ return enriched
diff --git a/agent/src/skills/fundamental-filter/SKILL.md b/agent/src/skills/fundamental-filter/SKILL.md
index b62b0f7f3..dee1d8692 100644
--- a/agent/src/skills/fundamental-filter/SKILL.md
+++ b/agent/src/skills/fundamental-filter/SKILL.md
@@ -1,6 +1,6 @@
---
name: fundamental-filter
-description: Fundamental factor screening — filter stocks by PE/PB/ROE and other financial metrics for value or growth selection. Supports A-shares (via tushare extra_fields) and HK/US stocks (via yfinance Ticker info).
+description: Fundamental factor screening — filter stocks by PE/PB/ROE, financial statement fields, and other metrics for value or growth selection. Supports A-shares (via tushare extra_fields or fundamental_fields) and HK/US stocks (via yfinance Ticker info).
category: flow
---
# Fundamental Factor Screening
@@ -14,6 +14,7 @@ Filter stocks using fundamental financial data (PE/PB/ROE, etc.) to build value
| Market | Data Source | Method | Supported Metrics |
|--------|-----------|--------|------------------|
| A-shares | tushare `daily_basic` | `extra_fields` in config.json | pe, pb, pe_ttm, ps_ttm, dv_ttm, total_mv, circ_mv, roe |
+| A-shares | Tushare statements | `fundamental_fields` in config.json | income, balancesheet, cashflow, fina_indicator fields |
| US stocks | yfinance `Ticker.info` | Direct API call | trailingPE, forwardPE, priceToBook, returnOnEquity, marketCap, dividendYield |
| HK stocks | yfinance `Ticker.info` | Direct API call | trailingPE, priceToBook, returnOnEquity, marketCap |
@@ -50,6 +51,51 @@ Filter stocks using fundamental financial data (PE/PB/ROE, etc.) to build value
The `extra_fields` columns are automatically merged into the daily DataFrame by the DataLoader.
+### A-Share Statement Pre-Filter
+
+Use `fundamental_fields` when the strategy needs PIT-safe financial statement data instead of daily valuation fields:
+
+```json
+{
+ "source": "tushare",
+ "codes": ["000001.SZ", "600036.SH", "000858.SZ"],
+ "start_date": "2023-01-01",
+ "end_date": "2024-12-31",
+ "fundamental_fields": {
+ "income": ["total_revenue", "n_income"],
+ "balancesheet": ["total_hldr_eqy_exc_min_int"],
+ "fina_indicator": ["roe", "debt_to_assets"]
+ },
+ "initial_cash": 1000000,
+ "commission": 0.001
+}
+```
+
+The backtest runner queries the configured tables through `TushareFundamentalProvider` and merges each published statement snapshot into daily bars only after its announcement/disclosure date. Statement columns are prefixed by table name:
+
+| Requested field | SignalEngine column |
+|-----------------|---------------------|
+| `income.total_revenue` | `income_total_revenue` |
+| `income.n_income` | `income_n_income` |
+| `balancesheet.total_hldr_eqy_exc_min_int` | `balancesheet_total_hldr_eqy_exc_min_int` |
+| `fina_indicator.roe` | `fina_indicator_roe` |
+
+Representative financial-quality pre-filter:
+
+```python
+revenue = row.get("income_total_revenue")
+profit = row.get("income_n_income")
+net_assets = row.get("balancesheet_total_hldr_eqy_exc_min_int")
+roe = row.get("fina_indicator_roe")
+
+passes = (
+ revenue is not None and revenue > 0
+ and profit is not None and profit > 0
+ and net_assets is not None and net_assets > 0
+ and roe is not None and roe >= 8.0
+)
+```
+
## HK/US Stock Usage (yfinance)
For HK/US stocks, fundamental data is not available as daily time-series via the backtest loader. Instead, use `yfinance` Ticker info for point-in-time screening:
@@ -110,6 +156,8 @@ results = screen_us_stocks(hk_tickers, criteria) # Same function works
## Common Pitfalls
- `extra_fields` columns may contain NaN (new listings, ST stocks) — must `fillna` or `dropna`
+- `fundamental_fields` columns are prefixed by table and may be NaN before the first statement is published in the backtest window
+- Do not forward-fill statement rows manually before their `ann_date` / `f_ann_date`; the runner's merge already enforces point-in-time visibility
- Negative PE means loss-making — always filter with `pe > 0`
- ROE units differ: tushare uses percentage (e.g., 15 = 15%), yfinance uses decimal (e.g., 0.15 = 15%)
- For portfolio strategies: N stocks passing the screen each get weight 1/N
diff --git a/agent/src/skills/fundamental-filter/example_signal_engine.py b/agent/src/skills/fundamental-filter/example_signal_engine.py
index b7a48a5cd..b3ce7a901 100644
--- a/agent/src/skills/fundamental-filter/example_signal_engine.py
+++ b/agent/src/skills/fundamental-filter/example_signal_engine.py
@@ -1,7 +1,8 @@
"""基本面因子过滤选股信号引擎。
基于 PE/PB/ROE 等财务指标对 A 股进行价值筛选,
-满足全部条件的股票等权做多。仅限 tushare 数据源(需 extra_fields)。
+满足全部条件的股票等权做多。支持 tushare `extra_fields`
+以及 `fundamental_fields` 注入的财务报表字段。
"""
from typing import Dict, List
@@ -32,6 +33,8 @@ class SignalEngine:
pe_max: float = 20.0,
pb_max: float = 3.0,
roe_min: float = 8.0,
+ revenue_min: float = 0.0,
+ net_assets_min: float = 0.0,
):
"""初始化基本面过滤引擎。
@@ -40,11 +43,34 @@ class SignalEngine:
pe_max: PE 上限(排除高估值)。
pb_max: PB 上限。
roe_min: ROE 下限(%)。
+ revenue_min: 营收下限,单位沿用 Tushare income 表。
+ net_assets_min: 净资产下限,单位沿用 Tushare balancesheet 表。
"""
self.pe_min = pe_min
self.pe_max = pe_max
self.pb_max = pb_max
self.roe_min = roe_min
+ self.revenue_min = revenue_min
+ self.net_assets_min = net_assets_min
+
+ def _passes_statement_filter(self, row: pd.Series) -> bool | None:
+ """Return statement-filter decision, or None when statement data is absent."""
+ revenue = _first_number(row, ["income_total_revenue", "income_revenue"])
+ profit = _first_number(row, ["income_n_income"])
+ net_assets = _first_number(row, ["balancesheet_total_hldr_eqy_exc_min_int"])
+ roe = _first_number(row, ["fina_indicator_roe", "roe"])
+
+ statement_values = [revenue, profit, net_assets, roe]
+ if all(pd.isna(value) for value in statement_values):
+ return None
+ if any(pd.isna(value) for value in statement_values):
+ return False
+ return (
+ revenue >= self.revenue_min
+ and profit > 0
+ and net_assets > self.net_assets_min
+ and roe >= self.roe_min
+ )
def generate(self, data_map: Dict[str, pd.DataFrame]) -> Dict[str, pd.Series]:
"""基于基本面条件过滤,对满足条件的股票等权做多。
@@ -73,6 +99,12 @@ class SignalEngine:
if dt not in df.index:
continue
row = df.loc[dt]
+ statement_pass = self._passes_statement_filter(row)
+ if statement_pass is not None:
+ if statement_pass:
+ qualified.append(code)
+ continue
+
pe = row.get("pe", np.nan)
pb = row.get("pb", np.nan)
roe = row.get("roe", np.nan)
@@ -94,6 +126,15 @@ class SignalEngine:
return result
+def _first_number(row: pd.Series, columns: List[str]) -> float:
+ """Return the first numeric value found in row, otherwise NaN."""
+ for column in columns:
+ value = row.get(column, np.nan)
+ if pd.notna(value):
+ return float(value)
+ return np.nan
+
+
if __name__ == "__main__":
# 演示:用随机数据模拟基本面过滤
np.random.seed(42)
diff --git a/agent/src/skills/strategy-generate/SKILL.md b/agent/src/skills/strategy-generate/SKILL.md
index 6ecdda9af..c5c675aeb 100644
--- a/agent/src/skills/strategy-generate/SKILL.md
+++ b/agent/src/skills/strategy-generate/SKILL.md
@@ -34,7 +34,7 @@ Extract the following from the user's description:
Before writing code, think through these 5 questions:
-1. **Data requirements**: what fields are needed (basic OHLCV only? or fundamentals such as `pe/pb/roe` as well?), data frequency (daily), and market (which determines the data source)
+1. **Data requirements**: what fields are needed (basic OHLCV only, daily valuation fields such as `pe/pb/roe`, or statement fields such as `income_total_revenue` / `fina_indicator_roe`?), data frequency (daily), and market (which determines the data source)
2. **Signal logic**: what are the entry conditions? What are the exit conditions? Direction (long / short / long-short)? Are there filters (volume, trend confirmation, and so on)?
3. **Position management**: equal-weight allocation or scaling in/out? Risk control (stop-loss, maximum position)? In portfolio strategies, once top N names are selected, each weight = 1/N
4. **Backtest parameters**: time range, initial capital (default 1,000,000), commission (default 0.1%)
@@ -50,7 +50,9 @@ class SignalEngine:
"""
Args:
data_map: code -> DataFrame (columns: open, high, low, close, volume, DatetimeIndex)
- If config.extra_fields is specified, pe, pb, roe, and similar columns will also be present.
+ If config.extra_fields is specified, pe, pb, roe, and similar daily_basic columns will also be present.
+ If config.fundamental_fields is specified, PIT-safe statement columns such as
+ income_total_revenue, income_n_income, and fina_indicator_roe will also be present.
Returns:
code -> signal Series, value range [-1.0, 1.0]
1.0 = fully long, 0.5 = half position, 0.0 = flat, -1.0 = fully short
@@ -97,12 +99,14 @@ Self-check after writing `signal_engine.py`:
| Pattern | Market | source | Extra Fields |
|------|------|--------|----------|
-| `^\d{6}\.(SZ\|SH\|BJ)$` | China A-shares | tushare | pe, pb, pe_ttm, ps_ttm, dv_ttm, total_mv, circ_mv, roe |
+| `^\d{6}\.(SZ\|SH\|BJ)$` | China A-shares | tushare | `extra_fields`: pe, pb, pe_ttm, ps_ttm, dv_ttm, total_mv, circ_mv, roe; `fundamental_fields`: income/balancesheet/cashflow/fina_indicator |
| `^[A-Z]+\.US$` | US stocks | yfinance | - |
| `^\d{3,5}\.HK$` | Hong Kong stocks | yfinance | - |
| `^[A-Z]+-USDT$` | Cryptocurrency | okx | - |
-**`extra_fields` selection logic**: only China A-shares (`tushare`) support fundamentals. If the strategy needs `PE/PB/ROE` and similar fields, specify them in `config.json.extra_fields` and `DataLoader` will retrieve them automatically. Hong Kong stocks, US stocks, and crypto do not support `extra_fields`.
+**`extra_fields` selection logic**: only China A-shares (`tushare`) support daily valuation fields. If the strategy needs `PE/PB/ROE` and similar daily_basic fields, specify them in `config.json.extra_fields` and `DataLoader` will retrieve them automatically. Hong Kong stocks, US stocks, and crypto do not support `extra_fields`.
+
+**`fundamental_fields` selection logic**: use this for China A-share financial statement pre-filters. The runner queries `income`, `balancesheet`, `cashflow`, and/or `fina_indicator` through the Tushare fundamental provider, then merges rows into daily bars only after their announcement/disclosure date. Output columns are prefixed by table name, for example `income_total_revenue`, `income_n_income`, `balancesheet_total_hldr_eqy_exc_min_int`, and `fina_indicator_roe`.
## `config.json` Format
@@ -116,6 +120,7 @@ Self-check after writing `signal_engine.py`:
"initial_cash": 1000000,
"commission": 0.001,
"extra_fields": null,
+ "fundamental_fields": null,
"optimizer": null,
"optimizer_params": {},
"engine": "daily",
@@ -130,6 +135,7 @@ Self-check after writing `signal_engine.py`:
- The annualization factor for minute backtests is inferred automatically from `source` (252 trading days for China A-shares, 365 calendar days for crypto)
- Minute backtests can be very data-heavy. Recommended limits are no more than 30 days for `1m`, or 1 year for `1H`
- `extra_fields`: China A-shares can use values such as `["pe", "pb", "roe"]`; other markets should use `null`
+- `fundamental_fields`: optional China A-share statement fields, such as `{"income": ["total_revenue", "n_income"], "fina_indicator": ["roe"]}`; use `null` unless the strategy needs financial statement pre-filtering
- `optimizer`: optional, one of `"equal_volatility"` / `"risk_parity"` / `"mean_variance"` / `"max_diversification"` / `null` (equal-weight by default)
- `optimizer_params`: optimizer parameters, such as `{"lookback": 60}`. `mean_variance` additionally supports `{"risk_free": 0.0}`
- `engine`: backtest engine, default `"daily"`. For options strategies, set `"options"` (requires `OptionsSignalEngine`)
diff --git a/agent/tests/test_engine_robustness.py b/agent/tests/test_engine_robustness.py
index 66397ce70..2759b793c 100644
--- a/agent/tests/test_engine_robustness.py
+++ b/agent/tests/test_engine_robustness.py
@@ -9,9 +9,8 @@
from __future__ import annotations
-import json
-import tempfile
from pathlib import Path
+from types import SimpleNamespace
from typing import Dict
from unittest.mock import patch
@@ -20,6 +19,7 @@ import pandas as pd
import pytest
from backtest.engines.base import _align
+from backtest.engines import base as base_engine
from backtest.engines.china_a import ChinaAEngine
from backtest.loaders.base import validate_date_range
from backtest.runner import BacktestConfigSchema
@@ -134,6 +134,113 @@ class TestSymbolIsolation:
assert len(engine.trades) > 0
assert all(t.symbol == "GOOD" for t in engine.trades)
+ def test_backtest_enriches_data_map_with_configured_fundamental_fields(
+ self,
+ monkeypatch: pytest.MonkeyPatch,
+ tmp_path: Path,
+ ) -> None:
+ """A-share backtests should expose configured statement fields to strategies."""
+ dates = pd.bdate_range("2024-04-01", periods=3)
+ bars = pd.DataFrame(
+ {
+ "open": [10.0, 11.0, 12.0],
+ "high": [10.5, 11.5, 12.5],
+ "low": [9.5, 10.5, 11.5],
+ "close": [10.2, 11.2, 12.2],
+ "volume": [1000, 1100, 1200],
+ },
+ index=dates,
+ )
+
+ class FakeLoader:
+ def fetch(self, *args, **kwargs):
+ return {"000001.SZ": bars.copy()}
+
+ class SignalEngine:
+ def generate(self, data_map):
+ frame = data_map["000001.SZ"]
+ assert "income_total_revenue" in frame.columns
+ assert frame["income_total_revenue"].iloc[-1] == 120.0
+ return {"000001.SZ": pd.Series(0.0, index=frame.index)}
+
+ def fake_enrich(data_map, provider, fields_by_table, *, as_of, periods=None):
+ assert fields_by_table == {"income": ["total_revenue"]}
+ assert as_of == "2024-04-30"
+ enriched = {code: frame.copy() for code, frame in data_map.items()}
+ enriched["000001.SZ"]["income_total_revenue"] = [None, 80.0, 120.0]
+ return enriched
+
+ monkeypatch.setattr(base_engine, "TushareFundamentalProvider", lambda: object(), raising=False)
+ monkeypatch.setattr(base_engine, "enrich_price_frames_with_fundamentals", fake_enrich, raising=False)
+
+ engine = ChinaAEngine({"initial_cash": 1_000_000})
+ engine.run_backtest(
+ {
+ "codes": ["000001.SZ"],
+ "start_date": "2024-04-01",
+ "end_date": "2024-04-30",
+ "source": "tushare",
+ "fundamental_fields": {"income": ["total_revenue"]},
+ "initial_cash": 1_000_000,
+ },
+ FakeLoader(),
+ SignalEngine(),
+ tmp_path,
+ )
+
+ def test_backtest_records_explicit_benchmark_metadata(
+ self,
+ monkeypatch: pytest.MonkeyPatch,
+ tmp_path: Path,
+ ) -> None:
+ """Explicit benchmark metadata should be added after metrics are computed."""
+ dates = pd.bdate_range("2024-04-01", periods=3)
+ bars = pd.DataFrame(
+ {
+ "open": [10.0, 11.0, 12.0],
+ "high": [10.5, 11.5, 12.5],
+ "low": [9.5, 10.5, 11.5],
+ "close": [10.2, 11.2, 12.2],
+ "volume": [1000, 1100, 1200],
+ },
+ index=dates,
+ )
+
+ class FakeLoader:
+ def fetch(self, *args, **kwargs):
+ return {"000001.SZ": bars.copy()}
+
+ class SignalEngine:
+ def generate(self, data_map):
+ return {"000001.SZ": pd.Series(0.0, index=data_map["000001.SZ"].index)}
+
+ def fake_resolve_benchmark(**kwargs):
+ return SimpleNamespace(
+ ticker="000300.SH",
+ ret_series=pd.Series([0.0, 0.01, -0.005], index=dates),
+ total_ret=0.00495,
+ )
+
+ monkeypatch.setattr("backtest.benchmark.resolve_benchmark", fake_resolve_benchmark)
+
+ engine = ChinaAEngine({"initial_cash": 1_000_000})
+ metrics = engine.run_backtest(
+ {
+ "codes": ["000001.SZ"],
+ "start_date": "2024-04-01",
+ "end_date": "2024-04-30",
+ "source": "tushare",
+ "benchmark": "000300.SH",
+ "initial_cash": 1_000_000,
+ },
+ FakeLoader(),
+ SignalEngine(),
+ tmp_path,
+ )
+
+ assert metrics["benchmark_ticker"] == "000300.SH"
+ assert metrics["benchmark_return"] == 0.00495
+
# ---------------------------------------------------------------------------
# 3. Config schema validation (pydantic)
diff --git a/agent/tests/test_fundamental_filter_example.py b/agent/tests/test_fundamental_filter_example.py
new file mode 100644
index 000000000..cde6dbca9
--- /dev/null
+++ b/agent/tests/test_fundamental_filter_example.py
@@ -0,0 +1,43 @@
+from __future__ import annotations
+
+import importlib.util
+from pathlib import Path
+
+import pandas as pd
+
+
+def _load_example_module():
+ path = Path("agent/src/skills/fundamental-filter/example_signal_engine.py")
+ spec = importlib.util.spec_from_file_location("fundamental_filter_example", path)
+ module = importlib.util.module_from_spec(spec)
+ assert spec.loader is not None
+ spec.loader.exec_module(module)
+ return module
+
+
+def test_example_signal_engine_uses_statement_fundamental_columns() -> None:
+ module = _load_example_module()
+ dates = pd.bdate_range("2024-05-06", periods=3)
+
+ good = pd.DataFrame(
+ {
+ "open": [10.0, 10.1, 10.2],
+ "high": [10.5, 10.6, 10.7],
+ "low": [9.8, 9.9, 10.0],
+ "close": [10.2, 10.3, 10.4],
+ "volume": [1000, 1100, 1200],
+ "income_total_revenue": [500.0, 500.0, 500.0],
+ "income_n_income": [50.0, 50.0, 50.0],
+ "balancesheet_total_hldr_eqy_exc_min_int": [300.0, 300.0, 300.0],
+ "fina_indicator_roe": [12.0, 12.0, 12.0],
+ },
+ index=dates,
+ )
+ weak = good.copy()
+ weak["income_n_income"] = [-10.0, -10.0, -10.0]
+
+ engine = module.SignalEngine(roe_min=8.0)
+ signals = engine.generate({"000001.SZ": good, "600000.SH": weak})
+
+ assert signals["000001.SZ"].tolist() == [1.0, 1.0, 1.0]
+ assert signals["600000.SH"].tolist() == [0.0, 0.0, 0.0]
diff --git a/agent/tests/test_tushare_fundamentals_provider.py b/agent/tests/test_tushare_fundamentals_provider.py
index 41b1298ea..6fd43b59d 100644
--- a/agent/tests/test_tushare_fundamentals_provider.py
+++ b/agent/tests/test_tushare_fundamentals_provider.py
@@ -10,6 +10,7 @@ from backtest.loaders.tushare_fundamentals import (
SchemaValidationError,
TushareFundamentalProvider,
UnknownTableError,
+ enrich_price_frames_with_fundamentals,
)
@@ -142,3 +143,54 @@ def test_query_fundamentals_validates_required_schema_columns() -> None:
with pytest.raises(SchemaValidationError, match="end_date"):
provider.query_fundamentals("fina_indicator", ["000001.SZ"], as_of="2024-04-30")
+
+
+def test_enrich_price_frames_with_fundamentals_respects_point_in_time_dates() -> None:
+ class StatementApi:
+ def income(self, **kwargs: object) -> pd.DataFrame:
+ return pd.DataFrame(
+ [
+ {
+ "ts_code": kwargs["ts_code"],
+ "end_date": "20231231",
+ "ann_date": "20240401",
+ "f_ann_date": "20240402",
+ "total_revenue": 80.0,
+ "n_income": 8.0,
+ },
+ {
+ "ts_code": kwargs["ts_code"],
+ "end_date": "20240331",
+ "ann_date": "20240425",
+ "f_ann_date": "20240506",
+ "total_revenue": 120.0,
+ "n_income": 12.0,
+ },
+ ]
+ )
+
+ dates = pd.to_datetime(["2024-04-01", "2024-04-03", "2024-05-07"])
+ bars = pd.DataFrame(
+ {
+ "open": [10.0, 11.0, 12.0],
+ "high": [10.5, 11.5, 12.5],
+ "low": [9.5, 10.5, 11.5],
+ "close": [10.2, 11.2, 12.2],
+ "volume": [1000, 1100, 1200],
+ },
+ index=dates,
+ )
+ provider = TushareFundamentalProvider(api=StatementApi())
+
+ enriched = enrich_price_frames_with_fundamentals(
+ {"000001.SZ": bars},
+ provider,
+ {"income": ["total_revenue", "n_income"]},
+ as_of="2024-05-31",
+ )
+
+ result = enriched["000001.SZ"]
+ assert pd.isna(result.loc[pd.Timestamp("2024-04-01"), "income_total_revenue"])
+ 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"