"""
RSI 均值回归策略。

RSI 低于超卖线 → 买入
RSI 高于超买线 → 平仓
"""

import pandas as pd

from backtest.base import BaseStrategy
from backtest.signal import factor_to_threshold_signal


class RSIMeanRevertStrategy(BaseStrategy):
    """RSI 超买超卖反转策略。"""

    category = "mean_revert"

    def __init__(self, oversold: float = 30, overbought: float = 70, rsi_column: str = "rsi_14"):
        self.oversold = oversold
        self.overbought = overbought
        self.rsi_column = rsi_column
        self.name = f"rsi_revert_{int(oversold)}_{int(overbought)}"

    def generate_signals(self, factor_df: pd.DataFrame) -> pd.Series:
        if self.rsi_column not in factor_df.columns:
            raise ValueError(f"factor_df 缺少 '{self.rsi_column}' 列")

        rsi = factor_df[self.rsi_column]
        return factor_to_threshold_signal(
            rsi,
            buy_threshold=self.oversold,
            sell_threshold=self.overbought,
            cross_direction="down",  # RSI 向下跌破 oversold → 买入
        )
