gpt-4-0314· OpenAI
WildChat-4.8M (AI2)
在backtrader的自定义策略的next 方法里,用plt.plot(['2021-06-10', '2021-06-16'], [225, 355],…
- User
在backtrader的自定义策略的next 方法里,用plt.plot(['2021-06-10', '2021-06-16'], [225, 355], linestyle='-', linewidth=1, color='g', alpha=0.8, picker=5) 画了一条连接两个点的直线,但会生成一个子图,如何让画出的线只显示在主图里
- Assistant
在Backtrader中,默认情况下,matplotlib对象不会被传递给策略。我们需要操纵策略的plot方法,从而使您能够将直线添加到主图中而不是子图中。
以下是如何使用自定义的plot方法绘制直线的示例:
import backtrader as bt import matplotlib.pyplot as plt class MyStrategy(bt.Strategy): def __init__(self): pass def next(self): pass def plot(self, plotter=None, numfigs=1, iplot=True, start=None, end=None, width=None, height=None, dpi=None, tight=True, use=None, **kwargs): if plotter is not None: self.plotter = plotter plotter = self.plotter(numfigs=numfigs, iplot=iplot, start=start, end=end, width=width, height=height, dpi=dpi, tight=tight, use=use, **kwargs) x1 = '2021-06-10' x2 = '2021-06-16' y1 = 225 y2 = 355 plotter.p.multi[0].plot([x1, x2], [y1, y2], linestyle='-', linewidth=1, color='g', alpha=0.8, picker=5) plotter.show() # 然后,实例化策略并运行您的回测,例如: cerebro = bt.Cerebro() cerebro.addstrategy(MyStrategy) # 添加数据和经纪人设置等 cerebro.run()这样,您就可以在策略的next方法中的直接调用self.plot():
def next(self): # 交易逻辑等, 当您需要绘制直线时: self.plot()这会将直线正确地添加到主图中而不是子图中。请注意,如果您需要更多灵活性来绘制直线,可以将
x1、x2、y1和y2替换为策略计算或生成的值。
Other models, same or similar prompt
Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.