Ausreißer-Erkennungs-Strategie mit N-Sigma-Konfidenzintervallen
Die Strategie identifiziert Ausreißer in Preisveränderungen mithilfe von N-Sigma-Konfidenzintervallen und handelt Mean Reversion bei extremen Bewegungen.
Details
- Einstiegskriterien:
- Short wenn z-score >
SecondLimit. - Long wenn z-score < -
SecondLimit.
- Short wenn z-score >
- Long/Short: Beide.
- Ausstiegskriterien:
- Position schließen wenn |z-score| <
FirstLimit.
- Position schließen wenn |z-score| <
- Stops: Keine.
- Standardwerte:
SampleSize= 30FirstLimit= 2SecondLimit= 3CandleType= TimeSpan.FromMinutes(1)
- Filter:
- Kategorie: Mean Reversion
- Richtung: Beide
- Indikatoren: StandardDeviation, Z-Score
- Stops: Nein
- Komplexität: Grundlegend
- Zeitrahmen: Beliebig
- Saisonalität: Nein
- Neuronale Netze: Nein
- Risikolevel: Mittel
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>
/// Outlier detector with N-sigma confidence intervals.
/// The close-to-close price change is turned into a z-score against the mean and standard deviation of the last SampleSize changes.
/// A z-score above SecondLimit goes short and one below -SecondLimit goes long, reversing an opposite position.
/// The position is closed once the absolute z-score falls back below FirstLimit.
/// </summary>
public class OutlierDetectorWithNSigmaConfidenceIntervalsStrategy : Strategy
{
private readonly StrategyParam<int> _sampleSize;
private readonly StrategyParam<decimal> _firstLimit;
private readonly StrategyParam<decimal> _secondLimit;
private readonly StrategyParam<DataType> _candleType;
private SimpleMovingAverage _mean;
private StandardDeviation _stdDev;
private decimal? _prevClose;
/// <summary>
/// Number of price changes in the sample.
/// </summary>
public int SampleSize
{
get => _sampleSize.Value;
set => _sampleSize.Value = value;
}
/// <summary>
/// Z-score below which the position is closed.
/// </summary>
public decimal FirstLimit
{
get => _firstLimit.Value;
set => _firstLimit.Value = value;
}
/// <summary>
/// Z-score beyond which a move counts as an outlier.
/// </summary>
public decimal SecondLimit
{
get => _secondLimit.Value;
set => _secondLimit.Value = value;
}
/// <summary>
/// Candle type.
/// </summary>
public DataType CandleType
{
get => _candleType.Value;
set => _candleType.Value = value;
}
/// <summary>
/// Constructor.
/// </summary>
public OutlierDetectorWithNSigmaConfidenceIntervalsStrategy()
{
_sampleSize = Param(nameof(SampleSize), 30)
.SetGreaterThanZero()
.SetDisplay("Sample Size", "Number of price changes in the sample", "Indicators");
_firstLimit = Param(nameof(FirstLimit), 2m)
.SetGreaterThanZero()
.SetDisplay("First Limit", "Z-score below which the position is closed", "Signals");
_secondLimit = Param(nameof(SecondLimit), 3m)
.SetGreaterThanZero()
.SetDisplay("Second Limit", "Z-score beyond which a move counts as an outlier", "Signals");
_candleType = Param(nameof(CandleType), TimeSpan.FromMinutes(1).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 OnReseted()
{
base.OnReseted();
_prevClose = null;
}
/// <inheritdoc />
protected override void OnStarted2(DateTime time)
{
base.OnStarted2(time);
_prevClose = null;
_mean = new SimpleMovingAverage { Length = SampleSize };
_stdDev = new StandardDeviation { Length = SampleSize };
var subscription = SubscribeCandles(CandleType);
subscription
.Bind(ProcessCandle)
.Start();
var area = CreateChartArea();
if (area != null)
{
DrawCandles(area, subscription);
DrawOwnTrades(area);
}
}
private void ProcessCandle(ICandleMessage candle)
{
if (candle.State != CandleStates.Finished)
return;
var prevClose = _prevClose;
_prevClose = candle.ClosePrice;
if (prevClose is not decimal prev)
return;
var change = candle.ClosePrice - prev;
var meanValue = _mean.Process(new DecimalIndicatorValue(_mean, change, candle.OpenTime) { IsFinal = true });
var stdValue = _stdDev.Process(new DecimalIndicatorValue(_stdDev, change, candle.OpenTime) { IsFinal = true });
if (!_mean.IsFormed || !_stdDev.IsFormed)
return;
var std = stdValue.GetValue<decimal>();
if (std <= 0)
return;
if (!IsFormedAndOnlineAndAllowTrading())
return;
var z = (change - meanValue.GetValue<decimal>()) / std;
if (z > SecondLimit && Position >= 0)
SellMarket(Volume + Math.Abs(Position));
else if (z < -SecondLimit && Position <= 0)
BuyMarket(Volume + Math.Abs(Position));
else if (Position != 0 && Math.Abs(z) < FirstLimit)
{
if (Position > 0)
SellMarket(Position);
else
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
from StockSharp.Algo.Indicators import SimpleMovingAverage, StandardDeviation, DecimalIndicatorValue
from StockSharp.Algo.Strategies import Strategy
class outlier_detector_with_n_sigma_confidence_intervals_strategy(Strategy):
"""
Outlier detector with N-sigma confidence intervals.
The close-to-close price change is turned into a z-score against the mean and standard deviation of the last SampleSize changes.
A z-score above SecondLimit goes short and one below -SecondLimit goes long, reversing an opposite position.
The position is closed once the absolute z-score falls back below FirstLimit.
"""
def __init__(self):
super(outlier_detector_with_n_sigma_confidence_intervals_strategy, self).__init__()
self._sample_size = self.Param("SampleSize", 30).SetGreaterThanZero().SetDisplay("Sample Size", "Number of price changes in the sample", "Indicators")
self._first_limit = self.Param("FirstLimit", 2.0).SetGreaterThanZero().SetDisplay("First Limit", "Z-score below which the position is closed", "Signals")
self._second_limit = self.Param("SecondLimit", 3.0).SetGreaterThanZero().SetDisplay("Second Limit", "Z-score beyond which a move counts as an outlier", "Signals")
self._candle_type = self.Param("CandleType", DataType.TimeFrame(TimeSpan.FromMinutes(1))).SetDisplay("Candle Type", "Type of candles to use", "General")
self._mean = None
self._std_dev = None
self._prev_close = None
@property
def candle_type(self):
return self._candle_type.Value
def OnReseted(self):
super(outlier_detector_with_n_sigma_confidence_intervals_strategy, self).OnReseted()
self._prev_close = None
def OnStarted2(self, time):
super(outlier_detector_with_n_sigma_confidence_intervals_strategy, self).OnStarted2(time)
self._prev_close = None
self._mean = SimpleMovingAverage()
self._mean.Length = self._sample_size.Value
self._std_dev = StandardDeviation()
self._std_dev.Length = self._sample_size.Value
subscription = self.SubscribeCandles(self.candle_type)
subscription.Bind(self._process_candle).Start()
area = self.CreateChartArea()
if area is not None:
self.DrawCandles(area, subscription)
self.DrawOwnTrades(area)
def _process_candle(self, candle):
if candle.State != CandleStates.Finished:
return
prev_close = self._prev_close
self._prev_close = candle.ClosePrice
if prev_close is None:
return
change = candle.ClosePrice - prev_close
mean_input = DecimalIndicatorValue(self._mean, change, candle.OpenTime)
mean_input.IsFinal = True
mean_value = self._mean.Process(mean_input)
std_input = DecimalIndicatorValue(self._std_dev, change, candle.OpenTime)
std_input.IsFinal = True
std_value = self._std_dev.Process(std_input)
if not self._mean.IsFormed or not self._std_dev.IsFormed:
return
std = std_value.GetValue[Decimal](None)
if std <= 0:
return
if not self.IsFormedAndOnlineAndAllowTrading():
return
z = (change - mean_value.GetValue[Decimal](None)) / std
second = Decimal(self._second_limit.Value)
first = Decimal(self._first_limit.Value)
if z > second and self.Position >= 0:
self.SellMarket(self.Volume + abs(self.Position))
elif z < -second and self.Position <= 0:
self.BuyMarket(self.Volume + abs(self.Position))
elif self.Position != 0 and abs(z) < first:
if self.Position > 0:
self.SellMarket(self.Position)
else:
self.BuyMarket(-self.Position)
def CreateClone(self):
return outlier_detector_with_n_sigma_confidence_intervals_strategy()