首页 > 解决方案 > How to use package TTR’s SMA function with weights?

问题描述

I don’t understand how the TTR SMA function is handling weights. First, what is the difference between wts and w? Then, there is a result I do not expect.

I want to use a set of linear weights at each position of the SMA calculation so that the current value being calculated has the highest weight applied and the nth most distant value has the lowest weight. Here is an example that should give back the weights, if they worked the way I assumed (my example provides the impulse function of a linear filter):

t <- replicate(0, n = 12)
t[5] <- 1
weights <- c(0.25, 0.5, 0.75, 1.0)
SMA(t, n = 4, wts = weights)

But this gives: NA NA NA 0.00 0.25 0.25 0.25 0.25 0.00 0.00 0.00 0.00

This is the same result one gets if you use a set of weights of c(1,1,1,1). I would expect to see items 5-8 as 1.0, 0.75, 0.5, 0.25. I am unable to find any explanation in the Internet about how SMA is calculating the weighted SMA function.

标签: rsmoothingweighted-average

解决方案


TTR's SMA doesn't use weights (w or wts). You can add w or wts to the SMA function, but it will not be used as you can see in the following check.

identical(SMA(t, n = 4), SMA(t, n = 4, wts = weights))
[1] TRUE

wts is meant for to be used with WMA. And w is meant to be used with VMA.

I do agree that the documentation should be a bit more clear on this point. This page from investopedia is a bit more clear on the descriptions of WMA.

And the VMA is more of an adaptive moving average and is adding a sort of weights to the EMA formula as shown below.

# parts from c code from TTR package
d_ratio =  2/(n+1)
EMA[i] = d_x[i] * d_ratio + d_result[i-1] * (1-d_ratio);
VMA[i] = d_x[i] * d_w[i] * d_ratio + d_result[i-1] * (1-d_ratio*d_w[i]);

Looking at your description of what you want, you should use the WMA function


推荐阅读