VQZL Z-Score
Strategy using z-score relative to a smoothed average.
Testing indicates an average annual return of about 42%. It performs best in the stock market.
The strategy calculates a smoothed moving average and standard deviation to compute a z-score. When price deviates beyond a threshold, it enters in the direction of the move.
Details
- Entry Criteria:
- Long:
Z-Score > threshold. - Short:
Z-Score < -threshold.
- Long:
- Long/Short: Both sides.
- Exit Criteria: Opposite signal.
- Stops: No.
- Default Values:
PriceSmoothing= 15ZLength= 100Threshold= 1.64CandleType= TimeSpan.FromMinutes(5)
- Filters:
- Category: Trend
- Direction: Both
- Indicators: SMA, StandardDeviation
- Stops: No
- Complexity: Basic
- Timeframe: Intraday
- Seasonality: No
- Neural networks: No
- Divergence: No
- Risk level: Medium
using System;
using System.Linq;
using System.Collections.Generic;
using Ecng.Common;
using Ecng.Collections;
using Ecng.Serialization;
using StockSharp.Algo.Indicators;
using StockSharp.Algo.Strategies;
using StockSharp.BusinessEntities;
using StockSharp.Messages;
namespace StockSharp.Samples.Strategies;
/// <summary>
/// Z-Score strategy based on price deviation from a moving average.
/// Long when z-score crosses above the threshold.
/// Short when z-score crosses below the negative threshold.
/// </summary>
public class VqzlZScoreStrategy : Strategy
{
private readonly StrategyParam<int> _priceSmoothing;
private readonly StrategyParam<int> _zLength;
private readonly StrategyParam<decimal> _threshold;
private readonly StrategyParam<DataType> _candleType;
/// <summary>
/// Period for price smoothing moving average.
/// </summary>
public int PriceSmoothing
{
get => _priceSmoothing.Value;
set => _priceSmoothing.Value = value;
}
/// <summary>
/// Lookback length for standard deviation calculation.
/// </summary>
public int ZLength
{
get => _zLength.Value;
set => _zLength.Value = value;
}
/// <summary>
/// Z-score threshold for entries.
/// </summary>
public decimal Threshold
{
get => _threshold.Value;
set => _threshold.Value = value;
}
/// <summary>
/// Candle type for calculations.
/// </summary>
public DataType CandleType
{
get => _candleType.Value;
set => _candleType.Value = value;
}
/// <summary>
/// Initializes a new instance of <see cref="VqzlZScoreStrategy"/>.
/// </summary>
public VqzlZScoreStrategy()
{
_priceSmoothing = Param(nameof(PriceSmoothing), 15)
.SetGreaterThanZero()
.SetDisplay("Price Smoothing", "Length of smoothing moving average", "ZScore")
.SetOptimize(5, 50, 5);
_zLength = Param(nameof(ZLength), 100)
.SetGreaterThanZero()
.SetDisplay("Z Length", "Lookback for standard deviation", "ZScore")
.SetOptimize(50, 200, 10);
_threshold = Param(nameof(Threshold), 1.64m)
.SetGreaterThanZero()
.SetDisplay("Z Threshold", "Z-score threshold", "ZScore")
.SetOptimize(1m, 3m, 0.5m);
_candleType = Param(nameof(CandleType), TimeSpan.FromMinutes(30).TimeFrame())
.SetDisplay("Candle Type", "Type of candles", "General");
}
/// <inheritdoc />
public override IEnumerable<(Security sec, DataType dt)> GetWorkingSecurities()
{
return [(Security, CandleType)];
}
/// <inheritdoc />
protected override void OnReseted()
{
base.OnReseted();
}
/// <inheritdoc />
protected override void OnStarted2(DateTime time)
{
base.OnStarted2(time);
var ma = new SMA { Length = PriceSmoothing };
var dev = new StandardDeviation { Length = ZLength };
var subscription = SubscribeCandles(CandleType);
subscription
.Bind(ma, dev, ProcessCandle)
.Start();
var area = CreateChartArea();
if (area != null)
{
DrawCandles(area, subscription);
DrawIndicator(area, ma);
DrawIndicator(area, dev);
DrawOwnTrades(area);
}
}
private void ProcessCandle(ICandleMessage candle, decimal maValue, decimal devValue)
{
if (candle.State != CandleStates.Finished)
return;
if (devValue == 0)
return;
var z = (candle.ClosePrice - maValue) / devValue;
if (z > Threshold && Position <= 0)
{
BuyMarket(Volume + Math.Abs(Position));
}
else if (z < -Threshold && Position >= 0)
{
SellMarket(Volume + Math.Abs(Position));
}
}
}
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 SimpleMovingAverage, StandardDeviation
from StockSharp.Algo.Strategies import Strategy
class vqzl_z_score_strategy(Strategy):
def __init__(self):
super(vqzl_z_score_strategy, self).__init__()
self._price_smoothing = self.Param("PriceSmoothing", 15) \
.SetDisplay("Price Smoothing", "Length of smoothing moving average", "ZScore")
self._z_length = self.Param("ZLength", 100) \
.SetDisplay("Z Length", "Lookback for standard deviation", "ZScore")
self._threshold = self.Param("Threshold", 1.64) \
.SetDisplay("Z Threshold", "Z-score threshold", "ZScore")
self._candle_type = self.Param("CandleType", DataType.TimeFrame(TimeSpan.FromMinutes(30))) \
.SetDisplay("Candle Type", "Type of candles", "General")
@property
def price_smoothing(self):
return self._price_smoothing.Value
@property
def z_length(self):
return self._z_length.Value
@property
def threshold(self):
return self._threshold.Value
@property
def candle_type(self):
return self._candle_type.Value
def OnReseted(self):
super(vqzl_z_score_strategy, self).OnReseted()
def OnStarted2(self, time):
super(vqzl_z_score_strategy, self).OnStarted2(time)
ma = SimpleMovingAverage()
ma.Length = self.price_smoothing
dev = StandardDeviation()
dev.Length = self.z_length
subscription = self.SubscribeCandles(self.candle_type)
subscription.Bind(ma, dev, self.on_process).Start()
area = self.CreateChartArea()
if area is not None:
self.DrawCandles(area, subscription)
self.DrawIndicator(area, ma)
self.DrawIndicator(area, dev)
self.DrawOwnTrades(area)
def on_process(self, candle, ma_value, dev_value):
if candle.State != CandleStates.Finished:
return
if dev_value == 0:
return
z = float(candle.ClosePrice - ma_value) / float(dev_value)
if z > float(self.threshold) and self.Position <= 0:
self.BuyMarket(self.Volume + Math.Abs(self.Position))
elif z < -float(self.threshold) and self.Position >= 0:
self.SellMarket(self.Volume + Math.Abs(self.Position))
def CreateClone(self):
return vqzl_z_score_strategy()