Skip to content
Home » Scripts » Starting with Momentum Trading Strategy in Algorithmic Trading

Starting with Momentum Trading Strategy in Algorithmic Trading

Jump to The Code

Beginning Your Journey with Momentum Trading Strategy in Algorithmic Trading

Are you starting out in algorithmic trading? Then, you might find the Momentum Trading Strategy quite interesting. This strategy helps traders make profits from market trends. It’s a strategy mentioned in “A Beginner’s Guide to the Stock Market” by Matthew R. Kratter[1].

The core idea of Momentum Trading Strategy is simple. If a stock is moving upwards, you buy. If it’s going down, you sell. This strategy works on the belief that stocks will continue to rise or fall for a while.

In “Algorithmic Trading Winning Strategies and Their Rationale” by Ernest P. Chan[2], this strategy gets a significant highlight. According to Chan, momentum trading is a favorite among algorithmic traders due to its simplicity and effectiveness.

How Does It Work?

When using the Momentum Trading Strategy, you monitor market trends closely. If a stock price starts to rise, you buy. If it starts to fall, you sell. This way, you always move with the market trend, earning profits along the way.

One crucial tool for implementing this strategy is the Momentum Indicator. This indicator tells you the rate at which the price of an asset is changing. A positive momentum means the price is rising, while a negative momentum means it’s falling.

Risk Management

Every trading strategy comes with its risks. For Momentum Trading, the risk lies in the trend reversing suddenly. To manage this risk, traders use stop-loss orders.

Summary

The Momentum Trading Strategy is a great place to start in algorithmic trading. It’s simple to understand and easy to implement. However, like all trading strategies, you must manage your risks effectively.

Remember to backtest any strategy before you start trading. Backtesting will give you a feel for the strategy and help you understand its risks and rewards.

References

[1] “A Beginner’s Guide to the Stock Market“, Matthew R. Kratter

[2] “Algorithmic Trading Winning Strategies and Their Rationale“, Ernest P. Chan

The Code

Sample #1 – Using Simple Moving Averages to Indicate Momentum

In this algorithm, we use two simple moving averages (SMA) with different periods (14 and 28 days). The 14-day SMA is the “fast” SMA because it responds more quickly to price changes, while the 28-day SMA is the “slow” SMA. When the fast SMA crosses above the slow SMA, it indicates upward momentum, and the algorithm goes long. When the fast SMA crosses below the slow SMA, it indicates downward momentum, and the algorithm exits the long position.

Click on the code to copy it to your clipboard.
Click here for detailed instructions on how to use the scripts in QuantConnect.

Python
from clr import AddReference
AddReference("System")
AddReference("QuantConnect.Algorithm")
AddReference("QuantConnect.Indicators")
AddReference("QuantConnect.Common")

from System import *
from QuantConnect import *
from QuantConnect.Algorithm import *
from QuantConnect.Indicators import *

class MomentumTradingExample(QCAlgorithm):
    def Initialize(self):
        self.SetStartDate(2018, 1, 1)  
        self.SetCash(100000)  
        self._symbol = self.AddEquity("AAPL", Resolution.Daily).Symbol

        # Create the indicators
        self._fastSMA = self.SMA(self._symbol, 14, Resolution.Daily)
        self._slowSMA = self.SMA(self._symbol, 28, Resolution.Daily)

    def OnData(self, data):
        if not self._fastSMA.IsReady or not self._slowSMA.IsReady:
            return

        # Fast SMA crosses above Slow SMA -> upward momentum -> go long
        if self._fastSMA.Current.Value > self._slowSMA.Current.Value and not self.Portfolio[self._symbol].Invested:
            self.SetHoldings(self._symbol, 1)
        # Fast SMA crosses below Slow SMA -> downward momentum -> exit long position
        elif self._fastSMA.Current.Value < self._slowSMA.Current.Value and self.Portfolio[self._symbol].Invested:
            self.Liquidate(self._symbol)
C#


#region imports
    using QuantConnect.Algorithm;
    using QuantConnect.Indicators;
    using QuantConnect.Data;
#endregion

namespace QuantConnect
{

 public class MomentumTradingExample : QCAlgorithm
    {
        private string _symbol = "AAPL";
        private SimpleMovingAverage _fastSMA;
        private SimpleMovingAverage _slowSMA;

        public override void Initialize()
        {
            SetStartDate(2018, 1, 1);  
            SetCash(100000);  

            AddEquity(_symbol, Resolution.Daily);
            
            _fastSMA = SMA(_symbol, 14);
            _slowSMA = SMA(_symbol, 28);
        }

        public override void OnData(Slice data)
        {
            if (!_fastSMA.IsReady || !_slowSMA.IsReady)
                return;
            
            // Fast SMA crosses above Slow SMA -> upward momentum -> go long
            if (_fastSMA > _slowSMA && !Portfolio[_symbol].Invested)
            {
                SetHoldings(_symbol, 1);
            }
            // Fast SMA crosses below Slow SMA -> downward momentum -> exit long position
            else if (_fastSMA < _slowSMA && Portfolio[_symbol].Invested)
            {
                Liquidate(_symbol);
            }
        }
    }
}

Sample #2 – Using the MOM Indicator in QuantConnect

In this example, the MomentumTradingAlgorithm monitors the momentum of the Apple Inc. (AAPL) stock on a daily basis. If the momentum is positive, the algorithm goes long on the stock. If the momentum is negative and the algorithm has already invested in the stock, it goes short. The algorithm also uses a trailing stop risk management model to limit its losses.

Click on the code to copy it to your clipboard.
Click here for detailed instructions on how to use the scripts in QuantConnect.

Python
from clr import AddReference
AddReference("System")
AddReference("QuantConnect.Algorithm")
AddReference("QuantConnect.Common")

from System import *
from QuantConnect import *
from QuantConnect.Algorithm import *
from QuantConnect.Indicators import *
from QuantConnect.Algorithm.Framework.Risk import TrailingStopRiskManagementModel

class MomentumTradingAlgorithm(QCAlgorithm):
    def Initialize(self):
        self.SetStartDate(2021, 1, 1)
        self.SetCash(100000)
        self._symbol = self.AddEquity("AAPL", Resolution.Daily).Symbol
        self._momentum = self.MOM(self._symbol, 14, Resolution.Daily)

        # Set Risk Management
        self.SetRiskManagement(TrailingStopRiskManagementModel(0.02))  # 2% Trailing Stop

    def OnData(self, data):
        if not self._momentum.IsReady: return

        # Going long
        if self._momentum.Current.Value > 0 and not self.Portfolio[self._symbol].Invested:
            self.SetHoldings(self._symbol, 1)
        # Going short
        elif self._momentum.Current.Value < 0 and self.Portfolio[self._symbol].Invested:
            self.SetHoldings(self._symbol, -1)
C#

#region imports
    using QuantConnect.Algorithm.Framework.Risk;
    using QuantConnect.Algorithm;
    using QuantConnect.Indicators;
    using QuantConnect.Data;
#endregion

namespace QuantConnect
{
    public class MomentumTradingAlgorithm : QCAlgorithm
    {
        private Symbol _symbol;
        private Momentum _momentum;
        private const int _momentumPeriod = 14;

        public override void Initialize()
        {
            SetStartDate(2021, 1, 1);
            SetCash(100000);

            _symbol = AddEquity("AAPL", Resolution.Daily).Symbol;
            _momentum = MOM(_symbol, _momentumPeriod, Resolution.Daily);

            // Set Risk Management
            SetRiskManagement(new TrailingStopRiskManagementModel(0.02m)); // 2% Trailing Stop
        }

        public override void OnData(Slice data)
        {
            if (!_momentum.IsReady) return;

            // Going long
            if (_momentum > 0 && !Portfolio[_symbol].Invested)
            {
                SetHoldings(_symbol, 1);
            }
            // Going short
                else if (_momentum < 0 && Portfolio[_symbol].Invested)
            {
                SetHoldings(_symbol, -1);
            }
        }
    }
}

 

Leave a Reply

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