QTrade/tests/temp/test_ensure_klines.py
cuizhan 1c35db7752 feat: 实现DataProvider数据访问层,优化DatabaseManager连接池
- 创建DataProvider静态类,提供统一的数据查询接口
- 支持批量查询多股票,返回Dict[str, DataFrame]格式
- 实现ensure_klines智能数据检查和save_klines批量保存
- 优化DatabaseManager使用连接池(pool_size=5, pool_pre_ping=True)
- 将数据下载器移至data_downloader子文件夹
- 添加数据库连接设计文档
- 创建测试用例验证功能完整性
2025-12-16 17:01:04 +08:00

230 lines
6.5 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.

"""
测试 DataProvider.ensure_klines 方法
"""
import os
import sys
from datetime import datetime
# 添加项目根目录到系统路径
project_root = os.path.dirname(
os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
)
sys.path.insert(0, project_root)
from src.data_provider import DataProvider, DataNotFoundError
def test_ensure_klines_with_existing_data():
"""测试获取存在的数据"""
print("\n" + "=" * 60)
print("测试1: 获取存在的数据")
print("=" * 60)
symbols = ["000001.SZ", "600000.SH"]
start_date = datetime(2024, 1, 1)
end_date = datetime(2024, 1, 10)
period = "1d"
try:
# 获取数据(存在的数据)
klines = DataProvider.ensure_klines(
symbols=symbols,
start_date=start_date,
end_date=end_date,
period=period,
raise_if_missing=False,
)
print(f"\n返回结果: {len(klines)} 只股票")
for symbol, df in klines.items():
if df.empty:
print(f" {symbol}: ✗ 无数据")
else:
print(f" {symbol}: ✓ 有数据 ({len(df)} 条)")
print(f" 时间范围: {df.index[0]} ~ {df.index[-1]}")
except Exception as e:
print(f"❌ 测试失败: {e}")
import traceback
traceback.print_exc()
def test_ensure_klines_with_missing_data():
"""测试获取不存在的数据(不抛异常)"""
print("\n" + "=" * 60)
print("测试2: 获取不存在的数据(返回空)")
print("=" * 60)
symbols = ["000001.SZ", "999999.SZ"] # 999999.SZ 不存在
start_date = datetime(2024, 1, 1)
end_date = datetime(2024, 1, 10)
period = "1d"
try:
klines = DataProvider.ensure_klines(
symbols=symbols,
start_date=start_date,
end_date=end_date,
period=period,
raise_if_missing=False, # 不抛异常
)
print(f"\n返回结果: {len(klines)} 只股票")
for symbol, df in klines.items():
if df.empty:
print(f" {symbol}: ✗ 无数据(返回空DataFrame)")
else:
print(f" {symbol}: ✓ 有数据 ({len(df)} 条)")
except Exception as e:
print(f"❌ 测试失败: {e}")
import traceback
traceback.print_exc()
def test_ensure_klines_raise_if_missing():
"""测试获取不存在的数据(抛异常)"""
print("\n" + "=" * 60)
print("测试3: 获取不存在的数据(抛出异常)")
print("=" * 60)
symbols = ["999999.SZ", "888888.SH"] # 都不存在
start_date = datetime(2024, 1, 1)
end_date = datetime(2024, 1, 10)
period = "1d"
try:
klines = DataProvider.ensure_klines(
symbols=symbols,
start_date=start_date,
end_date=end_date,
period=period,
raise_if_missing=True, # 抛异常
)
print(f"❌ 应该抛出异常但没有抛出")
except DataNotFoundError as e:
print(f"✓ 正确抛出 DataNotFoundError:")
print(f" {e}")
except Exception as e:
print(f"❌ 抛出了错误的异常类型: {type(e).__name__}")
print(f" {e}")
def test_ensure_klines_check_and_download():
"""测试典型使用场景:检查数据并决定是否下载"""
print("\n" + "=" * 60)
print("测试4: 检查数据并决定是否需要下载")
print("=" * 60)
symbols = ["000001.SZ", "600000.SH", "000002.SZ", "999999.SZ"]
start_date = datetime(2024, 1, 1)
end_date = datetime(2024, 1, 10)
period = "1d"
try:
# 获取数据
klines = DataProvider.ensure_klines(
symbols=symbols,
start_date=start_date,
end_date=end_date,
period=period,
raise_if_missing=False,
)
# 检查哪些需要下载
need_download = []
has_data = []
for symbol, df in klines.items():
if df.empty:
need_download.append(symbol)
else:
has_data.append(symbol)
print(f"\n数据统计:")
print(f" 已有数据: {len(has_data)} 只")
for symbol in has_data:
print(f" - {symbol}: {len(klines[symbol])} 条")
print(f"\n 需要下载: {len(need_download)} 只")
for symbol in need_download:
print(f" - {symbol}")
if need_download:
print(f"\n建议操作:")
print(f" 可使用 DataDownloader 下载以下股票:")
for symbol in need_download:
print(
f" downloader.download('{symbol}', '{start_date.date()}', '{end_date.date()}', '{period}')"
)
except Exception as e:
print(f"❌ 测试失败: {e}")
import traceback
traceback.print_exc()
def test_ensure_klines_batch_check():
"""测试批量检查多只股票"""
print("\n" + "=" * 60)
print("测试5: 批量检查多只股票")
print("=" * 60)
# 模拟从策略中获取的股票池
stock_pool = ["000001.SZ", "000002.SZ", "600000.SH"]
start_date = datetime(2024, 1, 1)
end_date = datetime(2024, 1, 10)
period = "1d"
try:
klines = DataProvider.ensure_klines(
symbols=stock_pool,
start_date=start_date,
end_date=end_date,
period=period,
)
# 统计数据完整性
total = len(stock_pool)
complete = sum(1 for df in klines.values() if not df.empty)
missing = total - complete
print(f"\n股票池数据完整性:")
print(f" 总数: {total} 只")
print(f" 完整: {complete} 只 ({complete / total * 100:.1f}%)")
print(f" 缺失: {missing} 只 ({missing / total * 100:.1f}%)")
if missing == 0:
print(f"\n✓ 所有股票数据完整,可以开始回测")
else:
print(f"\n⚠ 部分股票数据缺失,建议先下载数据")
except Exception as e:
print(f"❌ 测试失败: {e}")
import traceback
traceback.print_exc()
if __name__ == "__main__":
print("\n" + "=" * 60)
print("开始测试 DataProvider.ensure_klines()")
print("=" * 60)
test_ensure_klines_with_existing_data()
test_ensure_klines_with_missing_data()
test_ensure_klines_raise_if_missing()
test_ensure_klines_check_and_download()
test_ensure_klines_batch_check()
print("\n" + "=" * 60)
print("所有测试完成")
print("=" * 60)