Python and MACD Trading Strategies

Python and MACD Trading Strategy: Backtest, Rules, Code, Setup, Performance

Python is one of the most popular programming languages in finance. It is widely used for data analysis, machine learning and, of course, backtesting trading strategies.

Today we will show you how to calculate and backtest a MACD, Moving Average Convergence/Divergence (MACD), trading strategy using Python. As you will see, it doesn’t take a computer science degree to do it.

In this article, we are going to backtest a MACD trading strategy using Python: from downloading data from Yahoo Finance and calculating the MACD to generating the strategy returns and plotting the results.

Related reading:

Python-related resources

We have written many articles about Python, and you might find these interesting:

Downloading historical data from Yahoo Finance

We are going to download Apple’s historical data from Yahoo Finance using the yfinance library. If you want to learn more about how to use yfinance to download not only historical prices but also fundamental data such as dividends, income statements and multiples, check this post:

Besides importing the yfinance library we are going to be using pandas for data manipulation and matplotlib.pyplot to create some charts and illustrate the results and performance of the strategy.

To download Apple’s historical data, we are going to define a variable, which we will name ‘data’, and use the yf.download() function from yfinance to request the data from the website.

Python and MACD strategy

If we print data we get the following output:

How to make a MACD strategy in Python

We have all the daily open, high, low, close, adjusted close, and volume values for Apple since 1980!

Calculating the MACD indicator in Python

The MACD is a trend-following momentum indicator that shows the relationship between two moving averages of a security’s price.

The formula to calculate the MACD is very simple:

MACD = 12-period closing price EMA – 26-period closing price EMA

Pandas provides a function to calculate the Exponential Moving Average called ewm(), to which we have to add mean() at the end. 

After subtracting the EMA’s, we need to calculate the signal line. The signal line is the 9-period EMA of the MACD.

Again, we use the ewm() function and add mean() at the end.

Lastly, we need to calculate the histogram. This is done by simply subtracting the MACD from the signal line.

Python MACD trading strategy

Generating the regimes

For illustration purposes, we are going to backtest the classic MACD trading strategy: 

  • We buy when the MACD is higher than the Signal line (histogram is positive)
  • We sell when the MACD crosses below the Signal line (histogram is negative)

In order to do this, we are going to do a loop through the data frame using the for and if function. 

For every row in the data frame, if the histogram value is positive(>= 0) we are going to put 1 in the ‘regime’ column, otherwise, we put 0.

It is important to note that we put the 1 and 0 values in the next row(in i+1). This is because the day the signal is triggered(in i) we bought at the close, hence we didn’t expose ourselves to that day’s change in value of Apple. The returns start counting the day after the signal is triggered.

Python MACD strategy backtest

Here is how the data frame looks if we print it:

Python MACD trading strategy trading rules

Calculating the returns of the MACD trading strategy

Calculating the returns of the strategy is very simple.

Trading Rules

THIS SECTION IS FOR MEMBERS ONLY. _________________ Click Here To Get A Trial Access Click Here To Get Access To Trading Rules

Plotting the returns of the MACD strategy

Now is when matplotlib comes in handy. However, this is not a tutorial on how to use matplotlib, so here is what each line of code does:

  • Creates a blank chart of 12 inches in width and 9 inches in length
  • Plot the cumulative returns for the MACD strategy and add a label called ‘MACD Strategy’.
  • Same but with the cumulative returns of Apple and the label called ‘Apple B&H’
  • Shows the labels in the chart
  • Makes the y-scale logarithmic
  • Creates a title in the top of the chart
  • Displays the chart
Plotting the returns of the MACD strategy using Python

And here is the chart:

MACD Python trading strategy equity curve

The MACD strategy compounded money at a 15.04% CAGR while buy and hold returned 19.07% per year. However, the MACD strategy was invested only 51.13% of the time. The strategy is just for informational purposes.

MACD video

In case you’d like to know some other MACD strategies, you might be interested in our video:

Python and MACD strategy – conclusion

To sum up, today you learned how to backtest a MACD trading strategy in Python. We show you the base code and, with some time and dedication, you should be able to backtest and develop your own trading strategies using other indicators or combinations of indicators.

Similar Posts