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

backtesting.py绘图函数异常求助:Bokeh版本兼容问题排查

Backtesting.py 运行时Bokeh版本兼容警告问题

问题描述

我在学习backtesting.py时,运行示例代码弹出一系列Bokeh相关警告信息,尝试卸载并重新安装旧版本Bokeh后仍未解决。

报错信息

BokehDeprecationWarning: Passing lists of formats for DatetimeTickFormatter scales was deprecated in Bokeh 3.0. Configure a single string format for each scale
C:\Users\paul_\AppData\Local\Programs\Python\Python310\lib\site-packages\bokeh\models\formatters.py:399: UserWarning: DatetimeFormatter scales now only accept a single format. Using the first prodvided: '%d %b'
  warnings.warn(f"DatetimeFormatter scales now only accept a single format. Using the first prodvided: {fmt[0]!r} ")
BokehDeprecationWarning: Passing lists of formats for DatetimeTickFormatter scales was deprecated in Bokeh 3.0. Configure a single string format for each scale
C:\Users\paul_\AppData\Local\Programs\Python\Python310\lib\site-packages\bokeh\models\formatters.py:399: UserWarning: DatetimeFormatter scales now only accept a single format. Using the first prodvided: '%m/%Y'
  warnings.warn(f"DatetimeFormatter scales now only accept a single format. Using the first prodvided: {fmt[0]!r} ")
GridPlot(id='p11925', ...)

示例代码

import bokeh
import datetime
import pandas_ta as ta
import pandas as pd

from backtesting import Backtest
from backtesting import Strategy
from backtesting.lib import crossover
from backtesting.test import GOOG

class RsiOscillator(Strategy):

    upper_bound = 70
    lower_bound = 30
    rsi_window = 14

    # 提前完成初始计算
    def init(self):
        self.rsi = self.I(ta.rsi, pd.Series(self.data.Close), self.rsi_window)

    # 逐根K线处理
    def next(self):
        if crossover(self.rsi, self.upper_bound):
            self.position.close()
        elif crossover(self.lower_bound, self.rsi):
            self.buy()

bt = Backtest(GOOG, RsiOscillator, cash=10_000, commission=.002)
stats = bt.run()
bt.plot()

解决方法

方法1:安装兼容版本的Bokeh

backtesting.py部分版本未适配Bokeh 3.0+的API变更,指定安装Bokeh 2.x稳定版本即可:

pip uninstall -y bokeh
pip install bokeh==2.4.3

方法2:临时屏蔽警告

如果不想调整版本,可在代码最开头添加警告抑制代码,直接屏蔽Bokeh的弃用警告:

import warnings
warnings.filterwarnings("ignore", category=DeprecationWarning, module="bokeh")
warnings.filterwarnings("ignore", category=UserWarning, module="bokeh")

方法3:修改backtesting源码(不推荐)

找到backtesting库中调用DatetimeTickFormatter的代码位置,将传入的格式列表改为单个字符串。比如把:

formatter = DatetimeTickFormatter(days=["%d %b"], months=["%m/%Y"])

修改为:

formatter = DatetimeTickFormatter(days="%d %b", months="%m/%Y")

注意:后续库更新会覆盖修改,仅作为临时应急方案。

内容的提问来源于stack exchange,提问作者Ka Meng Ng

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.13 15:31:01