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

backtrader加载15分钟K线时所有蜡烛时间一致问题求助

问题:backtrader加载15分钟BTC K线时所有蜡烛时间一致

使用GenericCSVData加载BTCUSDT-15m-2022-01-01.csv的15分钟K线数据时,所有蜡烛的时间被统一设置为同一个值。

我的代码

data15 = bt.feeds.GenericCSVData(dataname='BTCUSDT-15m-2022-01-01.csv',
dtformat=lambda x: datetime.utcfromtimestamp(int(x)/1000))

排查分析

查看csvgeneric.py中的时间处理逻辑:

dt = datetime.strptime(dtfield, dtformat)
else:
    dt = self._dtconvert(dtfield)

if self.p.timeframe >= TimeFrame.Days:
    # check if the expected end of session is larger than parsed
    if self._tzinput:
        dtin = self._tzinput.localize(dt)  # pytz compatible-ized
    else:
        dtin = dt

    dtnum = date2num(dtin)  # utc'ize

    dteos = datetime.combine(dt.date(), self.p.sessionend)
    dteosnum = self.date2num(dteos)  # utc'ize

    if dteosnum > dtnum:
        self.lines.datetime[0] = dteosnum

验证后发现,单根K线的dt、dtin、dtnum均为正确的15分钟时间戳,但dteosnum始终等于当日会话结束时间(默认是16:00),且该值大于所有15分钟K线的时间戳,导致所有蜡烛时间被强制替换为dteosnum。

解决方案

问题出在backtrader默认将数据识别为日线级别,触发了针对日线及以上周期的会话时间修正逻辑。只需在初始化GenericCSVData时显式指定时间框架和压缩参数:

import backtrader as bt
from backtrader import TimeFrame

data15 = bt.feeds.GenericCSVData(
    dataname='BTCUSDT-15m-2022-01-01.csv',
    dtformat=lambda x: datetime.utcfromtimestamp(int(x)/1000),
    timeframe=TimeFrame.Minutes,
    compression=15
)

通过timeframe=TimeFrame.Minutes指定为分钟周期,compression=15定义每根K线代表15分钟,让backtrader跳过日线级别的时间修正,直接使用原始K线时间戳即可解决问题。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.17 04:55:30