""" ta-lib 因子基类(通用) 所有 ta-lib 因子继承此类,只需指定函数和参数 """ import talib import pandas as pd import numpy as np from framework_v2.core import FactorBase class TALibFactorBase(FactorBase): """ ta-lib 因子基类 子类只需实现: - name: 因子名称 - _talib_func: 返回 ta-lib 函数 """ category = "technical" def __init__(self, period: int = 14, **params): """ 初始化 Args: period: 周期参数 **params: 其他参数 """ super().__init__(period=period, **params) self.period = period def compute(self, data: pd.DataFrame) -> pd.Series: """ 计算因子值 Args: data: OHLCV 数据 Returns: 因子值序列 """ close = data['close'].values.astype(float) # 调用子类指定的 ta-lib 函数 result = self._talib_func(close, timeperiod=self.period) return pd.Series(result, index=data.index, name=self.name) @property def _talib_func(self): """子类必须实现,返回 ta-lib 函数""" raise NotImplementedError("Subclasses must implement _talib_func")