7 Sprints 全部完成: Sprint 0: 基础设施 (DataManager + MariaDB) Sprint 1: 因子引擎 (34因子/12分类) Sprint 2: VectorBT 回测 (5策略+截面) Sprint 3: Optuna 优化 (+Walk-Forward) Sprint 4: ML 模型 (LightGBM+CatBoost) Sprint 5: Qwen 情绪因子 (三源新闻+日期对齐) Sprint 6: Agent 系统 (4Agent+日报.md/.html) 生产加固 (15项): Tushare双源fallback, SSH自动恢复, pool_pre_ping, save_daily先删后插, load_dotenv绝对路径, 日报5d/20d修复, RiskAgent改上证指数, 昨日对比+数据截止, mac_report utf8mb4, CLAUDE-*.md 9条已知Bug, demo全参数化, djapi数据源归一化, indexDatas API修正 Co-Authored-By: Claude Opus 4.7 <noreply@anthropic.com>
59 lines
1.8 KiB
Python
59 lines
1.8 KiB
Python
"""
|
|
因子排序轮动策略。
|
|
|
|
定期按因子值排序,买入排名最高的股票(截面策略)。
|
|
"""
|
|
|
|
import pandas as pd
|
|
|
|
from backtest.base import BaseStrategy
|
|
|
|
|
|
class FactorRotationStrategy(BaseStrategy):
|
|
"""
|
|
因子排序选股策略。
|
|
|
|
适用于多股票截面场景:对每只股票计算因子值,
|
|
选排名最高的 top_n 只做多。
|
|
"""
|
|
|
|
category = "rotation"
|
|
|
|
def __init__(self, factor_name: str, top_n: int = 5, bottom_n: int = 0):
|
|
self.factor_name = factor_name
|
|
self.top_n = top_n
|
|
self.bottom_n = bottom_n
|
|
self.name = f"rotation_{factor_name}_top{top_n}"
|
|
|
|
def generate_signals(self, factor_df: pd.DataFrame) -> pd.Series:
|
|
"""
|
|
单股票/截面模式:factor_df 支持两种输入方式。
|
|
- 单股票: 对每只股票单次调用
|
|
- 截面: 通过 run_cross_section 逐股票调用
|
|
"""
|
|
if self.factor_name not in factor_df.columns:
|
|
raise ValueError(f"factor_df 缺少 '{self.factor_name}' 列")
|
|
|
|
factor = factor_df[self.factor_name]
|
|
valid = factor.dropna()
|
|
if len(valid) < self.top_n * 2:
|
|
return pd.Series(-1, index=factor_df.index)
|
|
|
|
threshold = valid.quantile(1 - self.top_n / max(len(valid), self.top_n))
|
|
signals = pd.Series(-1, index=factor_df.index)
|
|
signals[factor > threshold] = 1
|
|
|
|
return signals
|
|
|
|
def rank_stocks(
|
|
self, factor_values: dict[str, float]
|
|
) -> list[str]:
|
|
"""
|
|
对股票按因子值排序,返回 top N 的 ts_code 列表。
|
|
|
|
参数:
|
|
factor_values: {ts_code: factor_value}
|
|
"""
|
|
sorted_stocks = sorted(factor_values, key=factor_values.get, reverse=True)
|
|
return sorted_stocks[: self.top_n]
|