Beating the Market with a Momentum Trading Strategy using Python: How You Can Too

Zach English
Geek Culture
Published in
9 min readMar 7, 2021

--

Last month I wrote about automating gathering financial data with Python, today I am going to walk through creating a momentum trading strategy using financial data scraped from Yahoo Finance. The goal of a momentum trading strategy is to capitalize on run-ups and minimize downside risk by exiting the position before a sell off. Put simply, repeating buy low and sell high to maximize returns. For this strategy I am going to create buy and sell indicators using the price and volume moving averages for securities.

To get started we will pull price data from Yahoo Finance using Pandas DataReader. I am going to choose Facebook ($FB) as an example stock. First, we need to import the necessary modules: pandas, pandas_datareader, datetime and timedelta. How each module is used will be explained as we go along. The code to import the modules is shown below.

Choosing the Strategy’s Time Frame:

The first step when setting up a momentum trading strategy is deciding on the time frame. This can make or break how well your approach to quant trading works. For my momentum strategy I am going to focus on a medium sized window of a week to a couple months for buying and selling securities. I believe that this window will produce the best results. However, back-testing, previous trading and industry knowledge will be the best indicators for the length of time frame you should choose.

To begin, I pulled the price data for the last 150 days of trading for Facebook. In order to get the last 150 days consistently I am going to use date.today()and timedelta. Using timedelta, the start date will be 150 days in the past from the current date. This will collect data for approximately the previous 105 trading days when accounting for weekends and holidays.

Alright! First step completed. Now we have the data we want and can begin to manipulate it. Next, I am going to calculate the 30 day moving averages for price and volume. The moving averages will give us metrics to compare the current price and volume of a stock during the most recent trading session. From there we can begin to implement our momentum trading strategy. Our first objective is to find buy indicators, where the price consistently rises after a criteria is met.

Trading Assumptions

For the strategy, I am going to create buy indicators when the stock price is below…

--

--

Zach English
Geek Culture

Data engineering consultant and aspiring data scientist, writing about tech and finance