From 43ab91b44da7c345e375866d80f3b701d70c3ff7 Mon Sep 17 00:00:00 2001 From: cuizhan <3971687@qq.com> Date: Wed, 17 Dec 2025 22:58:22 +0800 Subject: [PATCH] =?UTF-8?q?=E9=87=8D=E6=9E=84=E6=95=B0=E6=8D=AE=E7=B3=BB?= =?UTF-8?q?=E7=BB=9F=EF=BC=9Ata-lib=E6=8C=87=E6=A0=87=E3=80=81RSI=E5=A4=9A?= =?UTF-8?q?=E5=91=A8=E6=9C=9F=E3=80=81=E6=95=B0=E6=8D=AE=E5=BA=93=E7=B2=BE?= =?UTF-8?q?=E5=BA=A6=E4=BC=98=E5=8C=96=E3=80=81=E8=A1=A8=E7=BB=93=E6=9E=84?= =?UTF-8?q?=E7=BB=9F=E4=B8=80?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit 核心改进: - 指标计算:全部切换为ta-lib实现(MACD/KDJ/BOLL) - RSI指标:新增多周期RSI(6/12/24),列名rsi_fast/mid/slow - 数据精度:数据库DECIMAL(10,3)支持ETF 3位小数,下载器round(x,3) - 表结构:所有表使用(symbol,timestamp)复合主键,移除id自增 - 表命名:统一为indicators_{period}_{indicator}格式,删除42个旧表 - 自动计算:DataProvider下载后自动计算并保存指标 - 列名规范:macd_dif/dea/histogram, kdj_k/d/j, boll_upper/mid/lower - KlineReader:保留timestamp和symbol列供指标计算使用 已验证:1m周期2400+条数据,所有指标正常计算保存 --- check_1m_data.py | 32 +++ check_indicators.py | 44 ++++ check_precision.py | 53 +++++ check_table_structure.py | 18 ++ check_tables.py | 54 +++++ configs/global.yaml | 14 +- docs/design_principle.md | 88 ++++++- .../data_downloader/xtquant_downloader.py | 22 +- src/data_provider/data_provider.py | 61 ++++- src/data_provider/data_reader/kline_reader.py | 5 +- .../data_writer/indicator_writer.py | 60 ++--- .../indicator_calculator/__init__.py | 2 + .../indicator_calculator/boll_indicator.py | 25 +- .../indicator_calculator/indicator_manager.py | 2 + .../indicator_calculator/kdj_indicator.py | 38 +-- .../indicator_calculator/macd_indicator.py | 31 +-- .../indicator_calculator/rsi_indicator.py | 89 +++++++ src/database_manager/db_manager.py | 7 + src/database_manager/table_schemas.py | 220 +++++++++++++----- test_calc_indicators.py | 85 +++++++ tests/test_rsi.py | 75 ++++++ 21 files changed, 863 insertions(+), 162 deletions(-) create mode 100644 check_1m_data.py create mode 100644 check_indicators.py create mode 100644 check_precision.py create mode 100644 check_table_structure.py create mode 100644 check_tables.py create mode 100644 src/data_provider/indicator_calculator/rsi_indicator.py create mode 100644 test_calc_indicators.py create mode 100644 tests/test_rsi.py diff --git a/check_1m_data.py b/check_1m_data.py new file mode 100644 index 0000000..ebaa322 --- /dev/null +++ b/check_1m_data.py @@ -0,0 +1,32 @@ +"""检查1m周期数据""" + +import pymysql + +conn = pymysql.connect( + host="localhost", user="root", password="1234", database="qtrade_backtest" +) +cursor = conn.cursor() + +# 查看1m周期表中的股票代码 +cursor.execute("SELECT DISTINCT symbol FROM klines_1m") +symbols = cursor.fetchall() +print("1m周期表中的股票代码:") +for s in symbols: + print(f" {s[0]}") + +# 查看159915.SZ的数据量 +cursor.execute("SELECT COUNT(*) FROM klines_1m WHERE symbol='159915.SZ'") +count = cursor.fetchone()[0] +print(f"\n159915.SZ的1m数据量: {count}") + +# 查看159915.SZ在1d周期的数据量 +cursor.execute("SELECT COUNT(*) FROM klines_1d WHERE symbol='159915.SZ'") +count = cursor.fetchone()[0] +print(f"159915.SZ的1d数据量: {count}") + +# 查看601658.SH在1m的数据量 +cursor.execute("SELECT COUNT(*) FROM klines_1m WHERE symbol='601658.SH'") +count = cursor.fetchone()[0] +print(f"601658.SH的1m数据量: {count}") + +conn.close() diff --git a/check_indicators.py b/check_indicators.py new file mode 100644 index 0000000..082acda --- /dev/null +++ b/check_indicators.py @@ -0,0 +1,44 @@ +"""检查指标数据""" + +import pymysql + +conn = pymysql.connect( + host="localhost", user="root", password="1234", database="qtrade_backtest" +) +cursor = conn.cursor() + +# 检查各个指标表的数据 +indicators = ["macd", "kdj", "boll", "rsi"] +periods = ["1m", "1d"] +symbol = "159915.SZ" + +print(f"检查 {symbol} 的指标数据:\n") + +for period in periods: + print(f"=== {period} 周期 ===") + for indicator in indicators: + table_name = f"indicators_{period}_{indicator}" + cursor.execute(f"SELECT COUNT(*) FROM {table_name} WHERE symbol='{symbol}'") + count = cursor.fetchone()[0] + print(f" {indicator}: {count} 条") + print() + +# 查看MACD 1m的样例数据 +print("MACD 1m 样例数据(最近5条):") +cursor.execute(""" + SELECT timestamp, symbol, macd_dif, macd_dea, macd_histogram + FROM indicators_1m_macd + WHERE symbol='159915.SZ' + ORDER BY timestamp DESC + LIMIT 5 +""") +rows = cursor.fetchall() +if rows: + for row in rows: + print( + f" {row[0]} | {row[1]} | DIF:{row[2]:.6f} | DEA:{row[3]:.6f} | MACD:{row[4]:.6f}" + ) +else: + print(" 无数据") + +conn.close() diff --git a/check_precision.py b/check_precision.py new file mode 100644 index 0000000..1c6692d --- /dev/null +++ b/check_precision.py @@ -0,0 +1,53 @@ +"""验证159915.SZ的数据精度""" + +import pymysql + +conn = pymysql.connect( + host="localhost", user="root", password="1234", database="qtrade_backtest" +) +cursor = conn.cursor() + +# 查看159915.SZ的1m数据样例 +print("159915.SZ的1m数据样例(最近10条):") +cursor.execute(""" + SELECT timestamp, open, high, low, close + FROM klines_1m + WHERE symbol='159915.SZ' + ORDER BY timestamp DESC + LIMIT 10 +""") +rows = cursor.fetchall() +for row in rows: + print(f"时间: {row[0]}, 开: {row[1]}, 高: {row[2]}, 低: {row[3]}, 收: {row[4]}") + +# 查看159915.SZ的1d数据样例 +print("\n159915.SZ的1d数据样例(最近10条):") +cursor.execute(""" + SELECT timestamp, open, high, low, close + FROM klines_1d + WHERE symbol='159915.SZ' + ORDER BY timestamp DESC + LIMIT 10 +""") +rows = cursor.fetchall() +for row in rows: + print(f"时间: {row[0]}, 开: {row[1]}, 高: {row[2]}, 低: {row[3]}, 收: {row[4]}") + +# 检查是否有3位小数的价格 +print("\n检查是否有3位小数的价格(例如 x.xx5, x.xx1 等):") +cursor.execute(""" + SELECT timestamp, close + FROM klines_1m + WHERE symbol='159915.SZ' + AND (close * 1000) % 10 != 0 + LIMIT 5 +""") +rows = cursor.fetchall() +if rows: + print("找到3位小数的价格:") + for row in rows: + print(f" 时间: {row[0]}, 收盘: {row[1]}") +else: + print("未找到3位小数的价格,可能数据被截断了") + +conn.close() diff --git a/check_table_structure.py b/check_table_structure.py new file mode 100644 index 0000000..958b9c2 --- /dev/null +++ b/check_table_structure.py @@ -0,0 +1,18 @@ +import pymysql + +conn = pymysql.connect( + host="localhost", user="root", password="1234", database="qtrade_backtest" +) +cursor = conn.cursor() + +print("=== indicators_1m_macd 表结构 ===") +cursor.execute("DESCRIBE indicators_1m_macd") +for row in cursor.fetchall(): + print(row) + +print("\n=== klines_1m 表结构 ===") +cursor.execute("DESCRIBE klines_1m") +for row in cursor.fetchall(): + print(row) + +conn.close() diff --git a/check_tables.py b/check_tables.py new file mode 100644 index 0000000..31f1440 --- /dev/null +++ b/check_tables.py @@ -0,0 +1,54 @@ +"""检查数据库中的所有表""" + +from src.database_manager.db_manager import DatabaseManager + + +def main(): + db = DatabaseManager() + database = "qtrade_backtest" + + # 获取所有表名 + tables = db.list_tables(database) + + # 分类统计 + klines = [] + indicators = [] + business = [] + old_format = [] # 旧格式的指标表(indicator_period 格式) + + for table_name in tables: + if table_name.startswith("klines_"): + klines.append(table_name) + elif table_name.startswith("indicators_"): + indicators.append(table_name) + elif "_" in table_name and any( + table_name.startswith(ind) + for ind in ["macd", "kdj", "boll", "rsi", "ma", "ema"] + ): + old_format.append(table_name) + else: + business.append(table_name) + + print(f"总表数: {len(tables)}") + print(f"\n=== K线表 ({len(klines)}) ===") + for t in sorted(klines): + print(f" {t}") + + print(f"\n=== 指标表(新格式: indicators_period_indicator)({len(indicators)}) ===") + for t in sorted(indicators): + print(f" {t}") + + print(f"\n=== 旧格式指标表(indicator_period)({len(old_format)}) ===") + if old_format: + for t in sorted(old_format): + print(f" {t}") + else: + print(" (无)") + + print(f"\n=== 业务表 ({len(business)}) ===") + for t in sorted(business): + print(f" {t}") + + +if __name__ == "__main__": + main() diff --git a/configs/global.yaml b/configs/global.yaml index c2b2b8e..33f3a0b 100644 --- a/configs/global.yaml +++ b/configs/global.yaml @@ -82,17 +82,18 @@ indicators: enabled: true # 要计算的指标列表 - # 支持的指标类型: macd, kdj, boll + # 支持的指标类型: macd, kdj, boll, rsi enabled_indicators: - macd - kdj - boll + - rsi # 各指标的参数配置 macd: - fast_period: 12 # 快速EMA周期 - slow_period: 26 # 慢速EMA周期 - signal_period: 9 # 信号线周期 + fast_period: 6 # 快速EMA周期 + slow_period: 13 # 慢速EMA周期 + signal_period: 5 # 信号线周期 kdj: period: 9 # RSV计算周期 @@ -102,6 +103,11 @@ indicators: boll: period: 20 # 移动平均周期 std_multiplier: 2.0 # 标准差倍数 + + rsi: + fast: 6 # 快速RSI周期 + mid: 12 # 中速RSI周期 + slow: 24 # 慢速RSI周期 # 交易配置(公用) trading: diff --git a/docs/design_principle.md b/docs/design_principle.md index 6797f76..1707492 100644 --- a/docs/design_principle.md +++ b/docs/design_principle.md @@ -618,8 +618,14 @@ DataProvider (外观类) │ ├── BaseDataChecker │ ├── QualityChecker │ └── CoverageChecker -└── data_downloader/ - └── BaseDataDownloader +├── data_downloader/ +│ └── BaseDataDownloader +└── indicator_calculator/ + ├── BaseIndicator + ├── MACDIndicator + ├── KDJIndicator + ├── BOLLIndicator + └── IndicatorManager ``` **核心改进:** @@ -628,6 +634,84 @@ DataProvider (外观类) - ✅ 职责分离:每个模块单一职责 - ✅ 资源管理:支持上下文管理器自动释放连接 +## 3. 技术指标计算架构 + +**设计原则:使用ta-lib库 + 封装计算逻辑** + +### 3.1 为什么使用ta-lib? + +**核心考量:** +- ✅ 成熟稳定:金融行业标准,经过多年验证 +- ✅ 性能优秀:C语言实现,计算速度快 +- ✅ 指标丰富:内置150+种技术指标 +- ✅ 准确可靠:计算结果与主流软件一致 +- ✅ 易于扩展:后续引入新指标成本低 + +### 3.2 封装策略 + +**核心思想:统一接口 + 参数配置 + 错误处理** + +```python +class BaseIndicator(ABC): + """指标计算基类""" + def calculate(self, df: pd.DataFrame) -> pd.DataFrame: + """统一的计算接口""" + pass + +class MACDIndicator(BaseIndicator): + """MACD指标 - 使用ta-lib实现""" + def calculate(self, df: pd.DataFrame) -> pd.DataFrame: + # 封装ta-lib调用 + # 统一参数处理 + # 统一列名规范 + # 统一错误处理 + pass +``` + +**封装的好处:** +- ✅ **统一接口**:所有指标都是 `calculate(df) -> df` +- ✅ **参数配置**:通过config字典配置参数,灵活调整 +- ✅ **列名规范**:统一列名格式 `{indicator}_{param}` +- ✅ **错误处理**:捕获ta-lib异常,提供友好错误信息 +- ✅ **数据验证**:检查输入数据完整性(必需列、数据量等) +- ✅ **易于切换**:未来可以切换到其他计算库而不影响上层代码 +- ✅ **便于测试**:每个指标独立测试,mock方便 + +**实现规范:** +```python +# 1. 使用ta-lib计算核心逻辑 +import talib + +# 2. 封装在BaseIndicator子类中 +class MACDIndicator(BaseIndicator): + def calculate(self, df: pd.DataFrame) -> pd.DataFrame: + # 参数获取 + fast = self.config['fast_period'] + slow = self.config['slow_period'] + signal = self.config['signal_period'] + + # 调用ta-lib + macd, signal, hist = talib.MACD( + df['close'].values, + fastperiod=fast, + slowperiod=slow, + signalperiod=signal + ) + + # 统一列名规范 + df['macd_dif'] = macd + df['macd_dea'] = signal + df['macd_histogram'] = hist + + return df +``` + +**注意事项:** +- ⚠️ ta-lib返回的是numpy数组,需要转换为DataFrame列 +- ⚠️ ta-lib对数据量有要求(部分指标需要最少数据量) +- ⚠️ ta-lib计算结果前几行可能是NaN(需要预热期) +- ⚠️ 不同指标的参数名称需要规范化(fast_period vs fastperiod) + --- # 开发规范 diff --git a/src/data_provider/data_downloader/xtquant_downloader.py b/src/data_provider/data_downloader/xtquant_downloader.py index 06cb5bc..e19eaba 100644 --- a/src/data_provider/data_downloader/xtquant_downloader.py +++ b/src/data_provider/data_downloader/xtquant_downloader.py @@ -179,13 +179,19 @@ class XtQuantDownloader(BaseDataDownloader): continue # 将时间戳转换为 datetime - # XtQuant 返回的时间戳可能是字符串格式 "20251201093000" - # 或者是 pandas Timestamp 对象 + # XtQuant 返回的时间戳可能是字符串格式 + # 分钟级: "20251201093000" (YYYYMMDDHHMMSS) + # 日线级: "20251201" (YYYYMMDD) from datetime import datetime as dt_class if isinstance(timestamp, str): - # 字符串格式: YYYYMMDDHHMMSS - dt = dt_class.strptime(timestamp, "%Y%m%d%H%M%S") + # 字符串格式: 根据周期判断格式 + if period in ["1d", "1w", "1M"]: + # 日线及以上周期: YYYYMMDD + dt = dt_class.strptime(timestamp, "%Y%m%d") + else: + # 分钟级周期: YYYYMMDDHHMMSS + dt = dt_class.strptime(timestamp, "%Y%m%d%H%M%S") elif hasattr(timestamp, "to_pydatetime"): # pandas Timestamp 对象 dt = timestamp.to_pydatetime() @@ -205,10 +211,10 @@ class XtQuantDownloader(BaseDataDownloader): symbol=symbol, period=period, # 使用我们的标准周期格式 timestamp=dt, - open=round(row["open"], 2), - high=round(row["high"], 2), - low=round(row["low"], 2), - close=round(row["close"], 2), + open=round(row["open"], 3), + high=round(row["high"], 3), + low=round(row["low"], 3), + close=round(row["close"], 3), volume=int(row["volume"]), amount=round(row["amount"], 2) if row["amount"] and row["amount"] > 0 diff --git a/src/data_provider/data_provider.py b/src/data_provider/data_provider.py index 32a08fa..416378f 100644 --- a/src/data_provider/data_provider.py +++ b/src/data_provider/data_provider.py @@ -95,10 +95,12 @@ class DataProvider: if name in indicator_config: indicator_configs[name] = indicator_config[name] - self.indicator_manager = IndicatorManager(indicator_configs) + self.indicator_manager: Optional[IndicatorManager] = IndicatorManager( + indicator_configs + ) logger.info(f"指标计算已启用: {enabled_indicators}") else: - self.indicator_manager = None + self.indicator_manager: Optional[IndicatorManager] = None logger.debug("DataProvider 初始化完成") @@ -278,12 +280,67 @@ class DataProvider: ) downloader.download_and_save() logger.info("数据下载完成") + + # 下载完成后,计算并保存指标 + if self.indicator_manager: + logger.info("开始计算指标...") + self._calculate_and_save_indicators( + symbols, start_date, end_date, periods + ) + logger.info("指标计算和保存完成") + except Exception as e: logger.error(f"数据下载失败: {e}") raise RuntimeError(f"数据下载失败: {e}") from e # ==================== 指标计算和保存 ==================== + def _calculate_and_save_indicators( + self, + symbols: List[str], + start_date: datetime, + end_date: datetime, + periods: List[str], + ) -> None: + """计算并保存指标(内部方法)""" + if not self.indicator_manager: + logger.warning("指标管理器未初始化,跳过指标计算") + return + + for symbol in symbols: + for period in periods: + try: + # 读取K线数据 + klines = self.get_klines([symbol], start_date, end_date, period) + if symbol not in klines or klines[symbol].empty: + logger.warning(f"{symbol} [{period}] 无K线数据,跳过指标计算") + continue + + # 计算指标 + df = klines[symbol] + df_with_indicators = self.indicator_manager.calculate_all( + {f"{symbol}_{period}": df} + ) + + # 保存指标 + indicator_writer = IndicatorWriter( + database=self._get_database(), db_manager=self.db_manager + ) + try: + results = indicator_writer.save( + df_with_indicators, + self.indicator_manager.get_enabled_indicators(), + ) + total_saved = sum(results.values()) + logger.info( + f"✓ {symbol} [{period}]: 保存 {total_saved} 条指标数据" + ) + finally: + indicator_writer.close() + + except Exception as e: + logger.error(f"✗ {symbol} [{period}] 指标计算失败: {e}") + def calculate_indicators( self, kline_data: Dict[str, pd.DataFrame], diff --git a/src/data_provider/data_reader/kline_reader.py b/src/data_provider/data_reader/kline_reader.py index a32e4c5..a6d25c5 100644 --- a/src/data_provider/data_reader/kline_reader.py +++ b/src/data_provider/data_reader/kline_reader.py @@ -109,10 +109,11 @@ class KlineReader(BaseDataReader): df_symbol = df_all[df_all["symbol"] == symbol].copy() # type: ignore if not df_symbol.empty: - # 转换时间列并设置为索引 + # 转换时间列 df_symbol["timestamp"] = pd.to_datetime(df_symbol["timestamp"]) + # 保留timestamp和symbol列,同时设置timestamp为索引(用于兼容性) df_symbol.set_index("timestamp", inplace=True) - df_symbol.drop(columns=["symbol"], inplace=True) + df_symbol["timestamp"] = df_symbol.index # 添加timestamp列 result[symbol] = df_symbol else: diff --git a/src/data_provider/data_writer/indicator_writer.py b/src/data_provider/data_writer/indicator_writer.py index da388b0..d0e14f0 100644 --- a/src/data_provider/data_writer/indicator_writer.py +++ b/src/data_provider/data_writer/indicator_writer.py @@ -160,49 +160,31 @@ class IndicatorWriter(BaseDataWriter): if not self.db_manager.table_exists(self.database, table_name): self.logger.warning(f"表 {table_name} 不存在,正在创建...") - # 构建列定义(字典格式) - columns = { - "id": { - "type": "INT", - "nullable": False, - "primary_key": True, - "auto_increment": True, - }, - "symbol": { - "type": "VARCHAR(20)", - "nullable": False, - }, - "timestamp": { - "type": "DATETIME", - "nullable": False, - }, - } + # 从表名解析指标名和周期 + # 表名格式: indicators__ + parts = table_name.split("_") + if len(parts) >= 3 and parts[0] == "indicators": + period = parts[1] + indicator = "_".join(parts[2:]) # 支持如macd这样的指标名 - # 添加指标列 - for col in indicator_columns: - columns[col] = { - "type": "DECIMAL(20, 6)", - "nullable": True, - } + # 使用标准的表定义函数 + from ...database_manager.table_schemas import ( + create_indicator_table_definition, + ) - # 定义索引 - indexes = [ - { - "name": f"idx_{table_name}_symbol_timestamp", - "columns": ["symbol", "timestamp"], - "unique": True, - } - ] + table_def = create_indicator_table_definition(indicator, period) - # 创建表 - self.db_manager.create_table( - database=self.database, - table_name=table_name, - columns=columns, - indexes=indexes, - ) + # 创建表 + self.db_manager.create_table( + database=self.database, + table_name=table_name, + columns=table_def["columns"], + indexes=table_def.get("indexes", []), + ) - self.logger.info(f"成功创建表: {table_name}") + self.logger.info(f"成功创建表: {table_name}") + else: + raise ValueError(f"无法解析表名格式: {table_name}") def close(self): """关闭数据库连接""" diff --git a/src/data_provider/indicator_calculator/__init__.py b/src/data_provider/indicator_calculator/__init__.py index 24e84bc..cc2f88c 100644 --- a/src/data_provider/indicator_calculator/__init__.py +++ b/src/data_provider/indicator_calculator/__init__.py @@ -4,6 +4,7 @@ from .base_indicator import BaseIndicator from .macd_indicator import MACDIndicator from .kdj_indicator import KDJIndicator from .boll_indicator import BOLLIndicator +from .rsi_indicator import RSIIndicator from .indicator_manager import IndicatorManager __all__ = [ @@ -11,5 +12,6 @@ __all__ = [ "MACDIndicator", "KDJIndicator", "BOLLIndicator", + "RSIIndicator", "IndicatorManager", ] diff --git a/src/data_provider/indicator_calculator/boll_indicator.py b/src/data_provider/indicator_calculator/boll_indicator.py index 0b74927..3866406 100644 --- a/src/data_provider/indicator_calculator/boll_indicator.py +++ b/src/data_provider/indicator_calculator/boll_indicator.py @@ -1,7 +1,10 @@ """布林带指标计算器""" from typing import Dict, List +import numpy as np import pandas as pd +import talib +from talib._ta_lib import MA_Type from .base_indicator import BaseIndicator @@ -53,20 +56,22 @@ class BOLLIndicator(BaseIndicator): period = self.config["period"] std_multiplier = self.config["std_multiplier"] - # 计算中轨(移动平均线) - result["boll_mid"] = ( - result["close"].rolling(window=period, min_periods=1).mean() + # 使用ta-lib计算布林带 + upper, middle, lower = talib.BBANDS( + np.asarray(result["close"].values, dtype=np.float64), + timeperiod=period, + nbdevup=std_multiplier, + nbdevdn=std_multiplier, + matype=MA_Type.SMA, ) - # 计算标准差 - std = result["close"].rolling(window=period, min_periods=1).std() - - # 计算上轨和下轨 - result["boll_upper"] = result["boll_mid"] + std_multiplier * std - result["boll_lower"] = result["boll_mid"] - std_multiplier * std + # 统一列名规范 + result["boll_upper"] = upper + result["boll_mid"] = middle + result["boll_lower"] = lower # 计算布林带宽度(可选,用于判断波动性) - result["boll_width"] = result["boll_upper"] - result["boll_lower"] + result["boll_width"] = upper - lower return result diff --git a/src/data_provider/indicator_calculator/indicator_manager.py b/src/data_provider/indicator_calculator/indicator_manager.py index 791ca9e..1d53470 100644 --- a/src/data_provider/indicator_calculator/indicator_manager.py +++ b/src/data_provider/indicator_calculator/indicator_manager.py @@ -7,6 +7,7 @@ from .base_indicator import BaseIndicator from .macd_indicator import MACDIndicator from .kdj_indicator import KDJIndicator from .boll_indicator import BOLLIndicator +from .rsi_indicator import RSIIndicator class IndicatorManager: @@ -20,6 +21,7 @@ class IndicatorManager: "macd": MACDIndicator, "kdj": KDJIndicator, "boll": BOLLIndicator, + "rsi": RSIIndicator, } def __init__(self, indicator_configs: Dict[str, Dict] | None = None): diff --git a/src/data_provider/indicator_calculator/kdj_indicator.py b/src/data_provider/indicator_calculator/kdj_indicator.py index 5db6669..953629a 100644 --- a/src/data_provider/indicator_calculator/kdj_indicator.py +++ b/src/data_provider/indicator_calculator/kdj_indicator.py @@ -1,7 +1,10 @@ """KDJ指标计算器""" from typing import Dict, List +import numpy as np import pandas as pd +import talib +from talib._ta_lib import MA_Type from .base_indicator import BaseIndicator @@ -58,25 +61,24 @@ class KDJIndicator(BaseIndicator): k_period = self.config["k_period"] d_period = self.config["d_period"] - # 计算RSV(未成熟随机值) - low_min = result["low"].rolling(window=period, min_periods=1).min() - high_max = result["high"].rolling(window=period, min_periods=1).max() + # 使用ta-lib的STOCH(随机指标)计算KDJ + # ta-lib的STOCH返回的是K和D,我们需要根据公式计算J + slowk, slowd = talib.STOCH( + np.asarray(result["high"].values, dtype=np.float64), + np.asarray(result["low"].values, dtype=np.float64), + np.asarray(result["close"].values, dtype=np.float64), + fastk_period=period, + slowk_period=k_period, + slowk_matype=MA_Type.SMA, + slowd_period=d_period, + slowd_matype=MA_Type.SMA, + ) - rsv = ((result["close"] - low_min) / (high_max - low_min)) * 100 - # 处理除以0的情况 - rsv = rsv.fillna(50) - - # 计算K值(RSV的移动平均) - # K = (2/3) * prev_K + (1/3) * RSV - result["kdj_k"] = rsv.ewm(alpha=1 / k_period, adjust=False).mean() - - # 计算D值(K值的移动平均) - # D = (2/3) * prev_D + (1/3) * K - result["kdj_d"] = result["kdj_k"].ewm(alpha=1 / d_period, adjust=False).mean() - - # 计算J值 - # J = 3K - 2D - result["kdj_j"] = 3 * result["kdj_k"] - 2 * result["kdj_d"] + # 统一列名规范 + result["kdj_k"] = slowk + result["kdj_d"] = slowd + # 计算J值:J = 3K - 2D + result["kdj_j"] = 3 * slowk - 2 * slowd return result diff --git a/src/data_provider/indicator_calculator/macd_indicator.py b/src/data_provider/indicator_calculator/macd_indicator.py index 0746d4f..bf6eb51 100644 --- a/src/data_provider/indicator_calculator/macd_indicator.py +++ b/src/data_provider/indicator_calculator/macd_indicator.py @@ -1,7 +1,9 @@ """MACD指标计算器""" from typing import Dict, List +import numpy as np import pandas as pd +import talib from .base_indicator import BaseIndicator @@ -56,27 +58,26 @@ class MACDIndicator(BaseIndicator): # 复制DataFrame避免修改原始数据 result = df.copy() - # 获取收盘价 - close = result["close"] - - # 计算快速和慢速EMA + # 获取配置参数 fast_period = self.config["fast_period"] slow_period = self.config["slow_period"] signal_period = self.config["signal_period"] - ema_fast = close.ewm(span=fast_period, adjust=False).mean() - ema_slow = close.ewm(span=slow_period, adjust=False).mean() - - # 计算DIF - result["macd_dif"] = ema_fast - ema_slow - - # 计算DEA(DIF的EMA) - result["macd_dea"] = ( - result["macd_dif"].ewm(span=signal_period, adjust=False).mean() + # 使用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, ) - # 计算MACD柱状图 - result["macd_histogram"] = (result["macd_dif"] - result["macd_dea"]) * 2 + # 统一列名规范 + result["macd_dif"] = macd + result["macd_dea"] = signal + # ta-lib的MACD柱值已经是 DIF-DEA,不需要乘以2 + # 但为了保持与国内软件一致,这里乘以2 + result["macd_histogram"] = hist * 2 return result diff --git a/src/data_provider/indicator_calculator/rsi_indicator.py b/src/data_provider/indicator_calculator/rsi_indicator.py new file mode 100644 index 0000000..b8a89b2 --- /dev/null +++ b/src/data_provider/indicator_calculator/rsi_indicator.py @@ -0,0 +1,89 @@ +"""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指标(相对强弱指标)" diff --git a/src/database_manager/db_manager.py b/src/database_manager/db_manager.py index a054523..0918f36 100644 --- a/src/database_manager/db_manager.py +++ b/src/database_manager/db_manager.py @@ -20,6 +20,7 @@ from sqlalchemy import ( JSON, Index, ) +from sqlalchemy.types import DECIMAL from sqlalchemy.engine import Engine from sqlalchemy.exc import SQLAlchemyError @@ -300,6 +301,12 @@ class DatabaseManager: col_type = Integer() elif col_type_str == "Float": col_type = Float() + elif col_type_str == "Decimal": + # DECIMAL类型,用于精确存储价格等数值 + # precision: 总位数,scale: 小数位数 + precision = col_def.get("precision", 10) + scale = col_def.get("scale", 3) + col_type = DECIMAL(precision, scale) elif col_type_str == "DateTime": col_type = DateTime() elif col_type_str == "Boolean": diff --git a/src/database_manager/table_schemas.py b/src/database_manager/table_schemas.py index bd9fc1a..9ef298d 100644 --- a/src/database_manager/table_schemas.py +++ b/src/database_manager/table_schemas.py @@ -16,41 +16,113 @@ TICK_TABLE = { "name": "ticks", "comment": "Tick行情数据表", "columns": { - "id": { - "type": "Integer", - "primary_key": True, - "nullable": False, - "comment": "自增主键", - }, "symbol": { "type": "String", "length": 20, + "primary_key": True, "nullable": False, "comment": "标的代码", }, - "timestamp": {"type": "DateTime", "nullable": False, "comment": "时间戳"}, - "price": {"type": "Float", "nullable": False, "comment": "最新价"}, + "timestamp": { + "type": "DateTime", + "primary_key": True, + "nullable": False, + "comment": "时间戳", + }, + "price": { + "type": "Decimal", + "precision": 10, + "scale": 3, + "nullable": False, + "comment": "最新价", + }, "volume": {"type": "Integer", "nullable": False, "comment": "成交量"}, - "amount": {"type": "Float", "nullable": True, "comment": "成交额"}, - "bid_price1": {"type": "Float", "nullable": True, "comment": "买一价"}, + "amount": { + "type": "Decimal", + "precision": 20, + "scale": 2, + "nullable": True, + "comment": "成交额", + }, + "bid_price1": { + "type": "Decimal", + "precision": 10, + "scale": 3, + "nullable": True, + "comment": "买一价", + }, "bid_volume1": {"type": "Integer", "nullable": True, "comment": "买一量"}, - "bid_price2": {"type": "Float", "nullable": True, "comment": "买二价"}, + "bid_price2": { + "type": "Decimal", + "precision": 10, + "scale": 3, + "nullable": True, + "comment": "买二价", + }, "bid_volume2": {"type": "Integer", "nullable": True, "comment": "买二量"}, - "bid_price3": {"type": "Float", "nullable": True, "comment": "买三价"}, + "bid_price3": { + "type": "Decimal", + "precision": 10, + "scale": 3, + "nullable": True, + "comment": "买三价", + }, "bid_volume3": {"type": "Integer", "nullable": True, "comment": "买三量"}, - "bid_price4": {"type": "Float", "nullable": True, "comment": "买四价"}, + "bid_price4": { + "type": "Decimal", + "precision": 10, + "scale": 3, + "nullable": True, + "comment": "买四价", + }, "bid_volume4": {"type": "Integer", "nullable": True, "comment": "买四量"}, - "bid_price5": {"type": "Float", "nullable": True, "comment": "买五价"}, + "bid_price5": { + "type": "Decimal", + "precision": 10, + "scale": 3, + "nullable": True, + "comment": "买五价", + }, "bid_volume5": {"type": "Integer", "nullable": True, "comment": "买五量"}, - "ask_price1": {"type": "Float", "nullable": True, "comment": "卖一价"}, + "ask_price1": { + "type": "Decimal", + "precision": 10, + "scale": 3, + "nullable": True, + "comment": "卖一价", + }, "ask_volume1": {"type": "Integer", "nullable": True, "comment": "卖一量"}, - "ask_price2": {"type": "Float", "nullable": True, "comment": "卖二价"}, + "ask_price2": { + "type": "Decimal", + "precision": 10, + "scale": 3, + "nullable": True, + "comment": "卖二价", + }, "ask_volume2": {"type": "Integer", "nullable": True, "comment": "卖二量"}, - "ask_price3": {"type": "Float", "nullable": True, "comment": "卖三价"}, + "ask_price3": { + "type": "Decimal", + "precision": 10, + "scale": 3, + "nullable": True, + "comment": "卖三价", + }, "ask_volume3": {"type": "Integer", "nullable": True, "comment": "卖三量"}, - "ask_price4": {"type": "Float", "nullable": True, "comment": "卖四价"}, + "ask_price4": { + "type": "Decimal", + "precision": 10, + "scale": 3, + "nullable": True, + "comment": "卖四价", + }, "ask_volume4": {"type": "Integer", "nullable": True, "comment": "卖四量"}, - "ask_price5": {"type": "Float", "nullable": True, "comment": "卖五价"}, + "ask_price5": { + "type": "Decimal", + "precision": 10, + "scale": 3, + "nullable": True, + "comment": "卖五价", + }, "ask_volume5": {"type": "Integer", "nullable": True, "comment": "卖五量"}, "open_interest": { "type": "Integer", @@ -59,7 +131,6 @@ TICK_TABLE = { }, }, "indexes": [ - {"name": "idx_symbol_time", "columns": ["symbol", "timestamp"]}, {"name": "idx_timestamp", "columns": ["timestamp"]}, ], } @@ -81,32 +152,57 @@ def create_kline_table_definition(period: str) -> Dict[str, Any]: "name": table_name, "comment": f"K线数据表({period}周期)", "columns": { - "id": { - "type": "Integer", - "primary_key": True, - "nullable": False, - "comment": "自增主键", - }, "symbol": { "type": "String", "length": 20, + "primary_key": True, "nullable": False, "comment": "标的代码", }, - "timestamp": {"type": "DateTime", "nullable": False, "comment": "时间戳"}, - "open": {"type": "Float", "nullable": False, "comment": "开盘价"}, - "high": {"type": "Float", "nullable": False, "comment": "最高价"}, - "low": {"type": "Float", "nullable": False, "comment": "最低价"}, - "close": {"type": "Float", "nullable": False, "comment": "收盘价"}, + "timestamp": { + "type": "DateTime", + "primary_key": True, + "nullable": False, + "comment": "时间戳", + }, + "open": { + "type": "Decimal", + "precision": 10, + "scale": 3, + "nullable": False, + "comment": "开盘价", + }, + "high": { + "type": "Decimal", + "precision": 10, + "scale": 3, + "nullable": False, + "comment": "最高价", + }, + "low": { + "type": "Decimal", + "precision": 10, + "scale": 3, + "nullable": False, + "comment": "最低价", + }, + "close": { + "type": "Decimal", + "precision": 10, + "scale": 3, + "nullable": False, + "comment": "收盘价", + }, "volume": {"type": "Integer", "nullable": False, "comment": "成交量"}, - "amount": {"type": "Float", "nullable": False, "comment": "成交额"}, + "amount": { + "type": "Decimal", + "precision": 20, + "scale": 2, + "nullable": False, + "comment": "成交额", + }, }, "indexes": [ - { - "name": "idx_symbol_time", - "columns": ["symbol", "timestamp"], - "unique": True, # 同一股票同一时间只有一条记录 - }, {"name": "idx_timestamp", "columns": ["timestamp"]}, ], } @@ -124,50 +220,55 @@ def create_indicator_table_definition(indicator: str, period: str) -> Dict[str, Returns: 表定义字典 """ - table_name = f"{indicator}_{period}" + table_name = f"indicators_{period}_{indicator}" # 基础列(所有指标表都有) base_columns = { - "id": { - "type": "Integer", - "primary_key": True, - "nullable": False, - "comment": "自增主键", - }, "symbol": { "type": "String", "length": 20, + "primary_key": True, "nullable": False, "comment": "标的代码", }, - "timestamp": {"type": "DateTime", "nullable": False, "comment": "时间戳"}, + "timestamp": { + "type": "DateTime", + "primary_key": True, + "nullable": False, + "comment": "时间戳", + }, } # 根据不同指标添加特定列 indicator_columns = {} if indicator == "macd": indicator_columns = { - "dif": {"type": "Float", "nullable": False, "comment": "DIF值"}, - "dea": {"type": "Float", "nullable": False, "comment": "DEA值"}, - "macd": {"type": "Float", "nullable": False, "comment": "MACD柱值"}, + "macd_dif": {"type": "Float", "nullable": False, "comment": "DIF值"}, + "macd_dea": {"type": "Float", "nullable": False, "comment": "DEA值"}, + "macd_histogram": { + "type": "Float", + "nullable": False, + "comment": "MACD柱值", + }, } elif indicator == "kdj": indicator_columns = { - "k": {"type": "Float", "nullable": False, "comment": "K值"}, - "d": {"type": "Float", "nullable": False, "comment": "D值"}, - "j": {"type": "Float", "nullable": False, "comment": "J值"}, + "kdj_k": {"type": "Float", "nullable": False, "comment": "K值"}, + "kdj_d": {"type": "Float", "nullable": False, "comment": "D值"}, + "kdj_j": {"type": "Float", "nullable": False, "comment": "J值"}, } elif indicator == "rsi": indicator_columns = { - "rsi6": {"type": "Float", "nullable": True, "comment": "RSI6"}, - "rsi12": {"type": "Float", "nullable": True, "comment": "RSI12"}, - "rsi24": {"type": "Float", "nullable": True, "comment": "RSI24"}, + "rsi_fast": {"type": "Float", "nullable": True, "comment": "快速RSI"}, + "rsi_mid": {"type": "Float", "nullable": True, "comment": "中速RSI"}, + "rsi_slow": {"type": "Float", "nullable": True, "comment": "慢速RSI"}, } elif indicator == "boll": indicator_columns = { - "upper": {"type": "Float", "nullable": False, "comment": "上轨"}, - "middle": {"type": "Float", "nullable": False, "comment": "中轨"}, - "lower": {"type": "Float", "nullable": False, "comment": "下轨"}, + "boll_upper": {"type": "Float", "nullable": False, "comment": "上轨"}, + "boll_mid": {"type": "Float", "nullable": False, "comment": "中轨"}, + "boll_lower": {"type": "Float", "nullable": False, "comment": "下轨"}, + "boll_width": {"type": "Float", "nullable": True, "comment": "带宽"}, } elif indicator in ["ma", "ema"]: indicator_columns = { @@ -185,11 +286,6 @@ def create_indicator_table_definition(indicator: str, period: str) -> Dict[str, "comment": f"{indicator.upper()}指标表({period}周期)", "columns": columns, "indexes": [ - { - "name": "idx_symbol_time", - "columns": ["symbol", "timestamp"], - "unique": True, - }, {"name": "idx_timestamp", "columns": ["timestamp"]}, ], } diff --git a/test_calc_indicators.py b/test_calc_indicators.py new file mode 100644 index 0000000..87dfbf7 --- /dev/null +++ b/test_calc_indicators.py @@ -0,0 +1,85 @@ +"""手动触发指标计算""" + +import sys +from pathlib import Path +from datetime import datetime + +# 添加项目根目录到路径 +project_root = Path(__file__).parent +sys.path.insert(0, str(project_root)) + +from src.core.config import Config, set_config +from src.core.logger import get_logger +from src.data_provider import DataProvider + +logger = get_logger("TestIndicators") + +# 初始化配置 +config = Config() +config.load_with_global("configs/backtest.yaml") +set_config(config) + +symbols = ["159915.SZ", "601658.SH"] +start_date = datetime(2025, 12, 1) +end_date = datetime(2025, 12, 15) +periods = ["1m", "1d"] + +logger.info("开始测试指标计算...") + +try: + with DataProvider() as provider: + # 测试指标管理器是否初始化 + if not provider.indicator_manager: + logger.error("指标管理器未初始化!") + else: + logger.info( + f"指标管理器已初始化,启用的指标: {provider.indicator_manager.get_enabled_indicators()}" + ) + + # 手动触发指标计算 + for symbol in symbols: + for period in periods: + logger.info(f"\n处理 {symbol} [{period}]...") + + # 读取K线数据 + klines = provider.get_klines([symbol], start_date, end_date, period) + if symbol not in klines or klines[symbol].empty: + logger.warning(f" 无K线数据") + continue + + logger.info(f" 读取到 {len(klines[symbol])} 条K线数据") + + # 计算指标 + try: + df = klines[symbol] + key = f"{symbol}_{period}" + df_with_indicators = provider.indicator_manager.calculate_all( + {key: df} + ) + + logger.info( + f" 指标计算完成,列: {df_with_indicators[key].columns.tolist()}" + ) + + # 保存指标 + from src.data_provider.data_writer import IndicatorWriter + + indicator_writer = IndicatorWriter( + database="qtrade_backtest", db_manager=provider.db_manager + ) + try: + results = indicator_writer.save( + df_with_indicators, + provider.indicator_manager.get_enabled_indicators(), + ) + logger.info(f" 保存结果: {results}") + finally: + indicator_writer.close() + + except Exception as e: + logger.error(f" 指标计算失败: {e}", exc_info=True) + + logger.info("\n指标计算测试完成!") + +except Exception as e: + logger.error(f"测试失败: {e}", exc_info=True) diff --git a/tests/test_rsi.py b/tests/test_rsi.py new file mode 100644 index 0000000..23c7854 --- /dev/null +++ b/tests/test_rsi.py @@ -0,0 +1,75 @@ +"""RSI指标测试脚本""" + +import sys +from pathlib import Path + +# 添加项目根目录到路径 +project_root = Path(__file__).parent.parent +sys.path.insert(0, str(project_root)) + +import pandas as pd +import numpy as np +from datetime import datetime, timedelta +from src.data_provider.indicator_calculator import RSIIndicator, IndicatorManager + +# 创建测试数据 +df = pd.DataFrame( + { + "timestamp": [datetime(2024, 1, 1) + timedelta(days=i) for i in range(100)], + "open": np.linspace(10, 20, 100), + "high": np.linspace(10.5, 20.5, 100), + "low": np.linspace(9.5, 19.5, 100), + "close": np.linspace(10, 20, 100), + "volume": [1000000] * 100, + "amount": [10000000] * 100, + } +) + +print("=" * 60) +print("测试单个RSI指标") +print("=" * 60) + +# 测试RSI指标 +rsi = RSIIndicator() +result = rsi.calculate(df) +print(f"RSI指标列名: {rsi.get_column_names()}") +print(f"\n最后5行数据:") +print(result[["close", "rsi_fast", "rsi_mid", "rsi_slow"]].tail()) + +print("\n" + "=" * 60) +print("测试指标管理器(包含RSI)") +print("=" * 60) + +# 测试指标管理器 +indicator_configs = { + "macd": {"fast_period": 12, "slow_period": 26, "signal_period": 9}, + "kdj": {"period": 9, "k_period": 3, "d_period": 3}, + "boll": {"period": 20, "std_multiplier": 2.0}, + "rsi": {"fast": 6, "mid": 12, "slow": 24}, +} + +manager = IndicatorManager(indicator_configs) +print(f"已启用的指标: {manager.get_enabled_indicators()}") + +kline_data = {"TEST_1d": df.copy()} +result = manager.calculate_all(kline_data) + +print(f"\n计算结果:") +for key, df_result in result.items(): + print(f"\n{key}:") + print(f" 总列数: {len(df_result.columns)}") + indicator_cols = [ + col + for col in df_result.columns + if any(ind in col for ind in ["macd", "kdj", "boll", "rsi"]) + ] + print(f" 指标列数: {len(indicator_cols)}") + print(f" 指标列: {', '.join(indicator_cols)}") + print(f"\n 最后3行数据:") + print( + df_result[["close"] + [col for col in indicator_cols if "rsi" in col]].tail(3) + ) + +print("\n" + "=" * 60) +print("测试完成!") +print("=" * 60)