"""RSI指标计算器""" from typing import Dict, List import numpy as np import pandas as pd import talib from .base_indicator import BaseIndicator class RSIIndicator(BaseIndicator): """RSI(Relative Strength Index,相对强弱指标)计算器 RSI指标是一种动量振荡指标,用于衡量价格变动的速度和变化: - RSI值范围:0-100 - 超买区域:RSI > 70 - 超卖区域:RSI < 30 - 中性区域:30-70 通常同时计算多个周期的RSI(如6、12、24),形成RSI指标组合 """ def __init__(self, config: Dict | None = None): """初始化RSI指标计算器 Args: config: 配置参数,包含: - fast: 快速周期,默认6 - mid: 中速周期,默认12 - slow: 慢速周期,默认24 """ super().__init__(config) def _validate_config(self): """验证配置参数""" # 设置默认值 self.config.setdefault("fast", 6) self.config.setdefault("mid", 12) self.config.setdefault("slow", 24) # 验证参数 if self.config["fast"] <= 0: raise ValueError("fast必须大于0") if self.config["mid"] <= 0: raise ValueError("mid必须大于0") if self.config["slow"] <= 0: raise ValueError("slow必须大于0") def calculate(self, df: pd.DataFrame) -> pd.DataFrame: """计算RSI指标 Args: df: K线数据DataFrame Returns: 添加了RSI指标列的DataFrame """ self._validate_dataframe(df) # 复制DataFrame避免修改原始数据 result = df.copy() fast_period = self.config["fast"] mid_period = self.config["mid"] slow_period = self.config["slow"] # 获取收盘价数组 close_array = np.asarray(result["close"].values, dtype=np.float64) # 使用ta-lib计算不同周期的RSI # 列名使用rsi_fast、rsi_mid、rsi_slow,更直观易懂 result["rsi_fast"] = talib.RSI(close_array, timeperiod=fast_period) result["rsi_mid"] = talib.RSI(close_array, timeperiod=mid_period) result["rsi_slow"] = talib.RSI(close_array, timeperiod=slow_period) return result def get_column_names(self) -> List[str]: """获取RSI指标的列名""" return ["rsi_fast", "rsi_mid", "rsi_slow"] @property def name(self) -> str: """指标名称""" return "rsi" @property def description(self) -> str: """指标描述""" return "RSI指标(相对强弱指标)"