Question

This is a question to continue from this (R: Recreate historical membership from a list of changes in membership) question.

The problem discussed there actually arises from a problem of general interest in finance where we typically have member stocks of an index and then changes in the index membership. Often we want to recreate this membership and the data at hand is the current membership and the dates of the changes with the changes.

However, the typical problem is to generate this membership for a regular time series (such as daily, weekly, etc.) while the changes are themselves an irregular time series.

The method suggested in the problem linked to above can be used here in such a fashion:

  1. Find membership at all known times of changes.
  2. Create a sequence of a favored time class at the desired frequency.
  3. Replicate membership for each time in the sequence using the last known change in membership.

I will like to write function methods for the recreate.memship function that can do the right thing for indx given in any time-series class in R. One way that I can think of is to define a method for each known class such as ts, Date, zoo, xts, ... for which a seq method exists.

The question after this long-winded discussion is two-fold:

  1. Is there a smart way of defining methods such that I don't have to write a new method for each known time class. (Paraphrasing, how will a programmer smarter than me design this?)
  2. Is there a known solution for this problem / class of problems?
Was it helpful?

Solution

xts already allows this. Look at Section 4 of the package vignette.

Basically, you call try.xts at the beginning of your function and reclass at the end. I use this paradigm in the TTR package. For example:

R> momentum
function (x, n = 1, na.pad = TRUE) 
{
    x <- try.xts(x, error = as.matrix)
    if (is.xts(x)) {
        mom <- diff(x, n, na.pad = na.pad)
    }
    else {
        NAs <- NULL
        if (na.pad) {
            NAs <- rep(NA, n)
        }
        mom <- c(NAs, diff(x, n))
    }
    reclass(mom, x)
}
<environment: namespace:TTR>
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top