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.
Key takeaways
- The article provides a comprehensive guide on implementing and backtesting a Moving Average Convergence/Divergence (MACD) trading strategy using Python.
- The key steps outlined in the article include:
- Downloading Historical Data: Utilizing the
yfinance
library to fetch historical price data for a chosen security, such as Apple’s stock, from Yahoo Finance. - Calculating the MACD Indicator: Computing the MACD line by subtracting the 26-period Exponential Moving Average (EMA) from the 12-period EMA. Subsequently, deriving the signal line as the 9-period EMA of the MACD line, and determining the histogram by subtracting the signal line from the MACD line.
- Generating Trading Signals: Establishing trading regimes based on the histogram’s value:
- Buy Signal: When the histogram is positive (MACD line is above the signal line).
- Sell Signal: When the histogram is negative (MACD line is below the signal line).
- Calculating Strategy Returns: Implementing a loop through the DataFrame to apply the trading signals and compute the strategy’s returns accordingly.
- Plotting the Results: Using libraries such as
matplotlib.pyplot
to visualize the performance of the MACD trading strategy over time.
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: How To Download Data For Your Trading Strategy From Yahoo!Finance With Python
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.
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.
Trading Rules
THIS SECTION IS FOR MEMBERS ONLY. _________________ BECOME A MEBER TO GET ACCESS TO TRADING RULES IN ALL ARTICLES
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 (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.