Using the TTR package to calculate an exponential moving average

Curious if anyone used it. I did a simple EMA operation in a time series. But could not reconcile very well.

I read that the value of the update constant = 2 / (N + 1). I defined x = 1:20 and made EMA(x,5 ). Then I did the EMA calculation using recursive calculation. These two results do not line up

Function returns

 EMA(x,5) [1] NA NA NA NA 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 

And my little thing gives me

 EMA [1] 1.000000 1.333333 1.888889 2.592593 3.395062 4.263374 5.175583 6.117055 7.078037 8.052025 9.034683 10.023122 11.015415 12.010276 13.006851 14.004567 [17] 15.003045 16.002030 17.001353 18.000902 
+4
source share
2 answers

To get the answer you are looking for, you need to write

 TTR::EMA(1:20, n=1, ratio=2/(5+1)) [1] 1.000000 1.333333 1.888889 2.592593 3.395062 4.263374 5.175583 [8] 6.117055 7.078037 8.052025 9.034683 10.023122 11.015415 12.010276 [15] 13.006851 14.004567 15.003045 16.002030 17.001353 18.000902 

If you call TTR::EMA(1:20, n=5) , this is equivalent to calling

 TTR::EMA(1:20, n=5, ratio=2/(5+1)) 

This puts NA in the first 4 places, and then 5th place will be the simple average of the first 5 entries. (i.e. 3 in this case). Then the EMA algorithm starts. 6th place will be 6 * 2/6 + 3 * 4/6 = 4. 7th place will be 7 * 2/6 + 4 * 4/6 = 5. Etc ...

You can see the exact algorithm here.

+6
source

TTR::EMA calculates the first not missing value as the arithmetic mean for the first variables n , and then starts to calculate recursively. You can compare your calculation by setting n=1 and ratio=1/3 .

 R> EMA(x,n=1,ratio=1/3) [1] 1.000000 1.333333 1.888889 2.592593 3.395062 4.263374 5.175583 [8] 6.117055 7.078037 8.052025 9.034683 10.023122 11.015415 12.010276 [15] 13.006851 14.004567 15.003045 16.002030 17.001353 18.000902 
+2
source

Source: https://habr.com/ru/post/1435818/


All Articles