RSI 추세 추종 전략


생성 날짜: 2023-11-16 15:33:40 마지막으로 수정됨: 2023-11-16 15:33:40
복사: 2 클릭수: 832
avatar of ChaoZhang ChaoZhang
1
집중하다
1617
수행원

RSI 추세 추종 전략

개요

이 전략은 RSI 지표와 중도 이동 평균을 결합하여 트렌드 추적 거래를 구현한다. RSI가 60 이상일 때 부자를, RSI가 40 이하일 때 부자를, 동시에 이동 평균이 트렌드 조건을 충족하도록 요구한다. 40 주기의 RSI를 트렌드 추적 지표로 사용한다. 중도 이동 평균은 다양한 무게를 사용하여 단기 변동의 영향을 줄인다. 전략은 동시에 중지 손실과 이동 스톱을 설정하여 위험을 제어한다.

전략 원칙

이 전략은 먼저 RSI와 중도 이동 평균을 계산한다. RSI의 길이는 20주기이고, 중도 이동 평균의 길이는 20이며, 단기 변동의 영향을 줄이기 위해 더 큰 무게를 설정한다. RSI가 60보다 크면 중도 이동 평균의 변화율이 1% 미만일 때, 더 많은 작업을 수행한다. RSI가 40보다 작고 중도 이동 평균의 변화율이 1% 미만일 때, 공백 작업을 수행한다.

더 많은 공백을 후, 동시에 스톱 손실 명령과 이동 스톱 명령을 설정한다. 스톱 손실은 현재 가격의 3배 ATR에서 떨어져 있다. 이동 스톱은 초기 활성 가격과 현재 가격의 4배 ATR에서 떨어져 있다. 이후 3%의 폭으로 이동한다. 가격이 스톱 손실이나 이동 스톱 중지 활성 가격에 닿으면, 해당 위치를 닫는다.

이 전략은 또한 고정 비율의 법칙을 통해 포지션을 조정하는 자금 관리 규칙을 추가한다. 수익 또는 손실이 고정 금액에 도달 할 때마다 고정 수의 거래량을 늘리거나 줄인다.

우위 분석

  • RSI를 사용하여 동향을 판단하여 동향을 효과적으로 추적할 수 있습니다.
  • 가중된 이동 평균은 가중치를 사용하여 단기 변동의 영향을 줄이고, 가설을 피합니다.
  • 모바일 스톱을 사용하여 수익을 극대화하십시오.
  • 고정 비율법 자금 관리 효과적 통제 위험

이 전략의 전체적인 장점은 동향을 추적할 수 있다는 점과 동시에 손실을 멈추고 이동을 멈추는 조치를 취하여 위험을 통제하여 강세를 보이는 상황에서 더 나은 수익을 얻을 수 있다는 것입니다.

위험 분석

  • RSI 지표가 잘못된 신호를 내보내면 불필요한 거래가 발생할 수 있습니다.
  • 스톱포드를 뚫거나 스톱포드를 움직일 때 강제 스톱포드, 트렌드를 지속적으로 추적할 수 없습니다.
  • 재무관리 규정이 너무 과격하여 손실이 발생할 수 있습니다.

이 전략의 주요 위험은 RSI 지표의 신뢰성 및 중지 이동 중지 설정이 합리적인지에 달려 있습니다. 변수가 잘못 설정되면 불필요한 평점 또는 견딜 수 있는 능력을 초과하는 손실이 발생할 수 있습니다. 또한, 중지 또는 중지 가격을 돌파 할 때 중단이 강제되어 추세를 계속 추적 할 수있는 기회를 잃을 수 있습니다.

RSI 변수를 최적화하거나 다른 지표의 보조 판단을 고려할 수 있습니다. 다양한 품종과 변동 상황에 맞게 중지 손해 이동 중지 변수를 조정하십시오. 마지막으로 재원 관리 규칙을 신중하게 설정하여 너무 과격하지 않도록하십시오.

최적화 방향

  • KD, MACD 등과 같은 다른 지표와 RSI를 결합하여 신호 확인을 시도하십시오.
  • 다양한 품종 특성과 변동 범위에 따라 최적화된 스톱 손실 이동 스톱 파라미터
  • 고정금융거래, 켈리 수식 등과 같은 다른 자금관리 방법을 시도하세요.
  • 부린 라인을 돌파하거나 RSI를 벗어나는 것과 같은 포지션 개시 조건을 추가합니다.
  • 강세를 보인 시점에서의 입지를 추가하기 위해 출구 가격을 추가하는 것을 고려하십시오.

이 전략은 여러 가지 측면에서 최적화 될 수 있습니다. 첫째, RSI 지표를 보조하거나 확인 할 수있는 다른 기술 지표를 찾아 신호 신뢰도를 높이는 것입니다. 둘째, 특정 품종 특성에 따라 스톱 로즈 이동 스톱 파라미터를 최적화하는 것이 중요합니다.

요약하다

이 RSI 트렌드 추적 전략의 전체적인 아이디어는 명확하며, 핵심은 RSI를 사용하여 트렌드 방향을 판단하고, 이동 평균을 가중화하여 판단 정확도를 향상시키는 데 있습니다. 전략의 장점은 트렌드를 추적하고 수익을 최대화 할 수 있다는 것입니다. 그러나 RSI 지표의 신뢰성이 낮고 매개 변수 설정에는 최적화 할 수있는 공간이 있습니다.

||

Overview

This strategy combines the RSI indicator and weighted moving average for trend following trading. It goes long when RSI is above 60 and goes short when RSI is below 40, with the moving average verifying the trend condition. The 40-period RSI acts as a trend following indicator. The weighted moving average uses different weights to reduce the impact of short-term fluctuations. The strategy also employs stop loss and trailing take profit to control risks.

Strategy Logic

The strategy firstly calculates the RSI and weighted moving average. The RSI length is 20 periods and the weighted MA length is 20 with higher weights that reduce the impact of short-term volatility. It goes long when RSI is above 60 and weighted MA rate of change is below -1%. It goes short when RSI is below 40 and weighted MA rate of change is above 1%.

After opening long or short, stop loss and trailing take profit orders are placed simultaneously. The stop loss is set at 3 ATR from the current price. The initial trailing take profit activation is 4 ATR away, and trails in 3% increments. When price hits either stop loss or trailing take profit activation, the position will be closed.

The strategy also incorporates money management rules based on the fixed fractional position sizing approach. Whenever PNL hits a fixed amount, the order size is increased or decreased by a fixed amount.

Advantage Analysis

  • RSI indicator can effectively track trends
  • Weighted MA reduces the impact of short-term fluctuations, avoiding whipsaws
  • Trailing take profit allows profits to be maximized
  • Fixed fraction position sizing controls risk effectively

The overall edge is the ability to follow trends, while taking stop loss and trailing take profit measures to control risks, thus capturing significant gains in strong trends.

Risk Analysis

  • False signals from RSI may cause unnecessary trades
  • Forced to stop out when price breaches stop or trailing take profit levels, unable to keep following trends
  • Aggressive money management rules may lead to large losses

The main risks come from the reliability of RSI signals and the stop loss/trailing take profit settings. Incorrect parameters may result in unnecessary closing of trades or losses beyond risk appetite. Breaking stop loss/take profit may also force unwarranted stop outs, losing the chance to continue trend trading.

Solutions include optimizing RSI parameters or adding other indicators for signal confirmation. Adjust stop/trailing take profit levels based on different products and volatility conditions. Also be prudent with money management rules to avoid excessive risks.

Optimization Directions

  • Test other indicators together with RSI for signal confirmation, e.g. KD, MACD etc
  • Optimize stop loss and trailing take profit parameters based on product characteristics and volatility range
  • Try other money management techniques like fixed size trading, Kelly formula etc
  • Add entry conditions like Bollinger breakouts, RSI divergences etc
  • Consider adding positions on strong trends

There are many aspects to optimize. First is identifying other indicators to supplement RSI signals. Next critical step is optimizing stop loss/trailing take profit parameters based on historical performance. Money management can also switch to other types. Finally, entry, add-on conditions can be enhanced to pyramiding positions in strong trends.

Summary

The RSI trend following strategy has clear logic, using RSI for trend direction and weighted MA for confirmation. Its strength lies in trend trading, maximizing profits with stops/money management controlling risks. But RSI reliability and parameter optimization need improvement. We can look into enhancing signal indicators, stop/trailing parameters, money management methods etc to make the strategy more robust across different products.

[/trans]

전략 소스 코드
/*backtest
start: 2023-01-01 00:00:00
end: 2023-06-24 00:00:00
period: 1d
basePeriod: 1h
exchanges: [{"eid":"Futures_Binance","currency":"BTC_USDT"}]
*/

// This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/
// © gsanson66


//This code is based on RSI and a backed weighted MA
//@version=5
strategy("RSI + MA BACKTESTING", overlay=true, initial_capital=1000, default_qty_type=strategy.fixed, commission_type=strategy.commission.percent, commission_value=0.18)


//------------------------FUNCTIONS---------------------------//

//@function which calculate a retro weighted moving average to minimize the impact of short term reversal
rwma(source, length) =>
    sum = 0.0
    denominator = 0.0
    weight = 0.0
    weight_x = 100/(4+(length-4)*1.30)
    weight_y = 1.30*weight_x
    for i=0 to length - 1
        if i <= 3
            weight := weight_x
        else
            weight := weight_y
        sum := sum + source[i] * weight
        denominator := denominator + weight
    rwma = sum/denominator

//@function which permits the user to choose a moving average type
ma(source, length, type) =>
    switch type
        "SMA" => ta.sma(source, length)
        "RWMA" => rwma(source, length)

//@function Displays text passed to `txt` when called.
debugLabel(txt, color) =>
    label.new(bar_index, high, text = txt, color=color, style = label.style_label_lower_right, textcolor = color.black, size = size.small)

//@function which looks if the close date of the current bar falls inside the date range
inBacktestPeriod(start, end) => (time >= start) and (time <= end)


//--------------------------------USER INPUTS-------------------------------//

//Technical parameters
rsiLengthInput = input.int(20, minval=1, title="RSI Length", group="RSI Settings")
maTypeInput = input.string("RWMA", title="MA Type", options=["SMA", "RWMA"], group="MA Settings", inline="1")
maLenghtInput = input.int(20, minval=1, title="MA Length", group="MA Settings", inline="1")
rsiLongSignalValue = input.int(60, minval=1, maxval=99, title="RSI Long Signal", group="Strategy parameters", inline="3")
rsiShortSignalValue = input.int(40, minval=1, maxval=99, title="RSI Short Signal", group="Strategy parameters", inline="3")
rocMovAverLongSignalValue = input.float(-1, maxval=0, title="ROC MA Long Signal", group="Strategy parameters", inline="4")
rocMovAverShortSignalValue = input.float(1, minval=0, title="ROC MA Short Signal", group="Strategy parameters", inline="4")
//TP Activation and Trailing TP
takeProfitActivationInput = input.float(4, minval=1.0, title="TP activation in multiple of ATR", group="Strategy parameters")
trailingStopInput = input.float(3, minval=0, title="Trailing TP in percentage", group="Strategy parameters")
//Money Management
fixedRatio = input.int(defval=400, minval=1, title="Fixed Ratio Value ($)", group="Money Management")
increasingOrderAmount = input.int(defval=200, minval=1, title="Increasing Order Amount ($)", group="Money Management")
//Backtesting period
startDate = input(title="Start Date", defval=timestamp("1 Jan 2018 00:00:00"), group="Backtesting Period")
endDate = input(title="End Date", defval=timestamp("1 July 2024 00:00:00"), group="Backtesting Period")

strategy.initial_capital = 50000

//------------------------------VARIABLES INITIALISATION-----------------------------//

float rsi = ta.rsi(close, rsiLengthInput)
float ma = ma(close, maLenghtInput, maTypeInput)
float roc_ma = ((ma/ma[maLenghtInput]) - 1)*100
float atr = ta.atr(20)
var float trailingStopOffset = na
var float trailingStopActivation = na
var float trailingStop = na
var float stopLoss = na
var bool long = na
var bool short = na
var bool bufferTrailingStopDrawing = na
float theoreticalStopPrice = na
bool inRange = na
equity = strategy.equity - strategy.openprofit
var float capital_ref = strategy.initial_capital
var float cashOrder = strategy.initial_capital * 0.95


//------------------------------CHECKING SOME CONDITIONS ON EACH SCRIPT EXECUTION-------------------------------//

//Checking if the date belong to the range
inRange := true

//Checking performances of the strategy
if equity > capital_ref + fixedRatio
    spread = (equity - capital_ref)/fixedRatio
    nb_level = int(spread)
    increasingOrder = nb_level * increasingOrderAmount
    cashOrder := cashOrder + increasingOrder
    capital_ref := capital_ref + nb_level*fixedRatio
if equity < capital_ref - fixedRatio
    spread = (capital_ref - equity)/fixedRatio
    nb_level = int(spread)
    decreasingOrder = nb_level * increasingOrderAmount
    cashOrder := cashOrder - decreasingOrder
    capital_ref := capital_ref - nb_level*fixedRatio

//Checking if we close all trades in case where we exit the backtesting period
if strategy.position_size!=0 and not inRange
    debugLabel("END OF BACKTESTING PERIOD : we close the trade", color=color.rgb(116, 116, 116))
    strategy.close_all()
    bufferTrailingStopDrawing := false
    stopLoss := na
    trailingStopActivation := na
    trailingStop := na
    short := false
    long := false


//------------------------------STOP LOSS AND TRAILING STOP ACTIVATION----------------------------//

// We handle the stop loss and trailing stop activation 
if (low <= stopLoss or high >= trailingStopActivation) and long
    if high >= trailingStopActivation
        bufferTrailingStopDrawing := true
    else if low <= stopLoss
        long := false
    stopLoss := na
    trailingStopActivation := na
if (low <= trailingStopActivation or high >= stopLoss) and short
    if low <= trailingStopActivation
        bufferTrailingStopDrawing := true
    else if high >= stopLoss
        short := false
    stopLoss := na
    trailingStopActivation := na


//-------------------------------------TRAILING STOP--------------------------------------//

// If the traling stop is activated, we manage its plotting with the bufferTrailingStopDrawing
if bufferTrailingStopDrawing and long
    theoreticalStopPrice := high - trailingStopOffset * syminfo.mintick
    if na(trailingStop)
        trailingStop := theoreticalStopPrice
    else if theoreticalStopPrice > trailingStop
        trailingStop := theoreticalStopPrice
    else if low <= trailingStop
        trailingStop := na
        bufferTrailingStopDrawing := false
        long := false
if bufferTrailingStopDrawing and short
    theoreticalStopPrice := low + trailingStopOffset * syminfo.mintick
    if na(trailingStop)
        trailingStop := theoreticalStopPrice
    else if theoreticalStopPrice < trailingStop
        trailingStop := theoreticalStopPrice
    else if high >= trailingStop
        trailingStop := na
        bufferTrailingStopDrawing := false
        short := false


//---------------------------------LONG CONDITION--------------------------//

if rsi >= 60 and roc_ma <= rocMovAverLongSignalValue and inRange and not long
    if short
        bufferTrailingStopDrawing := false
        stopLoss := na
        trailingStopActivation := na
        trailingStop := na
        short := false
    trailingStopActivation := close + takeProfitActivationInput*atr
    trailingStopOffset := (trailingStopActivation * trailingStopInput/100) / syminfo.mintick
    stopLoss := close - 3*atr
    long := true
    qty = cashOrder/close
    strategy.entry("Long", strategy.long, qty)
    strategy.exit("Exit Long", "Long", stop = stopLoss, trail_price = trailingStopActivation,
                 trail_offset = trailingStopOffset)


//--------------------------------SHORT CONDITION-------------------------------//

if rsi <= 40 and roc_ma >= rocMovAverShortSignalValue and inRange and not short
    if long
        bufferTrailingStopDrawing := false
        stopLoss := na
        trailingStopActivation := na
        trailingStop := na
        long := false
    trailingStopActivation := close - takeProfitActivationInput*atr
    trailingStopOffset := (trailingStopActivation * trailingStopInput/100) / syminfo.mintick
    stopLoss := close + 3*atr
    short := true
    qty = cashOrder/close
    strategy.entry("Short", strategy.short, qty)
    strategy.exit("Exit Short", "Short", stop = stopLoss, trail_price = trailingStopActivation,
                 trail_offset = trailingStopOffset)


//--------------------------------PLOTTING ELEMENT---------------------------------//

// Plotting of element in the graph
plotchar(rsi, "RSI", "", location.top, color.rgb(0, 214, 243))
plot(ma, "MA", color.rgb(219, 219, 18))
plotchar(roc_ma, "ROC MA", "", location.top, color=color.orange)
// Visualizer trailing stop and stop loss movement
plot(stopLoss, "SL", color.red, 3, plot.style_linebr)
plot(trailingStopActivation, "Trigger Trail", color.green, 3, plot.style_linebr)
plot(trailingStop, "Trailing Stop",  color.blue, 3, plot.style_linebr)