
第一段引用上面的摘要:
本文旨在解决在使用Backtesting库在Jupyter Notebook、Spyder或PyCharm等环境中进行回测时,Backtest.run()和Backtest.plot()方法只返回对象信息,而不显示回测结果和图表的问题。通过分析常见原因和提供解决方案,帮助读者成功运行Backtesting回测并可视化结果。
当你在Jupyter Notebook或类似的IDE(如Spyder, PyCharm)中使用backtesting.backtesting.Backtest 对象的 run() 和 plot() 方法时,可能会遇到只返回对象信息(例如 <bound method Backtest.run of <backtesting.backtesting.Backtest object at 0x...>>)而不显示实际回测结果和图表的问题。这通常与Backtesting库与这些IDE的集成方式有关,特别是涉及到Bokeh绘图库的配置。
首先,仔细阅读控制台中出现的UserWarning提示。例如:
UserWarning: Jupyter Notebook detected. Setting Bokeh output to notebook. This may not work in Jupyter clients without JavaScript support (e.g. PyCharm, Spyder IDE). Reset with `backtesting.set_bokeh_output(notebook=False)`.
warnings.warn('Jupyter Notebook detected. '这个警告表明Backtesting库检测到你正在使用Jupyter Notebook,并尝试将Bokeh输出设置为notebook模式。然而,某些IDE(如PyCharm、Spyder)的Jupyter客户端可能不支持JavaScript,导致图表无法正确显示。
尽管你在PyCharm或Spyder中使用的是Jupyter Notebook,但确保你实际上运行了一个独立的Jupyter Notebook服务器。PyCharm和Spyder内置的Jupyter Notebook功能可能不够完整。
虽然你已经尝试了 backtesting.set_bokeh_output(notebook=False),但确保将其放在代码的最前面,并在调用 Backtest.plot() 之前执行。 此外,检查你的代码中是否多次调用了 backtesting.set_bokeh_output() 函数,确保最终的设置是你期望的。
确保你安装了兼容的Bokeh版本。Backtesting库可能对Bokeh版本有特定要求。可以尝试更新或降级Bokeh版本。
pip install bokeh==<version>
替换 <version> 为你想要安装的具体版本号。
以下是一个完整的代码示例,演示了如何使用Backtesting库进行回测并绘制结果:
from backtesting import Backtest, Strategy
from backtesting.lib import crossover
import pandas as pd
# 示例数据(替换为你自己的数据)
data = pd.DataFrame({
'Open': [10, 11, 12, 13, 14, 15, 16, 17, 18, 19],
'High': [12, 13, 14, 15, 16, 17, 18, 19, 20, 21],
'Low': [8, 9, 10, 11, 12, 13, 14, 15, 16, 17],
'Close': [11, 12, 13, 14, 15, 16, 17, 18, 19, 20],
'Volume': [100, 110, 120, 130, 140, 150, 160, 170, 180, 190]
})
# 定义一个简单的交易策略
class MyStrategy(Strategy):
def init(self):
self.sma1 = self.I(lambda x: pd.Series(x).rolling(window=5).mean(), self.data.Close)
self.sma2 = self.I(lambda x: pd.Series(x).rolling(window=10).mean(), self.data.Close)
def next(self):
if crossover(self.sma1, self.sma2):
self.buy()
elif crossover(self.sma2, self.sma1):
self.sell()
# 运行回测
bt = Backtest(data, MyStrategy, cash=10000)
stats = bt.run()
bt.plot()解决Backtesting库在Jupyter Notebook中无法显示回测结果的问题,通常需要关注Bokeh的配置、Jupyter Notebook的运行方式以及代码环境。通过仔细阅读错误提示、启动独立的Jupyter Notebook服务器、正确设置Bokeh输出,以及检查代码逻辑和数据格式,可以有效解决此问题。
以上就是解决Backtesting库在Jupyter Notebook中运行无结果的问题的详细内容,更多请关注php中文网其它相关文章!
每个人都需要一台速度更快、更稳定的 PC。随着时间的推移,垃圾文件、旧注册表数据和不必要的后台进程会占用资源并降低性能。幸运的是,许多工具可以让 Windows 保持平稳运行。
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号