Building a Momentum Portfolio Using Python: A Step-by-Step Guide

MomentumLab
6 min readJun 6, 2024

--

In this article, We will be sharing a step-by-step guide on how to build a momentum portfolio using Python.

Outcome

By the end of this tutorial, you will be able to:

  • Understand the concept of a momentum portfolio
  • Write Python code to create your own momentum-based stock selection system

Why Use Python (or Any Programming Language)?

Before we dive into the code, let’s consider why you might want to use Python instead of manually building a portfolio.

Benefits of Using Python:

  1. Efficiency: Automating the process saves time and effort compared to manually building a portfolio using tools like Google Sheets or TradingView.
  2. Reusability: Once you write the code, you can reuse it for other strategies with minor tweaks.
  3. Advanced Techniques: Implementing machine learning and other data science techniques is much easier with code.
  4. Fulfillment: There is immense satisfaction in writing your own code and seeing it work as intended.

For this tutorial, I am using Python because of its vast resources and references available online. However, you can apply the same logic using other programming languages as well.

Prerequisites

You might wonder what you need to know already to follow this tutorial. Here’s a quick rundown:

  • Basic Python Knowledge: You don’t need to be an expert. As long as you can understand the logic, the code should be easy to follow.
  • Simple Rules: We are implementing a basic momentum strategy with simple rules, making the code straightforward.
  • Active Participation: I recommend you follow along with the tutorial and make your own changes to see how they affect the results.

With that, let’s jump right into it.

Define the Strategy

To put a momentum strategy into practice, let’s define it first. I’m using the book “Quantitative Momentum — A Practitioner’s Guide to Building a Momentum-Based Stock Selection System” by Wesley and Jack as a reference. They define two metrics related to momentum:

  1. Momentum itself
  2. Quality of Momentum (also called Smoothness)

We might not exactly imitate their calculations, but we’ll follow the basic idea.

Step-by-Step Code Implementation

Platform/IDE

There are multiple platforms or IDEs that you can use to run your Python code.

Desktop IDEs

  • PyCharm: Full-featured IDE by JetBrains.
  • VS Code: Free, extensible editor by Microsoft.
  • Spyder: IDE for scientific computing.
  • Jupyter Notebook: Web-based for interactive coding.
  • Thonny: Beginner-friendly IDE.
  • IDLE: Default Python IDE.

Online Platforms

  • Google Colab: Cloud-based Jupyter notebooks with GPU support.
  • Repl.it: Online IDE with real-time collaboration.
  • Kaggle Kernels: Data science and machine learning platform.
  • PythonAnywhere: Online IDE and web hosting.
  • Deepnote: Collaborative data science notebooks.

I personally use Google Colab because it has free access to GPUs/TPUs and allows for easy collaboration on Jupyter notebooks along with access to Google drive. Thought it has limited persistent storage and may be slower for large datasets or heavy computations, for our purpose of this code, this is not a roadblock.

Import Required Libraries

First, we need to import the necessary libraries for data handling and fetching stock data. If you are importing for the first time, make sure you install them first (use pip install ‘package’). Also, you can connect to your own google drive by using the google colab module

import yfinance as yf
import pandas as pd
from datetime import timedelta, date
from google.colab import drive
drive.mount('/content/drive')

Read Ticker Data

We start by reading the list of ticker symbols. For this example, the data is read from a CSV file stored on Google Drive. I downloaded this file from the NSE India website which includes all the symbols part of the NIFTY Total Market Index.

# Read ticker data from a local file or Google Drive
tickers = pd.read_csv('/content/drive/My Drive/Momentum/ind_niftytotalmarket_list.csv')
tickers['NSSymbol'] = tickers['Symbol'] + ".NS"

Define the Time Period and Download Data

Next, we define the time period for which we want to analyze the stock data. Here, we select data from one year ago to four weeks ago. We then download the stock data for the selected tickers.

start_date = date.today() - timedelta(weeks=52)
end_date = date.today() - timedelta(weeks=4)
stock_data = []
for ticker in tickers['NSSymbol']:
raw_data = yf.download(ticker, start=start_date, end=end_date, interval='1d')
raw_data['Symbol'] = ticker
stock_data.append(raw_data)
stock_data = pd.concat(stock_data)
stock_data.reset_index(inplace=True)

Calculate Weekly Close Prices

We calculate the closing prices at the end of each week to assess the momentum.

# Calculate week start date and weekday number
stock_data['WeekStartDate'] = stock_data['Date'] - pd.to_timedelta(stock_data['Date'].dt.dayofweek, unit='D')
stock_data['WeekDayNumber'] = stock_data['Date'].dt.weekday
# Group by 'Date' and 'WeekStartDate', and select the maximum 'WeekDayNumber' within each group
grouped_df = stock_data.groupby(['Symbol', 'WeekStartDate'])['WeekDayNumber'].max().reset_index()
# Merge to get the close price for max weekday number
friday_close_data = pd.merge(stock_data, grouped_df, on=['Symbol', 'WeekStartDate', 'WeekDayNumber'], how='inner')

Calculate Momentum

We calculate the momentum by comparing the current closing price with the closing price four weeks ago.

# Calculate the stock price four weeks ago for each date
friday_close_data['FourWeeksAgo'] = friday_close_data['WeekStartDate'] - pd.DateOffset(weeks=4)

# Perform a join operation to get the stock price four weeks ago
momentum_data = friday_close_data.merge(friday_close_data[['WeekStartDate', 'Symbol', 'Close']],
left_on=['Symbol', 'FourWeeksAgo'], right_on=['Symbol', 'WeekStartDate'],
suffixes=('', '_FourWeeksAgo'), how='left')
# Calculate the momentum for every week
momentum_data['Momentum'] = 1 + ((momentum_data['Close'] - momentum_data['Close_FourWeeksAgo']) /
momentum_data['Close_FourWeeksAgo'])
mom_by_ticker = momentum_data.groupby(['Symbol'])['Momentum'].agg('prod') - 1
mom_by_ticker = mom_by_ticker.reset_index()

Calculate Smoothness

Smoothness is calculated by measuring the week-to-week changes in stock prices. This helps in assessing the quality of momentum.

# Calculate the stock price one week ago for each date
friday_close_data['OneWeekAgo'] = friday_close_data['WeekStartDate'] - pd.DateOffset(weeks=1)

# Perform a join operation to get the stock price one week ago
momentum_data = friday_close_data.merge(friday_close_data[['WeekStartDate', 'Symbol', 'Close']],
left_on=['Symbol', 'OneWeekAgo'], right_on=['Symbol', 'WeekStartDate'],
suffixes=('', '_OneWeekAgo'), how='left')
# Calculate the smoothness for every week
momentum_data['Smoothness'] = momentum_data['Close'] - momentum_data['Close_OneWeekAgo']

# Get smoothness by ticker
smo_by_ticker = momentum_data.groupby('Symbol').agg(
Smoothness=('Smoothness', lambda x: (x > 0).sum() / (len(x) - 1))
).reset_index()

Combine Momentum and Smoothness

Finally, we combine the momentum and smoothness data and save the results to an Excel file.

momentum_smooth_by_ticker = mom_by_ticker.merge(smo_by_ticker, on='Symbol', how='inner')
momentum_smooth_by_ticker.to_excel('/content/drive/MyDrive/Momentum/momentum_smooth_by_ticker.xlsx', index=False)

Output

Once you run the entire script, you will see Momentum and Smoothness scores for each symbol. An approach one can take is to filter the Top x% symbols by Momentum scores and sort them by Smoothness to yield your top stocks depending on your portfolio size. You can run this script regularly based on the re-balancing frequency.

Momentum and Smoothness scores by Symbol (Sample Result)

Conclusion

In this tutorial, we have walked through the process of building a momentum portfolio using Python. By automating the strategy, we save time, ensure consistency, and open up opportunities for further enhancements and testing. Whether you are new to programming or an experienced developer, Python provides a powerful and flexible tool to implement and refine your trading strategies.

We encourage you to try this code, make your own modifications, and see how it performs with different stocks and time periods. In case you are still not clear, watch our step by step walk-through of this in a 2 part YouTube series here

— — — — — — — — — — — — — — — — — — — — — —

QuantX-Builder for Mastering Momentum Investing. 4 week comprehensive learning programme.

bit.ly/QuantX-MomentumLAB

— — — — — — — — — — — — — — — — — — — — — —

Feel free to leave your comments, questions, and thoughts below. Happy coding and investing!

Important Links
Youtube: https://www.youtube.com/@MomentumLab_IN
Twitter: https://x.com/MomentumLab_IN

**Disclaimer:** We are not SEBI registered advisors. Any content shared on or through our digital media channels is for information and education purposes only and should not be treated as investment or trading advice. Please do your own analysis or take independent professional financial advice before making any investments based on your own personal circumstances. Investment in securities is subject to market risks; please carry out your due diligence before investing. And last but not least, past performance is not indicative of future returns.

--

--

MomentumLab

Momentum Investing for DIY investors who believe in India's growth story!