The information that the backtrader strategy logic can use is not limited to datafeed, but any information. You haven't realized it yet?

All the cases and documents that come with backtrader, and almost all articles on the Internet, when writing strategy logic, the information used is limited to the data provided by datafeed. This can easily give beginners the impression that when formulating strategies, only the information in the datafeed can be used.

Sometimes, our strategy requires some extra information that is not suitable for datafeed. Can this be done? It is absolutely possible, as long as you put these external information in the ordinary pandas dataframe and pass it to the strategy in the form of parameters (note, not to the datafeed), the strategy can use this information at will.

Insert picture description here
The code template is as follows

...
# 创建策略类
class SmaCross(bt.Strategy):
    # 定义参数
    params = dict( period_fast=5,  # 移动平均期数
             dataframe=None, # 数据帧参数
)
    def __init__(self):
        # 移动平均线指标
        self.move_average = bt.ind.MovingAverageSimple(
            period=self.params.periodfast)

     def next(self):
         # 策略逻辑,这里可以访问self.p.dataframe的内容用于逻辑
         ...

...
###########
# 主程序开始
############
...
df = ... # 定义所需dataframe
cerebro.addstrategy(SmaCross, period_fast=3, dataframe=df)  # 将策略注入引擎,注意参数设置

Guess you like

Origin blog.csdn.net/qtbgo/article/details/109724967