Search code examples
rmatrixxtsperformanceanalytics

Obtaining xts object from R function that is based on matrix operations


I have the following R function that calculates EWMA volatility for given securities:

EWMAvol = function(returns, lambda, rollwindow){
  EWMA.mat = matrix(NA, nrow = nrow(returns), ncol = ncol(returns))
  for (k in 1 : ncol(returns)){  
    for (j in rollwindow : nrow(returns)){
      td = returns
      data = as.matrix(td[(j - rollwindow + 1) : j, k])
      ewmaVar.mat = matrix()
      ewmaVar.mat[1] = 0
      for (i in 2 : rollwindow){
        ewmaVar.mat[i] = lambda * ewmaVar.mat[i-1]+ (1 - lambda) * data[i]^2
      }
      EWMA.mat[j, k] = sqrt(ewmaVar.mat[length(ewmaVar.mat)])
    }
  }
  return(EWMA.mat)
}

The data that this function relies on is:

> class(rets)
[1] "xts" "zoo"

which is coming from the Return.calculate() function from PerformanceAnalytics package.

The output that I currently get is:

> class(EWMAvol)
[1] "matrix"

Is it possible to return a xts or zoo object/data from my code? Also, I would like to keep the column names. How can I achieve that?

Thank you.


Solution

  • The Return.calculate function returns an xts, so you can use the index of that to convert your final return value to an xts.

    I'd do it by substituting the last line of your function

    return(EWMA.mat)
    

    with the following:

    EWMA.xts = xts::xts(EWMA.mat, order.by = zoo::index(returns))
    colnames(EWMA.xts) = colnames(returns) # to preserve column names
    return(EWMA.xts)