what is momentum investing and how to automate it with python

What Is Momentum Investing and How to Automate It with Python

Imagine you’re at a busy train station, watching passengers rush toward a platform. If you see a crowd heading in one direction, there’s probably a good reason—perhaps that’s where the next train is departing. Momentum investing works on a surprisingly similar principle: assets that have been performing well recently tend to continue performing well, at least for a while.

But here’s where it gets exciting for us at PocketBots. What if you could track these movements automatically, without spending hours glued to financial charts? That’s exactly what we’re exploring today—understanding what momentum investing is and how to automate it with Python, even if you’ve never written a line of code in your life.

Whether you’re looking to supplement your income, build long-term wealth, or simply understand a strategy that professional fund managers have used for decades, this guide will walk you through everything step by step. No jargon, no assumptions about your background—just practical knowledge you can actually use.

Understanding Momentum Investing: The Basics

At its core, momentum investing is based on a simple observation: stocks, funds, and other assets that have risen in price over a certain period often continue rising, while those that have fallen tend to keep falling. It sounds almost too simple, doesn’t it? Yet academic research going back to the 1990s has consistently shown that momentum is one of the most persistent patterns in financial markets.

Think of it like a snowball rolling down a hill. Once it gets going, it tends to pick up more snow and move faster—until something stops it. In financial terms, this happens because of human psychology. When investors see an asset rising, more people want to buy it, which pushes the price up further. This creates a self-reinforcing cycle that momentum investors try to capture.

How Momentum Differs from Other Strategies

You might have heard of “buy and hold” investing, where you purchase assets and simply wait for them to grow over many years. Momentum investing is more active than this. Instead of holding everything forever, momentum investors regularly review their portfolios and shift money toward whatever is currently performing best.

It’s also different from “value investing,” which involves hunting for bargains—assets that seem underpriced compared to their true worth. Value investors are essentially saying “this is cheap, it should go up.” Momentum investors are saying “this is already going up, it should keep going.”

Neither approach is inherently better. They simply work in different market conditions and suit different personalities. Many sophisticated investors actually combine both strategies.

The Evidence Behind Momentum

You might be wondering: if momentum investing works, why doesn’t everyone do it? The truth is, many professional investors do. Research by academics like Jegadeesh and Titman found that stocks with strong recent performance outperformed those with weak performance by an average of about 1% per month over the following year.

However—and this is crucial to understand—momentum doesn’t work all the time. It can fail spectacularly during market reversals, such as the recovery from the 2009 financial crisis or the bounce-back after the 2020 pandemic crash. This is why understanding the risks is just as important as understanding the potential rewards.

Why Automation Makes Sense for Momentum Investing

Here’s where things get interesting for anyone interested in passive income. Momentum investing requires regular monitoring and rebalancing—checking which assets are performing well, calculating returns over specific periods, and making trades accordingly. Doing this manually is time-consuming and prone to emotional decision-making.

This is precisely why automation is so powerful. A Python script doesn’t get nervous during market dips. It doesn’t get greedy during rallies. It simply follows the rules you’ve set, executing your strategy consistently without the psychological pitfalls that trip up human investors.

The Benefits of Automating Your Strategy

  • Consistency: Your strategy runs exactly the same way every time, removing emotional bias from your decisions.
  • Time savings: Once set up, your system can do in seconds what might take you hours to calculate manually.
  • Backtesting: You can test your strategy against historical data to see how it would have performed before risking real money.
  • Scalability: The same script that monitors 10 assets can easily monitor 100 or even 1,000.
  • Learning opportunity: Building these systems teaches you valuable skills in both programming and finance.

A Real UK Example: Momentum Investing with Index Funds

Let’s make this concrete with a scenario that’s relevant to UK investors. Imagine Sarah, a 35-year-old teacher from Manchester, wants to implement a simple momentum strategy using her Stocks and Shares ISA. She’s not interested in picking individual stocks—too risky and time-consuming. Instead, she wants to rotate between broad market index funds based on their momentum.

Sarah chooses four funds available through her ISA provider:

  • A UK FTSE 100 tracker fund
  • A US S&P 500 tracker fund
  • A European equity fund
  • A global bond fund

Her momentum rule is simple: at the end of each month, calculate which fund has performed best over the past three months, and hold that fund for the following month. If the best performer has actually lost money over three months, hold the bond fund as a safety measure.

Let’s say Sarah starts with £10,000 in January 2023. Using historical data, she might find that the S&P 500 tracker gained 8% over the previous three months, while the FTSE 100 gained only 2%, European equities fell 1%, and bonds fell 3%. Her system would automatically identify the S&P 500 fund as the winner and allocate her entire £10,000 there.

Over the course of a year, this rotation might look something like:

  • January-March: S&P 500 (returns 4%)
  • April-June: S&P 500 (returns 2%)
  • July-September: FTSE 100 (returns 3%)
  • October-December: S&P 500 (returns 5%)

Sarah’s £10,000 would have grown to approximately £11,450—a 14.5% return for the year. Of course, this is a simplified example, and actual results would depend on market conditions, trading costs, and the specific funds chosen. Some years the strategy might underperform a simple buy-and-hold approach; other years it might significantly outperform.

Step-by-Step Guide: Automating Momentum Investing with Python

Now let’s get practical. Don’t worry if you’ve never programmed before—we’ll break this down into manageable steps. By the end, you’ll have a basic understanding of how to build a momentum tracking system.

Step 1: Setting Up Your Environment

First, you’ll need Python installed on your computer. Visit python.org and download the latest version for Windows or Mac. The installation process is straightforward—just follow the prompts and make sure to tick the box that says “Add Python to PATH.”

Next, you’ll need to install some additional tools called “libraries” that make financial analysis easier. Open your command prompt (Windows) or terminal (Mac) and type:

pip install yfinance pandas numpy

These three libraries will handle downloading financial data, organising it, and performing calculations.

Step 2: Downloading Market Data

The yfinance library lets you download historical price data for free. Here’s a simple script that downloads data for several UK-relevant assets:

import yfinance as yf

import pandas as pd

tickers = [“ISF.L”, “VUSA.L”, “VWRL.L”, “VGOV.L”]

data = yf.download(tickers, period=”1y”)[“Adj Close”]

In this example, ISF.L is the iShares Core FTSE 100 ETF, VUSA.L tracks the S&P 500, VWRL.L is a global equity fund, and VGOV.L holds UK government bonds. These are all traded on the London Stock Exchange in GBP, making them suitable for UK investors.

Step 3: Calculating Momentum Scores

Now we need to calculate how each asset has performed over our chosen lookback period. A common approach is to calculate the percentage return over the past 3, 6, or 12 months. Here’s how:

lookback_days = 63 (approximately 3 months of trading days)

momentum = data.pct_change(lookback_days).iloc[-1]

best_performer = momentum.idxmax()

This code calculates the percentage change over 63 trading days for each asset, then identifies which one performed best. The result tells you which fund has the strongest momentum.

Step 4: Building a Simple Signal System

Rather than manually checking your momentum calculations, you can create a script that runs automatically and sends you an email or notification when it’s time to rebalance. Here’s a basic structure:

if momentum[best_performer] > 0:

signal = f”Momentum signal: Buy {best_performer}”

else:

signal = “All assets have negative momentum. Consider holding cash or bonds.”

This adds a safety check—if even the best performer has lost money over your lookback period, the system suggests staying defensive.

Step 5: Backtesting Your Strategy

Before using any strategy with real money, you should test how it would have performed historically. This process is called backtesting. While a full backtesting system is beyond the scope of this introduction, the basic concept involves:

  1. Downloading several years of historical data
  2. Simulating what your strategy would have done at each rebalancing point
  3. Calculating the total returns, including any trading costs
  4. Comparing this to a simple buy-and-hold benchmark

Libraries like “backtrader” or “bt” can help with this process, and there are many free tutorials available online.

Step 6: Running Your Script Automatically

The final step in true automation is scheduling your script to run without you having to remember. On Windows, you can use Task Scheduler. On Mac, you can use cron jobs. Alternatively, cloud services like PythonAnywhere offer free tiers that let you schedule scripts to run daily or weekly.

Important Considerations for UK Investors

Before you rush off to implement this strategy, there are several UK-specific factors you need to consider carefully.

Tax Implications

Momentum investing typically involves more frequent trading than buy-and-hold strategies. Outside of an ISA or pension wrapper, this could trigger capital gains tax. The current CGT allowance for 2024-25 is just £3,000, down significantly from previous years. Gains above this amount are taxed at 10% for basic rate taxpayers and 20% for higher rate taxpayers.

This is why implementing momentum strategies within a Stocks and Shares ISA is so attractive—all gains are completely tax-free. You can contribute up to £20,000 per year to ISAs, making them ideal for strategies that generate frequent taxable events.

FCA Regulation and Platform Choice

Any platform you use for investing should be authorised and regulated by the Financial Conduct Authority (FCA). This provides important protections, including access to the Financial Services Compensation Scheme (FSCS), which protects up to £85,000 per person per institution if your provider fails.

Some platforms that offer API access (which you’d need for fully automated trading) include Interactive Brokers and IG. However, be aware that API trading is an advanced feature and comes with additional risks. For most people starting out, using Python for analysis and signals while executing trades manually through a standard platform like Hargreaves Lansdown, AJ Bell, or Vanguard is a safer approach.

Costs Matter

Trading costs can significantly erode momentum strategy returns. If you’re paying £10 per trade and rebalancing monthly across four funds, that’s potentially £480 per year in trading fees alone. On a £10,000 portfolio, that’s 4.8% of your capital—a substantial drag on returns.

Look for platforms offering commission-free trading on funds or ETFs. Some platforms charge percentage-based fees rather than flat fees, which can work out better or worse depending on your portfolio size.

The Risks You Must Understand

We wouldn’t be doing our job at PocketBots if we didn’t emphasise the risks involved in momentum investing and automated trading.

Momentum Crashes

The biggest risk specific to momentum strategies is the “momentum crash.” This happens when markets suddenly reverse direction. Assets that were falling start rising sharply, while previous winners collapse. This occurred dramatically in 2009 when beaten-down financial stocks surged while previous momentum winners lagged badly.

Technical Failures

Automated systems can fail. Data feeds can be incorrect. Code can have bugs. Internet connections can drop. If you’re using automation, always have safeguards in place and never risk more than you can afford to lose.

Past Performance Limitations

Just because a backtest looks profitable doesn’t mean the strategy will work going forward. Markets change, and strategies that worked historically can stop working. This is why diversification and position sizing remain important even with automated systems.

Getting Started: Your Action Plan

If you’re excited about learning what momentum investing is and how to automate it with Python, here’s a sensible path forward:

  1. Educate yourself first: Spend a few weeks reading about momentum investing and Python basics before risking any money.
  2. Start with paper trading: Run your momentum signals on paper (or in a spreadsheet) for several months to see how they would perform.
  3. Begin small: When you’re ready for real money, start with a small amount you’re genuinely comfortable losing.
  4. Use tax-efficient wrappers: Implement your strategy within an ISA or SIPP to avoid unnecessary tax complications.
  5. Keep learning: The Python and investing communities are incredibly helpful. Join forums, read blogs, and continuously improve your knowledge.

Conclusion: Your Journey Begins Here

Understanding what momentum investing is and how to automate it with Python opens up genuinely exciting possibilities for building passive income streams. It combines a time-tested investment approach with modern technology in a way that was simply impossible for ordinary investors just a decade ago.

But remember—this is a journey, not a destination. The most successful automated investors are those who start small, learn continuously, and treat early setbacks as valuable lessons rather than reasons to give up. The Python skills you develop along the way are valuable far beyond just investing, and the financial knowledge you gain will serve you for life.

At PocketBots, we believe that automation and AI should be accessible to everyone, not just tech experts or City professionals. Whether you’re a nurse in Newcastle, a teacher in Telford, or a shop worker in Sheffield, these tools are within your reach. The barriers

3 thoughts on “what is momentum investing and how to automate it with python”

  1. Pingback: what is the difference between ETF and index fund UK beginner guide - PocketBots

  2. Pingback: VYM ETF review high dividend yield for UK investors 2026 - PocketBots

  3. Pingback: how to set up a python script to buy ETFs automatically every week - PocketBots

Leave a Comment

Your email address will not be published. Required fields are marked *

Scroll to Top