How to Create a Momentum Trading Algorithm in Python
Momentum trading algorithms in Python can enhance your trading strategy, mitigate risk, and provide valuable market insights.
Buying low and selling high sounds easy, but owning a stock before the market discovers its value requires unique insight and effective timing. Many investors fall into this "value trap" and own a non-performing stock for too long, limiting their growth.
Enter momentum trading algorithms, which help solve these problems by investing in stocks trending upward and liquidating these positions just before stock price mean reversion occurs and wipes out any gains. Leveraging algorithmic trading (or algo trading) enhances momentum strategies by providing a structured and flexible investing framework, which reduces errors and allows you to focus on what works.
Let’s explore how to create momentum trading strategies in Python and leverage Composer’s automated trading tools without knowing a word in the Python library.
What is momentum trading?
Momentum trading is an investing style where traders buy and sell stocks based on recent price trends. This theory suggests that if sufficient force exists behind a price move, it’ll continue moving in the same direction until enough contrarian traders enter the market and momentum changes direction. The style involves critical elements, which include:
Momentum: Market momentum measures an asset’s speed or velocity––the greater the momentum, the longer a price trend can sustain itself.
Technical indicators: Momentum traders use various technical indicators––including moving average convergence divergence (MACD), relative strength index (RSI), and average directional index (ADX)––to predict price trends.
Fundamental analysis: Some momentum trading systems emphasize fundamental analysis factors, such as quarterly or annual earnings per share (EPS), to avoid making emotional decisions.
Price signals: Momentum traders usually aim to enter during a trend’s main body rather than the top or bottom by carefully watching price signals and tracking price movements over time.
Market sentiment: Momentum traders exploit market sentiment and herding––which is the tendency for traders to follow the majority––allowing them to capitalize on short-term price moves.
How can Python help?
Python is one of the most popular programming languages in finance. It’s an object-oriented language and excels at advanced statistics and data visualization, making it a favorite among algorithmic traders.
Python is also open-source, meaning traders can use many Python tools and libraries for free. It uses a simple syntax and can read English, which means even beginner algo traders can learn the language relatively quickly.
Python libraries like Scikit and Pybrain are available across the finance world. Manipulating financial data with Python is much quicker with these libraries because they often use pre-written code, simplifying backtesting and strategy analysis. Other add-ons like Scipy make working with data and finding market insights easier. Companies frequently use Python when importing financial data, such as stock quotes, using the Pandas DataFrame.
Ideally, traders should have a solid knowledge of code structure before creating a stock trading bot with Python. By taking time to backtest your trading bot strategy, they can limit risk and increase experience with algorithmic trading in a controlled environment.
Examples of momentum trading algorithms in Python
Curating and crafting various strategies using Python is easy (see a few examples using Composer's no-code editor below). Here are a few momentum trading algorithms you can make in Python:
Sector momentum
The sector momentum strategy takes advantage of each sector's unique characteristics. 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 stay updated with the top-performing stocks in the market, helping rebalance their portfolios accordingly. It’s a big-picture momentum strategy with a set holding period.
Big tech momentum
Big tech momentum, every month, invests in 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 traders to identify trends that can be captured during the monthly rebalance.
Commodity momentum
Each month, this strategy considers the performance of each commodity over the most recent time series and evaluates it relative to the portfolio’s set rules. These rules capture risk factors like the Sharpe ratio and market dynamics reflected in commodity prices.
Further, the strategy only includes commodity exchange-traded funds (ETFs) with sufficient trading volume. Traders can backtest commodity momentum with benchmarks, helping them estimate possible momentum returns.
Global momentum
The global momentum strategy looks for price trends that endure based on (under) reactions to new information in the global market. It evaluates world markets, such as the U.S., Europe, Australasia, the Far East, and emerging markets, as well as bonds and commodities markets. Once a month, this strategy invests in the best-performing asset within each category.
How to create your first algorithm
Crafting your first algorithm involves developing a momentum strategy that relies on the price moving average (e.g., dividing the stock close price on the last day by the stock close price 20 days ago). If the ratio exceeds 1 (positive trend), buy the stock. While this is a relatively simple example, it can help you understand how we build momentum strategies in Python.
Before moving on to step 1, research the Jupyter-notebook to learn Python because this is where you can execute your Python code. You can install Jupyter or use an online tool such as Google Colab.
Here’s a step-by-step guide to creating your first algorithm:
1. Install the necessary packages
Download and install pandas, alpaca-trade-API in the command line using pip:
pip install pandas pip install alpaca-trade-api
2. Create an alpaca account, and obtain your API key and secret
You can do this by signing up at https://alpaca.markets/. This allows you to easily access paper trading to test our strategies before implementing them with live money. You can use other brokerages, such as Interactive Brokers, but we'll use Alpaca for this tutorial.
3. Develop a new Python file, and import the necessary packages
Here’s how to execute this step in Python:
import alpaca_trade_api as tradeapi import pandas as pd
4. Set up the API credentials
The next step is to establish your credentials. Here’s how:
API_KEY = 'your-api-key' API_SECRET = 'your-api-secret' APCA_API_BASE_URL = 'https://paper-api.alpaca.markets' api = tradeapi.REST(API_KEY, API_SECRET, APCA_API_BASE_URL, api_version='v2')
Note: Make sure to replace API_KEY and API_SECRET with your own API key and secret, and store them securely in a .env file.
5. Define the stock universe you want to trade
For this example, we'll use the S&P 500:
universe = pd.DataFrame(api.list_assets(status='active')).query('symbol in @api.get_barset('SPY', '1D', limit=1).df.columns').symbol.tolist()
This will give you all the active stocks in the S&P 500.
6. Mention the time you want to look back on for the momentum calculation
For this example, we'll use the past 20 trading days:
momentum_period = 20
7. Determine a function to calculate a given stock’s momentum
Next, choose and mention a function.
def calculate_momentum(stock): df = api.get_barset(stock, 'day', limit=momentum_period).df[stock] momentum = df['close'][-1] / df['close'][0] return momentum
8. Describe a function to trade based on momentum
Here’s how to implement this step:
def trade_momentum(): for stock in universe: momentum = calculate_momentum(stock) if momentum > 1: api.submit_order( symbol=stock, qty=1, side='buy', type='market', time_in_force='gtc' )
This function loops through all the stocks in the universe, calculates their momentum, and buys any stock whose momentum exceeds one (indicating a positive trend).
9. Call the trade_momentum() function
This will execute the momentum strategy and buy stocks meeting the momentum criteria. You can then create a function that runs at a regular interval, like daily.
Note: This strategy only focuses on positive momentum buying, but you can also adapt the strategy to look for if the momentum ratio < X to sell.
The key questions you must answer include:
What stocks do you want to trade?
What time frame will you use?
What are the buy-and-sell signals?
One simple momentum trading strategy involves buying a stock when the price is below the 30-day moving average and the daily volume is above the 30-day moving average. The inverse of this could be a sell trigger.
No-code alternatives
Python-based strategies may seem daunting because they’re a little scientific and technical. And that’s where momentum trading comes into the picture. It’s a time-tested strategy that has historically delivered strong returns. Although Python-based algorithms offer a great way to create momentum trading strategies, coding in Python might not be suitable for investors without a solid technical background or who don't already know how to code.
Great news––Composer to your rescue.
Composer was built to simplify and streamline the trading process for all types of momentum traders, and now is an excellent 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.”


If you’re a focused or serious investor looking to generate returns through momentum trading, it’s time to head to composer.trade. We offer a customized, flexible, and backtested strategy that takes care of the coding while you focus on investing.
Important Disclosures
Investing in securities involves risks, including the risk of loss, including principal. Composer Securities LLC is a broker-dealer registered with the SEC and member of FINRA / SIPC. 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.