Create a function method for all possible time series classes

谁都会走 提交于 2019-12-11 09:44:47

问题


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?

回答1:


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>


来源:https://stackoverflow.com/questions/17569577/create-a-function-method-for-all-possible-time-series-classes

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!