How it works...

In this recipe, we built a trading strategy on top of bt.SignalStrategy. First, we defined the indicator (RSI), with selected arguments. We also added bt.talib.RSI(self.data,plotname='TA_RSI'), just to show that backtrader provides an easy way to use indicators from the popular TA-Lib library (the TA-Lib library must be installed for the code to work). The trading strategy does not depend on this second indicator; it is only plotted for reference, and we could add an arbitrary number of indicators.

Even when adding indicators for reference only, their existence influences the "warm-up period." For example, if we additionally included a 200-day SMA indicator, no trade would be carried out before there exists at least one value for the SMA indicator.

The next step was to define signals. To do so, we used the bt.CrossUp/bt.CrossDown indicators, which returned 1 if the first series (price) crossed the second (upper or lower RSI threshold) from below/above, respectively. For entering a short position, we made the signal negative, by adding a - in front of the bt.CrossDown indicator.

We can disable printing any indicator, by adding plot=False to the function call.

As the last step of defining the strategy, we added tracking of all the signals, by using the signal_add method. For exiting the positions, the conditions we used (an RSI value higher/lower than 50) resulted in a Boolean, which we had to make negative in case of exiting a long position: -True is the same as -1.

Setting up and running the backtest is analogous to the previous recipe, so please refer to it if in doubt regarding any of the steps.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.129.7.43