Quantitative Investment series:

Backtrader — Quantitative Investing in Python (part 1)

MACD Strategy (+26.9%)

Python quantitative investment combat tutorial (3) — A share back test MACD strategy

Github Repository: github.com/Ckend/pytho…


Last time, we did a simple quantitative investment analysis using Python and Backtrader using the simplest buy-sell strategy:

Backtrader — Quantitative Investing (part 1)

This time, let’s make the strategy a little more complicated and use the signal line cross trading method of MACD strategy:

Github Repository: github.com/Ckend/pytho…

Principle 1.

To explain the principle of MACD, we need to know first exponential moving averages (EMA), exponential moving averages is a kind of moving average, depending on the degree of old and new data points assigned different weights, its recent price, pay more attention to lighten the weight of past prices, while ordinary moving average weight on all prices are consistent, That’s the big difference.

The EMA line is also cyclical, with long-term investors often choosing 50, 100 or 200 cycles to track price trends over months or even years. Short periods of 12 and 26 days are popular with short-term investors. The MACD line of most stock software is also calculated according to 12-day EMA and 26-day EMA.

Okay, let’s start with the graph above, which shows two basic rules:

Bullish on blue line through signal line (orange).

Blue line signal line (orange) bearish.

What is the blue line? Is the MACD line, which is obtained by subtracting a price short EMA from a price long EMA. In most stock software, it is EMA(12) -EMA (26).

What is the signal line? It’s actually the EMA of the MACD line, with a period of 9.

The summary formula is as follows:

  • MACD= Price EMA(12) – price EMA(26).
  • Signal line = EMA of MACD (9)

The squares in the figure are the difference between the MACD line and the signal line, with positive values up and negative values down.

With that in mind, we can start building the backtest script:

Buy: when MACD line in the value of the previous day < the value of the signal line on the previous day and the value of the MACD line > the value of the signal line on the day of the gold fork, this time bullish, the next day to buy.

Sell: If you have made 10% profit, sell. If you have lost 10%, sell.

This strategy returned 26.9% a year on stock 603186 with 100 shares traded each time.

2. Prepare

Before you begin, make sure Python and PIP are successfully installed on your computer. If not, please visit this article: Super Detailed Python Installation Guide to install Python. If you are using Python for data analysis, you can install Anaconda directly: Python data analysis and mining helper – Anaconda

In Windows, open Cmd(Start – Run – Cmd). In Apple, open Terminal(command+ space enter Terminal).

Of course, I recommend that you use the VSCode editor, Copy this code, and run commands in the terminal below the editor to install dependency modules.

Enter the following command from the terminal to install the dependency modules we need:

pip install backtrader

If Successfully installed XXX is displayed, the installation is successful.

See our previous article: Backtrader Tutorial — Quantitative Investing tutorial (1)

You can download all the code for this article from “Quantitative Investing 2” in Python.

3. Build a strategy

If you haven’t read the first article, you probably don’t know how to build this strategy, so I recommend reading the BackTrader tutorial (1). Of course, if you just want to run and modify some parameters, you can download the full source code.

From the principle of MACD, we know that MACD is calculated from EMA lines, so we need to construct a short EMA and a long EMA. The conventional choice is EMA lines with period 12 and 26 respectively:

from backtrader.indicators import EMA
me1 = EMA(self.data, period=12)
me2 = EMA(self.data, period=26)
self.macd = me1 - me2
Copy the code

According to the previous analysis, we know that the signal line is the EMA of MACD line with a period of 9:

self.signal = EMA(self.macd, period=9)
Copy the code

So we’ve built these two important lines. Isn’t that easy? Next, as in the first article, write the buy/sell logic in the next function of the strategy:

    # Python utility guide
    def next(self):
        self.log('Close, %.2f' % self.dataclose[0])
        if self.order:
            return

        if not self.position:
            If MACD < Signal, Signal < MACD, buy the next day
            condition1 = self.macd[-1] - self.signal[-1]
            condition2 = self.macd[0] - self.signal[0]
            if condition1 < 0 and condition2 > 0:
                self.log('BUY CREATE, %.2f' % self.dataclose[0])
                self.order = self.buy()

        else:
            # Sell if you have made 10% profit; If you have lost 10%, sell.
            condition = (self.dataclose[0] - self.bar_executed_close) / self.dataclose[0]
            ifCondition > 0.1 or condition < -0.1: self.log()'SELL CREATE, %.2f' % self.dataclose[0])
                self.order = self.sell()
Copy the code

Buy logic is what we refer to in principle. If MACD < Signal yesterday, Signal today < MACD, buy next day.

The logic of selling is much simpler: if you have made 10%, sell. If you have lost 10%, sell.

Set the commission at 0.5%, each transaction is 100 shares, and the initial capital is RMB 10,000:

cerebro.broker.setcash(10000) cerebro.addsizer(bt.sizers.FixedSize, Gaining cerebro = 100). The broker. Setcommission (appointed = 0.005)Copy the code

Run the script on the command line:

python macd.py
Copy the code

The results of the back test are as follows:

It turned out surprisingly well, because it was a fairly straightforward strategy to add a sentence at the end of the code

cerebro.plot()
Copy the code

You can see the backtest of the whole policy as shown in the figure below:

Use red boxes to mark successful upswings and green boxes to mark downswings.

As you can see, 7 out of 8 operations are profitable. Why such a good result? First of all, 603186 is a good performance of the stock, its fundamentals are not bad, the early back test is also in a rising state, so it is expected that the back test effect is excellent.

In addition, our selling strategy, while brainless, worked very well in this situation, with several places successfully selling at the top.

You can see from this example, although the quantitative strategy is effective, but the most important thing is to pick stocks, how to choose the optimal stocks, need you see results, brain, there is no unearned wealth in the world, if the article to the freedom of the wealth of the roads have help to you, please remember watching or share.

So that’s the end of our article, if you’d like to see our Python tutorial today, please stay tuned and give us a thumbs up/check out if it was helpful. If you have any questions, please leave them in the comments below and we’ll be patient to answer them!


The Python Utility Guide is more than just a guide

MACD Strategy (+26.9%)