이동 평균

마지막 업데이트: 2022년 4월 28일 | 0개 댓글
  • 네이버 블로그 공유하기
  • 네이버 밴드에 공유하기
  • 페이스북 공유하기
  • 트위터 공유하기
  • 카카오스토리 공유하기
위의 과정은 t시점을 기준으로 이전 N개의 자료에 대한 평균을 구한 것입니다. t시점을 기준으로 이전 N/2개와 이후 N/2개 자료에 대한 평균을 구하는 방법도 있습니다. N항 중심이동평균이라고 불리며, sides=2 로 바꿔주면 됩니다.

Moving Average

The Moving Average Technical Indicator shows the mean instrument price value for a certain period of time. When one calculates the moving average, one averages out the instrument price for this time period. As the price changes, its moving average either increases, or decreases.

There are four different types of moving averages: Simple (also referred to as Arithmetic), Exponential, Smoothed and Weighted. Moving Average may be calculated for any sequential data set, including opening and closing prices, highest and lowest prices, trading volume or any other indicators. It is often the case when double moving averages are used.

The only thing where moving averages of different types diverge considerably from each other, is when weight coefficients, which are assigned to the latest data, are different. In case we are talking of Simple Moving Average, all prices of the time period in question are equal in value. Exponential Moving Average and Linear Weighted Moving Average attach more value to the latest prices.

The most common way to interpreting the price moving average is to compare its dynamics to the price action. When the instrument price rises above its moving average, a buy signal appears, if the price falls below its moving average, what we have is a sell signal.

This trading system, which is based on the moving average, is not designed to provide entrance into the market right in its lowest point, and its exit right on the peak. It allows to act according to the following trend: to buy soon after the prices reach the bottom, and to sell soon after the prices have reached their peak.

Moving averages may also be applied to indicators. That is where the interpretation of indicator moving averages is similar to the interpretation of price moving averages: if the indicator rises above its moving average, that means that the ascending indicator movement is likely to continue: if the indicator falls below its moving average, this means that it is likely to continue going downward.

Here are the types of moving averages on the chart:

  • Simple Moving Average (SMA)
  • Exponential Moving Average (EMA)
  • Smoothed Moving Average (SMMA)
  • Linear Weighted Moving Average (LWMA)

You can test the trade signals of this indicator by creating an Expert Advisor in MQL5 Wizard.

Moving Average

Calculation

Simple Moving Average (SMA) #

Simple, in other words, arithmetical moving average is calculated by summing up the prices of instrument closure over a certain number of single periods (for instance, 12 hours). This value is then divided by the number of such periods.

SMA = SUM (CLOSE (i), N) / N

SUM — sum;
CLOSE (i) — current period close price;
N — number of calculation periods.

Exponential Moving Average (EMA) #

Exponentially smoothed moving average is calculated by adding of a certain share of the current closing price to the previous value of the moving average. With exponentially smoothed moving averages, the latest close prices are of more value. P-percent exponential moving average will look like:

EMA = (CLOSE (i) * P) + (EMA (i - 1) * (1 - P))

CLOSE (i) — current period close price;
EMA (i - 1) — value of the Moving Average of a preceding period;
P — the percentage of using the price value.

Smoothed Moving Average (SMMA) #

The first value of this smoothed moving average is calculated as the simple moving average (SMA):

SUM1 = SUM (CLOSE (i), N)

The second moving average is calculated according to this formula:

SMMA (i) = (SMMA1*(N-1) + CLOSE (i)) / N

Succeeding moving averages are calculated according to the below formula:

PREVSUM = SMMA (i - 1) * N

SMMA (i) = (이동 평균 PREVSUM - SMMA (i - 1) + CLOSE (i)) / N

SUM — sum;
SUM1 — total sum of closing prices for N periods; it is counted from the previous bar;
PREVSUM — smoothed sum of the previous bar;
SMMA (i-1) — smoothed moving average of the previous bar;
SMMA (i) — smoothed moving average of the current bar (이동 평균 except for the first one);
CLOSE (i) — current close price;
N — smoothing period.

After arithmetic conversions the formula can be simplified:

SMMA (i) = (SMMA (i - 1) * (N - 1) + CLOSE (i)) / N

Linear Weighted Moving Average (LWMA) #

In the case of weighted moving average, the latest data is of more value than more early data. Weighted moving average is calculated by multiplying each one of the closing prices within the considered series, by a certain weight coefficient:

LWMA = SUM (CLOSE (i) * i, N) / SUM (i, N)

SUM — sum;
CLOSE(i) — current close price;
SUM (i, N) — total sum of weight coefficients;
N — smoothing period.

Displaced Moving Average (DMA)

Cory Mitchell, CMT is the founder of TradeThatSwing.com. He has been a professional day and swing trader since 2005. Cory is an expert on stock, forex and futures price action trading strategies.

Thomas J Catalano is a CFP and Registered Investment Adviser with the state of South Carolina, where he launched his own financial advisory firm in 2018. Thomas' experience gives him expertise in a variety of areas including investments, retirement, insurance, and financial planning.

What Is a Displaced Moving Average (DMA)?

A displaced moving average (DMA) is a moving average (MA) that has been adjusted forward or back in time in an attempt to better forecast trends or better fit the price movements of an asset.

Key Takeaways

  • A displaced moving average (DMA) is any moving average (MA) that has all its values shifted forward (positive displacement) or back (negative displacement) in time.
  • Investors can choose to shift a DMA so that it better aligns with highs or lows in price, and better contains or fits the price.
  • A DMA is used in the same way as a traditional MA in that it helps determine trend direction and reversals, may provide trade signals, and helps forecast potential support and resistance areas.

How a Displaced Moving Average (DMA) Works

An MA can be displaced forward on a chart, which is called positive displacement and will move the MA to the right. It can also be displaced back in time, called negative displacement, and that will move the MA to the left. The DMA 이동 평균 doesn't require any calculation beyond the MA calculation. Each value of the MA is moved forward or backward by the number of periods determined by the trader.

Displaced Moving Average

For example, assume a trader wants to displace their MA three periods into the future. The current MA value will be placed three periods into the future on the chart. The prior period's value will also be placed three periods into the future, and so on.

Most charting software does this automatically. When applying a MA, the settings will often ask for how much displacement is desired. Alternatively, there may be a separate displaced MA indicator with this setting.

What Does the Displaced Moving Average (DMA) Tell You?

The DMA does all the things a normal MA does. However, in some cases, it may do it better because it can better tailor to the asset being traded.

Trend Direction

In general, the DMA helps determine trend direction. When the price is above the MA, that helps indicate an uptrend, or at least that the price is above the average. Conversely, when the price is below the MA, the price is below average which is one sign of a downtrend.

Meanwhile, when the price moves through the MA that could signal the trend is changing. And, if the price falls through the MA from above, that could signal the uptrend is over and a downtrend is starting.

How the MA is displaced can aid in providing better reversal signals. Assume that in the past the uptrending price has just slightly dropped below the MA only to rally once again shortly after. In this case, the price dropping below the MA wasn't a reversal signal—the MA just didn't fit the price action well. Displacing the MA by several periods may help keep the price above the MA, creating a better fit for the asset's trend and thus avoiding some of the false signals.

Another option in the above scenario is to alter the lookback period of the average—how many periods it is calculating an average for. This, too, may result in the MA better fitting the price data. Increasing the lookback period typically results in the MA having more lag, as it is slower to react to price changes since recent price changes have less of an impact on a larger average. Therefore, displacement is an option when a trader wants the MA to better align with the price but doesn't want to increase lag.

Support and Resistance

A DMA can also help identify support and resistance. As discussed above, during an uptrend the MA can be aligned with price so that historical pullback lows align with the MA. When the price approaches the MA, the trader knows that the MA may provide support. If the price stalls at the MA and starts to rise again, a long trade can be taken with a stop loss below the recent low or below the 이동 평균 MA.

The same concept applies to downtrends. The DMA is adjusted to align with the pullback highs during the downtrend. On future pullbacks, the trader can watch to see 이동 평균 if the DMA still provides resistance. If it does, that may provide a short trade opportunity.

Displaced Moving Average (DMA) vs. Exponential Moving Average (EMA)

A DMA is any MA that is moved forward or back in time. While simple MAs are often used for displacement, an exponential moving average (EMA) can be displaced as well.

An EMA is a type of MA that reacts quicker to price changes than a simple MA. This is the result of a more complex calculation that puts more weight on recent price values and involves moving the EMA values forward or backward in time.

Displaced Moving Average (DMA) Limitations

An MA is the average price of an asset over a period of time. It does not inherently have any predictive calculations factored into it. Therefore, any MA, including a displaced one, won't always provide reliable information for trend reversals or support/resistance levels.

MAs in general, including displaced ones, tend to provide better information during trending markets, but provide little information when the price is choppy or moving sideways. During such times the price will move back and forth across the MA, but since the price is moving sideways overall the crossovers aren't likely to generate highly profitable trading opportunities and may result in losses.

Reversal, support, and resistance signals may not always work. The price may move through an MA only to move back in the original direction. While the MA may have provided support or resistance in the past, it may not in the future.

Investopedia does not provide tax, investment, or financial services and advice. The information is presented without consideration of the investment objectives, risk tolerance, or financial circumstances of any specific investor and might not be suitable for all investors. Past performance is not indicative of future performance. Investing involves risk, including the possible loss of principal.

간토끼 DataMining Lab

[시계열분석] 이동평균법(Moving Average Method)에 의한 분해(1)

이번 포스팅은 최근 M개의 관측치들만을 이용하여 평균을 구하는 방법인 이동평균법에 대해 다뤄보도록 하겠습니다.

이동평균(Moving Average)이란 평활법의 한 종류로, 표본평균처럼 관측값 전부에 동일한 가중값을 이동 평균 주는 대신에 최근 m개의 관측치를 이용하여 평균을 구하고 이를 이용해 예측을 하는 기법입니다.

여러 관측치의 평균을 이용하기에 지엽적인 변동을 제거하여 장기적인 추세를 쉽게 파악할 수 있도록 해주는 장점이 있으며,

시계열이 생성되는 시스템에 변화가 있을 경우 이 변화에 쉽게 대처할 수 있습니다.

그럼 간단한 형태인 단순이동평균법(Simple Moving Average Method)에 대해 다뤄보도록 하죠.

만약 시계열자료가 parameter βi.i.d를 따르는 오차항으로 이루어진 아주 단순한 모형을 따른다고 합시다.

이때 β의 추정량을 최소제곱법에 의해 구한다면, 단순히 시계열자료의 모든 관측치를 이용한 단순 평균꼴이 되겠죠.

평활법에서도 다루었지만, 이렇게 구할 이동 평균 경우 β가 시간에 따라 변하는 Parameter의 특성을 반영하기 어렵습니다.

[시계열분석] 단순지수평활법(Simple Exponential Smoothing Method)

안녕하십니까, 간토끼입니다. 지난 포스팅까지는 시계열자료의 추세(Trend)를 이용하여 미래의 시계열을 예측하는 추세분석에 대해서 다뤄봤습니다. 추세를 나타내는 변수 t, 혹은 t의 Polynomial Ter

이 평활법의 원리에 따라서 전체를 모두 반영하는 것보다 최근 관측치에 가중치를 좀 더 두자는 거죠.

최근 m개의 관측치만을 이용해 평균수준을 측정하면 변화를 보다 빨리 반영할 수 있습니다.

그럼 이때 m개의 관측값을 이용한 추정량을 M_(n)이라고 하면,

보시다시피 최근 m개의 관측치만을 이용한 평균의 꼴로 구해짐을 알 수 있습니다.

이때 M_(n)을 단순이동평균추정량이라고 하며, 우리는 이러한 추정량을 β의 추정량으로 쓸 수 있습니다.

그리고 위에서 보는 것처럼 이러한 추정량은 β의 불편추정량임을 알 수 있습니다.

평활법의 포스팅을 보고 오신 분들이라면 어느정도 감이 오셨을 겁니다.

바로 이동평균법에서의 m의 값은 지수평활법에서의 평활상수 w와 같은 역할을 한다는 것이죠.

m의 값이 클수록 관측치를 많이 사용하니까 평활의 효과가 크죠.

그러므로 지엽적인 변화에 둔감하게 반응합니다.

그러나 m의 값이 작을수록 최근의 관측치만을 사용하니까 평활의 효과가 작으며 지엽적인 변화에 빠르게 반응합니다.

하지만 처음 m개를 이용하여 m+1번째의 값을 예측하기 때문에 시계열의 첫 시작(t=1)부터 m개의 예측값은 구할 수 없다는 단점,

Excel에서 이동 평균

이 예제는 이동 평균 에있는 시계열의 뛰어나다. 이동 평균은 불규칙성 (봉우리와 골짜기)을 부드럽게하여 경향을 쉽게 인식하는 데 사용됩니다.

1. 먼저, 우리의 시계열을 살펴 봅시다.

Excel의 시계열

2. 데이터 탭의 분석 그룹에서 데이터 분석을 클릭합니다.

데이터 분석을 클릭하십시오.

참고 : 데이터 분석 단추를 찾을 수 없습니까? 여기를 클릭하여 Analysis ToolPak 이동 평균 추가 기능을로드하십시오.

3. 이동 평균을 선택하고. 인을 누르십시오.

이동 평균 선택

4. 입력 범위 상자를 클릭하고 B2 : M2 범위를 선택하십시오.

5. 간격 상자를 클릭하고 6을 입력하십시오.

6. 출력 범위 상자를 클릭하고 셀 B3을 선택합니다.

이동 평균 매개 변수

8.이 값의 그래프를 플롯하십시오.

증가 추세

설명: 간격을 6으로 설정했기 때문에 이동 평균은 이전 5 개 데이터 포인트와 현재 데이터 포인트의 평균입니다. 결과적으로, 봉우리와 골짜기가 매끈 해집니다. 그래프는 증가 추세를 보여줍니다. 이전 데이터 포인트가 충분하지 않기 때문에 Excel은 처음 5 개 데이터 포인트에 대한 이동 평균을 계산할 수 없습니다.

[시계열 분석]R에서 이동평균법(Moving Average 이동 평균 Method)과 지수평활법(Exponential Smoothing)

R에서 어떻게 이동평균법(Moving Average Method)와 지수평활법(Exponential Smoothing Method)을 사용하는지 알아보겠습니다. 이 둘을 사용하여 모형적합과 예측은 어떻게 진행되는지도 알아보겠습니다.

이동평균법(Moving Average Method)

평균을 이용하면 불필요한 변동을 줄일 수 있습니다. $Var(X)=\sigma^2$인데 반해, $Var(\bar)=\frac$임을 생각하면, 평균이 왜 불필요한 변동을 줄일 수 있는지 직관적으로 이해할 수 있습니다. 그렇다면 이동 평균 시계열자료 전체를 평균내어 분석을 진행할까요? 안타깝지만 자료 전체를 평균을 내면 시계열자료의 추세를 반영하지 못합니다.

그림에서 볼 수 있듯이 단순 평균은 시계열자료의 추세를 반영하지 못합니다. 따라서 추세를 반영해줄 수 있는 이동평균을 사용해아합니다. 이동평균을 수식으로 나타내면 다음과 같습니다.

N개 자료의 평균을 구했기 때문에 N항 이동평균이라고 불립니다.

위의 과정은 t시점을 기준으로 이전 N개의 자료에 대한 평균을 구한 것입니다. t시점을 기준으로 이전 N/2개와 이후 N/2개 자료에 대한 평균을 구하는 방법도 있습니다. N항 중심이동평균이라고 불리며, sides=2 로 바꿔주면 됩니다.

R에서 N항 이동평균은 어떻게 구하는지 알아보겠습니다.

R의 기본패키지 stats 에 있는 filter() 함수를 사용하면 N항 이동 평균을 구할 수 있습니다. 또한 filter=c() 옵션을 사용하면 가중치를 다르게 줄 수 있습니다. 여기서는 N개자료에 동일한 가중치를 주었습니다.

dplyr 패키지에서도 filter() 함수를 제공합니다. 함수명은 같지만 다른 역할을 하므로 중첩을 막기위해 패키지명::filter() 으로 사용할 수도 있습니다.

4개의 그림을 비교해보면 항의 수 N이 증가할수록 변동은 줄어들고 추세만 남게됨을 확인할 수 있습니다.

단순이동평균법

$M_t^$에서 (1)은 이동평균을 한번 했다는 의미입니다. 이를 단순이동평균(Simple Moving Average)이라고 합니다. 여기서 $M_^ \cdot \cdot \cdot M_^$를 한번 더 이동평균하게 되면 $M_t^$로 나타내고 이중이동평균(Double Moving Average)라고 부릅니다. 우선 단순이동평균을 사용해서 시계열자료를 Smoothing해보겠습니다.

ts() 를 사용하여 4개의 분기를 가지는 시계열 자료로 변환했습니다. 다음으로 filter() 를 사용하여 4항 단순이동평균을 구한 후 시각화합니다.

4항 이동평균이기 때문에 4번째 항부터 빨간 점선이 시작됩니다. 원 시계열자료보다 변동이 많이 줄었으며, 추세는 딱히 보이지 않습니다. 다음으로 모형의 잔차가 정상성을 만족하는지 확인해봅니다. tsdisplay() 함수는 잔차의 정상성 확인을 위한 그림을 제공합니다.

time plot이 백색잡음형태를 띄고 ACF와 PACF가 파란선을 벗어나지 않는 것으로 보아 정상성을 가짐을 알 수 있습니다. 마지막으로 Box.test() 를 통해 잔차가 자기상관성을 가지는지 검정합니다.

p-value=0.3229로 유의수준 0.05보다 큰 값을 가지므로, “잔차가 독립이다.”(“잔차는 자기상관이 없다.”)라는 귀무가설을 기각하지 못합니다.

이중이동평균법

단순이동평균 $M_^ \cdot \cdot \cdot M_^$를 다시 이동평균하게 되면 $M_t^$로 나타내고 이중이동평균(Double Moving Average)라고 합니다. filter() 를 두번 적용하면 이중이동평균을 쉽게 구할 수 있습니다.

빨간 선이 이중이동평균을 나타낸 그림입니다. 단순이동평균에서보다 더 평활해졌음을 알 수 있습니다. 다음으로 모형의 잔차가 정상성을 가지는지 확인해봅니다.

time plot이 백색잡음의 형태를 띄며 ACF와 PACF가 크게 벗어나지 않는 것으로 보아, 잔차가 정상성을 가지는 것으로 보입니다. 마지막으로 잔차의 자기상관성검정을 진행합니다.

p-value=0.3으로 아주 큰 값을 가지므로, “잔차는 자기상관성이 없다.”는 귀무가설을 기각하지 못합니다.

이동평균법을 활용한 시계열 예측

forecast 패키지의 ma() 를 사용하여도 이동평균을 구할 수 있습니다. order=3 은 3항 이동평균을, centre=T 는 중심이동평균을 뜻합니다.

$T$시점에서의 이동평균 $M_$은 $T+1$시점의 예측값 $\hat_$이 됩니다. forecast 패키지의 forecast 함수를 이용하면 시계열자료를 예측할 수 있습니다. 옵션 h=2 로 설정하여 이후 2개의 시점 $T+1$, $T+2$를 예측합니다.

파란 밴드는 80%신뢰구간을, 회색밴드는 95%신뢰구간을 나타냅니다.

accuracy() 함수는 모형을 평가하는 여러 지표를 제공합니다.

지수평활법(Exponential Smoothing Method)

이동평균법과 비교해서 지수평활법은 다음 두 가지 차이점을 가집니다. 하나는 최근값에 더 큰 가중치를 주는 것이고, 다른 하나는 이전 시점의 자료를 모두 사용한다는 것입니다.

단순지수평활법과 이중지수평활법

단순지수평활법

이중지수평활법

여기서 $\alpha$값은 0과 1사이의 값을 가지는 Hyperparameter로 최적의 값을 찾아야 합니다. 초기추정값 $F_^$ 또한 임의로 설정할 수 있지만, 가중치 $(1-\alpha)^T$가 기하급수적으로 감소하기 때문에, 어떤 값을 사용하더라도 모형에 큰 변화는 없습니다.

R에서 HoltWinters()

HoltWinters 함수를 사용하면, 알아서 최적의 $\alpha$값을 찾아줍니다. 단순지수평활법을 사용하고 싶다면 beta=F, gamma=F 를, 이중지수평활법을 사용하고 싶다면 gamma=F 옵션을 사용하면 됩니다. 여기서는 단순지수평활법을 사용합니다.


0 개 댓글

답장을 남겨주세요