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 Indicator
can Strategy
separate 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 Indicator
is: https://www.backtrader.com/docu/induse/
For example, the following is a Indicator
class, which is the same as a strategy:
def __init__
: Some functions initialized to generate some trading signalsdef next(self)
:Strategy
Consistent with the usage of next in the class, every simulated trading day, the class will be executed first , and then the methodIndicator
in 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: Indicator
There is no self.datetime
method 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:
- In the strategy class
Strategy
, perform the initializationdef __init__()
- In the signal class
Indicator
, perform the initializationdef __init__()
- In the signal class
Indicator
, executenext()
the function - In the strategy class
Strategy
, executenext()
the function