ZScore
Strategy based on Z-Score indicator for mean reversion trading
Testing indicates an average annual return of about 121%. It performs best in the crypto market.
ZScore measures price deviation from a moving average. Extreme high or low z-scores suggest overextension and prompt trades in the opposite direction. The trade ends when the z-score normalizes.
Z-Score is a flexible filter because it can be scaled to any time series. Using a volatility-adjusted exit helps the system adapt to changing market conditions.
Details
- Entry Criteria: Signals based on MA, ZScore.
- Long/Short: Both directions.
- Exit Criteria: Opposite signal or stop.
- Stops: Yes.
- Default Values:
ZScoreEntryThreshold= 2.0mZScoreExitThreshold= 0.0mMAPeriod= 20StdDevPeriod= 20StopLossPercent= 2.0mCandleType= TimeSpan.FromMinutes(5)
- Filters:
- Category: Mean Reversion
- Direction: Both
- Indicators: MA, ZScore
- Stops: Yes
- Complexity: Basic
- Timeframe: Intraday (5m)
- Seasonality: No
- Neural Networks: No
- Divergence: No
- Risk Level: Medium
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>
/// Strategy based on Z-Score indicator for mean reversion trading.
/// Z-Score measures the distance from the price to its moving average in standard deviations.
/// </summary>
public class ZScoreStrategy : Strategy
{
private readonly StrategyParam<decimal> _zScoreEntryThreshold;
private readonly StrategyParam<decimal> _zScoreExitThreshold;
private readonly StrategyParam<int> _maPeriod;
private readonly StrategyParam<int> _stdDevPeriod;
private readonly StrategyParam<DataType> _candleType;
private readonly StrategyParam<decimal> _stopLossPercent;
private Order _pendingOrder;
/// <summary>
/// Z-Score threshold for entry (default: 2.0)
/// </summary>
public decimal ZScoreEntryThreshold
{
get => _zScoreEntryThreshold.Value;
set => _zScoreEntryThreshold.Value = value;
}
/// <summary>
/// Half-width of the neutral exit zone (default: 0).
/// </summary>
public decimal ZScoreExitThreshold
{
get => _zScoreExitThreshold.Value;
set => _zScoreExitThreshold.Value = value;
}
/// <summary>
/// Period for Moving Average calculation (default: 20)
/// </summary>
public int MAPeriod
{
get => _maPeriod.Value;
set => _maPeriod.Value = value;
}
/// <summary>
/// Period for Standard Deviation calculation (default: 20)
/// </summary>
public int StdDevPeriod
{
get => _stdDevPeriod.Value;
set => _stdDevPeriod.Value = value;
}
/// <summary>
/// Type of candles used for strategy calculation.
/// </summary>
public DataType CandleType
{
get => _candleType.Value;
set => _candleType.Value = value;
}
/// <summary>
/// Initialize the Z-Score strategy.
/// </summary>
public ZScoreStrategy()
{
_zScoreEntryThreshold = Param(nameof(ZScoreEntryThreshold), 2m).SetGreaterThanZero()
.SetDisplay("Z-Score Entry", "Distance from mean in std devs for entry", "Z-Score")
.SetOptimize(1.5m, 3.0m, 0.5m);
_zScoreExitThreshold = Param(nameof(ZScoreExitThreshold), 0m).SetNotNegative()
.SetDisplay("Z-Score Exit", "Half-width of the neutral exit zone in standard deviations", "Z-Score")
.SetOptimize(0.0m, 1.0m, 0.2m);
_maPeriod = Param(nameof(MAPeriod), 20).SetGreaterThanZero()
.SetDisplay("MA Period", "Period for Moving Average", "Indicators")
.SetOptimize(10, 50, 5);
_stdDevPeriod = Param(nameof(StdDevPeriod), 20).SetGreaterThanZero()
.SetDisplay("StdDev Period", "Period for Standard Deviation", "Indicators")
.SetOptimize(10, 50, 5);
_candleType = Param(nameof(CandleType), TimeSpan.FromMinutes(5).TimeFrame())
.SetDisplay("Candle Type", "Type of candles to use", "General");
_stopLossPercent = Param(nameof(StopLossPercent), 2m).SetNotNegative()
.SetDisplay("Stop Loss (%)", "Actual-fill percent stop; zero disables it.", "Protection");
OrderRegistering += order => _pendingOrder = order;
}
public decimal StopLossPercent { get => _stopLossPercent.Value; set => _stopLossPercent.Value = value; }
/// <inheritdoc />
public override IEnumerable<(Security sec, DataType dt)> GetWorkingSecurities()
{
return [(Security, CandleType), (Security, DataType.Level1)];
}
/// <inheritdoc />
protected override void OnReseted()
{
base.OnReseted();
_pendingOrder = null;
}
/// <inheritdoc />
protected override void OnStarted2(DateTime time)
{
base.OnStarted2(time);
if (ZScoreExitThreshold >= ZScoreEntryThreshold)
throw new InvalidOperationException("ZScoreExitThreshold must be below ZScoreEntryThreshold.");
var sma = new SimpleMovingAverage { Length = MAPeriod };
var stdDev = new StandardDeviation { Length = StdDevPeriod };
StartProtection(new Unit(), new Unit(StopLossPercent, UnitTypes.Percent), useMarketOrders: true, isLocalStop: true);
foreach (var field in new[] { Level1Fields.BestBidPrice, Level1Fields.BestAskPrice })
{
var quotes = new Subscription(DataType.Level1, Security);
quotes.MarketData.BuildField = field;
SubscribeLevel1(quotes).Bind(ObserveProtectionQuote).Start();
}
var subscription = SubscribeCandles(CandleType);
subscription
.BindEx(sma, stdDev, ProcessCandle, false)
.Start();
var area = CreateChartArea();
if (area != null)
{
DrawCandles(area, subscription);
DrawIndicator(area, sma);
DrawIndicator(area, stdDev);
DrawOwnTrades(area);
}
}
private void ObserveProtectionQuote(Level1ChangeMessage quote)
{
// Native protection runs before the callback, including between finished candles.
}
private void ProcessCandle(ICandleMessage candle, IIndicatorValue maValue, IIndicatorValue stdDevValue)
{
if (candle.State != CandleStates.Finished)
return;
if (!maValue.IsFormed || !stdDevValue.IsFormed || !IsFormedAndOnlineAndAllowTrading())
return;
if (_pendingOrder is not null && _pendingOrder.State is not (OrderStates.Done or OrderStates.Failed))
return;
var sigma = stdDevValue.GetValue<decimal>();
// A constant-price variance window is explicitly neutral, not an exit blackout.
var zScore = sigma == 0m ? 0m : (candle.ClosePrice - maValue.GetValue<decimal>()) / sigma;
if (Position > 0m && zScore >= -ZScoreExitThreshold)
SellMarket(Position);
else if (Position < 0m && zScore <= ZScoreExitThreshold)
BuyMarket(Math.Abs(Position));
else if (Position == 0m && zScore < -ZScoreEntryThreshold)
BuyMarket(Volume);
else if (Position == 0m && zScore > ZScoreEntryThreshold)
SellMarket(Volume);
}
}
import clr
clr.AddReference("StockSharp.Messages")
clr.AddReference("StockSharp.Algo")
clr.AddReference("StockSharp.Algo.Indicators")
clr.AddReference("StockSharp.Algo.Strategies")
clr.AddReference("StockSharp.BusinessEntities")
from System import TimeSpan, Decimal, Math
from StockSharp.Messages import DataType, CandleStates, Unit, UnitTypes, OrderStates, Level1Fields
from StockSharp.BusinessEntities import Subscription
from StockSharp.Algo.Indicators import SimpleMovingAverage, StandardDeviation
from StockSharp.Algo.Strategies import Strategy
class z_score_strategy(Strategy):
"""
Z-Score mean reversion strategy.
Buys when Z-Score is below negative threshold, sells when above positive threshold.
"""
def __init__(self):
super(z_score_strategy, self).__init__()
self._z_entry = self.Param("ZScoreEntryThreshold", 2.0).SetGreaterThanZero().SetDisplay("Z-Score Entry", "Distance from mean in std devs for entry", "Z-Score")
self._z_exit = self.Param("ZScoreExitThreshold", 0.0).SetNotNegative().SetDisplay("Z-Score Exit", "Half-width of the neutral exit zone in standard deviations", "Z-Score")
self._ma_period = self.Param("MAPeriod", 20).SetGreaterThanZero().SetDisplay("MA Period", "Period for Moving Average", "Indicators")
self._std_period = self.Param("StdDevPeriod", 20).SetGreaterThanZero().SetDisplay("StdDev Period", "Period for Standard Deviation", "Indicators")
self._candle_type = self.Param("CandleType", DataType.TimeFrame(TimeSpan.FromMinutes(5))).SetDisplay("Candle Type", "Type of candles to use", "General")
self._stop_loss_percent = self.Param("StopLossPercent", 2.0).SetNotNegative() \
.SetDisplay("Stop Loss (%)", "Actual-fill percent stop; zero disables it.", "Protection")
self._pending_order = None
self.OrderRegistering += self._track_pending
def GetWorkingSecurities(self):
return [(self.Security, self.candle_type), (self.Security, DataType.Level1)]
def _track_pending(self, order):
self._pending_order = order
@property
def candle_type(self):
return self._candle_type.Value
def OnReseted(self):
super(z_score_strategy, self).OnReseted()
self._pending_order = None
def OnStarted2(self, time):
super(z_score_strategy, self).OnStarted2(time)
if self._z_exit.Value >= self._z_entry.Value:
raise ValueError("ZScoreExitThreshold must be below ZScoreEntryThreshold.")
sma = SimpleMovingAverage()
sma.Length = self._ma_period.Value
std = StandardDeviation()
std.Length = self._std_period.Value
self.StartProtection(Unit(), Unit(Decimal(self._stop_loss_percent.Value), UnitTypes.Percent), useMarketOrders=True, isLocalStop=True)
for field in (Level1Fields.BestBidPrice, Level1Fields.BestAskPrice):
quotes = Subscription(DataType.Level1, self.Security)
quotes.MarketData.BuildField = field
self.SubscribeLevel1(quotes).Bind(self._observe_protection_quote).Start()
subscription = self.SubscribeCandles(self.candle_type)
subscription.BindEx(sma, std, self._process_candle, False).Start()
area = self.CreateChartArea()
if area is not None:
self.DrawCandles(area, subscription)
self.DrawIndicator(area, sma)
self.DrawIndicator(area, std)
self.DrawOwnTrades(area)
def _observe_protection_quote(self, quote):
# Native protection runs before this callback, including between signal bars.
pass
def _process_candle(self, candle, ma_val, std_val):
if candle.State != CandleStates.Finished:
return
if not ma_val.IsFormed or not std_val.IsFormed or not self.IsFormedAndOnlineAndAllowTrading():
return
if self._pending_order is not None and self._pending_order.State not in (OrderStates.Done, OrderStates.Failed):
return
sigma = std_val.GetValue[Decimal](None)
# A constant-price variance window is explicitly neutral, not an exit blackout.
z = Decimal.Zero if sigma == 0 else (candle.ClosePrice - ma_val.GetValue[Decimal](None)) / sigma
entry = Decimal(self._z_entry.Value)
exit_t = Decimal(self._z_exit.Value)
if self.Position > 0 and z >= -exit_t:
self.SellMarket(self.Position)
elif self.Position < 0 and z <= exit_t:
self.BuyMarket(Math.Abs(self.Position))
elif self.Position == 0 and z < -entry:
self.BuyMarket(self.Volume)
elif self.Position == 0 and z > entry:
self.SellMarket(self.Volume)
def CreateClone(self):
return z_score_strategy()