Backtrader仅用收盘价绘图报错,求解决方案及建议
问题
当读取Backtrader测试数据(2005-2006-day-001.txt)全列数据时,能正常绘图,代码如下:
import backtrader as bt class St(bt.Strategy): def __init__(self): self.sma = bt.indicators.SimpleMovingAverage(self.data) data = bt.feeds.GenericCSVData( dataname='2005-2006-day-001.txt', datetime=0, close=4, open=1, high=2, low=3, volume=5, openinterest=6, dtformat=('%Y-%m-%d') ) cerebro = bt.Cerebro() cerebro.adddata(data) cerebro.addstrategy(St) cerebro.run() cerebro.plot() # 正常运行
但仅读取收盘价数据时,调用cerebro.plot()会触发ValueError: Axis limits cannot be NaN or Inf,代码如下:
import backtrader as bt class St(bt.Strategy): def __init__(self): self.sma = bt.indicators.SimpleMovingAverage(self.data) data = bt.feeds.GenericCSVData( dataname='2005-2006-day-001.txt', datetime=0, close=4, open=-1, high=-1, low=-1, volume=-1, openinterest=-1, dtformat=('%Y-%m-%d') ) cerebro = bt.Cerebro() cerebro.adddata(data) cerebro.addstrategy(St) cerebro.run() cerebro.plot() # 抛出ValueError
需要回测仅含收盘价数据的普通基金,请问Backtrader是否支持仅用收盘价绘图?或有其他可行建议?
解决方案
Backtrader支持仅用收盘价绘图,报错原因是默认绘图逻辑依赖OHLC(开高低收)数据计算坐标轴范围,当这些字段缺失时会产生NaN/Inf导致报错,可通过以下方式解决:
- 复用收盘价填充OHLC字段:初始化
GenericCSVData时,将open、high、low均指向收盘价的列索引,让绘图模块获得有效数据计算坐标轴。修改后数据源代码:
data = bt.feeds.GenericCSVData( dataname='2005-2006-day-001.txt', datetime=0, close=4, open=4, high=4, low=4, volume=-1, openinterest=-1, dtformat=('%Y-%m-%d') )
- 使用
LinePlotterIndicator单独绘制目标数据:在策略中添加该指示器直接绘制收盘价和均线,绕开默认绘图对OHLC的依赖。示例代码:
import backtrader as bt class St(bt.Strategy): def __init__(self): self.sma = bt.indicators.SimpleMovingAverage(self.data.close) # 单独绘制收盘价和均线 bt.indicators.LinePlotterIndicator(self.data.close, name='Close') bt.indicators.LinePlotterIndicator(self.sma, name='SMA') data = bt.feeds.GenericCSVData( dataname='2005-2006-day-001.txt', datetime=0, close=4, open=-1, high=-1, low=-1, volume=-1, openinterest=-1, dtformat=('%Y-%m-%d') ) cerebro = bt.Cerebro() cerebro.adddata(data) cerebro.addstrategy(St) cerebro.run() cerebro.plot()
- 自定义绘图逻辑(进阶):继承
backtrader.plot.plotter.Plot类,重写坐标轴范围计算逻辑,跳过对缺失OHLC字段的检查。该方式需要熟悉Backtrader绘图源码,适合个性化定制需求。
内容的提问来源于stack exchange,提问作者Doodle-loo
相关产品推荐
相关产品推荐

