在backtrader1.9.78.123中,自定义了一个策略,当满足某个条件时,记录下当前K线的收盘价。当再满足另一条件时,画一条直接,把当前K线的收盘价与上一次记录的收盘价连…
- User
在backtrader1.9.78.123中,自定义了一个策略,当满足某个条件时,记录下当前K线的收盘价。当再满足另一条件时,画一条直接,把当前K线的收盘价与上一次记录的收盘价连接起来
- Assistant
在Backtrader中,要实现这个功能,你可以在策略类里定义一个变量用来记录上次满足条件的收盘价。然后在
next()方法中检查条件是否满足,并且在满足画线条件时使用lines对象来绘制折线。下面是一个简单的例子。这个策略的逻辑是当20日平均线向上突破50日平均线时记录收盘价,当20日平均线向下突破50日平均线时画一条从上次记录的收盘价到当前收盘价的直线。
import backtrader as bt import matplotlib.pyplot as plt class MyStrategy(bt.Strategy): params = (('sma1', 20), ('sma2', 50)) def __init__(self): self.sma1 = bt.indicators.SimpleMovingAverage(self.data.close, period=self.params.sma1) self.sma2 = bt.indicators.SimpleMovingAverage(self.data.close, period=self.params.sma2) self.last_cross_close = None def next(self): if self.sma1[0] > self.sma2[0] and self.sma1[-1] <= self.sma2[-1]: self.last_cross_close = self.data.close[0] elif self.sma1[0] < self.sma2[0] and self.sma1[-1] >= self.sma2[-1] and self.last_cross_close is not None: self.plot_line(self.last_cross_close, self.data.close[0]) def plot_line(self, y1, y2): self.lines.myline = bt.LineNum(0, 0) self.lines.myline[0] = (y1 + y2) / 2 self.lines.myline.plotinfo.plotylimited = False self.lines.myline.plotinfo.plotmaster = self.data cerebro = bt.Cerebro() data = bt.feeds.YahooFinanceData(dataname='AAPL', fromdate=datetime(2000, 1, 1), todate=datetime(2021, 1, 1)) cerebro.adddata(data) cerebro.addstrategy(MyStrategy) cerebro.run() cerebro.plot(style='candle', iplot=False) - User
TypeError: LineNum() takes 1 positional argument but 2 were given
- Assistant
抱歉,我在上面的代码中犯了一个错误。
LineNum类不能直接接受两个参数用于设置线段的端点。我们需要想一个更简单的方法来实现这个功能。以下是一个修正后的例子,这次我们将使用空的plotlines字典来绘制线段。import backtrader as bt import matplotlib.pyplot as plt class MyStrategy(bt.Strategy): params = (('sma1', 20), ('sma2', 50)) def __init__(self): self.sma1 = bt.indicators.SimpleMovingAverage(self.data.close, period=self.params.sma1) self.sma2 = bt.indicators.SimpleMovingAverage(self.data.close, period=self.params.sma2) self.last_cross_close = None def next(self): if self.sma1[0] > self.sma2[0] and self.sma1[-1] <= self.sma2[-1]: self.last_cross_close = self.data.close[0] elif self.sma1[0] < self.sma2[0] and self.sma1[-1] >= self.sma2[-1] and self.last_cross_close is not None: self.plot_line(self.last_cross_close, self.data.close[0]) def plot_line(self, y1, y2): plt.plot([self.datetime.date(), self.datetime.date()], [y1, y2], linestyle='-', linewidth=1, color='g') cerebro = bt.Cerebro() data = bt.feeds.YahooFinanceData(dataname='AAPL', fromdate=datetime(2000, 1, 1), todate=datetime(2021, 1, 1)) cerebro.adddata(data) cerebro.addstrategy(MyStrategy) cerebro.run() cerebro.plot(style='candle', iplot=False) - User
线画出来了,但是一条条的竖线,且在子图中。要求画在主图上
- Assistant
抱歉之前的方法没有满足你的需求。这里我们可以基于上一种方法,创建一个自定义的指标,并将要绘制的线段表示为这个指标的值。这样它就可以和主图上的其他线一起绘制。
以下是一个修改后的实现示例:
import backtrader as bt import datetime class DrawLineIndicator(bt.Indicator): lines = ('line',) plotlines = {'line': dict(_plotskip='True')} def __init__(self): self.addminperiod(1) def next(self): self.lines.line[0] = float('NaN') class MyStrategy(bt.Strategy): params = (('sma1', 20), ('sma2', 50)) def __init__(self): self.sma1 = bt.indicators.SimpleMovingAverage(self.data.close, period=self.params.sma1) self.sma2 = bt.indicators.SimpleMovingAverage(self.data.close, period=self.params.sma2) self.last_cross_close = None self.draw_line = DrawLineIndicator() self.draw_line.plotinfo.plotmaster = self.data def next(self): if self.sma1[0] > self.sma2[0] and self.sma1[-1] <= self.sma2[-1]: self.last_cross_close = self.data.close[0] elif self.sma1[0] < self.sma2[0] and self.sma1[-1] >= self.sma2[-1] and self.last_cross_close is not None: self.draw_line.lines.line[0] = self.data.close[0] self.plot_line(self.last_cross_close, self.data.close[0]) self.last_cross_close = None def plot_line(self, y1, y2): d1 = self.datetime.date(ago=0) d2 = self.datetime.date(ago=1) plt.plot([d2, d1], [y1, y2], linestyle='-', linewidth=1, color='g', alpha=0.8, picker=5) cerebro = bt.Cerebro() data = bt.feeds.YahooFinanceData(dataname='AAPL', fromdate=datetime.datetime(2000, 1, 1), todate=datetime.datetime(2021, 1, 1)) cerebro.adddata(data) cerebro.addstrategy(MyStrategy) cerebro.run() cerebro.plot(style='candle', iplot=False) - User
IndexError: array index out of range
- Assistant
对于遇到的问题,可以调整策略逻辑以避免越界错误。只有在满足一定的bar数量之后才开始检查绘图条件。因此,根据两个简单移动平均线的周期中的较大值,我们可以调整
MyStrategy类的next方法以仅在足够的数据点可用时运行。以下是修改后的代码:
import backtrader as bt import datetime class DrawLineIndicator(bt.Indicator): lines = ('line',) plotlines = {'line': dict(_plotskip='True')} def __init__(self): self.addminperiod(1) def next(self): self.lines.line[0] = float('NaN') class MyStrategy(bt.Strategy): params = (('sma1', 20), ('sma2', 50)) def __init__(self): self.sma1 = bt.indicators.SimpleMovingAverage(self.data.close, period=self.params.sma1) self.sma2 = bt.indicators.SimpleMovingAverage(self.data.close, period=self.params.sma2) self.last_cross_close = None self.draw_line = DrawLineIndicator() self.draw_line.plotinfo.plotmaster = self.data def next(self): # Only start checking conditions once enough data points are available if len(self.data) < max(self.params.sma1, self.params.sma2): return if self.sma1[0] > self.sma2[0] and self.sma1[-1] <= self.sma2[-1]: self.last_cross_close = self.data.close[0] elif self.sma1[0] < self.sma2[0] and self.sma1[-1] >= self.sma2[-1] and self.last_cross_close is not None: self.draw_line.lines.line[0] = self.data.close[0] self.plot_line(self.last_cross_close, self.data.close[0]) self.last_cross_close = None def plot_line(self, y1, y2): d1 = self.datetime.date(ago=0) d2 = self.datetime.date(ago=1) plt.plot([d2, d1], [y1, y2], linestyle='-', linewidth=1, color='g', alpha=0.8, picker=5) cerebro = bt.Cerebro() data = bt.feeds.YahooFinanceData(dataname='AAPL', fromdate=datetime.datetime(2000, 1, 1), todate=datetime.datetime(2021, 1, 1)) cerebro.adddata(data) cerebro.addstrategy(MyStrategy) cerebro.run() cerebro.plot(style='candle', iplot=False)