问题描述
xtdata.download_history_data2(stock_list=stock_list, period=period, start_time=start_time, end_time=end_time, callback=f)
反馈一个 download_history_data2 的 BUG,如果 start_time 参数格式不对,函数就是卡死。
start_time=2025-02-25 如果输入这个格式的时间,函数就会卡死。
解决方案
感谢您的反馈!这是一个在 QMT/xtdata 使用过程中非常常见的问题。
问题原因分析
在 QMT 的底层 C++ 接口中,时间字符串的解析有着严格的格式要求。当您传入 2025-02-25 这种带有连字符 - 的格式时,底层解析器无法正确识别,且未能及时抛出 Python 级别的异常(Exception),从而导致底层线程陷入死循环或阻塞,表现出来的现象就是函数卡死。
正确的时间格式规范
根据 QMT API 文档规范,所有涉及时间字符串的参数(如 start_time, end_time),其标准格式必须是:
- 年月日:
YYYYMMDD(例如:20250225) - 年月日时分秒:
YYYYMMDDHHMMSS(例如:20250225093000)
绝对不能包含连字符 -、空格或冒号 : 等特殊字符。
解决方案与代码建议
为了避免这种卡死现象,建议在调用 download_history_data2 或其他获取数据的接口前,统一对时间字符串进行格式化清洗。您可以使用 Python 的 replace 方法或 datetime 模块来确保格式正确。
示例代码:
import datetime
from xtquant import xtdata
def safe_download_history(stock_list, period, start_time, end_time, callback=None):
# 1. 清洗时间字符串,移除常见的非法字符
clean_start = str(start_time).replace('-', '').replace(' ', '').replace(':', '')
clean_end = str(end_time).replace('-', '').replace(' ', '').replace(':', '')
print(f"准备下载数据,清洗后的时间: start={clean_start}, end={clean_end}")
# 2. 调用下载函数
try:
xtdata.download_history_data2(
stock_list=stock_list,
period=period,
start_time=clean_start,
end_time=clean_end,
callback=callback
)
print("下载任务已提交/完成")
except Exception as e:
print(f"下载发生异常: {e}")
# 测试调用
stock_list = ['000001.SZ']
period = '1d'
# 即使传入了带连字符的错误格式,也会被清洗为 20250225
bad_start_time = '2025-02-25'
bad_end_time = '2025-02-28'
safe_download_history(stock_list, period, bad_start_time, bad_end_time)
总结
在编写 QMT 策略或使用 xtdata 脚本时,养成严格校验和清洗时间参数的习惯,可以有效避免此类底层卡死的问题。同时,我们也会将此缺乏异常抛出的体验问题记录,期待官方在后续版本中增加对非法时间格式的报错提示,而不是直接卡死。