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

Python and MACD Trading Strategy

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:

MACD Trading Strategy

Table of contents:

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:

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. _________________ BECOME A MEBER TO GET ACCESS TO TRADING RULES IN ALL ARTICLES CLICK HERE TO SEE ALL 350 ARTICLES WITH 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:

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.

Python-related resources

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

I’ve got an Msc from Heriot-Watt University, Edinburgh (1996), in addition a to a business administration degree the Norwegian School of Management (BI – 1994). Did my mandatory military service in between.

After university, I worked two years as an auditor (1996-1998).

I co-founded Aksjeforum.com in 1998/99 - one of the first websites about trading and investing in Norway. It was later acquired by Digi.no in 2001.

I have written 4 books about trading (in Norwegian). One of them has sold 30,000 copies, a record for a financial book in Norway.

From 2001 until 2018 full-time independent prop trader (Series 7 in 2001) and investor.

2018-today: Investor, writer, analyst.