feat(selection): M6.4 回测与选股共用评分引擎(v2 §25 一致性锁定)
- quant/selection.score_panel_for_factors:复合分面板构建收敛为共享函数; LocalEngine.run_backtest 与 SelectionEngine.run_score_selection 均调它 —— 消除「回测一套评分、选股另一套」的隐患 - tests/test_selection_backtest_consistency.py:对回测每个调仓日验证 SelectionService.select(as_of=d, top_n) 候选 == 该日回测实际持仓(月调仓多时点), 排序方向一致性亦验证;全量 pytest 通过
This commit is contained in:
@@ -11,12 +11,8 @@ import pandas as pd
|
||||
|
||||
from app.domain.entities.research import BacktestResult, FactorTestReport, ResearchSpec
|
||||
from app.quant.factors import FactorError, get_factor
|
||||
from app.quant.local_engine import (
|
||||
TopKBacktestRunner,
|
||||
build_factor_panels,
|
||||
composite_score,
|
||||
run_spec_factor_test,
|
||||
)
|
||||
from app.quant.local_engine import TopKBacktestRunner, run_spec_factor_test
|
||||
from app.quant.selection import score_panel_for_factors
|
||||
|
||||
# LocalEngine 路径恒需 close(TopK 收盘撮合 / 前瞻收益)
|
||||
_CLOSE = {"close"}
|
||||
@@ -64,7 +60,7 @@ class LocalEngine:
|
||||
return report
|
||||
|
||||
def run_backtest(self, daily: pd.DataFrame, spec: ResearchSpec) -> BacktestResult:
|
||||
panels = build_factor_panels(daily, spec.factors)
|
||||
score = composite_score(panels)
|
||||
# 评分面板与选股共用同一构建(v2 §25:回测与当前选股同引擎)
|
||||
score = score_panel_for_factors(daily, spec.factors)
|
||||
close = daily.pivot(index="trade_date", columns="symbol", values="close").sort_index()
|
||||
return TopKBacktestRunner(spec, score, close).run()
|
||||
|
||||
@@ -29,6 +29,16 @@ _UNIMPLEMENTED_DEFAULT = [
|
||||
]
|
||||
|
||||
|
||||
def score_panel_for_factors(daily: pd.DataFrame, factor_specs) -> pd.DataFrame:
|
||||
"""因子加权复合分面板(index=trade_date, columns=symbol)。
|
||||
|
||||
回测(LocalEngine)与选股(run_score_selection)共用同一构建 ——
|
||||
保证 v2 §25/§27「历史回测与当前选股使用同一套引擎」的一致性。
|
||||
"""
|
||||
panels = build_factor_panels(daily, factor_specs) # 未知因子在此抛 FactorError
|
||||
return composite_score(panels)
|
||||
|
||||
|
||||
def resolve_observation_date(daily: pd.DataFrame, as_of: date | None) -> pd.Timestamp | None:
|
||||
"""<= as_of 的最近可用交易日;as_of=None 取数据最新一日。"""
|
||||
if daily.empty:
|
||||
@@ -84,8 +94,9 @@ def run_score_selection(
|
||||
config_snapshot=query.model_dump(mode="json"),
|
||||
)
|
||||
|
||||
panels = build_factor_panels(view, query.factors) # 未知因子在此抛 FactorError
|
||||
score = composite_score(panels).loc[obs].dropna().sort_values(ascending=False)
|
||||
score = score_panel_for_factors(view, query.factors).loc[obs].dropna().sort_values(
|
||||
ascending=False
|
||||
)
|
||||
|
||||
# 每因子在 obs 行的原始值(factor_values 供展示与解释;与 build_factor_panels 同数据)
|
||||
raw: dict[str, pd.Series] = {}
|
||||
|
||||
Reference in New Issue
Block a user