""" 因子阈值交叉策略。 通用策略:任意因子上穿/下穿阈值 → 交易信号。 支持: - 上穿买入 (cross_up: close < MA → cross above MA → buy) - 下穿买入 (cross_down: RSI > 70 → cross below 30 → buy) """ import pandas as pd from backtest.base import BaseStrategy from backtest.signal import factor_to_threshold_signal class FactorCrossStrategy(BaseStrategy): """ 因子阈值交叉策略。 适用场景: - 均线偏离度上穿 0 → 买入(趋势转多) - 波动率下穿阈值 → 买入(波动收敛后突破) """ category = "trend" def __init__( self, factor_column: str, buy_threshold: float, # 因子大于此值买 sell_threshold: float | None = None, cross_direction: str = "up", ): self.factor_column = factor_column self.buy_threshold = buy_threshold self.sell_threshold = sell_threshold self.cross_direction = cross_direction self.name = f"factor_cross_{factor_column}" def generate_signals(self, factor_df: pd.DataFrame) -> pd.Series: if self.factor_column not in factor_df.columns: raise ValueError(f"factor_df 缺少 '{self.factor_column}' 列") factor = factor_df[self.factor_column] return factor_to_threshold_signal( factor, buy_threshold=self.buy_threshold, sell_threshold=self.sell_threshold, cross_direction=self.cross_direction, )