[R-SIG-Finance] Base R question on XTS object
Joshua Ulrich
josh.m.ulrich at gmail.com
Wed Apr 10 12:15:57 CEST 2013
On Wed, Apr 10, 2013 at 4:45 AM, wlblount <bill at easterngrain.com> wrote:
> before the days of all these great packages, how would one with base R access
> only find the following assuming i have an XTS object with normal OHLC price
> data for 100 periods.
>
>
> 1 - change in price from yesterday to today. close[today] -
> close[yesterday]
>
x <- .xts(1:10,1:10)
diff(x)
> 2 -rolling or moving simple ave. of close[last 30 periods]
>
If you have an xts object, that means you have the zoo package loaded,
so you could use rollmean.
rollmean(x,5)
Or you could use cumsum with lag:
(cumsum(x)-lag(cumsum(x),5))/5
Or you could completely roll your own:
(cumsum(x)-c(rep(NA,5-1),0,cumsum(x)[1:(nrow(x)-5)]))/5
> 3 - rolling or moving sd of close[last 30 periods]
>
If I had to use base, I would use the embed function:
ex <- embed(x,5)
sqrt(1/(5-1)*rowSums((ex-rowMeans(ex))^2))
> i understand that this would all be done with quantmod /ttr etc today but
> would just like to stay within the bounds of base R for educational
> purposes.
>
> thanks for your help. Bill
>
Best,
--
Joshua Ulrich | about.me/joshuaulrich
FOSS Trading | www.fosstrading.com
R/Finance 2013: Applied Finance with R | www.RinFinance.com
More information about the R-SIG-Finance
mailing list