Skip to Content

How to Create a Momentum Trading Algorithm in Python | Composer

Introduction

For a long time, investors have tried to follow the conventional wisdom of "buy low and sell high". This entails having a unique insight and owning a stock before the market discovers its value. But what happens when your insight is too far ahead of its time, or is simply wrong? A lot of investors fall prey to this 'value trap' and end up owning a non-performing stock for far too long. But now there is a better way.

Momentum trading helps solve for these problems by investing in stocks which are on their way up, and liquidating these positions just as they seem to be mean-reverting (i.e. back on their way down). Essentially, momentum investing functions on the premise that recent winners will continue to remain winners in the short-term. In this article, we help you understand how you can leverage Python to create your own momentum-trading algorithm, and how we at Composer can help you create one without having to enter a single line of code. 

What is momentum trading?

Momentum trading is an investing style where you buy and sell stocks based on recent price trends. The idea is that if there is enough force behind a price move, it will continue to move in the same direction.

It also relies on a time-tested virtuous loop. When a stock reaches a higher price, it attracts more attention from traders and investors, which pushes its price even higher. This continues until a large number of sellers enter the market – for example, due to a change in company fundamentals based on quarterly earnings updates. Once enough sellers take over, the momentum changes direction and will force the stock price lower.

A momentum trader doesn’t necessarily attempt to find the top and bottom of a trend, but instead focuses on the main body of the price move. Think of this like a car picking up speed. You may not be part of the 0-20mph move, but you can definitely be part of the 20-100mph move. Momentum traders thus aim to exploit market sentiment and herding – the tendency for traders to follow the majority. You can check out more details on momentum trading here.

How can Python help?

Python is one of the most popular programming languages in finance. Because it is an object-oriented and open-source language, it is used by many large corporations, including Google, for a variety of projects. Simply put, Python can be used to import financial data such as stock quotes using the Pandas framework. The majority of the supporting tools and libraries are open source and freely available. It is also a very simple language because it can read English, which makes it beginner friendly. Further, it is well-known for its simple syntax.

Examples of momentum trading algorithms in Python

Technically, one can curate and craft a wide array of strategies using Python. A few examples of momentum trading algorithms that can be made on Python are:

a) Sector momentum

One strategy for taking advantage of each sector's unique characteristics is our Sector Momentum strategy. Once a month, this innovative strategy invests in the three sectors with the best performance over the past 200 days. Using Sector Momentum, investors can keep up-to-date with the performance of the heavy hitters in the stock market, helping to rebalance their portfolios accordingly. This methodology is a big-picture momentum strategy with a set holding period.

b) Big tech momentum

It’s simple: every month, this strategy invests in the two big tech stocks with the best performance over the past month. Looking at the past performance of heavy hitters like Amazon, Meta, Apple, and Microsoft allows us to identify trends that can be captured during the monthly rebalance each month.

c) Commodity momentum

Each month, we consider the performance of each commodity over the most recent time series and evaluate it relative to the portfolio’s set rules. These rules are meant to capture risk factors and market dynamics reflected in commodity prices. Further, only commodity ETFs with sufficient trading volume are included in the strategy. Commodity Momentum can be backtested with benchmarks to help investors understand what momentum returns are possible.

d) Global momentum

Looking for price trends that endure because of under reactions to new information in the global market can help make investment decisions. World markets, such as the US, Europe, Australasia, the Far East, and Emerging Markets are all evaluated alongside bonds and commodities. Once a month, this strategy invests in the best-performing asset within each category.

Taking advantage of domestic equities, international equities, bonds, commodities, and alternative investments, this momentum portfolio has it all.

e) Composer's new 60/40 portfolio:

Composer's new 60/40 Portfolio believes in diversification through leverage. This plan allocates two-thirds of the portfolio to a modestly leveraged ETF that should deliver returns similar to a traditional 60/40 strategy. This frees up one-third of the portfolio for diversifying assets, in this case, commodities. It’s a multi-strategy portfolio that combines 60/40 and commodity momentum. Check it out or build your own multi-strategy creation.

You can check out a detailed summary of these strategies here

Python basics

Ideally, one should have a good working knowledge of Python to execute these strategies by themselves.

Python as a language is made simpler by libraries, which are reusable chunks of code that someone else has already built for you. This particular language also has a robust framework of open-source, third-party libraries that are useful in all sorts of situations but specifically for finance.

Libraries like Scikit and Pybrain are especially useful in the finance world. Financial data analysis with Python is a lot quicker with these libraries because they often have code that is pre-written. A range of other add-ons, such as Scipy, make it easier to work with the data and find insights.

Creating your first algorithm

One simple way to create your first algorithm could be to develop a momentum strategy that relies on price and volume moving averages for securities.

We can start by using financial data scraped from Yahoo! Finance. This can be generated by using the Pandas library. The code would look something like this:

Python script for a momentum strategy that relies on price and volume moving averages for securities using the Pandas library.

Python script for a simple momentum strategy

The key questions to answer then are: i) What is the universe of stocks we will consider?, ii) What is the time frame to consider?, iii) What are the buy-and-sell signals? One simple momentum-trading strategy is to buy when stock price is below the 30-day moving average and daily volume is above the 30-day moving average. The inverse of this could be a sell trigger. Step-by-step basics of Python are available online through asynchronous courses or through step-by-step articles here.

No-code alternatives

All of these details on Python-based strategies might seem a little technical and time-consuming. That's because they are.

Composer was built to simplify and streamline the trading process for all different types of momentum traders and now is a good time to consider this investment strategy. Per the Composer investment team on the current market environment: “We are expecting continued dispersion in sector returns, and we prefer strategies like Sector Momentum, which have the potential to outperform a broad market portfolio.”

Sector Momentum investment strategy on Composer

Sector Momentum strategy built using Composer

A global momentum investment strategy on Composer

Global Momentum strategy built using Composer

Conclusion

Momentum trading is a time-tested strategy that has historically delivered strong returns. Python is a great way to create momentum trading strategies, but might not be suitable for those investors who don't have a strong technical background or don't already know how to code. 

If you are a focused or serious investor looking to generate returns through momentum trading, it might be a good idea to go with established platforms. Composer offer a customized, flexible, and backtested strategy that takes care of the coding while you focus on the investing. Get started here.

Important Disclosures

Investing in securities involves risks, including the risk of loss, including principal. Composer Technologies Inc., is an SEC Registered RIA. The SEC has not approved this message.

Certain information contained in here has been obtained from third-party sources. While taken from sources believed to be reliable, Composer has not independently verified such information and makes no representations about the accuracy of the information or its appropriateness for a given situation. In addition, this content may include third-party advertisements; Composer has not reviewed such advertisements and does not endorse any advertising content contained therein.

This content is provided for informational purposes only, as it was prepared without regard to any specific objectives, or financial circumstances, and should not be relied upon as legal, business, investment, or tax advice. You should consult your own advisers as to those matters. References to any securities or digital assets are for illustrative purposes only and do not constitute an investment recommendation or offer to provide investment advisory services. Furthermore, this content is not intended as a recommendation to purchase or sell any security and performance of certain hypothetical scenarios described herein is not necessarily indicative of actual results. Any investments referred to, or described are not representative of all investments in strategies managed by Composer, and there can be no assurance that the investments will be profitable or that other investments made in the future will have similar characteristics or results.

Charts and graphs provided within are for informational purposes solely and should not be relied upon when making any investment decision. Past performance is not indicative of future results. The content speaks only as of the date indicated. Any projections, estimates, forecasts, targets, prospects, and/or opinions expressed in these materials are subject to change without notice and may differ or be contrary to opinions expressed by others. Please see Composer's Legal Page for additional important information.