You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

使用backtrader导入毫秒时间戳CSV时报时间戳转日期错误如何解决?

错误原因

你提供的首列时间戳为13位毫秒级Unix时间戳,而backtrader的GenericCSVData中dtformat=1默认适配10位秒级Unix时间戳,直接传入13位整数会超出datetime.utcfromtimestamp的合法输入范围,因此抛出OSError: [Errno 22] Invalid argument报错。你尝试使用的dtformat=2适配的是带小数的秒级时间戳,直接传入13位整数同样会因为数值超限报错。

解决方案

通过自定义时间转换函数处理毫秒级时间戳即可,同时要注意匹配你的CSV列结构,忽略不需要的默认字段:

  1. 自定义转换函数将13位毫秒时间戳除以1000转为秒级,再完成时间转换
  2. 你的CSV数据没有openinterest(持仓兴趣)字段,需要显式指定为-1让backtrader忽略该列,避免字段错配

修正后完整代码

import backtrader as bt
from datetime import datetime

# 自定义毫秒时间戳转UTC时间函数
def millisec_to_dt(x):
    return datetime.utcfromtimestamp(int(x) // 1000)

cerebro = bt.Cerebro()
cerebro.broker.setcash(1000)

data = bt.feeds.GenericCSVData(
    dataname="./file.csv",
    dtformat=1,
    dtconvert=millisec_to_dt, # 传入自定义转换逻辑
    openinterest=-1 # 忽略不存在的持仓兴趣列
)

print('Starting Portfolio Value: %.2f' % cerebro.broker.getvalue())
cerebro.adddata(data)
cerebro.run()
cerebro.plot()
print('Final Portfolio Value: %.2f' % cerebro.broker.getvalue())

可选补充说明

如果你的时间戳为东八区或其他非UTC时区的时间,将转换函数中的utcfromtimestamp替换为fromtimestamp即可适配本地时区。

内容的提问来源于stack exchange,提问作者Apollo

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.09.26 19:54:04