QTrade/test_dataservice.py
cuizhan 199f0ba2ce feat: 实现常量体系和指标自动更新机制
主要更新:
- 新增 src/core/constants.py: 统一管理所有字符串常量(Period, IndicatorType, KlineColumns, IndicatorColumns)
- 统一命名规范: 所有指标类型和列名使用小写格式
- 实现 DataService.from_config() 工厂方法,自动初始化所有依赖组件
- 实现下载数据后自动重新计算指标功能
- 更新所有指标计算器使用 IndicatorColumns 常量定义列名
- 修复 table_schemas.py 表名格式bug (indicators_{period}_{indicator})
- 新增数据库清理脚本,删除旧格式的指标表
- 优化配置文件,调整指标参数

文档:
- docs/constants_guide.md: 常量使用指南
- docs/cache_storage_layout.md: 缓存和存储架构说明
2025-12-23 17:56:01 +08:00

217 lines
6.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.

"""
测试DataService功能
测试项目:
1. DataService初始化
2. 获取K线数据(缓存、数据库、下载)
3. 数据完整性验证
4. 指标计算和更新
5. 缓存机制
"""
import sys
from datetime import datetime
from src.core.config import Config
from src.data_service import DataService
from src.core.constants import Period, IndicatorType
print("=" * 80)
print("DataService 功能测试")
print("=" * 80)
# ========== 测试1: 初始化 ==========
print("\n【测试1】DataService初始化")
print("-" * 80)
try:
config = Config()
config.load_with_global("configs/backtest.yaml")
print("✓ 配置加载成功")
service = DataService.from_config(config)
print("✓ DataService初始化成功")
print(f" - Storage: {type(service.storage).__name__}")
print(f" - Cache: {type(service.cache).__name__}")
print(f" - Validator: {type(service.validator).__name__}")
print(f" - Downloader: {type(service.downloader).__name__}")
print(f" - IndicatorManager: {type(service.indicator_manager).__name__}")
except Exception as e:
print(f"✗ 初始化失败: {e}")
import traceback
traceback.print_exc()
sys.exit(1)
# ========== 测试2: 获取K线数据 ==========
print("\n【测试2】获取K线数据")
print("-" * 80)
test_symbol = "601658.SH"
test_period = Period.DAY_1
start_date = datetime(2024, 1, 1)
end_date = datetime(2024, 3, 31)
print(f"查询参数:")
print(f" - 标的: {test_symbol}")
print(f" - 周期: {test_period}")
print(f" - 时间: {start_date.date()} ~ {end_date.date()}")
try:
klines = service.get_klines(test_symbol, test_period, start_date, end_date)
if klines is not None and not klines.empty:
print(f"✓ 数据获取成功")
print(f" - 记录数: {len(klines)}")
print(f" - 时间范围: {klines.index[0]} ~ {klines.index[-1]}")
print(f" - 列名: {list(klines.columns)}")
print(f"\n前3条数据:")
print(klines.head(3))
else:
print("✗ 未获取到数据")
except Exception as e:
print(f"✗ 获取数据失败: {e}")
import traceback
traceback.print_exc()
# ========== 测试3: 缓存验证 ==========
print("\n【测试3】缓存验证")
print("-" * 80)
try:
# 第二次获取相同数据,应该从缓存返回
import time
start_time = time.time()
klines2 = service.get_klines(test_symbol, test_period, start_date, end_date)
elapsed = time.time() - start_time
if klines2 is not None:
print(f"✓ 缓存获取成功")
print(f" - 耗时: {elapsed * 1000:.2f}ms")
print(f" - 记录数: {len(klines2)}")
# 检查缓存统计
stats = service.get_stats()
print(f" - 缓存状态: {stats}")
else:
print("✗ 缓存获取失败")
except Exception as e:
print(f"✗ 缓存测试失败: {e}")
import traceback
traceback.print_exc()
# ========== 测试4: 不同周期数据 ==========
print("\n【测试4】获取不同周期数据")
print("-" * 80)
periods_to_test = [Period.MIN_5, Period.MIN_15, Period.DAY_1]
test_start = datetime(2024, 12, 1)
test_end = datetime(2024, 12, 15)
for period in periods_to_test:
try:
print(f"\n测试周期: {period}")
klines = service.get_klines(test_symbol, period, test_start, test_end)
if klines is not None and not klines.empty:
print(f" ✓ 成功 - {len(klines)} 条记录")
else:
print(f" ⊗ 无数据")
except Exception as e:
print(f" ✗ 失败: {e}")
# ========== 测试5: 获取指标数据 ==========
print("\n【测试5】获取指标数据")
print("-" * 80)
if klines is not None and not klines.empty:
indicators_to_test = [
IndicatorType.MACD,
IndicatorType.KDJ,
IndicatorType.BOLL,
IndicatorType.RSI,
]
for indicator_name in indicators_to_test:
try:
print(f"\n测试指标: {indicator_name}")
indicator_data = service.get_indicator(
test_symbol, test_period, indicator_name, start=start_date, end=end_date
)
if indicator_data is not None and not indicator_data.empty:
print(f" ✓ 成功 - {len(indicator_data)} 条记录")
print(f" - 列名: {list(indicator_data.columns)}")
print(f" 前3行:")
print(indicator_data.head(3))
else:
print(f" ⊗ 无数据(可能需要先计算)")
except Exception as e:
print(f" ✗ 失败: {e}")
import traceback
traceback.print_exc()
else:
print("跳过指标测试(无K线数据)")
# ========== 测试6: 批量获取 ==========
print("\n【测试6】批量获取多标的数据")
print("-" * 80)
symbols = ["601658.SH", "159915.SZ"]
try:
print(f"批量获取: {symbols}")
multi_data = service.get_multiple(symbols, test_period, start_date, end_date)
print(f"✓ 批量获取完成")
for symbol, data in multi_data.items():
if data is not None:
print(f" - {symbol}: {len(data)} 条记录")
else:
print(f" - {symbol}: 无数据")
except Exception as e:
print(f"✗ 批量获取失败: {e}")
import traceback
traceback.print_exc()
# ========== 测试7: 健康检查 ==========
print("\n【测试7】系统健康检查")
print("-" * 80)
try:
health = service.health_check()
print("健康状态:")
for component, status in health.items():
status_icon = "✓" if status else "✗"
print(f" {status_icon} {component}: {status}")
except Exception as e:
print(f"✗ 健康检查失败: {e}")
# ========== 测试8: 数据存在性检查 ==========
print("\n【测试8】数据存在性检查")
print("-" * 80)
try:
exists = service.exists(test_symbol, test_period, start_date, end_date)
print(f"数据存在性: {'存在' if exists else '不存在'}")
date_range = service.get_date_range(test_symbol, test_period)
if date_range:
print(f"数据时间范围: {date_range[0]} ~ {date_range[1]}")
else:
print("无数据范围信息")
except Exception as e:
print(f"✗ 检查失败: {e}")
# ========== 测试总结 ==========
print("\n" + "=" * 80)
print("测试完成")
print("=" * 80)
print("\n提示:")
print("- 如果某些测试失败,可能是因为数据库中没有对应数据")
print("- 可以使用 download_klines() 方法先下载数据")
print("- 指标数据需要先计算才能获取")