RSI 回归
该策略认为当RSI达到极端值后价格会回归。RSI跌破下限时买入,升破上限时卖出,RSI回到中值附近离场。阈值可根据市场调整,结合趋势过滤器可避免过早逆势。
测试表明年均收益约为 115%,该策略在股票市场表现最佳。
详情
- 入场条件: 基于 RSI 的信号
- 多空方向: 双向
- 退出条件: 反向信号或止损
- 止损: 是
- 默认值:
RsiPeriod= 14OversoldThreshold= 30mOverboughtThreshold= 70mExitLevel= 50mStopLossPercent= 2mCandleType= TimeSpan.FromMinutes(5)
- 过滤器:
- 类型: 均值回归
- 方向: 双向
- 指标: RSI
- 止损: 是
- 复杂度: 基础
- 时间框架: 日内 (5m)
- 季节性: 无
- 神经网络: 无
- 背离: 无
- 风险等级: 中
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 RSI mean reversion.
/// Buys when RSI enters the oversold zone, sells when it enters the overbought zone.
/// Exits at the neutral level and uses native actual-fill percent protection.
/// </summary>
public class RsiReversionStrategy : Strategy
{
private readonly StrategyParam<int> _rsiPeriod;
private readonly StrategyParam<DataType> _candleType;
private readonly StrategyParam<decimal> _oversoldThreshold;
private readonly StrategyParam<decimal> _overboughtThreshold;
private readonly StrategyParam<decimal> _exitLevel;
private readonly StrategyParam<decimal> _stopLossPercent;
private decimal _prevRsi;
private bool _hasPrevValues;
private Order _pendingOrder;
/// <summary>
/// RSI period.
/// </summary>
public int RsiPeriod
{
get => _rsiPeriod.Value;
set => _rsiPeriod.Value = value;
}
/// <summary>
/// Candle type.
/// </summary>
public DataType CandleType
{
get => _candleType.Value;
set => _candleType.Value = value;
}
public decimal OversoldThreshold { get => _oversoldThreshold.Value; set => _oversoldThreshold.Value = value; }
public decimal OverboughtThreshold { get => _overboughtThreshold.Value; set => _overboughtThreshold.Value = value; }
public decimal ExitLevel { get => _exitLevel.Value; set => _exitLevel.Value = value; }
public decimal StopLossPercent { get => _stopLossPercent.Value; set => _stopLossPercent.Value = value; }
/// <summary>
/// Initializes a new instance of the <see cref="RsiReversionStrategy"/>.
/// </summary>
public RsiReversionStrategy()
{
_rsiPeriod = Param(nameof(RsiPeriod), 14).SetGreaterThanZero()
.SetDisplay("RSI Period", "Period for RSI calculation", "Indicators")
.SetOptimize(10, 20, 2);
_candleType = Param(nameof(CandleType), TimeSpan.FromMinutes(5).TimeFrame())
.SetDisplay("Candle Type", "Type of candles to use", "General");
_oversoldThreshold = Param(nameof(OversoldThreshold), 30m).SetRange(0m, 100m)
.SetDisplay("Oversold Threshold", "Enter long on a strict downward crossing.", "Indicators");
_overboughtThreshold = Param(nameof(OverboughtThreshold), 70m).SetRange(0m, 100m)
.SetDisplay("Overbought Threshold", "Enter short on a strict upward crossing.", "Indicators");
_exitLevel = Param(nameof(ExitLevel), 50m).SetRange(0m, 100m)
.SetDisplay("Exit Level", "Close on return to the neutral level.", "Indicators");
_stopLossPercent = Param(nameof(StopLossPercent), 2m).SetNotNegative()
.SetDisplay("Stop Loss (%)", "Actual-fill percent stop; zero disables it.", "Protection");
OrderRegistering += order => _pendingOrder = order;
}
/// <inheritdoc />
public override IEnumerable<(Security sec, DataType dt)> GetWorkingSecurities()
{
return [(Security, CandleType), (Security, DataType.Level1)];
}
/// <inheritdoc />
protected override void OnReseted()
{
base.OnReseted();
_prevRsi = default;
_hasPrevValues = default;
_pendingOrder = null;
}
/// <inheritdoc />
protected override void OnStarted2(DateTime time)
{
base.OnStarted2(time);
if (!(OversoldThreshold < ExitLevel && ExitLevel < OverboughtThreshold))
throw new InvalidOperationException("OversoldThreshold must be below ExitLevel, which must be below OverboughtThreshold.");
var rsi = new RelativeStrengthIndex { Length = RsiPeriod };
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
.Bind(rsi, ProcessCandle)
.Start();
var area = CreateChartArea();
if (area != null)
{
DrawCandles(area, subscription);
DrawIndicator(area, rsi);
DrawOwnTrades(area);
}
}
private void ObserveProtectionQuote(Level1ChangeMessage quote)
{
// Native protection runs before the callback, including between finished candles.
}
private void ProcessCandle(ICandleMessage candle, decimal rsiValue)
{
if (candle.State != CandleStates.Finished)
return;
if (!IsFormedAndOnlineAndAllowTrading())
return;
if (!_hasPrevValues)
{
_hasPrevValues = true;
_prevRsi = rsiValue;
return;
}
if (_pendingOrder is not null && _pendingOrder.State is not (OrderStates.Done or OrderStates.Failed))
{
_prevRsi = rsiValue;
return;
}
// Fade entry INTO each extreme; this is not a crossing out of the extreme zone.
if (_prevRsi >= OversoldThreshold && rsiValue < OversoldThreshold && Position <= 0m)
{
var volume = Volume + Math.Abs(Position);
BuyMarket(volume);
}
else if (_prevRsi <= OverboughtThreshold && rsiValue > OverboughtThreshold && Position >= 0m)
{
var volume = Volume + Math.Abs(Position);
SellMarket(volume);
}
else if (Position > 0m && rsiValue >= ExitLevel)
SellMarket(Position);
else if (Position < 0m && rsiValue <= ExitLevel)
BuyMarket(Math.Abs(Position));
_prevRsi = rsiValue;
}
}
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 RelativeStrengthIndex
from StockSharp.Algo.Strategies import Strategy
class rsi_reversion_strategy(Strategy):
"""
Strategy based on RSI mean reversion.
Buys when RSI enters oversold, sells when it enters overbought, exits at neutral.
"""
def __init__(self):
super(rsi_reversion_strategy, self).__init__()
self._rsi_period = self.Param("RsiPeriod", 14).SetGreaterThanZero() \
.SetDisplay("RSI Period", "Period for RSI calculation", "Indicators")
self._candle_type = self.Param("CandleType", DataType.TimeFrame(TimeSpan.FromMinutes(5))) \
.SetDisplay("Candle Type", "Type of candles to use", "General")
self._oversold_threshold = self.Param("OversoldThreshold", 30.0).SetRange(0.0, 100.0) \
.SetDisplay("Oversold Threshold", "Enter long on a strict downward crossing.", "Indicators")
self._overbought_threshold = self.Param("OverboughtThreshold", 70.0).SetRange(0.0, 100.0) \
.SetDisplay("Overbought Threshold", "Enter short on a strict upward crossing.", "Indicators")
self._exit_level = self.Param("ExitLevel", 50.0).SetRange(0.0, 100.0) \
.SetDisplay("Exit Level", "Close on return to the neutral level.", "Indicators")
self._stop_loss_percent = self.Param("StopLossPercent", 2.0).SetNotNegative() \
.SetDisplay("Stop Loss (%)", "Actual-fill percent stop; zero disables it.", "Protection")
self._prev_rsi = Decimal.Zero
self._has_prev_values = False
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(rsi_reversion_strategy, self).OnReseted()
self._prev_rsi = Decimal.Zero
self._has_prev_values = False
self._pending_order = None
def OnStarted2(self, time):
super(rsi_reversion_strategy, self).OnStarted2(time)
if not (self._oversold_threshold.Value < self._exit_level.Value < self._overbought_threshold.Value):
raise ValueError("OversoldThreshold must be below ExitLevel, which must be below OverboughtThreshold.")
rsi = RelativeStrengthIndex()
rsi.Length = self._rsi_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.Bind(rsi, self._process_candle).Start()
area = self.CreateChartArea()
if area is not None:
self.DrawCandles(area, subscription)
self.DrawIndicator(area, rsi)
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, rsi_value):
if candle.State != CandleStates.Finished or not self.IsFormedAndOnlineAndAllowTrading():
return
rv = rsi_value
if not self._has_prev_values:
self._has_prev_values = True
self._prev_rsi = rv
return
if self._pending_order is not None and self._pending_order.State not in (OrderStates.Done, OrderStates.Failed):
self._prev_rsi = rv
return
if self._prev_rsi >= Decimal(self._oversold_threshold.Value) and rv < Decimal(self._oversold_threshold.Value) and self.Position <= 0:
self.BuyMarket(self.Volume + Math.Abs(self.Position))
elif self._prev_rsi <= Decimal(self._overbought_threshold.Value) and rv > Decimal(self._overbought_threshold.Value) and self.Position >= 0:
self.SellMarket(self.Volume + Math.Abs(self.Position))
elif self.Position > 0 and rv >= Decimal(self._exit_level.Value):
self.SellMarket(self.Position)
elif self.Position < 0 and rv <= Decimal(self._exit_level.Value):
self.BuyMarket(Math.Abs(self.Position))
self._prev_rsi = rv
def CreateClone(self):
return rsi_reversion_strategy()