이동 평균 크로스오버 전략

저자:차오장, 날짜: 2023-10-10 10:44:25
태그:

전반적인 설명

이동평균 크로스오버 전략은 이동평균을 기반으로 일반적으로 사용되는 거래 전략이다. 더 빠른 이동평균과 더 느린 이동평균의 크로스오버를 거래 신호로 사용합니다. 더 빠른 이동평균이 아래에서 느린 이동평균을 넘을 때, 그것은 구매 신호입니다. 더 빠른 이동평균이 위에서 느린 이동평균을 넘을 때, 그것은 판매 신호입니다. 이 전략은 50일 MA를 더 빠른 MA로, 200일 MA를 더 느린 MA로 사용합니다.

전략 논리

이 전략의 핵심 논리는 이동 평균의 이론에 기초한다. 이동 평균은 가격 변동을 효과적으로 부드럽게하고 가격 추세를 나타낼 수 있다. 더 빠른 MA는 가격 변화에 더 민감하며 트렌드 반전 지점을 파악할 수 있다. 더 느린 MA는 가격 변화에 덜 민감하며 단기 변동을 필터링할 수 있다. 더 빠른 MA가 느린 MA보다 높을 때, 그것은 가격의 상승 추세를 나타낸다. 더 빠른 MA가 느린 MA보다 낮을 때, 그것은 가격의 하락 추세를 나타낸다.

특히, 이 전략은 먼저 50일 MA와 200일 MA를 정의한다. 더 빠른 MA가 더 느린 MA를 넘을 때 긴 진입 조건이 설정된다. 더 빠른 MA가 더 느린 MA를 넘을 때 짧은 진입 조건이 설정된다. 중복되는 거래를 피하기 위해 전략은 isEntry와 isExit 플래그를 제어하기 위해 사용합니다. 진입 조건이 충족되면 isEntry가 true로 설정됩니다. 출구 조건이 충족되면 isExit가 true로 설정됩니다. isEntry가 거짓되고 구매 신호가 표시될 때만 긴 포지션이 열릴 것입니다. isExit가 거짓되고 판매 신호가 표시될 때만 짧은 포지션이 열릴 것입니다.

또한, 전략은 또한 수익을 취하고 손실을 멈추는 수준을 설정합니다. 사용자는 입력을 통해 TP/SL 비율 거리를 정의할 수 있습니다. TP 및 SL 가격은 입시 가격 비율에 따라 계산됩니다. 포지션 크기가 0보다 크면 TP 및 SL는 긴 TP/SL 비율에 따라 실행됩니다. 포지션 크기가 0보다 작을 때 TP 및 SL는 짧은 TP/SL 비율에 따라 계산됩니다.

이점 분석

이 전략의 장점은 다음과 같습니다.

  1. 구현하기 쉽습니다. 그것은 순전히 MA 크로스를 기반으로 거래합니다. 거래 경험이없는 초보자에게 적합합니다.

  2. 리스크 관리와 함께 제어 할 수 있는 마감. 이동 평균은 단기 변동을 필터링하고 중단되는 것을 피할 수 있습니다.

  3. 적응력을 위해 사용자 정의 가능한 매개 변수. 사용자는 MA 기간 및 TP / SL 수준과 같은 매개 변수를 최적화 할 수 있습니다.

  4. 명확한 시각화. 전략은 주요 MAs, 항목, TP / SL 수준을 차트에 표시합니다.

  5. 확장 가능한 프레임워크 전략 구조가 완료되었습니다. 새로운 신호와 지표가 추가 될 수 있습니다.

위험 분석

이 전략의 위험은 다음과 같습니다.

  1. 극단적인 시장 이벤트 중 손실을 막을 수 없으므로 큰 마감으로 이어집니다. 더 빠른 MA는 가격 변화에 민감하며 극단적인 조건에서 실패 할 수 있습니다.

  2. 다양한 시장에서 부진을 일으켜 연속적인 손실을 초래합니다.

  3. 거래 비용은 고려되지 않습니다. 실제 거래에서 수수료와 미끄러짐은 수익성에 크게 영향을 줄 것입니다.

  4. 백테스트 오버파이팅 실제 시장 조건은 복잡하고 백테스트 결과는 실시간 성능을 나타내지 않을 수 있습니다.

그 해결책은 다음과 같습니다.

  1. 더 넓은 스톱 손실을 사용하거나 추가 브레이크오웃 스톱 손실을 추가합니다.

  2. MA 거리를 넓히거나 거래 빈도를 줄이거나 다른 필터를 추가합니다.

  3. 실제 거래 비용을 고려하고 더 넓은 수익 목표 공간을 설정합니다.

  4. 매개 변수를 점진적으로 최적화하고 변화하는 시장 조건을 고려하여 과잉 장착을 줄이십시오.

최적화 방향

이 전략은 다음과 같은 측면에서 최적화 될 수 있습니다.

  1. 다양한 매개 변수 조합을 테스트하여 최적의 매개 변수를 찾습니다.

  2. MACD, KD 등과 같은 다른 지표를 필터로 추가하여 화이트사이를 피합니다.

  3. 더 나은 리스크 관리를 위해 스톱 로스 전략을 최적화하십시오.

  4. 지점 크기를 높이고 리버웨어를 사용해서 수익을 높이고 동시에 위험을 조절합니다.

  5. 거래 비용을 고려하고 실시간 거래의 매개 변수를 최적화합니다.

  6. 과도한 장착을 줄이기 위해 통계적인 방법을 사용하여 매개 변수 안정성을 평가합니다.

결론

결론적으로,이 MA 크로스오버 전략은 명확한 논리를 가지고 있으며 구현하기가 간단하며, 알고 거래의 도입 전략으로 적합합니다. 그러나 위험과 한계도 있습니다. 안정적인 수익을 달성하기 위해 신중한 매개 변수 및 필터 최적화 및 위험 통제가 필요합니다.이 전략은 사용자가 자신의 거래 스타일에 맞게 혁신하고 최적화 할 수있는 큰 확장성을 가지고 있습니다.


/*backtest
start: 2023-10-02 00:00:00
end: 2023-10-09 00:00:00
period: 3m
basePeriod: 1m
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/
// © gjfsdrtytru

//@version=4
strategy("Backtest Engine", "Backtest", overlay=true, commission_type=strategy.commission.percent, commission_value=0.07, initial_capital = 1000, default_qty_type = strategy.percent_of_equity, default_qty_value = 100, currency = currency.USD)


// Start code here...
fastMA = sma(close,50)
slowMA = sma(close,200)

plot(fastMA, "Fast MA",  color.blue)
plot(slowMA, "Slow MA",  color.red)

// Long Enrty/Exit
longCondition = crossover(fastMA,slowMA)
closeLong = crossover(slowMA,fastMA)

// Short Enrty/Exit
shortCondition = crossover(slowMA,fastMA)
closeShort = crossover(fastMA,slowMA)


// Bot web-link alert - {{strategy.order.comment}}
botLONG = "ENTRY LONG ALERT"
botCLOSELONG = "CLOSE LONG ALERT"
botSHORT = "ENTRY SHORT ALERT"
botCLOSESHORT = "CLOSE SHORT ALERT"

//////////////////////////////////////////////////////////////////
//////////////////////// BACKTEST ENGINE \\\\\\\\\\\\\\\\\\\\\\\\\
/////////////////// [NO USER INPUT REQUIRED] /////////////////////
//////////////////////////////////////////////////////////////////

// Time period
testStartYear = input(2020, "Backtest Start Year")
testStartMonth = input(5, "Backtest Start Month")
testStartDay = input(11, "Backtest Start Day")
testPeriodStart = timestamp(testStartYear,testStartMonth,testStartDay,0,0)

periodLength = input(3650, "Backtest Period (days)", minval=0,tooltip="Days until strategy ends") * 86400000 // convert days into UNIX time
testPeriodStop = testPeriodStart + periodLength

testPeriod() =>
    time >= testPeriodStart and time <= testPeriodStop ? true : false

// Convert Take profit and Stop loss to percentage
longTP = input(title="Long Take Profit (%)", type=input.float, minval=0.0, step=0.1, defval=0) * 0.01 // Set levels with input options
longSL = input(title="Long Stop Loss (%)", type=input.float, minval=0.0, step=0.1, defval=0) * 0.01 // Set levels with input options
shortTP = input(title="Short Take Profit (%)", type=input.float, minval=0.0, step=0.1, defval=0) * 0.01 // Set levels with input options
shortSL = input(title="Short Stop Loss (%)", type=input.float, minval=0.0, step=0.1, defval=0) * 0.01 // Set levels with input options

// 0% TP/SL = OFF (a value of 0 turns off TP/SL feature)
longProfitPerc = longTP == 0 ? 1000 : longTP
longStopPerc = longSL == 0 ? 1 : longSL
shortProfitPerc = shortTP == 0 ? 1 : shortTP
shortStopPerc = shortSL == 0 ? 1000 : shortSL

// Determine TP/SL price based on percentage given
longProfitPrice  = strategy.position_avg_price * (1 + longProfitPerc)
longStopPrice  = strategy.position_avg_price * (1 - longStopPerc)
shortProfitPrice  = strategy.position_avg_price * (1 - shortProfitPerc)
shortStopPrice  = strategy.position_avg_price * (1 + shortStopPerc)

// Anti-overlap
isEntry_Long = false
isEntry_Long := nz(isEntry_Long[1], false)
isExit_Long = false
isExit_Long := nz(isExit_Long[1], false)
isEntry_Short = false
isEntry_Short := nz(isEntry_Short[1], false)
isExit_Short = false
isExit_Short := nz(isExit_Short[1], false)

entryLong = not isEntry_Long and longCondition
exitLong = not isExit_Long and closeLong
entryShort = not isEntry_Short and  shortCondition
exitShort = not isExit_Short and closeShort

if (entryLong)
    isEntry_Long := true
    isExit_Long := false
if (exitLong)
    isEntry_Long := false
    isExit_Long := true
if (entryShort)
    isEntry_Short := true
    isExit_Short := false
if (exitShort)
    isEntry_Short := false
    isExit_Short := true

// Order Execution
if testPeriod() 
    if entryLong
        strategy.entry(id="Long", long=true, when = entryLong, comment=botLONG) // {{strategy.order.comment}}
    if entryShort
        strategy.entry(id="Short", long=false, when = entryShort, comment=botSHORT) // {{strategy.order.comment}}


// TP/SL Execution
if (strategy.position_size > 0)
    strategy.exit(id="Long SL/TP", from_entry="Long", limit=longProfitPrice, stop=longStopPrice)
    strategy.close(id="Long", when=exitLong, comment=botCLOSELONG) // {{strategy.order.comment}}

if (strategy.position_size < 0)
    strategy.exit(id="Short TP/SL", from_entry="Short", limit=shortProfitPrice, stop=shortStopPrice)
    strategy.close(id="Short", when=exitShort, comment=botCLOSESHORT) // {{strategy.order.comment}}
    
// Draw Entry, TP and SL Levels for Long Positions
plot(strategy.position_size > 0 ? longTP == 0 ? na : longProfitPrice : na, style=plot.style_linebr, color=color.green, title="Long TP")
plot(strategy.position_size > 0 ? strategy.position_avg_price : na, style=plot.style_linebr, color=color.blue, title="Long Entry")
plot(strategy.position_size > 0 ? longSL == 0 ? na : longStopPrice : na, style=plot.style_linebr, color=color.red, title="Long SL")
// Draw Entry, TP and SL Levels for Short Positions
plot(strategy.position_size < 0 ? shortTP == 0 ? na : shortProfitPrice : na, style=plot.style_linebr, color=color.green, title="Short TP")
plot(strategy.position_size < 0 ? strategy.position_avg_price : na, style=plot.style_linebr, color=color.blue, title="Short Entry")
plot(strategy.position_size < 0 ? shortSL == 0 ? na : shortStopPrice : na, style=plot.style_linebr, color=color.red, title="Short SL")

더 많은