"""
均线交叉策略。

短期均线上穿长期均线 → 买入
短期均线下穿长期均线 → 平仓
"""

import pandas as pd

from backtest.base import BaseStrategy
from backtest.signal import cross_signal


class SMACrossStrategy(BaseStrategy):
    """快慢均线交叉策略。"""

    category = "trend"

    def __init__(self, fast: int = 5, slow: int = 20):
        self.fast = fast
        self.slow = slow
        self.name = f"sma_cross_{fast}_{slow}"

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

        close = factor_df["close"]
        min_p = min(self.fast, self.slow)
        ma_fast = close.rolling(window=self.fast, min_periods=self.fast).mean()
        ma_slow = close.rolling(window=self.slow, min_periods=self.slow).mean()

        return cross_signal(ma_fast, ma_slow)
