主要改进: 1. 架构重构 - 按周期分表存储 - 创建 table_utils.py 提供动态表名生成工具 - 支持7个周期的K线表: klines_1m, klines_5m, klines_15m, klines_30m, klines_60m, klines_1d, klines_1w - 支持6个指标库的分表: macd, kdj, rsi, boll, ma, ema (每个指标7个周期) - 动态生成49个周期表定义 2. 数据访问层更新 - 更新 data_provider.py 中10处SQL查询使用动态表名 - 更新 base_downloader.py 自动创建所有周期表 - 修改数据插入逻辑使用正确的周期表 3. 时间戳处理修复 - 修复 XtQuant 返回字符串时间戳(YYYYMMDDHHMMSS)解析问题 - 添加字符串转datetime支持: datetime.strptime(timestamp, '%Y%m%d%H%M%S') - 兼容 pandas Timestamp 和 datetime 对象 4. 配置更新 - 添加 XtQuant token 到 configs/global.yaml - 添加优化地址配置 5. 主程序完善 - 创建 src/main.py 实现完整的数据下载工作流 - 支持查询现有数据、下载历史数据、验证数据 - 错误处理和日志输出优化 测试结果: - 成功下载 5302 条1分钟K线数据 - 时间范围: 2025-12-01 09:30:00 ~ 2025-12-15 15:00:00 - 601658.SH (邮储银行): 2651条 - 159915.SZ (创业板ETF): 2651条 - 数据验证通过,时间戳正确
179 lines
5.3 KiB
Python
179 lines
5.3 KiB
Python
"""
|
||
测试 XtQuant 数据下载器
|
||
"""
|
||
|
||
import sys
|
||
import os
|
||
from pathlib import Path
|
||
from datetime import datetime
|
||
|
||
# 设置输出编码(必须在最开始)
|
||
if sys.platform == "win32":
|
||
import io
|
||
|
||
sys.stdout = io.TextIOWrapper(sys.stdout.buffer, encoding="utf-8")
|
||
sys.stderr = io.TextIOWrapper(sys.stderr.buffer, encoding="utf-8")
|
||
|
||
# 添加项目根目录到路径
|
||
project_root = Path(__file__).parent.parent.parent
|
||
sys.path.insert(0, str(project_root))
|
||
|
||
# 设置环境变量
|
||
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)
|
||
|
||
# 初始化配置
|
||
config = Config()
|
||
config.load_with_global("configs/backtest.yaml")
|
||
set_config(config)
|
||
|
||
# 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 下载器")
|
||
try:
|
||
downloader = XtQuantDownloader(
|
||
symbols=["000001.SZ", "600000.SH"],
|
||
start_date="2024-12-01",
|
||
end_date="2024-12-15",
|
||
periods=["1d"],
|
||
database="qtrade_backtest",
|
||
token=token,
|
||
optimize_addresses=optimize_addresses,
|
||
)
|
||
print("✓ 下载器初始化成功")
|
||
print(f" 标的: {downloader.symbols}")
|
||
print(f" 时间范围: {downloader.start_date.date()} ~ {downloader.end_date.date()}")
|
||
print(f" 周期: {downloader.periods}")
|
||
print(f" 数据库: {downloader.database}")
|
||
except Exception as e:
|
||
print(f"✗ 初始化失败: {e}")
|
||
import traceback
|
||
|
||
traceback.print_exc()
|
||
sys.exit(1)
|
||
|
||
# 测试2: 下载并保存数据
|
||
print("\n测试2: 下载并保存数据")
|
||
try:
|
||
stats = downloader.download_and_save()
|
||
|
||
print("\n下载统计:")
|
||
print(f" 成功: {stats['success_count']}")
|
||
print(f" 失败: {stats['failed_count']}")
|
||
print(f" 总记录数: {stats['total_records']}")
|
||
|
||
print("\n详细信息:")
|
||
for detail in stats["details"]:
|
||
if detail["status"] == "success":
|
||
print(
|
||
f" ✓ {detail['symbol']} [{detail['period']}]: "
|
||
f"下载 {detail['downloaded']}, 保存 {detail['saved']}"
|
||
)
|
||
else:
|
||
print(f" ✗ {detail['symbol']} [{detail['period']}]: {detail['status']}")
|
||
|
||
except Exception as e:
|
||
print(f"✗ 下载失败: {e}")
|
||
import traceback
|
||
|
||
traceback.print_exc()
|
||
sys.exit(1)
|
||
|
||
# 测试3: 验证数据已保存到数据库
|
||
print("\n测试3: 验证数据已保存到数据库")
|
||
try:
|
||
db = DatabaseManager()
|
||
|
||
if db.table_exists("qtrade_backtest", "klines"):
|
||
from sqlalchemy import create_engine, text
|
||
from src.core.config import Config
|
||
|
||
config = Config()
|
||
connection_url = (
|
||
f"mysql+pymysql://{config.get('database.user')}:"
|
||
f"{config.get('database.password')}@"
|
||
f"{config.get('database.host')}:{config.get('database.port')}"
|
||
f"/qtrade_backtest?charset=utf8mb4"
|
||
)
|
||
engine = create_engine(connection_url)
|
||
|
||
with engine.connect() as conn:
|
||
# 查询总记录数
|
||
result = conn.execute(text("SELECT COUNT(*) FROM klines"))
|
||
row = result.fetchone()
|
||
total_count = row[0] if row else 0
|
||
|
||
# 查询标的列表
|
||
result = conn.execute(
|
||
text(
|
||
"SELECT DISTINCT symbol FROM klines "
|
||
"WHERE DATE(timestamp) >= '2024-12-01' "
|
||
"AND DATE(timestamp) <= '2024-12-15' "
|
||
"ORDER BY symbol"
|
||
)
|
||
)
|
||
symbols = [row[0] for row in result]
|
||
|
||
# 查询周期列表
|
||
result = conn.execute(text("SELECT DISTINCT period FROM klines"))
|
||
periods = [row[0] for row in result]
|
||
|
||
# 查询最新数据样本
|
||
result = conn.execute(
|
||
text(
|
||
"SELECT * FROM klines "
|
||
"WHERE timestamp >= '2024-12-01' "
|
||
"ORDER BY timestamp DESC LIMIT 5"
|
||
)
|
||
)
|
||
samples = result.fetchall()
|
||
|
||
print("✓ 数据库验证:")
|
||
print(f" 总记录数: {total_count}")
|
||
print(f" 本次下载标的: {symbols}")
|
||
print(f" 周期: {periods}")
|
||
|
||
if samples:
|
||
print(f"\n 最新数据样本(前5条):")
|
||
for sample in samples:
|
||
print(
|
||
f" {sample[1]} [{sample[2]}] {sample[3]}: "
|
||
f"O={sample[4]:.2f} H={sample[5]:.2f} "
|
||
f"L={sample[6]:.2f} C={sample[7]:.2f} V={sample[8]}"
|
||
)
|
||
|
||
engine.dispose()
|
||
db.close()
|
||
else:
|
||
print("✗ klines 表不存在")
|
||
|
||
except Exception as e:
|
||
print(f"✗ 验证失败: {e}")
|
||
import traceback
|
||
|
||
traceback.print_exc()
|
||
|
||
# 测试4: 清理连接
|
||
print("\n测试4: 清理连接")
|
||
downloader.close()
|
||
print("✓ 连接已关闭")
|
||
|
||
print("\n" + "=" * 70)
|
||
print("✅ XtQuant 数据下载器测试完成!")
|
||
print("=" * 70)
|