[R-SIG-Finance] Writing code that works with a variety of time series classes

Jeff Ryan jeff.a.ryan at gmail.com
Sun Oct 5 04:52:23 CEST 2008


Ajay,

In terms of use-case, this is exactly what xts was written for.  'xts'
is at its core a matrix, with an attribute called 'index', exactly
like zoo (well almost, zoo needn't be a matrix).

Most of the functionality of quantmod uses xts internally for the very
reason you describe.  The ability to handle any time series object
without having to write unique methods for each of them (I think
eleven(!) possible classes as of last count).

Once an xts object, all standard zoo tools work.  Some have been
rewritten to accommodate additional features of xts (such as strict
time-based indexing, arbitrary attribute attachment, automatic
reconversion via reclass, and time-based ISO-style subsetting), but
all behave as one would expect them to in R and zoo --- which in my
opinion is very natural and logical.

One unique part of the current xts implementation is the ability to
use the 'reclass' function to take the results of your calculation,
and automatically reconvert them back into the original object class
the user passed in.  All this is managed internally, and requires only
two additions to code that already makes use of zoo-style data
management:

try.xts: convert (or try) to an xts object from any of the supported classes.
reclass: convert back to the original data class if possible.

The main vignette (
http://cran.r-project.org/web/packages/xts/vignettes/xts.pdf ) gives
some examples of the process, and the functions period.apply (xts),
chartSeries (quantmod), as well as many others in those packages and
others provide additional examples of the whole try.xts and reclass
functionality.

e.g.
> period.apply
function (x, INDEX, FUN, ...)
{
    x <- try.xts(x, error = FALSE)
    FUN <- match.fun(FUN)
    xx <- sapply(1:(length(INDEX) - 1), function(y) {
        FUN(x[(INDEX[y] + 1):INDEX[y + 1]], ...)
    })
    reclass(xx, x[INDEX])
}
<environment: namespace:xts>
>

This function works on numeric data or any class convertible to xts
(be it a properly formated data.frame, matrix, ts, its, irts, zoo,
timeSeries, or even xts!), AND returns that original class back to the
user.  All with 2 lines of code, and all seamlessly to the end-user.

My slides from this year's Rmetrics at Meielisalp also contain quite a
few examples of the xts as well.

http://www.quantmod.com/Rmetrics2008

For those who didn't make it to Meielisalp, I want to mention what a
truly great and unique workshop it was.  I highly recommend going if
you have the opportunity!

HTH,
Jeff


-- 
Jeffrey Ryan
jeffrey.ryan at insightalgo.com

ia: insight algorithmics
www.insightalgo.com



More information about the R-SIG-Finance mailing list