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:**

## 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.

If we print data we get the following output:

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.

- MACD Trading Strategies (Backtest, Indicator, Rules and Settings)
- MACD and RSI Trading Strategy (Rules, Setup, Backtest â€“ 80% Win Rate)
- MACD and Bollinger Bands Strategy (Backtest And Example)
- MACD Histogram Trading Strategy

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.

## 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.

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

## Calculating the returns of the MACD trading strategy

Calculating the returns of the strategy is very simple.

First we have to calculate the daily returns of Apple. For that purpose, we are going to use the **pct_change()** function and sum 1 at the end.

Now that we have the daily percentage returns, we will create a new column called â€˜returnsâ€™ and put the daily change of Apple when the â€˜regimeâ€™ column equals one. We will have to use the **for** and **if** functions again.

When the strategy is not invested in Apple the â€˜returnsâ€™ column values will be 1.

## 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

And here is the chart:

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.