DEV Community

Cover image for Beginner Tutorial for Momentum Trading Algorithms
Isabelle
Isabelle

Posted on

Beginner Tutorial for Momentum Trading Algorithms

Momentum trading algorithms have always fascinated me. I discovered that they are used by some of the world’s biggest hedge funds, as well as people trading at home like me. I remember when I first dipped my toes into algorithmic trading. Momentum strategies seemed like a good entry point. They are simple, well-studied, and very appealing for beginners. In this guide, I want to share what I learned about momentum trading. I’ll walk you through how I built a simple momentum algorithm for stocks. I’ll also talk about common mistakes I made, best practices I wish I knew sooner, and some things you should keep in mind.

Note: This piece was written with artificial intelligence support and may reference projects I'm affiliated with.

What Is Momentum Trading?

To me, momentum trading started making sense when I realized a basic truth. Assets that have recently gone up tend to keep going up, and losers tend to stay weak. The whole idea is to ride price trends, buying when things are strong and hoping they stay strong. In other types of trading, like mean reversion, you bet on things bouncing back. Momentum is more about riding waves and following what’s working.

Some famous traders like Paul Tudor Jones and Mark Minervini are big fans of momentum. I use the same basic ideas. I’ve tried momentum on stocks, forex, crypto, and even a little with commodities. Each one is slightly different, but the same approach works in all of them.

The big ideas in momentum trading that helped me are:

  • Spotting strong trends by using stats or just checking recent returns
  • Ranking assets so I only focus on the top few
  • Rotating the portfolio by replacing weak assets with stronger ones
  • Holding winners until they lose steam, then rinse and repeat

Getting Started: Building a Basic Momentum Algorithm

The first time I built a momentum strategy, I worked with stocks because the data was easy to find. If you’re just starting, I’d recommend going this route too. I kept things very simple at first, and that helped me learn how everything works.

Step 1: Get the Right Data

Good data is the backbone of all these systems. I use Python and the yfinance, pandas, and numpy libraries to download and manage price data. Usually, traders use something like the S&P 500 as their universe. I made a rookie mistake early on by only looking at the current S&P 500 member stocks. I later learned about survivorship bias and how it can trick you into thinking your strategy was way better than it really was.

How I avoid survivorship bias now:

  • I include stocks that have been removed from the index up to the date they were removed.
  • I only add stocks to my universe as of the date they joined the index.
  • Now, I make sure my trading universe is “time-correct,” even though it’s more work.

Step 2: Measuring Momentum

It surprised me how many ways you can measure momentum. The simplest way is to look at the rate of change over a period of time, like checking the percentage a stock price rose in 12 months. I’ve also tried things like moving averages and relative strength indicators. Each method has its fans, but over time, I found that simple is best when learning.

Here’s how I usually calculate 12-Month Momentum

import yfinance as yf
import pandas as pd

# Download price data for a list of stocks
data = yf.download(['AAPL', 'MSFT', 'GOOG'], start='2015-01-01')

# Compute 12-month momentum (252 trading days)
momentum = data['Adj Close'].pct_change(periods=252)
Enter fullscreen mode Exit fullscreen mode
  • I sort all the stocks by their 12-month momentum and focus on the top few.
  • I usually pick something like the top 15.
  • I also filter out stocks that are under their 200-day moving average. I found this helps avoid big downturns.

Step 3: Portfolio Construction and Rebalancing

When I have my list ranked, I choose the strongest names for my portfolio. I try not to fill up on one sector or too many names. I learned the hard way that owning too many stocks just waters down the performance.

  • I usually pick 10 or 15 winners and stick with them.
  • I rebalance every month. Each time, I sell anything that has lost momentum or fallen below the 200-day moving average, then add new leaders.
  • In the beginning, I used an equal amount of money for each position. This is called equal weighting and keeps things simple.

Step 4: Backtesting and Validation

Before I risked any money, I always tested my strategy on historical data.

  • I compare the strategy’s performance to a buy-and-hold approach.
  • I look at things like CAGR (which is annual growth), biggest loss periods, and the Sharpe ratio.
  • Most important, I make sure my code never cheats by using info from the future. Early tests fooled me until I learned about look-ahead bias.

Step 5: Risk Management Rules

Risk management keeps me in the game. I had some painful lessons by not cutting losses fast enough. With momentum, you have a lot of small losses and just a few big wins. The key is never letting a loser get out of hand. I always use stop-losses, keep positions a reasonable size, and have a clear risk plan.

Example Trading Logic (Monthly Rebalancing)

  • At the start of each month, I rank all the S&P 500 stocks by their 12-month returns.
  • I buy the top 15, but only if they’re above the 200-day moving average.
  • I hold them for a month.
  • Next month, I repeat this process. Sell names that drop out of the top or lose technical strength. Replace them with new winners.

Classic Momentum Strategy in Python

Let me show what a simple top-15 momentum strategy looks like in code with pandas. I tinkered with something very close to this:

# Simulated example: Top-15 momentum strategy

all_symbols = [...]  # List of S&P 500 tickers, updated for survivorship
prices = yf.download(all_symbols, start='2015-01-01')['Adj Close']

roll_12mo = prices.pct_change(252)
ma_200 = prices.rolling(200).mean()

results = []

for dt in roll_12mo.index[252::21]:  # Every approx 1 month
    eligible = (prices.loc[dt] > ma_200.loc[dt])
    momentum = roll_12mo.loc[dt][eligible].dropna()
    top = momentum.sort_values(ascending=False).head(15).index
    returns = prices[top].loc[dt:dt+pd.DateOffset(days=21)].pct_change().iloc[1:]
    results.append(returns.mean(axis=1))

strategy_returns = pd.concat(results)
Enter fullscreen mode Exit fullscreen mode

This template is where I started. I quickly saw how lots of details can be added. You may want to think about trading fees, slippage, tighter risk controls, or smarter rules. After running this for the first time, I realized my results needed work, and that became a valuable part of my learning.

Practical Insights and Tips for Beginners

I wish someone had drilled these truths into me early on:

  • Trend-following momentum works great in clear trending markets, but it struggles when price action is stuck in a range or is choppy.
  • Lots of losses: Most trades will lose, but the few winners can more than cover them. I had to get used to this lopsided outcome.
  • Timeframes matter: You can use momentum for days, weeks, or months. I prefer monthly because it keeps things simple and less stressful.
  • Not all assets are the same: My success settings for stocks did not work the same for forex. Always tune to your market.
  • Fake money practice: I made dozens of paper trades before risking anything real. I kept notes on each trade and used a spreadsheet to track what worked and what didn’t.
  • Think about risk before reward: I write down where I will exit for a loss. I only take trades where the reward could be bigger than the risk.

One area that challenged me-and most beginners-is translating more nuanced, discretionary trading ideas into systematic strategies you can actually test and rely on. For example, concepts like failed breakouts, specific price action patterns, or market structure can be tough to quantify and automate. If you want to bridge that gap between your trading instincts and rigorous, institutional-grade backtesting, I've found tools like Nvestiq incredibly helpful. Nvestiq is an AI-powered platform that lets you describe your strategies in plain language, making it much easier to test out those "intuition-based" ideas with statistical evidence. This approach brought more clarity and confidence to how I refined my momentum systems and removed a lot of the guesswork from my decision-making.

Visual Example: Momentum in Action

Imagine you use a momentum strategy on something like the Nasdaq 100. At the start of each month, you buy the 15 stocks with the biggest 12-month gains, as long as they are above the 200-day moving average. Hold for a month, then reshuffle and repeat. When I tried this on the S&P and Nasdaq over several years, I found it often beat the broad index with less ups and downs. There were tough stretches, but it felt much smoother than day trading.

What I love about this low-frequency, rules-based style is that it only takes an hour or two each month. I spend more time living and less time glued to screens.

Common Pitfalls in Algorithmic Momentum Trading

  • Forgetting about trading fees and slippage. They add up.
  • Overlooking survivorship bias and look-ahead bias. Both will trick you.
  • Tuning your system too much for the past, which is called overfitting.
  • Not using stop-losses or letting bad trades linger.
  • Giving up too soon. Momentum sometimes goes through rough patches, but you must stick with it.

Momentum Trading: What’s Next?

As I got more comfortable, I started adding improvements:

  • Screening out very risky or volatile stocks
  • Sizing my positions based on the risk for each trade
  • Combining several momentum signals, like using both price momentum and sector strength
  • Automating my trading and performance checks so I don’t miss anything

I use sites like TradingView, some backtesting platforms, and basic Python code to keep learning faster.

FAQ

What’s the difference between momentum and trend-following?

I’ve always seen momentum and trend-following as cousins. Both look for moves that keep going. Momentum is about buying the recent winners, ranking stocks by their returns. Trend-following usually relies on signals like moving average crossovers. Sometimes, I blend both to strengthen my systems.

Does momentum trading work on all asset classes and timeframes?

Yes, momentum works on stocks, forex, commodities, crypto, and more. You will need to adjust your settings. What works for stocks on a monthly chart rarely works for bitcoin on a 1-hour chart. I always test any new setup on the exact market and frequency I want to trade.

Why do so many momentum strategies fail in sideways or choppy markets?

I learned this the hard way. Momentum needs strong trends to work well. In flat or jumpy markets, you get false signals and lots of losing trades. I accept these dull periods and focus on catching the next big run. Sticking with the process is key.

Can I implement a momentum trading strategy without coding experience?

Absolutely. Early on, I started with spreadsheets. I used Excel and Google Sheets to rank stocks and build sample portfolios. You can check your top picks once a month, then place trades at your broker. Learning some Python helps a lot once you are ready to automate.


Momentum trading became my favorite way to trade because it’s clear and systematic. I feel better when I focus on what’s working and use a repeatable plan. My biggest gains came from sticking with the process and paying close attention to risk. If you practice, keep learning, and stay patient, you’ll eventually see results. Good luck, and happy trading!

Top comments (0)