Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using TTR package to calculate Exponential moving average

Tags:

r

computation

Curious if anyone used it. I did a simple EMA operation on a time series. But wasn't able to reconcile very well.

I read that the value of the update constant = 2/(N+1). I defined x = 1:20, and did EMA(x,5). Then I did an EMA computation using the recursive computation. The two results don't really line up

The 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
like image 440
ganesh reddy Avatar asked Sep 24 '12 01:09

ganesh reddy


People also ask

How do you calculate exponential moving average?

Finally, the following formula is used to calculate the current EMA: EMA = Closing price x multiplier + EMA (previous day) x (1-multiplier)

How do you calculate exponential moving average in R?

We can use the movavg() function from the pracma package to calculate the exponentially weighted moving average for a certain number of previous periods. where: x: Time series as numeric vector. n: Number of previous periods to use for average.

What is get a TTR function used for?

Normal Function The TTR gene provides instructions for producing a protein called transthyretin. This protein transports vitamin A (retinol) and a hormone called thyroxine throughout the body.

Is weighted moving average the same as exponential smoothing?

Exponential smoothing is a rule of thumb technique for smoothing time series data using the exponential window function. Whereas in the simple moving average the past observations are weighted equally, exponential functions are used to assign exponentially decreasing weights over time.


1 Answers

To get the answer you are looking for you would 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) it is equivalent to calling

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

This will put NA's in the first 4 places and then the 5th place will be the simple mean of the first 5 entries. (i.e. 3 in this case). Then the EMA algorithm will start. The 6th place will be 6 * 2 / 6 + 3 * 4 / 6 = 4. The 7th place will be 7 * 2 / 6 + 4 * 4 / 6 = 5. Etc...

You can see the exact algorithm here

like image 180
Sameer Avatar answered Sep 22 '22 00:09

Sameer