RSI and EMA Dual Filter Strategy

Author: ChaoZhang, Date: 2024-03-22 15:37:08
Tags:

img

Overview

The RSI and EMA Dual Filter Strategy is a quantitative trading strategy based on the Relative Strength Index (RSI) and Exponential Moving Average (EMA). The strategy uses the RSI indicator to determine overbought and oversold conditions in the market, while also incorporating the trend judgment of two EMA lines, fast and slow, as the basis for entry and exit. Through the dual filtering of RSI and EMA, the strategy can effectively reduce false signals and improve stability and profitability.

Strategy Principle

The core principles of this strategy can be divided into the following parts:

  1. Calculation and application of the RSI indicator: The strategy first calculates an RSI indicator with a custom period (default is 2). When the RSI value is below the oversold threshold (default is 10), it indicates that the market is oversold, and a long position can be considered. When the RSI value is above the overbought threshold (default is 90), it indicates that the market is overbought, and a short position can be considered.

  2. Trend judgment of fast and slow EMA lines: The strategy calculates two EMA lines, a slow line (default period is 200) and a fast line (default period is 50). When the fast line is above the slow line and the price is above the slow line, the market is considered to be in an uptrend. Conversely, when the fast line is below the slow line and the price is below the slow line, the market is considered to be in a downtrend.

  3. Trend filter: The strategy provides an option for trend filtering. If this option is enabled, a long position will only be opened when the RSI is oversold in an uptrend, and a short position will only be opened when the RSI is overbought in a downtrend. This can further reduce the risk of counter-trend trading.

  4. Confirmation of trading signals: The strategy comprehensively considers the results of the RSI indicator and EMA trend judgment to generate final trading signals. In an uptrend, when the RSI is below the oversold threshold, a long position is opened. In a downtrend, when the RSI is above the overbought threshold, a short position is opened.

  5. Position management: The strategy uses a minimum trading interval (default is 5 minutes) to control the trading frequency and avoid excessive trading. At the same time, the strategy uses a combination of trailing stop loss and fixed stop loss for risk management, which allows profits to extend fully while effectively controlling losses.

Advantage Analysis

The RSI and EMA Dual Filter Strategy has the following advantages:

  1. Strong trend-tracking ability: Through the trend judgment of fast and slow EMA lines, the strategy can effectively grasp the main trend of the market and avoid frequent trading in a range-bound market.

  2. Effective filtering of false signals: The RSI indicator tends to generate many false signals, especially in markets with unclear trends. However, EMA trend filtering can effectively identify the main trend and reduce false signals generated by RSI.

  3. Comprehensive risk management: The strategy uses a combination of trailing stop loss and fixed stop loss, which allows profits to extend fully while effectively controlling losses. This risk management approach can improve the stability and drawdown control ability of the strategy.

  4. Flexible and adjustable parameters: The strategy provides multiple parameters for users to adjust, such as RSI period, overbought/oversold thresholds, EMA period, stop loss ratio, etc. This makes the strategy adaptable to different market environments and trading habits.

Risk Analysis

Despite the advantages of the RSI and EMA Dual Filter Strategy, there are still some potential risks:

  1. Trend reversal risk: When the market trend reverses, EMA lines may lag, causing the strategy to miss the best entry point or delay the exit.

  2. Parameter optimization risk: The performance of this strategy is sensitive to parameter settings, and different parameter combinations may bring completely different results. If the parameters are over-optimized, the strategy may perform poorly in future markets.

  3. Black swan event risk: The strategy is based on historical data for backtesting and optimization, but historical data cannot fully reflect extreme events that may occur in the future. Once a black swan event occurs, the strategy may suffer significant losses.

To address these risks, the following solutions can be considered:

  1. Combine other technical indicators or price behavior patterns to assist in judging trend reversals and make adjustments early.

  2. Adopt moderate parameter optimization to avoid over-fitting historical data. At the same time, regularly review and adjust parameters to adapt to the latest market characteristics.

  3. Set reasonable stop loss levels to control the maximum loss of a single trade. Additionally, implement risk control at the portfolio level, such as diversification and position sizing.

Optimization Direction

  1. Introduce more technical indicators: In addition to the existing RSI and EMA indicators, more effective technical indicators can be introduced, such as MACD, Bollinger Bands, etc., to improve the signal accuracy and stability of the strategy.

  2. Optimize trend judgment methods: In addition to using EMA lines to judge trends, other trend judgment methods can be explored, such as higher highs and higher lows, moving average systems, etc. By combining multiple trend judgment methods, the adaptability of the strategy can be improved.

  3. Improve risk management methods: Based on the existing trailing stop loss and fixed stop loss, more advanced risk management methods can be introduced, such as volatility stop loss, dynamic stop loss, etc. These methods can better adapt to changes in market volatility and thus better control risks.

  4. Add position management module: Currently, the strategy adopts a fixed position size approach. A dynamic position management module can be considered to dynamically adjust positions based on factors such as market volatility and account equity, thus improving capital utilization efficiency.

  5. Adapt to multiple markets and varieties: Expand the strategy to more trading markets and varieties, and reduce overall risk through diversification. At the same time, study the correlation between different markets and varieties, and use this information to optimize the asset allocation of the strategy.

Summary

The RSI and EMA Dual Filter Strategy effectively captures market trends while reducing the problem of false signals easily generated by the RSI indicator through the organic combination of the Relative Strength Index and Exponential Moving Average. The strategy logic is clear and includes comprehensive risk management measures, with good stability and profit potential. However, the strategy also has some potential risks, such as trend reversal risk, parameter optimization risk, and black swan event risk. To address these risks, we have proposed corresponding countermeasures and optimization directions, such as introducing more technical indicators, optimizing trend judgment methods, improving risk management methods, adding position management modules, and expanding to multiple markets and varieties. Through continuous optimization and improvement, we believe that the strategy can better adapt to future market changes and bring stable returns for investors.


/*backtest
start: 2024-02-01 00:00:00
end: 2024-02-29 23:59:59
period: 1h
basePeriod: 15m
exchanges: [{"eid":"Futures_Binance","currency":"BTC_USDT"}]
*/

//@version=4
strategy("RSI2", overlay=true)

// RSILength input
len = input(2, minval=1, title="RSILength")

// Threshold RSI up input
RSIthreshUP = input(90, title="Threshold RSI up")

// Threshold RSI down input
RSIthreshDWN = input(10, title="Threshold RSI down")

// Slow MA length input
mmlen = input(200, title="Slow MA len")

// Fast MA length input
mmflen = input(50, title="Fast MA len")

// Moving Average type input
machoice = input("EMA", defval="EMA", options=["SMA", "EMA"])

// Ticker size input
tick=input(0.5,title="Ticker size",type=input.float)

// Trend Filter input
filter=input(true,title="Trend Filter",type=input.bool)

// Trailing Stop percentage input
ts_percent = input(1, title="TrailingStop%")

// Stop Loss percentage input
sl_percent = input(0.3, title="Stop Loss %")

// Calculate RSI
src = close
up = rma(max(change(src), 0), len)
down = rma(-min(change(src), 0), len)
rsi = down == 0 ? 100 : up == 0 ? 0 : 100 - 100 / (1 + up / down)

// Calculate moving averages
mmslow = machoice == "SMA" ? sma(close, mmlen) : ema(close, mmlen)
mmfast = machoice == "SMA" ? sma(close, mmflen) : ema(close, mmflen)

// Plot moving averages
plot(mmslow, color=color.white)
plot(mmfast, color=color.yellow)

// Conditions for entry and exit
var lastLongEntryTime = 0
var lastShortEntryTime = 0

ConditionEntryL = if filter == true
    mmfast > mmslow and close > mmslow and rsi < RSIthreshDWN
else 
    mmfast > mmslow and rsi < RSIthreshDWN
    
ConditionEntryS = if filter == true
    mmfast < mmslow and close < mmslow and rsi > RSIthreshUP
else
    mmfast < mmslow and rsi > RSIthreshUP

// Calculate trailing stop and stop loss
ts_calc = close * (1/tick) * ts_percent * 0.01
sl_price = close * (1 - sl_percent / 100)

// Entry and exit management
if ConditionEntryL and time - lastLongEntryTime > 1000 * 60 * 5 // 5 minutes
    strategy.entry("RSILong", strategy.long)
    lastLongEntryTime := time

if ConditionEntryS and time - lastShortEntryTime > 1000 * 60 * 5 // 5 minutes
    strategy.entry("RSIShort", strategy.short)
    lastShortEntryTime := time

lastLongEntryTimeExpired = time - lastLongEntryTime >= 1000 * 60 * 5
lastShortEntryTimeExpired = time - lastShortEntryTime >= 1000 * 60 * 5

strategy.exit("ExitLong", "RSILong", when=lastLongEntryTimeExpired, trail_points=0, trail_offset=ts_calc, stop=sl_price)
strategy.exit("ExitShort", "RSIShort", when=lastShortEntryTimeExpired, trail_points=0, trail_offset=ts_calc, stop=sl_price)

More