对于程序来讲,该有的代码一行都不会少,但是把代码分块就可以很直观的阅读或修改代码。使用Indicator
可以将策略的信号从策略类Strategy
中脱离出来,方便策略进行协调与控制
文章目录
策略信号示例代码策略信号
官网中对于Indicator
的解释是:/docu/induse/
比如下面就是一个Indicator
类,和策略一样:
def __init__
:初始化的一些函数,可生成一些交易信号def next(self)
:与Strategy
类中的next用法一致,每一个模拟的交易日,都会先执行Indicator
类,然后才会执行这个交易日的策略类中的next()
方法
class BuySignalIndicator(bt.Indicator):lines = ("",)def __init__(self):self.should_buy = Falsedef next(self):if self.datas[0].close[0] > self.datas[0].open[0]:self.should_buy = Trueelse:self.should_buy = False
注意:在Indicator
类中是没有self.datetime
方法的,因此在信号类中其实是无法直接读取当天的日期的
示例代码
import backtrader as btclass BuySignalIndicator(bt.Indicator):lines = ("",)def __init__(self):self.should_buy = Falsedef next(self):if self.datas[0].close[0] > self.datas[0].open[0]:self.should_buy = Trueelse:self.should_buy = Falseclass TestStrategy(bt.Strategy): # 策略def __init__(self):self.close_price = self.datas[0].close # 这里加一个数据引用,方便后续操作self.my_indicator = BuySignalIndicator()def next(self):if self.my_indicator.should_buy:self.buy(size=500, price=self.data.close[0])else:if self.position:self.sell(size=500, price=self.data.close[0])
这样,在执行策略时,执行顺序是:
在策略类Strategy
中,执行初始化def __init__()
在信号类Indicator
中,执行初始化def __init__()
在信号类Indicator
中,执行next()
函数在策略类Strategy
中,执行next()
函数
如果觉得《Backtrader量化回测11——策略信号Indicator》对你有帮助,请点赞、收藏,并留下你的观点哦!