Skip to content
The Chat Archive
gpt-3.5-turbo-0301· OpenAI WildChat-4.8M (AI2)

在backtrader中,自义定一个画线指标,用来连接指定两根K线的收盘价

  1. User

    在backtrader中,自义定一个画线指标,用来连接指定两根K线的收盘价

  2. Assistant

    在backtrader中,自定义画线指标可以通过继承Indicator类来实现。以下为一个连接两根K线的收盘价的画线指标代码:

    from backtrader.indicators import Indicator
    
    class CloseLine(Indicator):
        '''
        连接指定两根K线的收盘价的画线指标
        '''
        params = (('start_bar', 0), ('end_bar', -1))
    
        def __init__(self):
            pass
    
        def next(self):
            start_bar = min(self.start, len(self))
            end_bar = min(self.end, len(self))
            if len(self) > end_bar:
                self.l.close[0] = 0
            elif len(self) > start_bar:
                self.l.close[0] = self.data.close[start_bar] if end_bar == start_bar else 0
    

    其中,params参数可以传入指定的起点和终点K线的下标(start_bar和end_bar)。

    在next()方法中,首先获取指定起点和终点的下标,然后根据当前的指标长度判断是否需要继续画线。如果指标长度超过终点K线,则画线结束,将当前收盘价置为0;否则,判断当前下标是否大于等于起点K线下标,并根据终点和起点下标的关系将当前收盘价设置为起点K线的收盘价或0。

    使用该指标示例:

    import backtrader as bt
    import pandas as pd
    
    # 自定义数据
    data = pd.DataFrame({
        'close': [100, 102, 98, 106, 105],
    })
    
    # 初始化Cerebro对象
    cerebro = bt.Cerebro()
    
    # 添加数据
    data_feed = bt.feeds.PandasData(dataname=data)
    cerebro.adddata(data_feed)
    
    # 添加指标
    cerebro.indicators.append(CloseLine(start_bar=0, end_bar=2))
    cerebro.indicators.append(CloseLine(start_bar=2, end_bar=4))
    
    # 运行回测
    cerebro.run()
    cerebro.plot(style='bar')
    

    结果图像如下图所示:

    [image: backtrader-indicator-close-line] open