[R-SIG-Finance] SMA and TTR
Brian G. Peterson
brian at braverock.com
Thu May 3 15:03:28 CEST 2012
On Thu, 2012-05-03 at 08:47 -0400, Gordon Erlebacher wrote:
> I wish to compute trading criteria only for past 10 days. That
> involves,
> say, a 50 day moving average. The SMA function does not allow me to
> only
> compute the 50 day moving average over the past 10 days, even if I
> have the
> symbol series for the past 200 days!
>
> getSymbols("AAPL")
> SMA(AAPL, 10)
>
> will compute the moving average for the entire series with 9 NAs. But
> that is more expensive than computing only the last 10 moving
> averages, necessary for my trading system. (this is just an example).
>
> If I am mistaken, could you please let me know how? I believe that all
> the TTR functions should be amended to compute the time series between
> a from and to date.
>
Yes, you are mistaken. Please look for information on 'vectorization'
in R.
While it is sometimes true that TTR will not use a vectorized
calculation, you can always subset your data in xts to use a shorter
series.
the 'from' and 'to' date in this case would be represented like so:
from <- '2012-04-01'
to <- '2012-05-02'
#assume x is my xts time series
SMA(x[paste(from,to,sep='/')],10)
Also note that you would need only 20 days of data, not 50, for get 10
periods of a ten day SMA. The subset you need is easily computed from
the indices of the data, using e.g.
lt <- length(index(x))
lf <- lt-20
SMA(x[lf:lt,],10)
>
--
Brian G. Peterson
http://braverock.com/brian/
Ph: 773-459-4973
IM: bgpbraverock
More information about the R-SIG-Finance
mailing list