QTrade/tests/temp/test_xtquant_downloader.py
cuizhan 552eca59f6 refactor(config): 重构XtQuant配置位置
变更说明:
- 将 XtQuant 相关配置从 qmt 节点移到 data_source.xtquant 节点
- 配置项包括:
  * xtquant_path: XtQuant 数据目录路径
  * xtquant_token: XtQuant API Token
  * optimize_addresses: 优化地址列表

- 更新相关代码读取配置的路径:
  * xtquant_downloader.py: 从 data_source.xtquant 读取配置
  * test_xtquant_downloader.py: 更新测试配置路径

- qmt 节点仅保留交易相关配置(account_type)

设计理念:
- data_source.xtquant: 数据下载器配置
- qmt: QMT交易客户端配置
- 职责分离,配置结构更清晰
2025-12-17 15:46:10 +08:00

179 lines
5.4 KiB
Python
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

"""
测试 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("data_source.xtquant.xtquant_token")
if not token:
print("错误: 请在 configs/global.yaml 中配置 data_source.xtquant.xtquant_token")
sys.exit(1)
# 优化地址(从配置文件读取)
optimize_addresses = config.get("data_source.xtquant.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)