Time Series Momentum
This approach goes long or short each asset based on its own past returns. If the trailing return is positive the model buys; if negative it sells, forming a diversified trend‑following portfolio.
Signals are evaluated monthly using one‑year lookbacks and positions are equally weighted across assets.
Details
- Data: Monthly total returns for each asset.
- Entry: Long when 12‑month return > 0; short when < 0.
- Exit: Reverse when the signal changes sign.
- Instruments: Broad set of futures or ETFs.
- Risk: Volatility scaling and diversification.
// TimeSeriesMomentumStrategy.cs
// -----------------------------------------------------------------------------
// Time series momentum strategy with volatility scaling.
// Uses rate of change (momentum) and standard deviation (volatility)
// to determine position direction and sizing.
// Long when momentum positive, short when negative.
// Cooldown prevents excessive trading.
// -----------------------------------------------------------------------------
// Date: 2 Aug 2025
// -----------------------------------------------------------------------------
using System;
using System.Collections.Generic;
using Ecng.Common;
using StockSharp.Algo.Indicators;
using StockSharp.Algo.Strategies;
using StockSharp.BusinessEntities;
using StockSharp.Messages;
namespace StockSharp.Samples.Strategies;
/// <summary>
/// Time series momentum strategy with volatility scaling.
/// </summary>
public class TimeSeriesMomentumStrategy : Strategy
{
private readonly StrategyParam<int> _momentumPeriod;
private readonly StrategyParam<int> _volPeriod;
private readonly StrategyParam<int> _cooldownBars;
private readonly StrategyParam<DataType> _candleType;
/// <summary>
/// Momentum lookback period.
/// </summary>
public int MomentumPeriod
{
get => _momentumPeriod.Value;
set => _momentumPeriod.Value = value;
}
/// <summary>
/// Volatility measurement period.
/// </summary>
public int VolPeriod
{
get => _volPeriod.Value;
set => _volPeriod.Value = value;
}
/// <summary>
/// Cooldown bars between trades.
/// </summary>
public int CooldownBars
{
get => _cooldownBars.Value;
set => _cooldownBars.Value = value;
}
/// <summary>
/// The type of candles to use for strategy calculation.
/// </summary>
public DataType CandleType
{
get => _candleType.Value;
set => _candleType.Value = value;
}
private RateOfChange _momentum;
private StandardDeviation _volatility;
private int _cooldownRemaining;
public TimeSeriesMomentumStrategy()
{
_momentumPeriod = Param(nameof(MomentumPeriod), 20)
.SetDisplay("Momentum Period", "Lookback for momentum calculation", "Parameters");
_volPeriod = Param(nameof(VolPeriod), 14)
.SetDisplay("Volatility Period", "Period for volatility estimation", "Parameters");
_cooldownBars = Param(nameof(CooldownBars), 25)
.SetDisplay("Cooldown Bars", "Bars to wait between trades", "Risk");
_candleType = Param(nameof(CandleType), TimeSpan.FromMinutes(30).TimeFrame())
.SetDisplay("Candle Type", "Type of candles to use", "General");
}
/// <inheritdoc />
public override IEnumerable<(Security sec, DataType dt)> GetWorkingSecurities()
{
if (Security != null)
yield return (Security, CandleType);
}
/// <inheritdoc />
protected override void OnReseted()
{
base.OnReseted();
_momentum = null;
_volatility = null;
_cooldownRemaining = 0;
}
/// <inheritdoc />
protected override void OnStarted2(DateTime time)
{
base.OnStarted2(time);
_momentum = new RateOfChange { Length = MomentumPeriod };
_volatility = new StandardDeviation { Length = VolPeriod };
SubscribeCandles(CandleType)
.Bind(_momentum, _volatility, ProcessCandle)
.Start();
}
private void ProcessCandle(ICandleMessage candle, decimal momentumValue, decimal volatilityValue)
{
if (candle.State != CandleStates.Finished)
return;
if (!_momentum.IsFormed || !_volatility.IsFormed)
return;
if (!IsFormedAndOnlineAndAllowTrading())
return;
if (_cooldownRemaining > 0)
{
_cooldownRemaining--;
return;
}
// Positive momentum -> long; Negative momentum -> short
if (momentumValue > 0 && Position <= 0)
{
if (Position < 0)
BuyMarket(Math.Abs(Position));
BuyMarket(Volume);
_cooldownRemaining = CooldownBars;
}
else if (momentumValue < 0 && Position >= 0)
{
if (Position > 0)
SellMarket(Math.Abs(Position));
SellMarket(Volume);
_cooldownRemaining = CooldownBars;
}
}
}
import clr
clr.AddReference("StockSharp.Messages")
clr.AddReference("StockSharp.Algo")
clr.AddReference("StockSharp.Algo.Indicators")
clr.AddReference("StockSharp.Algo.Strategies")
from System import TimeSpan, Math
from StockSharp.Messages import DataType, CandleStates
from StockSharp.Algo.Indicators import RateOfChange, StandardDeviation
from StockSharp.Algo.Strategies import Strategy
class time_series_momentum_strategy(Strategy):
"""Time series momentum strategy with volatility scaling."""
def __init__(self):
super(time_series_momentum_strategy, self).__init__()
self._momentum_period = self.Param("MomentumPeriod", 20) \
.SetDisplay("Momentum Period", "Lookback for momentum calculation", "Parameters")
self._vol_period = self.Param("VolPeriod", 14) \
.SetDisplay("Volatility Period", "Period for volatility estimation", "Parameters")
self._cooldown_bars = self.Param("CooldownBars", 25) \
.SetDisplay("Cooldown Bars", "Bars to wait between trades", "Risk")
self._candle_type = self.Param("CandleType", DataType.TimeFrame(TimeSpan.FromMinutes(30))) \
.SetDisplay("Candle Type", "Type of candles to use", "General")
self._momentum = None
self._volatility = None
self._cooldown_remaining = 0
@property
def candle_type(self):
return self._candle_type.Value
def OnReseted(self):
super(time_series_momentum_strategy, self).OnReseted()
self._momentum = None
self._volatility = None
self._cooldown_remaining = 0
def OnStarted2(self, time):
super(time_series_momentum_strategy, self).OnStarted2(time)
self._momentum = RateOfChange()
self._momentum.Length = int(self._momentum_period.Value)
self._volatility = StandardDeviation()
self._volatility.Length = int(self._vol_period.Value)
subscription = self.SubscribeCandles(self.candle_type)
subscription \
.Bind(self._momentum, self._volatility, self._process_candle) \
.Start()
def _process_candle(self, candle, momentum_val, vol_val):
if candle.State != CandleStates.Finished:
return
if not self._momentum.IsFormed or not self._volatility.IsFormed:
return
if not self.IsFormedAndOnlineAndAllowTrading():
return
if self._cooldown_remaining > 0:
self._cooldown_remaining -= 1
return
mv = float(momentum_val)
if mv > 0 and self.Position <= 0:
if self.Position < 0:
self.BuyMarket(Math.Abs(self.Position))
self.BuyMarket(self.Volume)
self._cooldown_remaining = int(self._cooldown_bars.Value)
elif mv < 0 and self.Position >= 0:
if self.Position > 0:
self.SellMarket(Math.Abs(self.Position))
self.SellMarket(self.Volume)
self._cooldown_remaining = int(self._cooldown_bars.Value)
def CreateClone(self):
return time_series_momentum_strategy()