Skip to content

Base R question on XTS object

4 messages · wlblount, Joshua Ulrich, Brian G. Peterson +1 more

#
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]

2 -rolling or moving simple ave. of close[last 30 periods]

3 - rolling or moving sd of close[last 30 periods]

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






--
View this message in context: http://r.789695.n4.nabble.com/Base-R-question-on-XTS-object-tp4663858.html
Sent from the Rmetrics mailing list archive at Nabble.com.
#
On Wed, Apr 10, 2013 at 4:45 AM, wlblount <bill at easterngrain.com> wrote:
x <- .xts(1:10,1:10)
diff(x)
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
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))
Best,
--
Joshua Ulrich  |  about.me/joshuaulrich
FOSS Trading  |  www.fosstrading.com

R/Finance 2013: Applied Finance with R  | www.RinFinance.com
#
On 04/10/2013 04:45 AM, wlblount wrote:
?diff
(part of base)
?apply
(in base)

?rollapply
(today)
Rollapply is basically a loop that constructs the windowed index.
Then read an old book on S.

?ts

the 'ts' class has been part of the S language basically since inception.

Alternatively, all this code is open source.  Look at the code.

Cheers,

Brian
#
On Wed, Apr 10, 2013 at 5:17 AM, Brian G. Peterson <brian at braverock.com> wrote:
'xts' is not part of base R, so if your students can get 'xts' they
should be able to get 'quantmod'. In fact, if you simply have them
install.packages("quantmod") that will get them zoo, TTR, and xts
automatically.