diff --git a/configs/global.yaml b/configs/global.yaml index 81637ae..e1eaebc 100644 --- a/configs/global.yaml +++ b/configs/global.yaml @@ -65,4 +65,11 @@ services: # QMT配置(公用部分) qmt: xtquant_path: "C:\\Program Files\\国金证券QMT交易端\\userdata_mini\\datadir" + xtquant_token: "e83d8eec5226c0b4db4a1d40830e09e4ffe73e15" # XtQuant 数据接口 token(需要申请) account_type: "STOCK" # STOCK-股票账户, CREDIT-信用账户 + # XtQuant 优化地址(可选) + optimize_addresses: + - "115.231.218.73:55310" + - "115.231.218.79:55310" + - "218.16.123.11:55310" + - "218.16.123.27:55310" diff --git a/src/data_provider/data_downloader/base_downloader.py b/src/data_provider/data_downloader/base_downloader.py index b528fbf..a111141 100644 --- a/src/data_provider/data_downloader/base_downloader.py +++ b/src/data_provider/data_downloader/base_downloader.py @@ -134,16 +134,25 @@ class BaseDataDownloader(ABC): self.logger.warning(f"数据库 {self.database} 不存在,正在创建...") db_manager.create_database(self.database) - # 确保 klines 表存在 - klines_def = get_table_definition("klines") - if not db_manager.table_exists(self.database, "klines"): - self.logger.warning("表 klines 不存在,正在创建...") - db_manager.create_table( - database=self.database, - table_name=klines_def["name"], - columns=klines_def["columns"], - indexes=klines_def["indexes"], - ) + # 确保对应周期的 klines 表存在 + from ...database_manager.table_utils import ( + get_kline_table_name, + SUPPORTED_PERIODS, + ) + from ...database_manager.table_schemas import create_kline_table_definition + + # 为所有支持的周期创建表(如果不存在) + for period in SUPPORTED_PERIODS: + table_name = get_kline_table_name(period) + if not db_manager.table_exists(self.database, table_name): + self.logger.warning(f"表 {table_name} 不存在,正在创建...") + table_def = create_kline_table_definition(period) + db_manager.create_table( + database=self.database, + table_name=table_def["name"], + columns=table_def["columns"], + indexes=table_def["indexes"], + ) db_manager.close() @@ -292,12 +301,16 @@ class BaseDataDownloader(ABC): session = self.Session() saved_count = 0 + # 使用动态表名 + from ...database_manager.table_utils import get_kline_table_name + + table_name = get_kline_table_name(period) + try: for kline in klines: - # 转换为数据库记录 + # 转换为数据库记录(不再需要period字段) record = { "symbol": kline.symbol, - "period": period, "timestamp": kline.timestamp, "open": kline.open, "high": kline.high, @@ -309,11 +322,11 @@ class BaseDataDownloader(ABC): # 使用 INSERT ... ON DUPLICATE KEY UPDATE 避免重复 # 这里使用原始 SQL - sql = """ - INSERT INTO klines - (symbol, period, timestamp, open, high, low, close, volume, amount) + sql = f""" + INSERT INTO {table_name} + (symbol, timestamp, open, high, low, close, volume, amount) VALUES - (:symbol, :period, :timestamp, :open, :high, :low, :close, :volume, :amount) + (:symbol, :timestamp, :open, :high, :low, :close, :volume, :amount) ON DUPLICATE KEY UPDATE open=VALUES(open), high=VALUES(high), low=VALUES(low), close=VALUES(close), volume=VALUES(volume), amount=VALUES(amount) diff --git a/src/data_provider/data_downloader/xtquant_downloader.py b/src/data_provider/data_downloader/xtquant_downloader.py index 91cdd67..517cfe7 100644 --- a/src/data_provider/data_downloader/xtquant_downloader.py +++ b/src/data_provider/data_downloader/xtquant_downloader.py @@ -72,9 +72,9 @@ class XtQuantDownloader(BaseDataDownloader): self, token: Optional[str], optimize_addresses: Optional[List[str]] ): """初始化 XtQuant 数据中心""" - # 获取 token + # 获取 token(从配置文件 qmt.xtquant_token 读取) if token is None: - token = self.config.get("xtquant.token") + token = self.config.get("qmt.xtquant_token") if not token: raise ValueError( "XtQuant token 未设置,请在配置文件中设置或通过参数传入" @@ -95,7 +95,7 @@ class XtQuantDownloader(BaseDataDownloader): # 设置优化地址 if optimize_addresses is None: - optimize_addresses = self.config.get("xtquant.optimize_addresses", []) + optimize_addresses = self.config.get("qmt.optimize_addresses", []) if optimize_addresses: try: @@ -165,6 +165,7 @@ class XtQuantDownloader(BaseDataDownloader): # 转换为 Kline 对象 klines = [] + first_logged = False for timestamp, row in df.iterrows(): # 跳过无效数据 if ( @@ -175,16 +176,41 @@ class XtQuantDownloader(BaseDataDownloader): ): continue + # 将时间戳转换为 datetime + # XtQuant 返回的时间戳可能是字符串格式 "20251201093000" + # 或者是 pandas Timestamp 对象 + from datetime import datetime as dt_class + + if isinstance(timestamp, str): + # 字符串格式: YYYYMMDDHHMMSS + dt = dt_class.strptime(timestamp, "%Y%m%d%H%M%S") + elif hasattr(timestamp, "to_pydatetime"): + # pandas Timestamp 对象 + dt = timestamp.to_pydatetime() + else: + # 已经是 datetime 对象 + dt = timestamp + + # 打印第一条数据的时间戳信息用于调试 + if not first_logged: + self.logger.debug( + f"第一条时间戳 - 原始: {timestamp}, 类型: {type(timestamp)}" + ) + self.logger.debug(f"第一条时间戳 - 转换后: {dt}, 类型: {type(dt)}") + first_logged = True + kline = Kline( symbol=symbol, period=period, # 使用我们的标准周期格式 - timestamp=timestamp, + timestamp=dt, open=round(row["open"], 2), high=round(row["high"], 2), low=round(row["low"], 2), close=round(row["close"], 2), volume=int(row["volume"]), - amount=round(row["amount"], 2) if row["amount"] > 0 else None, + amount=round(row["amount"], 2) + if row["amount"] and row["amount"] > 0 + else 0.0, # 使用 0.0 替代 None open_interest=0, # 股票没有持仓量 ) klines.append(kline) diff --git a/src/data_provider/data_provider.py b/src/data_provider/data_provider.py index 79647f9..6d1841f 100644 --- a/src/data_provider/data_provider.py +++ b/src/data_provider/data_provider.py @@ -11,6 +11,7 @@ from sqlalchemy import create_engine, text from ..core.config import get_config from ..core.logger import get_logger from ..core.models import Kline +from ..database_manager.table_utils import get_kline_table_name logger = get_logger("DataProvider") @@ -348,19 +349,19 @@ class DataProvider: ) engine = create_engine(connection_url) + # 使用动态表名 + table_name = get_kline_table_name(period) query = text( - """ - SELECT * FROM klines - WHERE symbol = :symbol AND period = :period + f""" + SELECT * FROM {table_name} + WHERE symbol = :symbol ORDER BY timestamp DESC LIMIT 1 """ ) with engine.connect() as conn: - df = pd.read_sql( - query, conn, params={"symbol": symbol, "period": period} - ) + df = pd.read_sql(query, conn, params={"symbol": symbol}) engine.dispose() @@ -414,12 +415,15 @@ class DataProvider: ) engine = create_engine(connection_url) + # 使用动态表名 + table_name = get_kline_table_name(period) + # 构建查询 if end_date: query = text( - """ - SELECT * FROM klines - WHERE symbol = :symbol AND period = :period + f""" + SELECT * FROM {table_name} + WHERE symbol = :symbol AND timestamp <= :end_date ORDER BY timestamp DESC LIMIT :count @@ -427,20 +431,19 @@ class DataProvider: ) params = { "symbol": symbol, - "period": period, "end_date": end_date, "count": count, } else: query = text( - """ - SELECT * FROM klines - WHERE symbol = :symbol AND period = :period + f""" + SELECT * FROM {table_name} + WHERE symbol = :symbol ORDER BY timestamp DESC LIMIT :count """ ) - params = {"symbol": symbol, "period": period, "count": count} + params = {"symbol": symbol, "count": count} with engine.connect() as conn: df = pd.read_sql(query, conn, params=params) @@ -525,14 +528,16 @@ class DataProvider: ) engine = create_engine(connection_url) + # 使用动态表名 + table_name = get_kline_table_name(period) query = text( - """ + f""" SELECT MIN(timestamp) as start_date, MAX(timestamp) as end_date, COUNT(*) as count - FROM klines - WHERE symbol = :symbol AND period = :period + FROM {table_name} + WHERE symbol = :symbol AND timestamp BETWEEN :start_date AND :end_date """ ) @@ -542,7 +547,6 @@ class DataProvider: query, { "symbol": symbol, - "period": period, "start_date": start_date, "end_date": end_date, }, @@ -595,7 +599,9 @@ class DataProvider: ) engine = create_engine(connection_url) - query = text("SELECT DISTINCT symbol FROM klines ORDER BY symbol") + # 使用默认1d周期的表来查询symbol列表 + table_name = get_kline_table_name("1d") + query = text(f"SELECT DISTINCT symbol FROM {table_name} ORDER BY symbol") with engine.connect() as conn: result = conn.execute(query) @@ -629,6 +635,8 @@ class DataProvider: database = config.get("database.database") try: + from ..database_manager.table_utils import SUPPORTED_PERIODS + config = get_config() connection_url = ( f"mysql+pymysql://{config.get('database.user')}:" @@ -638,13 +646,17 @@ class DataProvider: ) engine = create_engine(connection_url) - query = text( - "SELECT DISTINCT period FROM klines WHERE symbol = :symbol ORDER BY period" - ) - - with engine.connect() as conn: - result = conn.execute(query, {"symbol": symbol}) - periods = [row[0] for row in result] + # 检查每个周期的表中是否有该symbol的数据 + periods = [] + for period in SUPPORTED_PERIODS: + table_name = get_kline_table_name(period) + query = text( + f"SELECT 1 FROM {table_name} WHERE symbol = :symbol LIMIT 1" + ) + with engine.connect() as conn: + result = conn.execute(query, {"symbol": symbol}).fetchone() + if result: + periods.append(period) engine.dispose() return periods @@ -963,6 +975,9 @@ class DataProvider: columns_to_save = required_columns + optional_columns df_to_save = df_copy[columns_to_save] + # 使用动态表名 + table_name = get_kline_table_name(period) + # 使用事务保存 with engine.connect() as conn: trans = conn.begin() @@ -970,36 +985,35 @@ class DataProvider: for _, row in df_to_save.iterrows(): # 根据 on_duplicate 策略构建 SQL if on_duplicate == "update": - sql = text(""" - INSERT INTO klines - (symbol, period, timestamp, open, high, low, close, volume, amount) + sql = text(f""" + INSERT INTO {table_name} + (symbol, timestamp, open, high, low, close, volume, amount) VALUES - (:symbol, :period, :timestamp, :open, :high, :low, :close, :volume, :amount) + (:symbol, :timestamp, :open, :high, :low, :close, :volume, :amount) ON DUPLICATE KEY UPDATE open=VALUES(open), high=VALUES(high), low=VALUES(low), close=VALUES(close), volume=VALUES(volume), amount=VALUES(amount) """) elif on_duplicate == "ignore": - sql = text(""" - INSERT IGNORE INTO klines - (symbol, period, timestamp, open, high, low, close, volume, amount) + sql = text(f""" + INSERT IGNORE INTO {table_name} + (symbol, timestamp, open, high, low, close, volume, amount) VALUES - (:symbol, :period, :timestamp, :open, :high, :low, :close, :volume, :amount) + (:symbol, :timestamp, :open, :high, :low, :close, :volume, :amount) """) else: # replace - sql = text(""" - REPLACE INTO klines - (symbol, period, timestamp, open, high, low, close, volume, amount) + sql = text(f""" + REPLACE INTO {table_name} + (symbol, timestamp, open, high, low, close, volume, amount) VALUES - (:symbol, :period, :timestamp, :open, :high, :low, :close, :volume, :amount) + (:symbol, :timestamp, :open, :high, :low, :close, :volume, :amount) """) - # 执行插入 + # 执行插入(不再需要period参数) conn.execute( sql, { "symbol": row["symbol"], - "period": row["period"], "timestamp": row["timestamp"], "open": float(row["open"]), "high": float(row["high"]), @@ -1149,22 +1163,23 @@ class DataProvider: ) engine = create_engine(connection_url) + # 使用动态表名 + table_name = get_kline_table_name(period) + # 构建批量查询 SQL placeholders = ", ".join([f":symbol{i}" for i in range(len(symbols))]) query = text( f""" - SELECT * FROM klines + SELECT * FROM {table_name} WHERE symbol IN ({placeholders}) - AND period = :period AND timestamp BETWEEN :start_date AND :end_date ORDER BY symbol, timestamp """ ) - # 构建参数 + # 构建参数(不再需要period) params = { **{f"symbol{i}": symbol for i, symbol in enumerate(symbols)}, - "period": period, "start_date": start_date, "end_date": end_date, } diff --git a/src/database_manager/__init__.py b/src/database_manager/__init__.py index a2ba3f0..4cd19f3 100644 --- a/src/database_manager/__init__.py +++ b/src/database_manager/__init__.py @@ -8,13 +8,14 @@ from .table_schemas import ( get_table_definition, get_all_table_names, TICK_TABLE, - KLINE_TABLE, ORDER_TABLE, TRADE_TABLE, POSITION_TABLE, ACCOUNT_TABLE, SIGNAL_TABLE, SYMBOL_TABLE, + create_kline_table_definition, + create_indicator_table_definition, ) __all__ = [ @@ -23,11 +24,12 @@ __all__ = [ "get_table_definition", "get_all_table_names", "TICK_TABLE", - "KLINE_TABLE", "ORDER_TABLE", "TRADE_TABLE", "POSITION_TABLE", "ACCOUNT_TABLE", "SIGNAL_TABLE", "SYMBOL_TABLE", + "create_kline_table_definition", + "create_indicator_table_definition", ] diff --git a/src/database_manager/table_schemas.py b/src/database_manager/table_schemas.py index 9b89c72..bd9fc1a 100644 --- a/src/database_manager/table_schemas.py +++ b/src/database_manager/table_schemas.py @@ -1,9 +1,15 @@ """ 表结构定义 根据 core/models 中的对象定义数据库表结构 +支持按周期分表存储(klines_1m, macd_1m 等) """ from typing import Dict, Any, List +from .table_utils import ( + get_all_kline_table_names, + get_all_indicator_table_names, + SUPPORTED_PERIODS, +) # ==================== Tick 表 ==================== TICK_TABLE = { @@ -58,11 +64,70 @@ TICK_TABLE = { ], } -# ==================== Kline 表 ==================== -KLINE_TABLE = { - "name": "klines", - "comment": "K线数据表", - "columns": { + +# ==================== Kline 表(按周期分表)==================== +def create_kline_table_definition(period: str) -> Dict[str, Any]: + """ + 创建指定周期的K线表定义 + + Args: + period: 周期(1m/5m/60m/1d等) + + Returns: + 表定义字典 + """ + table_name = f"klines_{period}" + return { + "name": table_name, + "comment": f"K线数据表({period}周期)", + "columns": { + "id": { + "type": "Integer", + "primary_key": True, + "nullable": False, + "comment": "自增主键", + }, + "symbol": { + "type": "String", + "length": 20, + "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": "收盘价"}, + "volume": {"type": "Integer", "nullable": False, "comment": "成交量"}, + "amount": {"type": "Float", "nullable": False, "comment": "成交额"}, + }, + "indexes": [ + { + "name": "idx_symbol_time", + "columns": ["symbol", "timestamp"], + "unique": True, # 同一股票同一时间只有一条记录 + }, + {"name": "idx_timestamp", "columns": ["timestamp"]}, + ], + } + + +# ==================== 指标表(按周期分表)==================== +def create_indicator_table_definition(indicator: str, period: str) -> Dict[str, Any]: + """ + 创建指定指标和周期的表定义 + + Args: + indicator: 指标名称(macd/kdj/rsi等) + period: 周期(1m/5m/60m/1d等) + + Returns: + 表定义字典 + """ + table_name = f"{indicator}_{period}" + + # 基础列(所有指标表都有) + base_columns = { "id": { "type": "Integer", "primary_key": True, @@ -75,29 +140,60 @@ KLINE_TABLE = { "nullable": False, "comment": "标的代码", }, - "period": { - "type": "String", - "length": 10, - "nullable": False, - "comment": "周期(1m/5m/15m/30m/60m/1d/1w)", - }, "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": "收盘价"}, - "volume": {"type": "Integer", "nullable": False, "comment": "成交量"}, - "amount": {"type": "Float", "nullable": False, "comment": "成交额"}, - }, - "indexes": [ - { - "name": "idx_symbol_period_time", - "columns": ["symbol", "period", "timestamp"], - "unique": True, - }, - {"name": "idx_timestamp", "columns": ["timestamp"]}, - ], -} + } + + # 根据不同指标添加特定列 + 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柱值"}, + } + 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值"}, + } + 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"}, + } + elif indicator == "boll": + indicator_columns = { + "upper": {"type": "Float", "nullable": False, "comment": "上轨"}, + "middle": {"type": "Float", "nullable": False, "comment": "中轨"}, + "lower": {"type": "Float", "nullable": False, "comment": "下轨"}, + } + elif indicator in ["ma", "ema"]: + indicator_columns = { + "ma5": {"type": "Float", "nullable": True, "comment": "5周期均线"}, + "ma10": {"type": "Float", "nullable": True, "comment": "10周期均线"}, + "ma20": {"type": "Float", "nullable": True, "comment": "20周期均线"}, + "ma60": {"type": "Float", "nullable": True, "comment": "60周期均线"}, + } + + # 合并列定义 + columns = {**base_columns, **indicator_columns} + + return { + "name": table_name, + "comment": f"{indicator.upper()}指标表({period}周期)", + "columns": columns, + "indexes": [ + { + "name": "idx_symbol_time", + "columns": ["symbol", "timestamp"], + "unique": True, + }, + {"name": "idx_timestamp", "columns": ["timestamp"]}, + ], + } + # ==================== Order 表 ==================== ORDER_TABLE = { @@ -483,9 +579,26 @@ SYMBOL_TABLE = { } # ==================== 所有表定义 ==================== +# 动态生成所有周期的K线表 +ALL_KLINE_TABLES = { + f"klines_{period}": create_kline_table_definition(period) + for period in SUPPORTED_PERIODS +} + +# 动态生成所有指标表(所有周期×所有指标) +from .table_utils import SUPPORTED_INDICATORS + +ALL_INDICATOR_TABLES = { + f"{indicator}_{period}": create_indicator_table_definition(indicator, period) + for indicator in SUPPORTED_INDICATORS + for period in SUPPORTED_PERIODS +} + +# 合并所有表定义 ALL_TABLES = { + **ALL_KLINE_TABLES, + **ALL_INDICATOR_TABLES, "ticks": TICK_TABLE, - "klines": KLINE_TABLE, "orders": ORDER_TABLE, "trades": TRADE_TABLE, "positions": POSITION_TABLE, diff --git a/src/database_manager/table_utils.py b/src/database_manager/table_utils.py new file mode 100644 index 0000000..c599101 --- /dev/null +++ b/src/database_manager/table_utils.py @@ -0,0 +1,106 @@ +""" +数据库表名工具函数 +支持按周期分表存储 +""" + +from typing import List + +# 支持的周期列表 +SUPPORTED_PERIODS = ["1m", "5m", "15m", "30m", "60m", "1d", "1w"] + +# 支持的指标列表 +SUPPORTED_INDICATORS = ["macd", "kdj", "rsi", "boll", "ma", "ema"] + + +def get_kline_table_name(period: str) -> str: + """ + 获取K线表名 + + Args: + period: 周期(1m/5m/60m/1d等) + + Returns: + 表名(如 klines_1m) + + Examples: + >>> get_kline_table_name("1m") + 'klines_1m' + >>> get_kline_table_name("1d") + 'klines_1d' + """ + return f"klines_{period}" + + +def get_indicator_table_name(indicator: str, period: str) -> str: + """ + 获取指标表名 + + Args: + indicator: 指标名称(macd/kdj/rsi等) + period: 周期(1m/5m/60m/1d等) + + Returns: + 表名(如 macd_1m) + + Examples: + >>> get_indicator_table_name("macd", "1m") + 'macd_1m' + >>> get_indicator_table_name("kdj", "1d") + 'kdj_1d' + """ + return f"{indicator}_{period}" + + +def get_all_kline_table_names() -> List[str]: + """ + 获取所有K线表名 + + Returns: + 所有周期的K线表名列表 + + Examples: + >>> get_all_kline_table_names() + ['klines_1m', 'klines_5m', 'klines_15m', 'klines_30m', 'klines_60m', 'klines_1d', 'klines_1w'] + """ + return [get_kline_table_name(period) for period in SUPPORTED_PERIODS] + + +def get_all_indicator_table_names() -> List[str]: + """ + 获取所有指标表名 + + Returns: + 所有指标和周期组合的表名列表 + + Examples: + >>> tables = get_all_indicator_table_names() + >>> len(tables) + 42 # 6个指标 x 7个周期 + """ + tables = [] + for indicator in SUPPORTED_INDICATORS: + for period in SUPPORTED_PERIODS: + tables.append(get_indicator_table_name(indicator, period)) + return tables + + +def parse_table_name(table_name: str) -> tuple[str, str]: + """ + 解析表名,提取数据类型和周期 + + Args: + table_name: 表名(如 klines_1m 或 macd_1d) + + Returns: + (数据类型, 周期) 元组 + + Examples: + >>> parse_table_name("klines_1m") + ('klines', '1m') + >>> parse_table_name("macd_1d") + ('macd', '1d') + """ + parts = table_name.rsplit("_", 1) + if len(parts) == 2: + return parts[0], parts[1] + raise ValueError(f"无效的表名格式: {table_name}") diff --git a/src/main.py b/src/main.py new file mode 100644 index 0000000..87c7696 --- /dev/null +++ b/src/main.py @@ -0,0 +1,243 @@ +""" +QTrade 主程序 +下载历史数据 +""" + +from datetime import datetime +from .core.config import Config, set_config +from .core.logger import get_logger +from .data_provider import DataProvider + +logger = get_logger("Main") + + +def download_historical_data(): + """下载历史数据""" + + logger.info("=" * 60) + logger.info("开始下载历史数据") + logger.info("=" * 60) + + # 股票列表:邮储银行、创业板ETF + symbols = [ + "601658.SH", # 邮储银行 + "159915.SZ", # 创业板ETF + ] + + # 时间范围:2025-12-01 到 2025-12-15 + start_date = datetime(2025, 12, 1) + end_date = datetime(2025, 12, 15) + + # 周期:1分钟数据 + periods = ["1m"] + + logger.info(f"\n下载配置:") + logger.info(f" 股票代码: {', '.join(symbols)}") + logger.info(f" 时间范围: {start_date.date()} ~ {end_date.date()}") + logger.info(f" 数据周期: {', '.join(periods)}") + + try: + # 使用 DataProvider 下载数据 + result = DataProvider.download_klines( + symbols=symbols, + start_date=start_date, + end_date=end_date, + periods=periods, + downloader_type="xtquant", + ) + + logger.info(f"\n下载结果:") + logger.info(f" 总股票数: {result['total_symbols']}") + logger.info(f" 总周期数: {result['total_periods']}") + logger.info(f" 成功数量: {result['success_count']}") + logger.info(f" 失败数量: {result['failed_count']}") + logger.info(f" 总记录数: {result['total_records']}") + + # 显示详细信息 + if result["details"]: + logger.info(f"\n详细信息:") + for detail in result["details"]: + status = "✓" if detail.get("success", False) else "✗" + logger.info( + f" {status} {detail['symbol']} - {detail['period']}: " + f"{detail.get('records', 0)} 条 " + f"({detail.get('message', 'N/A')})" + ) + + logger.info(f"\n{'=' * 60}") + logger.info("历史数据下载完成") + logger.info(f"{'=' * 60}") + + return result + + except Exception as e: + logger.error(f"下载失败: {e}", exc_info=True) + raise + + +def verify_downloaded_data(): + """验证下载的数据""" + + logger.info(f"\n{'=' * 60}") + logger.info("验证已下载的数据") + logger.info(f"{'=' * 60}") + + symbols = ["601658.SH", "159915.SZ"] + start_date = datetime(2025, 12, 1) + end_date = datetime(2025, 12, 15) + period = "1m" + + try: + # 查询数据 + klines = DataProvider.get_klines( + symbols=symbols, start_date=start_date, end_date=end_date, period=period + ) + + logger.info(f"\n数据验证结果:") + for symbol, df in klines.items(): + if df.empty: + logger.warning(f" ✗ {symbol}: 无数据") + else: + logger.info(f" ✓ {symbol}: {len(df)} 条记录") + logger.info(f" 时间范围: {df.index[0]} ~ {df.index[-1]}") + logger.info(f" 数据示例:") + logger.info(f"{df.head(3).to_string()}") + + return klines + + except Exception as e: + logger.error(f"验证失败: {e}", exc_info=True) + raise + + +def query_existing_data(): + """查询已有数据并打印""" + + logger.info("=" * 60) + logger.info("查询数据库中的历史数据") + logger.info("=" * 60) + + # 股票列表 + symbols = ["601658.SH", "159915.SZ"] + + # 时间范围 + start_date = datetime(2025, 12, 1) + end_date = datetime(2025, 12, 15) + + # 周期 + period = "1m" + + logger.info(f"\n查询配置:") + logger.info(f" 股票代码: {', '.join(symbols)}") + logger.info(f" 时间范围: {start_date.date()} ~ {end_date.date()}") + logger.info(f" 数据周期: {period}") + + try: + # 使用 DataProvider 查询数据 + klines = DataProvider.get_klines( + symbols=symbols, start_date=start_date, end_date=end_date, period=period + ) + + logger.info(f"\n查询结果:") + logger.info("=" * 60) + + for symbol, df in klines.items(): + if df.empty: + logger.warning(f"\n{symbol}: 无数据") + else: + logger.info(f"\n{symbol}:") + logger.info(f" 数据条数: {len(df)} 条") + logger.info(f" 时间范围: {df.index[0]} ~ {df.index[-1]}") + logger.info(f" 数据列: {', '.join(df.columns.tolist())}") + logger.info(f"\n 前5条数据:") + logger.info(f"\n{df.head(5).to_string()}") + logger.info(f"\n 后5条数据:") + logger.info(f"\n{df.tail(5).to_string()}") + + # 统计信息 + logger.info(f"\n 统计信息:") + logger.info( + f" 开盘价: {df['open'].min():.2f} ~ {df['open'].max():.2f}" + ) + logger.info( + f" 最高价: {df['high'].min():.2f} ~ {df['high'].max():.2f}" + ) + logger.info( + f" 最低价: {df['low'].min():.2f} ~ {df['low'].max():.2f}" + ) + logger.info( + f" 收盘价: {df['close'].min():.2f} ~ {df['close'].max():.2f}" + ) + logger.info(f" 成交量: {df['volume'].sum():,.0f}") + + logger.info("\n" + "=" * 60) + return klines + + except Exception as e: + logger.error(f"查询失败: {e}", exc_info=True) + raise + + +def main(): + """主函数""" + + # 初始化配置(使用回测环境) + logger.info("初始化配置...") + config = Config() + config.load_with_global("configs/backtest.yaml") + set_config(config) + logger.info(f"✓ 配置加载完成: {config.get('app.name')}") + + # 第一步:尝试查询已有数据(如果表不存在会报错,直接跳到下载) + logger.info("\n" + "=" * 60) + logger.info("第一步:查询数据库中的现有数据") + logger.info("=" * 60) + + klines = {} + need_download = True + + try: + klines = query_existing_data() + # 检查是否需要下载数据 + need_download = any(df.empty for df in klines.values()) + except Exception as e: + logger.warning(f"查询失败(表可能不存在),直接进入下载流程: {e}") + need_download = True + + if need_download: + # 第二步:检查 token 并下载数据 + logger.info("\n" + "=" * 60) + logger.info("第二步:下载历史数据") + logger.info("=" * 60) + + token = config.get("qmt.xtquant_token") + if not token: + logger.error("\n" + "=" * 60) + logger.error("XtQuant token 未配置!") + logger.error("=" * 60) + logger.error("\n请按以下步骤配置:") + logger.error("1. 打开 configs/global.yaml 文件") + logger.error("2. 在 qmt 配置节点下设置 xtquant_token") + logger.error("3. 如果还没有 token,请访问 XtQuant 官网申请") + logger.error("\n示例配置:") + logger.error("qmt:") + logger.error(' xtquant_token: "your_token_here"') + logger.error("\n" + "=" * 60) + return + + # 下载数据 + download_historical_data() + + # 第三步:验证下载的数据 + logger.info("\n" + "=" * 60) + logger.info("第三步:验证下载的数据") + logger.info("=" * 60) + verify_downloaded_data() + else: + logger.info("\n✓ 数据库中已有完整数据,无需下载") + + logger.info("\n✓ 所有任务完成!") + + +if __name__ == "__main__": + main() diff --git a/tests/temp/test_xtquant_downloader.py b/tests/temp/test_xtquant_downloader.py index 674b11c..ad96431 100644 --- a/tests/temp/test_xtquant_downloader.py +++ b/tests/temp/test_xtquant_downloader.py @@ -23,21 +23,25 @@ os.environ["CONFIG_FILE"] = "configs/backtest.yaml" from src.data_provider import XtQuantDownloader # noqa: E402 from src.database_manager import DatabaseManager # noqa: E402 +from src.core.config import Config, set_config # noqa: E402 print("=" * 70) print("测试 XtQuant 数据下载器") print("=" * 70) -# XtQuant Token -token = "e83d8eec5226c0b4db4a1d40830e09e4ffe73e15" +# 初始化配置 +config = Config() +config.load_with_global("configs/backtest.yaml") +set_config(config) -# 优化地址 -optimize_addresses = [ - "115.231.218.73:55310", - "115.231.218.79:55310", - "218.16.123.11:55310", - "218.16.123.27:55310", -] +# XtQuant Token(从配置文件读取) +token = config.get("qmt.xtquant_token") +if not token: + print("错误: 请在 configs/global.yaml 中配置 qmt.xtquant_token") + sys.exit(1) + +# 优化地址(从配置文件读取) +optimize_addresses = config.get("qmt.optimize_addresses", []) # 测试1: 初始化下载器 print("\n测试1: 初始化 XtQuant 下载器")