Стратегия ZScore Reversal
Стратегия ZScore Reversal измеряет, насколько цена отклоняется от скользящей средней в стандартных отклонениях. Полученный Z‑Score выявляет статистически растянутые состояния, которые могут вернуться к среднему.
Тестирование показывает среднегодичную доходность около 91%. Стратегию лучше запускать на фондовом рынке.
Покупка совершается, когда Z‑Score падает ниже отрицательного порога, указывая на перепроданность. Короткая сделка открывается, когда Z‑Score превышает положительный порог. Позиция закрывается, когда Z‑Score снова пересекает ноль, что говорит о нормализации цены.
Эта техника привлекательна для трейдеров, ориентированных на возврат к среднему, которым нужны объективные уровни входа. Процентный стоп‑лосс помогает контролировать неблагоприятные движения, пока ждёшь возврата.
Детали
- Условия входа:
- Лонг: Z‑Score < -Порог
- Шорт: Z‑Score > Порог
- Лонг/Шорт: обе стороны.
- Условия выхода:
- Лонг: Выход при пересечении Z‑Score выше 0
- Шорт: Выход при пересечении Z‑Score ниже 0
- Стопы: да, процентный стоп‑лосс.
- Значения по умолчанию:
LookbackPeriod = 20
ZScoreThreshold = 2
StopLossPercent = 2
Z-Score = (close - SMA) / StdDev, где простая скользящая средняя и стандартное отклонение цен закрытия считаются за одни и те же LookbackPeriod свечей. Стоп — фиксированный StopLossPercent от цены входа, он отслеживается и между свечами. Сигнал на вход против открытой позиции разворачивает её.
CandleType = TimeSpan.FromMinutes(10)
- Фильтры:
- Категория: Mean Reversion
- Направление: Оба
- Индикаторы: Z‑Score
- Стопы: Да
- Сложность: Средняя
- Таймфрейм: Внутридневной
- Сезонность: Нет
- Нейросети: Нет
- Дивергенция: Нет
- Уровень риска: Средний
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>
/// ZScore Reversal strategy.
/// The Z-Score is the distance of the close from the LookbackPeriod simple moving average in standard deviations over the same candles.
/// A Z-Score below minus ZScoreThreshold goes long and one above ZScoreThreshold goes short, reversing an opposite position.
/// A long closes once the Z-Score crosses above zero and a short once it crosses below, and a percent stop limits the loss.
/// </summary>
public class ZScoreReversalStrategy : Strategy
{
private readonly StrategyParam<int> _lookbackPeriod;
private readonly StrategyParam<decimal> _zScoreThreshold;
private readonly StrategyParam<decimal> _stopLossPercent;
private readonly StrategyParam<DataType> _candleType;
/// <summary>
/// Period of the moving average and the standard deviation.
/// </summary>
public int LookbackPeriod
{
get => _lookbackPeriod.Value;
set => _lookbackPeriod.Value = value;
}
/// <summary>
/// Z-Score distance from zero that opens a position.
/// </summary>
public decimal ZScoreThreshold
{
get => _zScoreThreshold.Value;
set => _zScoreThreshold.Value = value;
}
/// <summary>
/// Stop loss percentage from entry price.
/// </summary>
public decimal StopLossPercent
{
get => _stopLossPercent.Value;
set => _stopLossPercent.Value = value;
}
/// <summary>
/// Candle type.
/// </summary>
public DataType CandleType
{
get => _candleType.Value;
set => _candleType.Value = value;
}
/// <summary>
/// Constructor.
/// </summary>
public ZScoreReversalStrategy()
{
_lookbackPeriod = Param(nameof(LookbackPeriod), 20)
.SetGreaterThanZero()
.SetDisplay("Lookback Period", "Period of the moving average and the standard deviation", "Indicators");
_zScoreThreshold = Param(nameof(ZScoreThreshold), 2m)
.SetGreaterThanZero()
.SetDisplay("Z-Score Threshold", "Z-Score distance from zero that opens a position", "Indicators");
_stopLossPercent = Param(nameof(StopLossPercent), 2m)
.SetNotNegative()
.SetDisplay("Stop Loss %", "Stop loss percentage from entry price", "Risk");
_candleType = Param(nameof(CandleType), TimeSpan.FromMinutes(10).TimeFrame())
.SetDisplay("Candle Type", "Type of candles to use", "General");
}
/// <inheritdoc />
public override IEnumerable<(Security sec, DataType dt)> GetWorkingSecurities()
{
return [(Security, CandleType)];
}
/// <inheritdoc />
protected override void OnStarted2(DateTime time)
{
base.OnStarted2(time);
var ma = new SimpleMovingAverage { Length = LookbackPeriod };
var stdev = new StandardDeviation { Length = LookbackPeriod };
var subscription = SubscribeCandles(CandleType);
subscription
.BindEx(ma, stdev, ProcessCandle)
.Start();
StartProtection(new Unit(), new Unit(StopLossPercent, UnitTypes.Percent), useMarketOrders: true, isLocalStop: true);
// The stop has to see prices between candles, not only at their close.
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 area = CreateChartArea();
if (area != null)
{
DrawCandles(area, subscription);
DrawIndicator(area, ma);
DrawOwnTrades(area);
var oscillators = CreateChartArea();
if (oscillators != null)
{
DrawIndicator(oscillators, stdev);
}
}
}
private void ObserveProtectionQuote(Level1ChangeMessage quote)
{
// The high-level handler activates native protection before this callback, also between signal bars.
}
private void ProcessCandle(ICandleMessage candle, IIndicatorValue maValue, IIndicatorValue stdDevValue)
{
if (candle.State != CandleStates.Finished)
return;
if (!maValue.IsFormed || !stdDevValue.IsFormed)
return;
if (!IsFormedAndOnlineAndAllowTrading())
return;
var deviation = stdDevValue.GetValue<decimal>();
if (deviation == 0)
return;
var zScore = (candle.ClosePrice - maValue.GetValue<decimal>()) / deviation;
if (zScore < -ZScoreThreshold && Position <= 0)
BuyMarket(Volume + Math.Abs(Position));
else if (zScore > ZScoreThreshold && Position >= 0)
SellMarket(Volume + Math.Abs(Position));
else if (Position > 0 && zScore > 0)
SellMarket(Position);
else if (Position < 0 && zScore < 0)
BuyMarket(-Position);
}
}
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
from StockSharp.Messages import DataType, CandleStates, Unit, UnitTypes, Level1Fields
from StockSharp.BusinessEntities import Subscription
from StockSharp.Algo.Indicators import SimpleMovingAverage, StandardDeviation
from StockSharp.Algo.Strategies import Strategy
class z_score_reversal_strategy(Strategy):
"""
ZScore Reversal strategy.
The Z-Score is the distance of the close from the LookbackPeriod simple moving average in standard deviations over the same candles.
A Z-Score below minus ZScoreThreshold goes long and one above ZScoreThreshold goes short, reversing an opposite position.
A long closes once the Z-Score crosses above zero and a short once it crosses below, and a percent stop limits the loss.
"""
def __init__(self):
super(z_score_reversal_strategy, self).__init__()
self._lookback_period = self.Param("LookbackPeriod", 20).SetGreaterThanZero().SetDisplay("Lookback Period", "Period of the moving average and the standard deviation", "Indicators")
self._z_score_threshold = self.Param("ZScoreThreshold", 2.0).SetGreaterThanZero().SetDisplay("Z-Score Threshold", "Z-Score distance from zero that opens a position", "Indicators")
self._stop_loss_percent = self.Param("StopLossPercent", 2.0).SetNotNegative().SetDisplay("Stop Loss %", "Stop loss percentage from entry price", "Risk")
self._candle_type = self.Param("CandleType", DataType.TimeFrame(TimeSpan.FromMinutes(10))).SetDisplay("Candle Type", "Type of candles to use", "General")
@property
def candle_type(self):
return self._candle_type.Value
def OnStarted2(self, time):
super(z_score_reversal_strategy, self).OnStarted2(time)
ma = SimpleMovingAverage()
ma.Length = self._lookback_period.Value
stdev = StandardDeviation()
stdev.Length = self._lookback_period.Value
subscription = self.SubscribeCandles(self.candle_type)
subscription.BindEx(ma, stdev, self._process_candle).Start()
self.StartProtection(Unit(), Unit(Decimal(self._stop_loss_percent.Value), UnitTypes.Percent), useMarketOrders=True, isLocalStop=True)
# The stop has to see prices between candles, not only at their close.
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()
area = self.CreateChartArea()
if area is not None:
self.DrawCandles(area, subscription)
self.DrawIndicator(area, ma)
self.DrawOwnTrades(area)
oscillators = self.CreateChartArea()
if oscillators is not None:
self.DrawIndicator(oscillators, stdev)
def _observe_protection_quote(self, quote):
# The high-level handler activates native protection before the callback, including between bars.
pass
def _process_candle(self, candle, ma_value, std_dev_value):
if candle.State != CandleStates.Finished:
return
if not ma_value.IsFormed or not std_dev_value.IsFormed:
return
if not self.IsFormedAndOnlineAndAllowTrading():
return
deviation = std_dev_value.GetValue[Decimal](None)
if deviation == 0:
return
z_score = (candle.ClosePrice - ma_value.GetValue[Decimal](None)) / deviation
threshold = Decimal(self._z_score_threshold.Value)
if z_score < -threshold and self.Position <= 0:
self.BuyMarket(self.Volume + abs(self.Position))
elif z_score > threshold and self.Position >= 0:
self.SellMarket(self.Volume + abs(self.Position))
elif self.Position > 0 and z_score > 0:
self.SellMarket(self.Position)
elif self.Position < 0 and z_score < 0:
self.BuyMarket(-self.Position)
def CreateClone(self):
return z_score_reversal_strategy()