Outlier Detector with N-Sigma Confidence Intervals 策略
该策略利用 Nσ 置信区间识别价格变化中的异常波动,在出现极端运动时进行均值回归交易。
细节
- 入场条件:
- 当 z-score >
SecondLimit时做空。 - 当 z-score < -
SecondLimit时做多。
- 当 z-score >
- 多/空:双向。
- 出场条件:
- 当 |z-score| <
FirstLimit时平仓。
- 当 |z-score| <
- 止损:无。
- 默认值:
SampleSize= 30FirstLimit= 2SecondLimit= 3CandleType= TimeSpan.FromMinutes(1)
- 筛选:
- 类别: Mean Reversion
- 方向: 双向
- 指标: StandardDeviation, Z-Score
- 止损: 无
- 复杂度: 基础
- 时间框架: 任意
- 季节性: 否
- 神经网络: 否
- 风险等级: 中等
using System;
using Ecng.Common;
using StockSharp.Algo.Indicators;
using StockSharp.Algo.Strategies;
using StockSharp.Messages;
namespace StockSharp.Samples.Strategies;
public class OutlierDetectorWithNSigmaConfidenceIntervalsStrategy : Strategy
{
private readonly StrategyParam<int> _sampleSize;
private readonly StrategyParam<decimal> _nSigma;
private readonly StrategyParam<DataType> _candleType;
public int SampleSize { get => _sampleSize.Value; set => _sampleSize.Value = value; }
public decimal NSigma { get => _nSigma.Value; set => _nSigma.Value = value; }
public DataType CandleType { get => _candleType.Value; set => _candleType.Value = value; }
public OutlierDetectorWithNSigmaConfidenceIntervalsStrategy()
{
_sampleSize = Param(nameof(SampleSize), 50).SetGreaterThanZero();
_nSigma = Param(nameof(NSigma), 2.0m);
_candleType = Param(nameof(CandleType), TimeSpan.FromMinutes(5).TimeFrame());
}
/// <inheritdoc />
protected override void OnStarted2(DateTime time)
{
base.OnStarted2(time);
var sma = new SimpleMovingAverage { Length = SampleSize };
var stdDev = new StandardDeviation { Length = SampleSize };
var lastSignal = DateTimeOffset.MinValue;
var cooldown = TimeSpan.FromMinutes(360);
var subscription = SubscribeCandles(CandleType);
subscription
.Bind(sma, stdDev, (candle, avg, std) =>
{
if (candle.State != CandleStates.Finished)
return;
if (!sma.IsFormed || !stdDev.IsFormed)
return;
if (std <= 0 || candle.OpenTime - lastSignal < cooldown)
return;
var upper = avg + NSigma * std;
var lower = avg - NSigma * std;
if (candle.ClosePrice > upper && Position <= 0)
{
BuyMarket();
lastSignal = candle.OpenTime;
}
else if (candle.ClosePrice < lower && Position >= 0)
{
SellMarket();
lastSignal = candle.OpenTime;
}
})
.Start();
var area = CreateChartArea();
if (area != null)
{
DrawCandles(area, subscription);
DrawIndicator(area, sma);
DrawOwnTrades(area);
}
}
}
import clr
clr.AddReference("StockSharp.Messages")
clr.AddReference("StockSharp.Algo")
clr.AddReference("StockSharp.Algo.Indicators")
clr.AddReference("StockSharp.Algo.Strategies")
from System import TimeSpan
from StockSharp.Messages import DataType, CandleStates
from StockSharp.Algo.Indicators import SimpleMovingAverage, StandardDeviation
from StockSharp.Algo.Strategies import Strategy
class outlier_detector_with_n_sigma_confidence_intervals_strategy(Strategy):
def __init__(self):
super(outlier_detector_with_n_sigma_confidence_intervals_strategy, self).__init__()
self._sample_size = self.Param("SampleSize", 50) \
.SetGreaterThanZero()
self._n_sigma = self.Param("NSigma", 2.0)
self._candle_type = self.Param("CandleType", DataType.TimeFrame(TimeSpan.FromMinutes(5)))
self._last_signal_ticks = 0
@property
def candle_type(self):
return self._candle_type.Value
@candle_type.setter
def candle_type(self, value):
self._candle_type.Value = value
def OnReseted(self):
super(outlier_detector_with_n_sigma_confidence_intervals_strategy, self).OnReseted()
self._last_signal_ticks = 0
def OnStarted2(self, time):
super(outlier_detector_with_n_sigma_confidence_intervals_strategy, self).OnStarted2(time)
self._last_signal_ticks = 0
self._sma = SimpleMovingAverage()
self._sma.Length = self._sample_size.Value
self._std = StandardDeviation()
self._std.Length = self._sample_size.Value
subscription = self.SubscribeCandles(self.candle_type)
subscription.Bind(self._sma, self._std, self.OnProcess).Start()
def OnProcess(self, candle, avg, std):
if candle.State != CandleStates.Finished:
return
if not self._sma.IsFormed or not self._std.IsFormed:
return
av = float(avg)
sd = float(std)
close = float(candle.ClosePrice)
if sd <= 0:
return
cooldown_ticks = TimeSpan.FromMinutes(360).Ticks
current_ticks = candle.OpenTime.Ticks
if current_ticks - self._last_signal_ticks < cooldown_ticks:
return
ns = float(self._n_sigma.Value)
upper = av + ns * sd
lower = av - ns * sd
if close > upper and self.Position <= 0:
self.BuyMarket()
self._last_signal_ticks = current_ticks
elif close < lower and self.Position >= 0:
self.SellMarket()
self._last_signal_ticks = current_ticks
def CreateClone(self):
return outlier_detector_with_n_sigma_confidence_intervals_strategy()