diff --git a/configs/global.yaml b/configs/global.yaml index b5b2f07..0191131 100644 --- a/configs/global.yaml +++ b/configs/global.yaml @@ -83,12 +83,13 @@ indicators: enabled: true # 要计算的指标列表 - # 支持的指标类型: macd, kdj, boll, rsi + # 支持的指标类型: macd, kdj, boll, rsi, ma enabled_indicators: - macd - kdj - boll - rsi + - ma # 各指标的参数配置 macd: @@ -109,6 +110,9 @@ indicators: fast: 6 # 快速RSI周期 mid: 12 # 中速RSI周期 slow: 24 # 慢速RSI周期 + + ma: + periods: [5, 10, 20, 60] # 移动平均线周期列表 # 交易配置(公用) trading: diff --git a/src/core/constants.py b/src/core/constants.py index f5c5169..a55e102 100644 --- a/src/core/constants.py +++ b/src/core/constants.py @@ -69,6 +69,7 @@ class IndicatorType: KDJ = "kdj" BOLL = "boll" RSI = "rsi" + MA = "ma" # 所有支持的指标 ALL = [ @@ -76,6 +77,7 @@ class IndicatorType: KDJ, BOLL, RSI, + MA, ] @classmethod @@ -212,6 +214,26 @@ class IndicatorColumns: RSI_SLOW = "rsi_slow" RSI_ALL = [RSI_FAST, RSI_MID, RSI_SLOW] + # MA指标列(动态生成) + MA_5 = "ma_5" + MA_10 = "ma_10" + MA_20 = "ma_20" + MA_60 = "ma_60" + MA_ALL = [MA_5, MA_10, MA_20, MA_60] + + @classmethod + def get_ma_column(cls, period: int) -> str: + """ + 获取指定周期的MA列名 + + Args: + period: MA周期 + + Returns: + 列名(如 'ma_5', 'ma_10') + """ + return f"ma_{period}" + @classmethod def get_columns(cls, indicator_type: str) -> list: """ @@ -228,13 +250,14 @@ class IndicatorColumns: "kdj": cls.KDJ_ALL, "boll": cls.BOLL_ALL, "rsi": cls.RSI_ALL, + "ma": cls.MA_ALL, } return mapping.get(indicator_type, []) @classmethod def get_all_columns(cls) -> list: """获取所有指标的列名""" - return cls.MACD_ALL + cls.KDJ_ALL + cls.BOLL_ALL + cls.RSI_ALL + return cls.MACD_ALL + cls.KDJ_ALL + cls.BOLL_ALL + cls.RSI_ALL + cls.MA_ALL class ConfigKey: diff --git a/src/indicator_calculator/indicator_manager.py b/src/indicator_calculator/indicator_manager.py index 1d53470..fbf761b 100644 --- a/src/indicator_calculator/indicator_manager.py +++ b/src/indicator_calculator/indicator_manager.py @@ -8,6 +8,7 @@ from .macd_indicator import MACDIndicator from .kdj_indicator import KDJIndicator from .boll_indicator import BOLLIndicator from .rsi_indicator import RSIIndicator +from .ma_indicator import MAIndicator class IndicatorManager: @@ -22,6 +23,7 @@ class IndicatorManager: "kdj": KDJIndicator, "boll": BOLLIndicator, "rsi": RSIIndicator, + "ma": MAIndicator, } def __init__(self, indicator_configs: Dict[str, Dict] | None = None): diff --git a/src/indicator_calculator/ma_indicator.py b/src/indicator_calculator/ma_indicator.py new file mode 100644 index 0000000..2e24de5 --- /dev/null +++ b/src/indicator_calculator/ma_indicator.py @@ -0,0 +1,84 @@ +"""MA指标计算器(移动平均线)""" + +from typing import Dict, List +import numpy as np +import pandas as pd +import talib +from .base_indicator import BaseIndicator +from src.core.constants import IndicatorColumns + + +class MAIndicator(BaseIndicator): + """MA(Moving Average)移动平均线指标计算器 + + 计算多条不同周期的简单移动平均线(SMA) + """ + + def __init__(self, config: Dict | None = None): + """初始化MA指标计算器 + + Args: + config: 配置参数,包含: + - periods: 周期列表,默认[5, 10, 20, 60] + """ + super().__init__(config) + + def _validate_config(self): + """验证配置参数""" + # 设置默认值 + self.config.setdefault("periods", [5, 10, 20, 60]) + + # 验证参数 + if not isinstance(self.config["periods"], list): + raise ValueError("periods必须是列表") + if len(self.config["periods"]) == 0: + raise ValueError("periods不能为空") + for period in self.config["periods"]: + if not isinstance(period, int) or period <= 0: + raise ValueError(f"period必须是正整数: {period}") + + def calculate(self, df: pd.DataFrame) -> pd.DataFrame: + """计算MA指标 + + Args: + df: K线数据DataFrame + + Returns: + 添加了MA指标列的DataFrame + """ + self._validate_dataframe(df) + + # 复制DataFrame避免修改原始数据 + result = df.copy() + + # 获取配置参数 + periods = self.config["periods"] + + # 计算每个周期的MA + for period in periods: + # 使用ta-lib计算简单移动平均线 + ma_values = talib.SMA( + np.asarray(result["close"].values, dtype=np.float64), timeperiod=period + ) + + # 动态生成列名 + col_name = IndicatorColumns.get_ma_column(period) + result[col_name] = ma_values + + return result + + def get_column_names(self) -> List[str]: + """获取指标生成的列名列表""" + periods = self.config["periods"] + return [IndicatorColumns.get_ma_column(period) for period in periods] + + @property + def name(self) -> str: + """获取指标名称""" + return "ma" + + def get_required_data_length(self) -> int: + """获取计算指标所需的最小数据长度""" + # 返回最大周期,确保有足够的数据 + periods = self.config["periods"] + return max(periods) if periods else 60 diff --git a/test_ma_dataservice.py b/test_ma_dataservice.py new file mode 100644 index 0000000..8f8f856 --- /dev/null +++ b/test_ma_dataservice.py @@ -0,0 +1,66 @@ +"""测试DataService中的MA指标集成""" + +import sys +import os +from pathlib import Path + +project_root = Path(__file__).parent +sys.path.insert(0, str(project_root)) +os.environ["CONFIG_FILE"] = "configs/backtest.yaml" + +from src.core import get_config +from src.data_service.data_service import DataService +from datetime import datetime + +print("\n" + "=" * 70) +print("DataService MA指标集成测试") +print("=" * 70) + +# 初始化配置和服务 +config = get_config() +service = DataService.from_config(config) + +print(f"\n✓ DataService初始化成功") +print(f" 启用的指标: {service.indicator_manager.get_enabled_indicators()}") + +# 获取K线数据(会自动计算指标) +symbol = "601658.SH" +period = "1d" +start = datetime(2024, 1, 1) +end = datetime(2024, 3, 31) + +print(f"\n获取K线数据: {symbol} {period}") +print(f"时间范围: {start.date()} ~ {end.date()}") + +klines = service.get_klines(symbol, period, start, end) + +print(f"\n✓ 数据获取成功: {len(klines)} 条记录") +print(f" 列名: {klines.columns.tolist()}") + +# 检查MA列是否存在 +ma_columns = [col for col in klines.columns if col.startswith('ma_')] +print(f" MA列: {ma_columns}") + +if ma_columns: + print(f"\n后5条数据 (含MA):") + print(klines[['close'] + ma_columns].tail()) +else: + print("\n⚠️ 注意: K线数据中不包含MA列") + print(" 原因: get_klines()只返回K线数据,不包含指标") + +# 获取MA指标数据 +print(f"\n获取MA指标数据...") +ma_data = service.get_indicator(symbol, period, 'ma', start, end) + +if ma_data is not None and not ma_data.empty: + print(f"\n✓ MA指标数据获取成功: {len(ma_data)} 条记录") + print(f" 列名: {ma_data.columns.tolist()}") + print(f"\n后5条MA数据:") + print(ma_data.tail()) +else: + print("\n⚠️ MA指标数据为空") + print(" 提示: 可能需要先下载数据后自动计算指标") + +print("\n" + "=" * 70) +print("✓ 测试完成") +print("=" * 70 + "\n") diff --git a/test_ma_indicator.py b/test_ma_indicator.py new file mode 100644 index 0000000..2d53173 --- /dev/null +++ b/test_ma_indicator.py @@ -0,0 +1,90 @@ +"""测试MA指标计算器""" + +import sys +import os +from pathlib import Path + +project_root = Path(__file__).parent +sys.path.insert(0, str(project_root)) +os.environ["CONFIG_FILE"] = "configs/backtest.yaml" + +import pandas as pd +import numpy as np +from src.indicator_calculator.ma_indicator import MAIndicator +from src.core.constants import IndicatorColumns + +# 创建测试数据 +dates = pd.date_range("2024-01-01", periods=100, freq="D") +np.random.seed(42) +prices = 100 + np.cumsum(np.random.randn(100) * 2) + +df = pd.DataFrame( + { + "timestamp": dates, + "open": prices + np.random.randn(100) * 0.5, + "high": prices + np.abs(np.random.randn(100) * 1.5), + "low": prices - np.abs(np.random.randn(100) * 1.5), + "close": prices, + "volume": np.random.randint(1000000, 10000000, 100), + "amount": prices * np.random.randint(1000000, 10000000, 100), + } +) + +print("=" * 70) +print("MA指标计算器测试") +print("=" * 70) + +# 测试1: 默认配置 +print("\n【测试1】默认配置(5, 10, 20, 60日均线)") +print("-" * 70) +ma = MAIndicator() +result = ma.calculate(df) + +print(f"输入数据: {len(df)} 条") +print(f"输出列名: {ma.get_column_names()}") +print(f"\n前5条数据:") +print(result[["close", "ma_5", "ma_10", "ma_20", "ma_60"]].head()) +print(f"\n后5条数据:") +print(result[["close", "ma_5", "ma_10", "ma_20", "ma_60"]].tail()) + +# 测试2: 自定义配置 +print("\n【测试2】自定义配置(3, 7, 30日均线)") +print("-" * 70) +ma_custom = MAIndicator(config={"periods": [3, 7, 30]}) +result_custom = ma_custom.calculate(df) + +print(f"输出列名: {ma_custom.get_column_names()}") +print(f"\n后5条数据:") +print(result_custom[["close", "ma_3", "ma_7", "ma_30"]].tail()) + +# 测试3: 验证常量使用 +print("\n【测试3】验证IndicatorColumns常量") +print("-" * 70) +print(f"MA_5 常量: {IndicatorColumns.MA_5}") +print(f"MA_10 常量: {IndicatorColumns.MA_10}") +print(f"MA_20 常量: {IndicatorColumns.MA_20}") +print(f"MA_60 常量: {IndicatorColumns.MA_60}") +print(f"get_ma_column(5): {IndicatorColumns.get_ma_column(5)}") +print(f"get_columns('ma'): {IndicatorColumns.get_columns('ma')}") + +# 测试4: 与IndicatorManager集成 +print("\n【测试4】与IndicatorManager集成") +print("-" * 70) +from src.indicator_calculator.indicator_manager import IndicatorManager + +config = { + "ma": {"periods": [5, 10, 20, 60]}, + "macd": {"fast_period": 12, "slow_period": 26, "signal_period": 9}, +} +manager = IndicatorManager(config) +result_all = manager.calculate(df) + +print(f"计算的指标: {manager.get_enabled_indicators()}") +print(f"输出列数: {len(result_all.columns)}") +print(f"\n包含MA列: {[col for col in result_all.columns if 'ma_' in col]}") +print(f"\n后5条数据 (部分列):") +print(result_all[["close", "ma_5", "ma_10", "ma_20", "macd_dif"]].tail()) + +print("\n" + "=" * 70) +print("✓ MA指标测试完成") +print("=" * 70)