Using rollapply function for VaR calculation using R

橙三吉。 提交于 2019-12-02 00:23:49

There are columns which are completely missing in first few (3) width=20 windows, hence the error

data(managers)
class(managers) # [1] "xts" "zoo"
class(managers$HAM4) # [1] "xts" "zoo"
var2<-rollapply(managers,width=20,FUN=function(x) VaR(R=x,p=.95,method="modified"),by.column=TRUE)

With traceback, you can inspect the possible sources of error, notice step 12, of na.omit(x), see ?na.omit

traceback()
#17: as.matrix.xts(x)
#16: as.matrix(x)
#15: as.vector(as.matrix(x), mode = mode)
#14: as.vector.zoo(x, mode)
#13: as.vector(x, mode)
#12: as.vector(na.omit(R[, column]))
#11: VaR.CornishFisher(R = R, p = p)
#10: VaR(R = managers, p = 0.95, method = "modified") at #1
#9: FUN(.subset_xts(data, (i - width + 1):i, j), ...)
#8: FUN(newX[, i], ...)
#7: apply(ind, 1, function(i) FUN(.subset_xts(data, (i - width + 
#       1):i, j), ...))
#6: FUN(1:10[[5L]], ...)
#5: lapply(X = X, FUN = FUN, ...)
#4: sapply(1:NCOL(data), function(j) apply(ind, 1, function(i) FUN(.subset_xts(data, 
#       (i - width + 1):i, j), ...)))
#3: xts(sapply(1:NCOL(data), function(j) apply(ind, 1, function(i) FUN(.subset_xts(data, 
#       (i - width + 1):i, j), ...))), tt, if (by == 1) attr(data, 
#       "frequency"))
#2: rollapply.xts(managers, width = 20, FUN = function(managers) VaR(R = managers, 
#       p = 0.95, method = "modified"), by.column = TRUE)
#1: rollapply(managers, width = 20, FUN = function(managers) VaR(R = managers, 
#       p = 0.95, method = "modified"), by.column = TRUE)
#

For your first window=20 (actually around 60) observations, columns HAM5,HAM6 are missing completely and these result in empty data in the step 12. above

head(managers,20)

#Empty data since NA columns are omitted see step 12 above.
na.omit(head(managers,20))
#     [,1] [,2] [,3] [,4] [,5] [,6] [,7] [,8] [,9] [,10]
#>

There are no missing values in edhec data , hence there were no issues

any(is.na(edhec))
any(is.na(managers))

An easier way is to retain rows which do not have any missing values and compute statistics over them

managers_sub = managers[complete.cases(managers),]   

var3<-rollapply(managers_sub,width=20,FUN=function(x) VaR(R=x,p=.95,method="modified"),by.column=TRUE)

OR

You could find the index where none of the columns are completely missing and subset accordingly

sapply(colnames(managers),function(x) all(is.na(managers[60:80,x])))
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!