상대적 강도 전략의 MACD

저자:차오장, 날짜: 2023-12-21 12:01:01
태그:

img

전반적인 설명

이 전략은 두 가지 잘 알려진 지표: MACD 및 상대적 강도 (RS) 를 기반으로 합니다. 그것들을 결합함으로써 강력한 구매 신호를 얻을 수 있습니다. 사실, 이 전략의 특수 특징은 지표로부터 지표를 생성한다는 것입니다. 따라서, 우리는 RS의 값이 소스인 MACD를 구성합니다. 전략은 구매 신호만을 취하고, 판매 신호를 무시합니다. 그들은 대부분 손실자이기 때문에. 또한 수익의 일부를 재투자하거나 상당한 손실이 발생할 경우 주문 크기를 줄일 수 있는 돈 관리 방법이 있습니다.

전략 논리

RS는 동력과 시장 효율성 가정 사이의 이상성을 측정하는 지표입니다. 전문가들이 사용하는 것으로 가장 강력한 지표 중 하나입니다. 아이디어는 과거의 성과에 따라 평균보다 더 좋은 자산을 소유하는 것입니다. 우리는 이 공식을 사용하여 RS를 계산합니다.

RS = 현재 가격 / RS 기간 중 최고 최고

따라서 우리는 현재 가격을 사용자 정의 기간 동안 가장 높은 가격과 비교할 수 있습니다.

MACD는 두 개의 기하급수적 이동 평균 사이의 거리를 측정하는 가장 유명한 지표 중 하나입니다. 하나는 빠르고 하나는 느립니다. 넓은 거리는 빠른 운동량을 나타냅니다. 우리는이 거리의 값을 그래프로 그려서 이 선을 macdline 라고 부릅니다. MACD는 첫 두 개보다 낮은 기간을 가진 세 번째 이동 평균을 사용합니다. 이 마지막 이동 평균은 macdline를 넘을 때 신호를 제공합니다. 따라서 Macdline의 값을 소스로 사용하여 구성됩니다.

첫 두 MAs는 RS 값을 원천으로 사용하여 구성되었음을 주목할 필요가 있습니다. 그래서 우리는 단지 지표의 지표를 만들었습니다. 이 유형의 방법은 거의 사용되지 않기 때문에 매우 강력하며 전략에 가치를 제공합니다.

이점 분석

이 전략은 MACD와 RS라는 두 개의 개별적으로 매우 강력한 지표를 결합합니다. MACD는 단기 트렌드와 추진력 변화를 포착 할 수 있으며 RS는 중장기 트렌드의 강도를 반영합니다. 그것들을 함께 사용하면 단기 및 장기 요인을 모두 고려하여 구매 신호를 더 신뢰할 수 있습니다.

또한, 전략은 RS 지표에서 MACD를 도출하여 전략의 효과를 창의적으로 강화함으로써 매우 독특합니다. 이러한 혁신적인 디자인은 거의 이 접근 방식을 사용하지 않기 때문에 알파 수익을 초래할 가능성이 있습니다.

마지막으로, 전략은 위험 관리 및 스톱 로스 메커니즘을 가지고 있으며, 이는 효과적으로 위험을 제어하고 거래 당 손실을 제한합니다.

위험 분석

이 전략의 가장 큰 위험은 RS 및 MACD 지표가 잘못된 신호를 줄 가능성이 있습니다. 두 지표가 강력하더라도 기술 지표는 100% 미래를 예측할 수 없으며 신호는 때때로 실패 할 수 있습니다. 또한 RS 자체는 중장기 트렌드 판단에 편향되어 있으며 단기간에 잘못된 신호를 생성 할 수 있습니다.

리스크를 줄이기 위해 RS와 MACD의 매개 변수는 특정 거래 도구와 시장 환경에 더 잘 맞게 조정 할 수 있습니다. 또한 더 엄격한 스톱 로스 범위가 부과 될 수 있습니다. 일반적으로 거래 손실 당 스톱 로스를 제어하는 것이이 전략의 위험을 해결하는 가장 좋은 방법입니다.

개선 방향

먼저 어떤 시장 (주식, 외환, 암호화폐 등) 이 전략의 가장 좋은 효과를 주는지를 테스트하고, 최적의 자산에 집중합니다.

둘째, 기계 학습 알고리즘을 사용하여 RS와 MACD 매개 변수를 수동으로 고정하는 대신 자동으로 최적화하십시오. 이것은 매개 변수의 적응력을 크게 향상시킬 수 있습니다.

셋째, 거래 신호를 설정하기 위해 다른 지표를 통합하는 것을 고려하여 신호 정확성을 향상시키기 위해 다중 요소 모델을 형성하십시오. 예를 들어 볼륨 지표를 추가하십시오.

결론

이 전략은 강력한 구매 신호를 공급하기 위해 MACD와 RS 지표를 시너지적으로 활용합니다. 이 전략의 새로움은 RS 지표에서 MACD를 도출하여 효율성을 높이기 위해 지표 간의 결합을 실현하는 데 있습니다. 전략은 위험을 효과적으로 제어하는 명확한 엔트리, 스톱 로스 및 돈 관리 메커니즘을 갖추고 있습니다. 다음 단계는 매개 변수 최적화, 신호 생성 정제, 다른 요소를 추가하는 등 전략의 추가 개선이 될 수 있습니다.


/*backtest
start: 2022-12-14 00:00:00
end: 2023-12-20 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 strategy calculates the Relative Strength and plot the MACD of this Relative Strenght
//We take only buy signals send by MACD
//@version=5
strategy("MACD OF RELATIVE STRENGHT STRATEGY", shorttitle="MACD RS STRATEGY", precision=4, overlay=false, initial_capital=1000, default_qty_type=strategy.cash, default_qty_value=950, commission_type=strategy.commission.percent, commission_value=0.18, slippage=3)


//------------------------------TOOL TIPS--------------------------------//

t1 = "Relative Strength length i.e. number of candles back to find the highest high and compare the current price with this high."
t2 = "Relative Strength fast EMA length used to plot the MACD."
t3 = "Relative Strength slow EMA length used to plot the MACD."
t4 = "Macdline SMA length used to plot the MACD."
t5 = "The maximum loss a trade can incur (in percentage of the trade value)"
t6 = "Each gain or losse (relative to the previous reference) in an amount equal to this fixed ratio will change quantity of orders."
t7 = "The amount of money to be added to or subtracted from orders once the fixed ratio has been reached."


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

//@function Displays text passed to `txt` when called.
debugLabel(txt, color, loc) =>
    label.new(bar_index, loc, 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
rs_lenght = input.int(defval=300, minval=1, title="RS Length", group="Technical parameters", tooltip=t1)
fast_length = input(title="MACD Fast Length", defval=14, group="Technical parameters", tooltip=t2)
slow_length = input(title="MACD Slow Length", defval=26, group="Technical parameters", tooltip=t3)
signal_length = input.int(title="MACD Signal Smoothing",  minval=1, maxval=50, defval=10, group="Technical parameters", tooltip=t4)
//Risk Management
slMax = input.float(8, "Max risk per trade (in %)", minval=0, group="Risk Management", tooltip=t5)
//Money Management
fixedRatio = input.int(defval=400, minval=1, title="Fixed Ratio Value ($)", group="Money Management", tooltip=t6)
increasingOrderAmount = input.int(defval=200, minval=1, title="Increasing Order Amount ($)", group="Money Management", tooltip=t7)
//Backtesting period
startDate = input(title="Start Date", defval=timestamp("1 Jan 2020 00:00:00"), group="Backtesting Period")
endDate = input(title="End Date", defval=timestamp("1 July 2024 00:00:00"), group="Backtesting Period")


//----------------------------------VARIABLES INITIALISATION-----------------------------//
strategy.initial_capital = 50000
//Relative Strenght Calculation
rs = close/ta.highest(high, rs_lenght)
//MACD of RS Calculation
[macdLine, signalLine, histLine] = ta.macd(rs, fast_length, slow_length, signal_length)
//Money management
equity = math.abs(strategy.equity - strategy.openprofit)
var float capital_ref = strategy.initial_capital
var float cashOrder = strategy.initial_capital * 0.95
//Backtesting period
bool inRange = na


//------------------------------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
    strategy.close_all()
    debugLabel("END OF BACKTESTING PERIOD : we close the trade", color=color.rgb(116, 116, 116), loc=macdLine)


//-----------------------------------EXIT SIGNAL------------------------------//

if strategy.position_size>0 and histLine<0
    strategy.close("Long")


//-------------------------------BUY CONDITION-------------------------------------//

if histLine>0 and not (strategy.position_size>0) and inRange
    qty = cashOrder/close
    stopLoss = close*(1-slMax/100)
    strategy.entry("Long", strategy.long, qty)
    strategy.exit("Exit Long", "Long", stop=stopLoss)


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

hline(0, "Zero Line", color=color.new(#787B86, 50))
plot(macdLine, title="MACD", color=color.blue)
plot(signalLine, title="Signal", color=color.orange)
plot(histLine, title="Histogram", style=plot.style_columns, color=(histLine>=0 ? (histLine[1] < histLine ? #26A69A : #B2DFDB) : (histLine[1] < histLine ? #FFCDD2 : #FF5252)))
plotchar(rs, "Relative Strenght", "", location.top, color=color.yellow)

더 많은