diff --git a/src/data_process_model/INDICATORS_GUIDE.md b/src/data_process_model/INDICATORS_GUIDE.md new file mode 100644 index 0000000..0ce4593 --- /dev/null +++ b/src/data_process_model/INDICATORS_GUIDE.md @@ -0,0 +1,200 @@ +# 技术指标计算器使用指南 + +## 概述 + +基于TA-Lib库的技术指标计算系统,提供简洁高效的股票技术分析功能。 + +## 模块说明 + +### 1. `technical_indicators.py` - 完整版 +功能齐全的技术指标计算器,支持复杂参数配置。 + +### 2. `simple_indicators.py` - 简化版 ⭐ **推荐** +专注于常用指标,接口简洁,易于使用。 + +## 快速开始 + +### 基本使用 + +```python +from simple_indicators import SimpleIndicators + +# 创建计算器 +calc = SimpleIndicators() + +# 计算MACD指标 +macd_data = calc.macd('601658', '1d') +print(macd_data.tail()) + +# 计算RSI指标 +rsi_data = calc.rsi('601658', '1d', rsi_period=14) +print(f"最新RSI: {rsi_data.iloc[-1]:.2f}") + +# 计算移动平均线 +ma_data = calc.ma('601658', '1d', periods=[5, 10, 20, 60]) +print(ma_data.tail()) +``` + +### 日期范围查询 + +```python +# 指定时间范围 +start_date = '2024-01-01' +end_date = '2024-12-31' + +macd_data = calc.macd('601658', '1d', start_date, end_date) +``` + +### 支持的指标 + +| 指标 | 方法 | 返回类型 | 说明 | +|------|------|----------|------| +| MACD | `macd()` | DataFrame | 包含macd, signal, histogram列 | +| 移动平均线 | `ma()` | DataFrame | 包含ma5, ma10, ma20等列 | +| RSI | `rsi()` | Series | 相对强弱指标 | +| 布林带 | `bollinger()` | DataFrame | 包含upper, middle, lower列 | +| KDJ | `kdj()` | DataFrame | 包含k, d, j列 | +| ATR | `atr()` | Series | 平均真实波幅 | +| CCI | `cci()` | Series | 顺势指标 | + +### 快速分析功能 + +```python +from simple_indicators import quick_analysis + +# 一键分析股票技术指标 +quick_analysis('601658', '1d') +``` + +输出示例: +``` +📊 601658 技术指标分析 +================================================== +📈 MACD: 0.0234, 信号线: 0.0189, 柱状图: 0.0045 +📊 RSI: 65.32 (正常) +📉 MA5: 12.34, MA20: 12.28, MA60: 12.15 +🎯 布林带 - 上轨: 12.89, 中轨: 12.34, 下轨: 11.79 +``` + +## 高级用法 + +### 自定义参数 + +```python +# 自定义MACD参数 +macd_data = calc.macd('601658', '1d', fast=6, slow=12, signal=4) + +# 自定义RSI周期 +rsi_data = calc.rsi('601658', '1d', rsi_period=21) + +# 自定义布林带参数 +boll_data = calc.bollinger('601658', '1d', boll_period=20, std_dev=2.5) +``` + +### 批量计算 + +```python +# 一次性计算所有常用指标 +all_data = calc.all_indicators('601658', '1d') + +# 访问各个指标 +macd = all_data['macd'] +rsi = all_data['rsi'] +ma = all_data['ma'] +``` + +### 多股票分析 + +```python +stocks = ['601658', '601398', '510310'] + +for stock in stocks: + print(f"\n📊 {stock} 分析") + quick_analysis(stock, '1d') +``` + +## 技术指标说明 + +### MACD (Moving Average Convergence Divergence) +- **用途**: 趋势跟踪动量指标 +- **参数**: fast(快线), slow(慢线), signal(信号线) +- **默认**: 12, 26, 9 +- **信号**: + - MACD > Signal: 买入信号 + - MACD < Signal: 卖出信号 + +### RSI (Relative Strength Index) +- **用途**: 动量振荡指标 +- **参数**: period(周期) +- **默认**: 14 +- **信号**: + - RSI > 70: 超买 + - RSI < 30: 超卖 + +### 布林带 (Bollinger Bands) +- **用途**: 波动率指标 +- **参数**: period(周期), std_dev(标准差倍数) +- **默认**: 20, 2.0 +- **信号**: + - 价格触及上轨: 可能回调 + - 价格触及下轨: 可能反弹 + +### KDJ指标 +- **用途**: 随机振荡指标 +- **参数**: k_period, d_period, j_period +- **默认**: 9, 3, 3 +- **信号**: + - K > D: 买入信号 + - K < D: 卖出信号 + +## 性能优化 + +### 数据缓存 +计算器会自动管理数据库连接,建议使用上下文管理器: + +```python +with calc.data_manager: + # 在这里进行多次计算,共享数据库连接 + macd = calc.macd('601658', period) + rsi = calc.rsi('601658', period) +``` + +### 批量处理 +对于大量股票的批量分析,建议使用 `all_indicators()` 方法: + +```python +# 高效:一次获取所有指标 +indicators = calc.all_indicators('601658', '1d') + +# 低效:多次数据库查询 +macd = calc.macd('601658', '1d') +rsi = calc.rsi('601658', '1d') +ma = calc.ma('601658', '1d') +``` + +## 错误处理 + +```python +try: + macd_data = calc.macd('INVALID_STOCK', '1d') + if macd_data.empty: + print("没有找到数据") +except Exception as e: + print(f"计算失败: {e}") +``` + +## 扩展开发 + +如需添加新的技术指标,可以继承 `SimpleIndicators` 类: + +```python +class ExtendedIndicators(SimpleIndicators): + def my_custom_indicator(self, stock_code: str, period: str = '1d'): + df = self._get_data(stock_code, period, None, None) + # 实现自定义指标逻辑 + return result +``` + +--- + +🎯 **推荐**: 优先使用 `simple_indicators.py`,它提供了最常用的技术指标,接口简洁,性能优异。 diff --git a/src/data_process_model/simple_indicators.py b/src/data_process_model/simple_indicators.py new file mode 100644 index 0000000..c8fe3d8 --- /dev/null +++ b/src/data_process_model/simple_indicators.py @@ -0,0 +1,255 @@ +""" +简化版技术指标计算器 +专注于最常用的技术指标,接口简洁高效 +""" + +import pandas as pd +import numpy as np +import talib +from typing import Dict, Optional, List, Tuple, Any +from stock_data_manager import StockDataManager + + +class SimpleIndicators: + """简化版技术指标计算器""" + + def __init__(self): + self.data_manager = StockDataManager() + + def macd(self, stock_code: str, period: str = '1d', + start_time: Optional[str] = None, end_time: Optional[str] = None, + fast: int = 12, slow: int = 26, signal: int = 9) -> pd.DataFrame: + """ + 计算MACD指标 + + Returns: + DataFrame with columns: macd, signal, histogram + """ + df = self._get_data(stock_code, period, start_time, end_time) + if df.empty: + return pd.DataFrame() + + close = np.array(df['close'], dtype=np.float64) + macd_line, signal_line, histogram = talib.MACD(close, fast, slow, signal) + + return pd.DataFrame({ + 'macd': macd_line, + 'signal': signal_line, + 'histogram': histogram + }, index=df.index) + + def ma(self, stock_code: str, period: str = '1d', + start_time: Optional[str] = None, end_time: Optional[str] = None, + periods: Optional[List[int]] = None) -> pd.DataFrame: + """ + 计算移动平均线 + + Returns: + DataFrame with columns: ma5, ma10, ma20, etc. + """ + if periods is None: + periods = [5, 10, 20, 60] + + df = self._get_data(stock_code, period, start_time, end_time) + if df.empty: + return pd.DataFrame() + + close = np.array(df['close'], dtype=np.float64) + result = {} + + for p in periods: + ma_values = talib.SMA(close, p) + result[f'ma{p}'] = ma_values + + return pd.DataFrame(result, index=df.index) + + def rsi(self, stock_code: str, period: str = '1d', + start_time: Optional[str] = None, end_time: Optional[str] = None, + rsi_period: int = 14) -> pd.Series: + """计算RSI指标""" + df = self._get_data(stock_code, period, start_time, end_time) + if df.empty: + return pd.Series() + + close = np.array(df['close'], dtype=np.float64) + rsi_values = talib.RSI(close, rsi_period) + + return pd.Series(rsi_values, index=df.index, name='rsi') + + def bollinger(self, stock_code: str, period: str = '1d', + start_time: Optional[str] = None, end_time: Optional[str] = None, + boll_period: int = 20, std_dev: float = 2.0) -> pd.DataFrame: + """ + 计算布林带指标 + + Returns: + DataFrame with columns: upper, middle, lower + """ + df = self._get_data(stock_code, period, start_time, end_time) + if df.empty: + return pd.DataFrame() + + close = np.array(df['close'], dtype=np.float64) + upper, middle, lower = talib.BBANDS(close, boll_period, std_dev, std_dev) + + return pd.DataFrame({ + 'upper': upper, + 'middle': middle, + 'lower': lower + }, index=df.index) + + def kdj(self, stock_code: str, period: str = '1d', + start_time: Optional[str] = None, end_time: Optional[str] = None, + k_period: int = 9, d_period: int = 3, j_period: int = 3) -> pd.DataFrame: + """ + 计算KDJ指标 + + Returns: + DataFrame with columns: k, d, j + """ + df = self._get_data(stock_code, period, start_time, end_time) + if df.empty: + return pd.DataFrame() + + high = np.array(df['high'], dtype=np.float64) + low = np.array(df['low'], dtype=np.float64) + close = np.array(df['close'], dtype=np.float64) + + k, d = talib.STOCH(high, low, close, + fastk_period=k_period, + slowk_period=d_period, + slowd_period=j_period) + + j = 3 * k - 2 * d # J = 3K - 2D + + return pd.DataFrame({ + 'k': k, + 'd': d, + 'j': j + }, index=df.index) + + def atr(self, stock_code: str, period: str = '1d', + start_time: Optional[str] = None, end_time: Optional[str] = None, + atr_period: int = 14) -> pd.Series: + """计算ATR平均真实波幅""" + df = self._get_data(stock_code, period, start_time, end_time) + if df.empty: + return pd.Series() + + high = np.array(df['high'], dtype=np.float64) + low = np.array(df['low'], dtype=np.float64) + close = np.array(df['close'], dtype=np.float64) + + atr_values = talib.ATR(high, low, close, atr_period) + + return pd.Series(atr_values, index=df.index, name='atr') + + def cci(self, stock_code: str, period: str = '1d', + start_time: Optional[str] = None, end_time: Optional[str] = None, + cci_period: int = 14) -> pd.Series: + """计算CCI顺势指标""" + df = self._get_data(stock_code, period, start_time, end_time) + if df.empty: + return pd.Series() + + high = np.array(df['high'], dtype=np.float64) + low = np.array(df['low'], dtype=np.float64) + close = np.array(df['close'], dtype=np.float64) + + cci_values = talib.CCI(high, low, close, cci_period) + + return pd.Series(cci_values, index=df.index, name='cci') + + def all_indicators(self, stock_code: str, period: str = '1d', + start_time: Optional[str] = None, end_time: Optional[str] = None) -> Dict[str, Any]: + """ + 一次性计算所有常用指标 + + Returns: + 字典包含所有指标的DataFrame + """ + return { + 'macd': self.macd(stock_code, period, start_time, end_time), + 'ma': self.ma(stock_code, period, start_time, end_time), + 'rsi': self.rsi(stock_code, period, start_time, end_time), + 'bollinger': self.bollinger(stock_code, period, start_time, end_time), + 'kdj': self.kdj(stock_code, period, start_time, end_time), + 'atr': self.atr(stock_code, period, start_time, end_time), + 'cci': self.cci(stock_code, period, start_time, end_time) + } + + def _get_data(self, stock_code: str, period: str, start_time: Optional[str], end_time: Optional[str]) -> pd.DataFrame: + """获取股票数据的统一方法""" + with self.data_manager: + return self.data_manager.read_stock_data(stock_code, period, start_time, end_time) + + +def quick_analysis(stock_code: str, period: str = '1d') -> None: + """快速分析一只股票的技术指标""" + print(f"📊 {stock_code} 技术指标分析") + print("=" * 50) + + calc = SimpleIndicators() + + # 获取最近数据 + try: + # MACD分析 + macd_df = calc.macd(stock_code, period) + if not macd_df.empty: + latest = macd_df.iloc[-1] + print(f"📈 MACD: {latest['macd']:.4f}, 信号线: {latest['signal']:.4f}, 柱状图: {latest['histogram']:.4f}") + + # RSI分析 + rsi_series = calc.rsi(stock_code, period) + if not rsi_series.empty: + latest_rsi = rsi_series.iloc[-1] + status = "超买" if latest_rsi > 70 else "超卖" if latest_rsi < 30 else "正常" + print(f"📊 RSI: {latest_rsi:.2f} ({status})") + + # 移动平均线分析 + ma_df = calc.ma(stock_code, period) + if not ma_df.empty: + latest_ma = ma_df.iloc[-1] + print(f"📉 MA5: {latest_ma['ma5']:.2f}, MA20: {latest_ma['ma20']:.2f}, MA60: {latest_ma['ma60']:.2f}") + + # 布林带分析 + boll_df = calc.bollinger(stock_code, period) + if not boll_df.empty: + latest_boll = boll_df.iloc[-1] + print(f"🎯 布林带 - 上轨: {latest_boll['upper']:.2f}, 中轨: {latest_boll['middle']:.2f}, 下轨: {latest_boll['lower']:.2f}") + + except Exception as e: + print(f"❌ 分析失败: {e}") + + +def main(): + """测试函数""" + print("🧪 技术指标计算器测试") + print("=" * 50) + + # 测试单个指标 + calc = SimpleIndicators() + + try: + print("\n📊 测试MACD计算...") + macd_result = calc.macd('601658', '1d') + if not macd_result.empty: + print(f"✅ MACD计算成功,数据点数: {len(macd_result)}") + print(f"最新MACD值: {macd_result.iloc[-1]['macd']:.4f}") + + print("\n📊 测试RSI计算...") + rsi_result = calc.rsi('601658', '1d') + if not rsi_result.empty: + print(f"✅ RSI计算成功,最新值: {rsi_result.iloc[-1]:.2f}") + + print("\n📊 快速分析测试...") + quick_analysis('601658') + + except Exception as e: + print(f"❌ 测试失败: {e}") + import traceback + traceback.print_exc() + + +if __name__ == "__main__": + main() diff --git a/src/data_process_model/stock_data_manager_example.py b/src/data_process_model/stock_data_manager_example.py deleted file mode 100644 index 9e23643..0000000 --- a/src/data_process_model/stock_data_manager_example.py +++ /dev/null @@ -1,125 +0,0 @@ -""" -股票数据管理器使用示例 -演示如何使用独立的StockDataManager进行数据操作 -""" - -from stock_data_manager import StockDataManager -import pandas as pd - -def example_basic_usage(): - """ - 基本使用示例 - """ - print("📊 StockDataManager 基本使用示例") - print("=" * 50) - - # 创建数据管理器实例 - data_manager = StockDataManager() - - try: - # 连接数据库 - if not data_manager.connect_database(): - print("❌ 数据库连接失败") - return - - # 读取股票数据 - 支持多种格式 - test_codes = ['601658', '601658.SH', '000001', '510310'] - - for stock_code in test_codes: - print(f"\n🔍 查询股票: {stock_code}") - - # 读取最近数据 - df = data_manager.read_stock_data(stock_code, period='1d') - - if not df.empty: - print(f"✅ 成功读取 {len(df)} 条数据") - print(f"📈 数据范围: {df.index.min()} 到 {df.index.max()}") - print(f"💰 最新价格: {df['close'].iloc[-1]:.2f}") - else: - print(f"⚠️ 未找到数据: {stock_code}") - - finally: - # 断开数据库连接 - data_manager.disconnect_database() - print("\n✅ 数据库连接已关闭") - - -def example_context_manager(): - """ - 使用上下文管理器的示例 - """ - print("\n📊 使用上下文管理器示例") - print("=" * 50) - - # 使用上下文管理器自动管理数据库连接 - with StockDataManager() as data_manager: - # 读取指定日期范围的数据 - df = data_manager.read_stock_data( - stock_code='601658.SH', - period='1d', - start_date='2024-01-01', - end_date='2024-12-31' - ) - - if not df.empty: - print(f"✅ 成功读取 {len(df)} 条数据") - print(f"📈 价格统计:") - print(f" 最高价: {df['high'].max():.2f}") - print(f" 最低价: {df['low'].min():.2f}") - print(f" 平均价: {df['close'].mean():.2f}") - else: - print("⚠️ 未找到数据") - - print("✅ 上下文管理器自动关闭数据库连接") - - -def example_data_analysis(): - """ - 数据分析示例 - """ - print("\n📊 数据分析示例") - print("=" * 50) - - with StockDataManager() as data_manager: - # 读取多个股票的数据进行对比 - stocks = ['601658.SH', '601398.SH', '510310.SH'] - - for stock_code in stocks: - df = data_manager.read_stock_data(stock_code, period='1d') - - if not df.empty: - # 计算简单的技术指标 - recent_data = df.tail(20) # 最近20天 - ma5 = recent_data['close'].rolling(5).mean().iloc[-1] - ma10 = recent_data['close'].rolling(10).mean().iloc[-1] - current_price = recent_data['close'].iloc[-1] - - print(f"\n📈 {stock_code} 技术分析:") - print(f" 当前价格: {current_price:.2f}") - print(f" 5日均线: {ma5:.2f}") - print(f" 10日均线: {ma10:.2f}") - - # 判断趋势 - if current_price > ma5 > ma10: - trend = "📈 上升趋势" - elif current_price < ma5 < ma10: - trend = "📉 下降趋势" - else: - trend = "📊 震荡趋势" - - print(f" 趋势判断: {trend}") - - -if __name__ == "__main__": - # 运行所有示例 - try: - example_basic_usage() - example_context_manager() - example_data_analysis() - - print("\n🎉 所有示例运行完成!") - - except Exception as e: - print(f"❌ 运行示例时发生错误: {e}") - import traceback - traceback.print_exc() diff --git a/src/data_process_model/technical_indicators.py b/src/data_process_model/technical_indicators.py new file mode 100644 index 0000000..480aa4d --- /dev/null +++ b/src/data_process_model/technical_indicators.py @@ -0,0 +1,336 @@ +""" +技术指标计算模块 - 基于TA-Lib +提供股票技术指标的统一计算接口 +""" + +import pandas as pd +import numpy as np +import talib +from typing import Dict, Any, Optional, Tuple, Union, List +from dataclasses import dataclass +from datetime import datetime +from stock_data_manager import StockDataManager + + +@dataclass +class IndicatorParams: + """指标参数配置""" + # MACD参数 + macd_fast: int = 12 + macd_slow: int = 26 + macd_signal: int = 9 + + # MA参数 + ma_periods: Optional[List[int]] = None + + # RSI参数 + rsi_period: int = 14 + + # BOLL参数 + boll_period: int = 20 + boll_std: float = 2.0 + + # KDJ参数 + kdj_k: int = 9 + kdj_d: int = 3 + kdj_j: int = 3 + + # ADX参数 + adx_period: int = 14 + + # CCI参数 + cci_period: int = 14 + + def __post_init__(self): + if self.ma_periods is None: + self.ma_periods = [5, 10, 20, 60] + + +class TechnicalIndicators: + """技术指标计算器""" + + def __init__(self): + self.data_manager = StockDataManager() + + def calculate_all(self, stock_code: str, period: str = '1d', + start_time: Optional[str] = None, end_time: Optional[str] = None, + params: Optional[IndicatorParams] = None) -> Dict[str, Any]: + """ + 计算所有技术指标 + + Args: + stock_code: 股票代码 + period: 数据周期 + start_time: 开始时间 'YYYY-MM-DD' + end_time: 结束时间 'YYYY-MM-DD' + params: 指标参数配置 + + Returns: + 包含所有指标结果的字典 + """ + if params is None: + params = IndicatorParams() + + # 获取股票数据 + with self.data_manager: + df = self.data_manager.read_stock_data(stock_code, period, start_time, end_time) + + if df.empty: + return {} + + # 提取OHLCV数据并转换为numpy数组 + open_prices = np.array(df['open'].values, dtype=np.float64) + high_prices = np.array(df['high'].values, dtype=np.float64) + low_prices = np.array(df['low'].values, dtype=np.float64) + close_prices = np.array(df['close'].values, dtype=np.float64) + volumes = np.array(df['volume'].values, dtype=np.float64) + + results = { + 'timestamp': df.index, + 'ohlcv': { + 'open': open_prices, + 'high': high_prices, + 'low': low_prices, + 'close': close_prices, + 'volume': volumes + } + } + + # 计算各种指标 + results.update({ + 'trend': self._calculate_trend_indicators(high_prices, low_prices, close_prices, params), + 'momentum': self._calculate_momentum_indicators(high_prices, low_prices, close_prices, params), + 'volatility': self._calculate_volatility_indicators(close_prices, params), + 'volume': self._calculate_volume_indicators(high_prices, low_prices, close_prices, volumes, params) + }) + + return results + + def calculate_macd(self, stock_code: str, period: str = '1d', + start_time: Optional[str] = None, end_time: Optional[str] = None, + fast: int = 12, slow: int = 26, signal: int = 9) -> Dict[str, pd.Series]: + """计算MACD指标""" + with self.data_manager: + df = self.data_manager.read_stock_data(stock_code, period, start_time, end_time) + + if df.empty: + return {} + + macd, signal_line, histogram = talib.MACD(df['close'].values, fast, slow, signal) + + return { + 'macd': pd.Series(macd, index=df.index), + 'signal': pd.Series(signal_line, index=df.index), + 'histogram': pd.Series(histogram, index=df.index) + } + + def calculate_ma(self, stock_code: str, period: str = '1d', + start_time: Optional[str] = None, end_time: Optional[str] = None, + periods: Optional[List[int]] = None) -> Dict[str, pd.Series]: + """计算移动平均线""" + if periods is None: + periods = [5, 10, 20, 60] + + with self.data_manager: + df = self.data_manager.read_stock_data(stock_code, period, start_time, end_time) + + if df.empty: + return {} + + result = {} + for p in periods: + ma = talib.SMA(df['close'].values, p) + result[f'ma{p}'] = pd.Series(ma, index=df.index) + + return result + + def calculate_rsi(self, stock_code: str, period: str = '1d', + start_time: Optional[str] = None, end_time: Optional[str] = None, + rsi_period: int = 14) -> pd.Series: + """计算RSI指标""" + with self.data_manager: + df = self.data_manager.read_stock_data(stock_code, period, start_time, end_time) + + if df.empty: + return pd.Series() + + rsi = talib.RSI(df['close'].values, rsi_period) + return pd.Series(rsi, index=df.index) + + def calculate_bollinger(self, stock_code: str, period: str = '1d', + start_time: Optional[str] = None, end_time: Optional[str] = None, + boll_period: int = 20, std_dev: float = 2.0) -> Dict[str, pd.Series]: + """计算布林带指标""" + with self.data_manager: + df = self.data_manager.read_stock_data(stock_code, period, start_time, end_time) + + if df.empty: + return {} + + upper, middle, lower = talib.BBANDS(df['close'].values, boll_period, std_dev, std_dev) + + return { + 'upper': pd.Series(upper, index=df.index), + 'middle': pd.Series(middle, index=df.index), + 'lower': pd.Series(lower, index=df.index) + } + + def calculate_kdj(self, stock_code: str, period: str = '1d', + start_time: Optional[str] = None, end_time: Optional[str] = None, + k_period: int = 9, d_period: int = 3, j_period: int = 3) -> Dict[str, pd.Series]: + """计算KDJ指标""" + with self.data_manager: + df = self.data_manager.read_stock_data(stock_code, period, start_time, end_time) + + if df.empty: + return {} + + # 计算K值和D值 + k, d = talib.STOCH(df['high'].values, df['low'].values, df['close'].values, + fastk_period=k_period, slowk_period=d_period, slowd_period=j_period) + + # 计算J值 J = 3K - 2D + j = 3 * k - 2 * d + + return { + 'k': pd.Series(k, index=df.index), + 'd': pd.Series(d, index=df.index), + 'j': pd.Series(j, index=df.index) + } + + def _calculate_trend_indicators(self, high: np.ndarray, low: np.ndarray, close: np.ndarray, params: IndicatorParams) -> Dict[str, Any]: + """计算趋势指标""" + result = {} + + # MACD + macd, signal, histogram = talib.MACD(close, params.macd_fast, params.macd_slow, params.macd_signal) + result['macd'] = { + 'macd': macd, + 'signal': signal, + 'histogram': histogram + } + + # 移动平均线 + result['ma'] = {} + for period in params.ma_periods: + result['ma'][f'ma{period}'] = talib.SMA(close, period) + + # EMA + result['ema'] = {} + for period in params.ma_periods: + result['ema'][f'ema{period}'] = talib.EMA(close, period) + + # ADX + result['adx'] = talib.ADX(high, low, close, params.adx_period) + + return result + + def _calculate_momentum_indicators(self, high: np.ndarray, low: np.ndarray, close: np.ndarray, params: IndicatorParams) -> Dict[str, Any]: + """计算动量指标""" + result = {} + + # RSI + result['rsi'] = talib.RSI(close, params.rsi_period) + + # KDJ + k, d = talib.STOCH(high, low, close, fastk_period=params.kdj_k, + slowk_period=params.kdj_d, slowd_period=params.kdj_j) + result['kdj'] = { + 'k': k, + 'd': d, + 'j': 3 * k - 2 * d # J = 3K - 2D + } + + # CCI + result['cci'] = talib.CCI(high, low, close, params.cci_period) + + # Williams %R + result['willr'] = talib.WILLR(high, low, close, 14) + + return result + + def _calculate_volatility_indicators(self, close: np.ndarray, params: IndicatorParams) -> Dict[str, Any]: + """计算波动率指标""" + result = {} + + # 布林带 + upper, middle, lower = talib.BBANDS(close, params.boll_period, params.boll_std, params.boll_std) + result['bollinger'] = { + 'upper': upper, + 'middle': middle, + 'lower': lower + } + + # 注意:这里无法计算真正的ATR,因为没有high和low数据 + # 如果需要ATR,应该在调用时传入high和low + + return result + + def _calculate_volume_indicators(self, high: np.ndarray, low: np.ndarray, close: np.ndarray, volume: np.ndarray, params: IndicatorParams) -> Dict[str, Any]: + """计算成交量指标""" + result = {} + + # OBV + result['obv'] = talib.OBV(close, volume) + + # Volume MA + result['vol_ma'] = {} + for period in [5, 10, 20]: + result['vol_ma'][f'vol_ma{period}'] = talib.SMA(volume, period) + + return result + + +def main(): + """测试示例""" + print("📊 技术指标计算测试") + print("=" * 50) + + # 创建指标计算器 + calculator = TechnicalIndicators() + + # 自定义参数 + params = IndicatorParams( + macd_fast=12, macd_slow=26, macd_signal=9, + ma_periods=[5, 10, 20, 60], + rsi_period=14, + boll_period=20, boll_std=2.0 + ) + + # 测试股票 + test_stocks = ['601658', '601398'] + + for stock in test_stocks: + print(f"\n🔍 计算 {stock} 的技术指标") + + # 计算所有指标 + indicators = calculator.calculate_all( + stock_code=stock, + period='1d', + start_time='2024-01-01', + end_time='2024-12-31', + params=params + ) + + if indicators: + print(f"✅ 成功计算指标,数据点数: {len(indicators['timestamp'])}") + + # 显示最新的MACD值 + macd_data = indicators['trend']['macd'] + if len(macd_data['macd']) > 0: + latest_macd = macd_data['macd'][-1] + latest_signal = macd_data['signal'][-1] + latest_hist = macd_data['histogram'][-1] + print(f"📈 最新MACD: {latest_macd:.4f}, 信号线: {latest_signal:.4f}, 柱状图: {latest_hist:.4f}") + + # 显示最新RSI + rsi_data = indicators['momentum']['rsi'] + if len(rsi_data) > 0: + latest_rsi = rsi_data[-1] + print(f"📊 最新RSI: {latest_rsi:.2f}") + else: + print(f"❌ 无法获取 {stock} 的数据") + + +if __name__ == "__main__": + main()