Python and Momentum Trading Strategy (Backtest, Rules, Code, Setup Overview)
There are many factors that quants and algorithmic traders use when they develop trading strategies. Some of them are value, quality, size and, the one we will be backtesting today, momentum.
Momentum is an investing factor that aims to benefit from the ongoing trend of a stock or asset. A stock that has been rising is said to have positive momentum while a stock that has been crashing is said to have negative momentum. We show you how to code such a strategy using Python.
In this article, we are going to show you how to backtest a momentum trading strategy in Python: from downloading the data and calculating momentum to backtesting the strategy and plotting the results.
The first step to backtest any trading strategy is to gather the necessary data. In this case we are going to download the historical data using the library yfinance. If you want to know more about how to download not only historical stock prices but also fundamental data from the Yahoo Finance website check out these two posts:
- How To Download Data For Your Trading Strategy From Yahoo!Finance With Python
- How To Build A Trading Strategy From FRED Data In Python (Strategy, Backtest, Rules)
For the purpose of this backtest, we will also use the libraries pandas, numpy and matplotlib.pyplot.
Related reading:
- A comprehensive list of stock market trading systems
- Python Trading Strategy Backtesting – How To Do It (Plenty of examples with code and images)
Downloading historical data
Regarding the strategy we are going to backtest today, we are going to be using the select sectors SPDR ETFs. The ticker symbols are:
- XLK: Technology
- XLY: Consumer discretionary
- XLP: Consumer staples
- XLU: Utilities
- XLI: Industrials
- XLE: Energy
- XLF: Financials
- XLV: Healthcare
- XLC: Communications
With this in mind, all we need to do is create a list with all the tickers symbols, define a variable(data), and use the yf.download() function to download the data. Take into account we wi
