적응형 이동 평균 양적 전략


생성 날짜: 2023-11-17 17:14:36 마지막으로 수정됨: 2023-11-17 17:14:36
복사: 0 클릭수: 713
avatar of ChaoZhang ChaoZhang
1
집중하다
1617
수행원

적응형 이동 평균 양적 전략

개요

이 전략은 이동 평균을 기반으로 하고, 자동으로 파라미터를 조정할 수 있으며, 높은 시간 주기에서 변동하는 시장에 적용된다. 그것은 자동으로 최적의 파라미터 조합을 찾아, 가격이 이동 평균을 깨면 거래 신호를 생성할 수 있다.

전략 원칙

이 전략은 트레이딩 신호로 자기 적응 이동 평균을 사용한다. 먼저 지정된 주기 (start) 의 간단한 이동 평균 (simple moving average, CMA) 을 계산한다. 그리고는 CMA 주위의 변수 조합을 테스트하여, K선 개체와 그림자 선이 가장 적게 접촉하는 CMA 라인을 결정한다. 마지막으로 가장 적게 접촉하는 CMA 신호를 라인으로 사용한다.

구체적으로, 전략은 CMA 회기 +1 (CMA_P1) 및 -1 (CMA_M1) 이후의 CMA 라인, 통계 실체 라인 및 그림자 라인이 접촉하는 횟수를 테스트한다. CMA의 접촉 횟수가 CMA_P1과 CMA_M1보다 적으면 현재 CMA 회기를 유지한다.

가격이 아래에서 위로 CMA를 돌파할 때, 구매 신호를 생성한다. 가격이 위에서 아래로 CMA를 돌파할 때, 판매 신호를 생성한다.

우위 분석

이러한 적응형 이동 평균 전략은 다음과 같은 장점이 있습니다.

  1. 자동으로 최적의 변수를 찾습니다. 이동 평균의 주기를 수동으로 선택하지 않고, 전략은 자동으로 다른 주기를 테스트하여 최적의 변수를 찾습니다.

  2. 허위 신호를 줄여줍니다. 고정된 주기 이동 평균에 비해, 적응 이동 평균은 더 많은 잡음을 제거하여 많은 허위 신호를 줄일 수 있습니다.

  3. 시장 변화에 적응한다. 시장이 추세로 전환할 때, 이동 평균 주기가 자동으로 길어지는 신호가 발생한다. 시장이 추세로 전환할 때, 이동 평균 주기가 자동으로 짧아지는 신호가 발생한다. 따라서 전략은 시장의 변화에 동적으로 적응할 수 있다.

  4. 단순화 거래 시스템. 이러한 자기 적응 방식은 모든 거래 시스템을 단순화 할 수 있으며, 수동적으로 최적화 된 매개 변수가 필요하지 않습니다.

  5. 확장성이 강하다. 이 전략적 아이디어는 다른 지표로 확대될 수 있으며, 브린밴드, KD와 같은 전략을 설계할 수 있다.

위험 분석

이 전략에는 몇 가지 위험도 있습니다.

  1. 낙관 옵션 위험. 시장에서 낙관 옵션 행사가 발생하면, 실물 선이 이동 평균을 뚫지 못하여 잘못된 신호를 유발할 수 있다. 이러한 위험을 줄이기 위해 필터링 조건을 추가해야합니다.

  2. 돌파 실패의 위험. 이동 평균 돌파가 항상 계속되는 것은 아니며, 일부 돌파 실패의 위험이 있습니다. 따라서 돌파 성공률을 보장하기 위해 돌파 검증이 필요합니다.

  3. 트렌드 반전 위험. 트렌드 시장에 진입한 뒤의 반전은 적시에 방향을 전환해야 하며, 그렇지 않으면 손실이 발생할 수 있다. 손실을 제어하기 위해 스톱 조건을 설정할 수 있다.

  4. 파라미터 최적화 위험. 자율 조정된 파라미터는 로컬 최적화에 빠질 수 있으며, 이로 인해 명백한 과잉 이동 평균이 발생할 수 있다. 이 문제를 피하기 위해 모델 평가 방법을 도입해야 한다.

  5. 과도한 최적화 위험. 적응 조정 매개 변수는 과도하게 최적화 될 수 있으며, 모델의 일반화 능력을 잃는다. 다양한 시장 환경에서 오랜 시간 검증이 필요하며, 재검토 결과에 과도하게 의존할 수 없다.

최적화 방향

이러한 적응형 이동 평균 전략은 다음과 같은 방향으로 최적화될 수 있습니다.

  1. 트렌드 브레이크 검증 메커니즘을 추가하여 연속적인 브레이크를 통해 가짜 브레이크를 필터링합니다.

  2. 가격의 이동 평균의 반대편으로 돌아가는 것을 멈추는 손실 전략을 추가합니다.

  3. 선택권 필터링을 추가하여 낙관 옵션 시장에서 잘못된 신호를 피하십시오.

  4. 평가 지표의 도입은 IC, LIC, SIC 등과 같은 파라미터 조정에 대한 제약으로, 파라미터가 지나치게 최적화되는 것을 피한다.

  5. 다른 지표로 확장하여, 골드 포크 사다리 전략, 브린 벨트 전략 등을 설계하십시오.

  6. 이동 평균을 계산하는 방법을 최적화하여 가중 이동 평균, 지수 이동 평균 등으로 부드러운 이동 평균을 사용한다.

요약하다

이 전략은 이동 평균 주기를 조정하여 최적의 매개 변수를 찾아 거래 신호를 생성합니다. 고정 매개 변수에 비해 많은 가짜 신호를 줄여 시장의 변화에 적응 할 수 있습니다. 그러나 우리는 또한 몇 가지 잠재적인 위험을 주의해야하며 실제 거래에서 안정적으로 수익을 올리기 위해 전략에 대한 검증과 워크 포워드 최적화를 필요로합니다.

||

Overview

This strategy is based on moving average, can automatically adjust parameters, and is suitable for wavy markets at high timeframes. It can automatically find the optimal parameter combination and generate trading signals when price breaks through the moving average line.

Strategy Logic

This strategy uses an adaptive moving average as trading signal. First it calculates the simple moving average (CMA) of the specified period (start). Then it tests the CMA parameters around the period, judging which combination has the least touches by candlestick body and wick. Finally it uses the CMA with the least touches as the signal line.

Specifically, the strategy tests the CMA with period plus 1 (CMA_P1) and minus 1 (CMA_M1), counts the number of touches by body and wick. If CMA has less touches than CMA_P1 and CMA_M1, then keep the current period; if CMA_P1 has less touches, then increase the period by 1; if CMA_M1 has less touches, then decrease the period by 1. This finds a relatively smooth CMA as the signal line.

When price breaks through CMA upward, a buy signal is generated; when price breaks through CMA downward, a sell signal is generated.

Advantage Analysis

This adaptive moving average strategy has the following advantages:

  1. Automatically find optimal parameters. No need to manually select moving average period, the strategy will test different periods and find the optimum.

  2. Reduce false signals. Compared with fixed period MA, the adaptive MA can filter out more noise and reduce many false signals.

  3. Adapt to market changes. When market switches from range-bound to trending, the MA period will automatically increase to generate signals; when market switches from trending to range-bound, the MA period will automatically decrease. So the strategy can dynamically adapt to market changes.

  4. Simplify trading system. This adaptive method can simplify the whole trading system without manual parameter optimization.

  5. Good scalability. The concept can be applied to other indicators like adaptive Bollinger Bands, adaptive KD etc.

Risk Analysis

There are also some risks to note for this strategy:

  1. Call option risk. When market has a call option pattern, the candle body may fail to break the MA line, resulting in wrong signals. Filter conditions need to be added to reduce such risk.

  2. Failed breakout risk. MA breakout does not always continuation, some failed breakouts may occur. Breakout validation is needed to ensure high success rate.

  3. Trend reversal risk. Trend reversal after entering the trend needs to be switched timely, otherwise it may cause losses. Stop loss should be set to control the loss.

  4. Parameter optimization risk. Adaptive adjusted parameters may fall into local optimization, resulting in redundant MAs. Model evaluation methods need to be introduced to avoid this problem.

  5. Overfitting risk. Excessive parameter tuning may lead to overfitting and lose the model generalization ability. Prolonged verification in different market environments is needed, not just rely on backtest results.

Improvement Directions

Some directions to improve this adaptive MA strategy:

  1. Add trend breakout validation via consecutive breakouts to filter false breakouts.

  2. Increase stop loss strategy, stop loss when price moves back to the other side of MA.

  3. Add option filter to avoid wrong signals when call option appears.

  4. Introduce evaluation metrics like IC, LIC, SIC etc. to constrain parameter tuning and prevent overfitting.

  5. Expand to other indicators like adaptive golden cross strategy, adaptive Bollinger Bands etc.

  6. Optimize MA calculation by using weighted MA, exponential MA etc. to get smoother MA.

Summary

This strategy generates trading signals by adaptively adjusting the MA period to find optimal parameters. Compared with fixed parameters, it can reduce many false signals and adapt to market changes. But we also need to watch out for potential risks, and do verification and walk-forward optimization before applying it in live trading for steady profits.

[/trans]

전략 소스 코드
/*backtest
start: 2022-11-10 00:00:00
end: 2023-11-16 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/
// © fondDealer96636

//@version=5

strategy('Automatic Moving Average', overlay=true, max_bars_back=201, pyramiding=0, currency=currency.USD, default_qty_type=strategy.cash, default_qty_value=10000, initial_capital=10000)

// input
start = 20
lookback = input(20, "Sensitivity", tooltip="Low (High Sensitivity), High (Low Sensitivity).\n\nAdjust according to timeframe and asset.")
smoothing = input(3, "Smoothing")
source = input(close, "Source")
startYear = input(2020, "Start year")
resp = 1

in_date_range = time >= timestamp(syminfo.timezone, startYear, 1, 1, 0, 0)

// global
var ix = -1
var mal = array.new_int(0)


// functions
avg(source, len) =>
    sum = 0.0
    for i = 0 to len-1
        sum += source[i]
    sum/len

bull = close > open

wick_touch(x) =>
    bull ? ((close <= x and x <= high) or (low <= x and x <= open)) : ((open <= x and x <= high) or (low <= x and x <= close))

body_touch(x) =>
    bull ? (open < x and x < close) : (close < x and x < open)

touches(t) =>
    touches = 0
    for i = 0 to lookback-1
        touches += t[i] ? 1 : 0
    touches


// local
ix := ix+1
prev_mal = ix >= 1 ? array.get(mal, ix-1) : start

cma = avg(source, prev_mal)
cma_p1 = avg(source, prev_mal+1)
cma_m1 = avg(source, prev_mal-1)

d = touches(wick_touch(cma))
d_p1 = touches(wick_touch(cma_p1))
d_m1 = touches(wick_touch(cma_m1))

d_b = touches(body_touch(cma))
d_p1_b = touches(body_touch(cma_p1))
d_m1_b = touches(body_touch(cma_m1))

any_body_touch = d_b > 0 or d_p1_b > 0 or d_m1_b > 0
no_wick_touch = d <= 0 and d_p1 <= 0 and d_m1 <= 0
wick_maximized = d >= d_p1 and d >= d_m1 ? prev_mal : (d_p1 >= d and d_p1 >= d_m1 ? prev_mal+resp : (d_m1 >= d and d_m1 >= d_p1 ? prev_mal-resp : na))

up = cma > cma[1]
down = cma < cma[1]
against_trend = (up and close < cma) or (down and close > cma)

new_mal = no_wick_touch or against_trend ? prev_mal-resp : (any_body_touch ? prev_mal+resp : wick_maximized)
next_mal = na(new_mal) ? prev_mal : new_mal

array.push(mal, next_mal < 2 ? 2 : (next_mal > 200 ? 200 : next_mal))


// graph
scma = ta.ema(cma, smoothing)

uptrend = scma > scma[1]
downtrend = scma < scma[1]

plot(scma, "Automatic MA", color=uptrend ? color.green : color.red)

uptrending = close > scma and uptrend
downtrending = close < scma and downtrend

defy = not uptrending and not downtrending
defy_cross = defy and body_touch(scma)

barcolor(uptrending ? color.lime : (downtrending ? color.red : (defy_cross ? color.black : color.white)))


// strategy
change_to_uptrend = uptrending and downtrend[1]
change_to_downtrend = downtrending and uptrend[1]

long = in_date_range and change_to_uptrend
short = in_date_range and change_to_downtrend

if long
    strategy.entry("Long", strategy.long)
if short
    strategy.entry("Short", strategy.short)