Backtrader Quantification & Backtesting 11 - Strategy Signal Indicator

As far as the program is concerned, there should be no less than one line of code, but the code can be read or modified intuitively by dividing the code into blocks. Use Indicatorcan Strategyseparate the signal of the strategy from the strategy class to facilitate the coordination and control of the strategy

Article Directory

strategic signal

The explanation on the official website Indicatoris: https://www.backtrader.com/docu/induse/

For example, the following is a Indicatorclass, which is the same as a strategy:

  • def __init__: Some functions initialized to generate some trading signals
  • def next(self): StrategyConsistent with the usage of next in the class, every simulated trading day, the class will be executed first , and then the method Indicatorin the strategy class of this trading day will be executednext()
class BuySignalIndicator(bt.Indicator):
    lines = ("",)

    def __init__(self):
        self.should_buy = False

    def next(self):
        if self.datas[0].close[0] > self.datas[0].open[0]:
            self.should_buy = True
        else:
            self.should_buy = False

Note: IndicatorThere is no self.datetimemethod in the class, so it is actually impossible to directly read the date of the day in the signal class

sample code

import backtrader as bt

class BuySignalIndicator(bt.Indicator):
    lines = ("",)

    def __init__(self):
        self.should_buy = False

    def next(self):
        if self.datas[0].close[0] > self.datas[0].open[0]:
            self.should_buy = True
        else:
            self.should_buy = False


class 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])

Thus, when executing policies, the order of execution is:

  1. In the strategy class Strategy, perform the initializationdef __init__()
  2. In the signal class Indicator, perform the initializationdef __init__()
  3. In the signal class Indicator, execute next()the function
  4. In the strategy class Strategy, execute next()the function

Guess you like

Origin blog.csdn.net/weixin_35757704/article/details/129472501