[R-SIG-Finance] SMA and TTR

G See gsee000 at gmail.com
Thu May 3 16:14:41 CEST 2012


Just a slightly different approach:

getSymbols("AAPL", src='yahoo')
# 50 day moving average for last 10 days
tail(SMA(tail(Ad(AAPL), 59), 50), 10)

Garrett

On Thu, May 3, 2012 at 8:03 AM, Brian G. Peterson <brian at braverock.com> wrote:
> 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
>
> _______________________________________________
> R-SIG-Finance at r-project.org mailing list
> https://stat.ethz.ch/mailman/listinfo/r-sig-finance
> -- Subscriber-posting only. If you want to post, subscribe first.
> -- Also note that this is not the r-help list where general R questions should go.



More information about the R-SIG-Finance mailing list