[R] Month end calculations

Jeff Ryan jeff.a.ryan at gmail.com
Thu Aug 30 16:31:51 CEST 2007


Shubha,

I apologize if this is a bit late - consequence of digest summary preference.

If I understand what you need, it is to calculate the value at month
end given a data object. For zoo objects the following should do what
you need. Actually is part of my new package on CRAN quantmod -
basically a workflow management tool for quant finance modelling.
Also visible at www.quantmod.com

If you convert your data.frame to a zoo object (designed for ordered
obs. -  e.g. time-series)

# for your data - which I don't know : )
zoo.ts <- zoo(youdataframe[,-1],as.Date(yourdataframe[,1]))

#                            ^
          ^
#                           ^ ^
        ^ ^
#                     minus 'date' column                  the 'date'
column - in CCYY-MM-DD format


My example:

A zoo time series object consisting of 231 days:

> zoo.ts <- zoo(rnorm(231),as.Date(13514:13744))
> start(zoo.ts)
[1] "2007-01-01"
> end(zoo.ts)
[1] "2007-08-19"

# these are the end points of each period
> breakpoints(zoo.ts,months,TRUE)
[1]   0  31  59  90 120 151 181 212 231

# get the associated values
> zoo.ts[breakpoints(zoo.ts,months,TRUE)]
  2007-01-31   2007-02-28   2007-03-31   2007-04-30   2007-05-31   2007-06-30
-0.008829668 -2.207802921  0.171705151 -1.820125167  1.776643162  0.884558259
  2007-07-31   2007-08-19
 0.655305543  0.191870144

You can also apply a function inside each of these periods (intervals)
with the function
period.apply:

e.g. the standard deviation of each period would be had with:

> period.apply(zoo.ts,breakpoints(zoo.ts,months,TRUE),FUN=sd)
[1] 0.9165168 1.2483743 1.0717529 1.2002236 0.9568443 0.8112068 0.8563814
[8] 0.8671502

The functions (and many others) are in quantmod - on CRAN and most up
to date at www.quantmod.com

For those who'd rather just have the functions:

breakpoints <-
function (x, by = c(weekdays, weeks, months, quarters, years), ...)
{
    if (length(by) != 1)
        stop("choose ONE method for \"by\"")
    by <- match.fun(by)
    breaks <- which(diff(as.numeric(by(x, ...))) != 0)
    breaks <- c(0, breaks, NROW(x))
    return(breaks)
}


period.apply <-
function (x, INDEX, FUN, ...)
{
    FUN <- match.fun(FUN)
    y <- NULL
    for (i in 1:(length(INDEX) - 1)) {
        sindex <- (INDEX[i] + 1):INDEX[i + 1]
        dat <- x[sindex]
        y <- c(y, FUN(dat, ...))
    }
    return(y)
}

Jeff Ryan



More information about the R-help mailing list