- 将indicator_calculator移动到独立的src/indicators/模块 - CacheManager添加get_indicator()方法,支持指标计算和缓存 - MarketDataCache更新以使用CacheManager的指标功能 - 添加10个集成测试,验证指标缓存功能 - 支持指标时间切片和自定义参数 - 所有测试通过(21/21)
97 lines
3.0 KiB
Python
97 lines
3.0 KiB
Python
"""MACD指标计算器"""
|
||
|
||
from typing import Dict, List
|
||
import numpy as np
|
||
import pandas as pd
|
||
import talib
|
||
from .base_indicator import BaseIndicator
|
||
|
||
|
||
class MACDIndicator(BaseIndicator):
|
||
"""MACD(Moving Average Convergence Divergence)指标计算器
|
||
|
||
MACD指标包含三个值:
|
||
- DIF(差离值):快速EMA - 慢速EMA
|
||
- DEA(讯号线):DIF的EMA
|
||
- MACD柱状图:(DIF - DEA) * 2
|
||
"""
|
||
|
||
def __init__(self, config: Dict | None = None):
|
||
"""初始化MACD指标计算器
|
||
|
||
Args:
|
||
config: 配置参数,包含:
|
||
- fast_period: 快速EMA周期,默认12
|
||
- slow_period: 慢速EMA周期,默认26
|
||
- signal_period: 信号线周期,默认9
|
||
"""
|
||
super().__init__(config)
|
||
|
||
def _validate_config(self):
|
||
"""验证配置参数"""
|
||
# 设置默认值
|
||
self.config.setdefault("fast_period", 12)
|
||
self.config.setdefault("slow_period", 26)
|
||
self.config.setdefault("signal_period", 9)
|
||
|
||
# 验证参数
|
||
if self.config["fast_period"] <= 0:
|
||
raise ValueError("fast_period必须大于0")
|
||
if self.config["slow_period"] <= 0:
|
||
raise ValueError("slow_period必须大于0")
|
||
if self.config["signal_period"] <= 0:
|
||
raise ValueError("signal_period必须大于0")
|
||
if self.config["fast_period"] >= self.config["slow_period"]:
|
||
raise ValueError("fast_period必须小于slow_period")
|
||
|
||
def calculate(self, df: pd.DataFrame) -> pd.DataFrame:
|
||
"""计算MACD指标
|
||
|
||
Args:
|
||
df: K线数据DataFrame
|
||
|
||
Returns:
|
||
添加了MACD指标列的DataFrame
|
||
"""
|
||
self._validate_dataframe(df)
|
||
|
||
# 复制DataFrame避免修改原始数据
|
||
result = df.copy()
|
||
|
||
# 获取配置参数
|
||
fast_period = self.config["fast_period"]
|
||
slow_period = self.config["slow_period"]
|
||
signal_period = self.config["signal_period"]
|
||
|
||
# 使用ta-lib计算MACD
|
||
# 注意:ta-lib返回的是 (DIF, DEA, MACD柱),与传统定义略有不同
|
||
macd, signal, hist = talib.MACD(
|
||
np.asarray(result["close"].values, dtype=np.float64),
|
||
fastperiod=fast_period,
|
||
slowperiod=slow_period,
|
||
signalperiod=signal_period,
|
||
)
|
||
|
||
# 统一列名规范
|
||
result["macd_dif"] = macd
|
||
result["macd_dea"] = signal
|
||
# ta-lib的MACD柱值已经是 DIF-DEA,不需要乘以2
|
||
# 但为了保持与国内软件一致,这里乘以2
|
||
result["macd_histogram"] = hist * 2
|
||
|
||
return result
|
||
|
||
def get_column_names(self) -> List[str]:
|
||
"""获取MACD指标的列名"""
|
||
return ["macd_dif", "macd_dea", "macd_histogram"]
|
||
|
||
@property
|
||
def name(self) -> str:
|
||
"""指标名称"""
|
||
return "macd"
|
||
|
||
@property
|
||
def description(self) -> str:
|
||
"""指标描述"""
|
||
return "MACD指标(异同移动平均线)"
|