[R] rollapply() produces NAs

Gabor Grothendieck ggrothendieck at gmail.com
Sun May 28 16:15:28 CEST 2017

Maybe you want this.It computes VaRfun(r[c(i-500, i-1)] for each i for
which the argument to r makes sense.

rollapply(r, width = list(c(-500, -1)), FUN = VaRfun),

On Sat, May 27, 2017 at 5:29 PM, Sepp via R-help <r-help at r-project.org> wrote:
> Hello,
> I am fairly new to R and trying to calculate value at risk with exponentially decreasing weights.My function works for a single vector of returns but does not work with rollapply(), which is what I want to use. The function I am working on should assig exponentially decreasing weights to the K most recent returns and then order the returns in an ascending order. Subsequently it should pick the last return for which the cumulative sum of the weights is smaller or equal to a significance level. Thus, I am trying to construct a cumulative distribution function and find a quantile.
> This is the function I wrote:
> VaRfun <- function(x, lambda = 0.94) {
> #create data.frame and order returns such that the lates return is the first  df <- data.frame(weight = c(1:length(x)), return = rev(x))  K <- nrow(df)  constant <- (1-lambda)/(1-lambda^(K))#assign weights to the returns    for(i in 1:nrow(df)) {    df$weight[i] <- lambda^(i-1) * constant    }#order returns in an ascending order  df <- df[order(df$return),]
> #add the cumulative sum of the weights  df$cum.weight <- cumsum(df$weight)
> #calculate value at risk  VaR <- -tail((df$return[df$cum.weight <= .05]), 1)  signif(VaR, digits = 3)}
> It works for a single vector of returns but if I try to use it with rollapply(), such as
> rollapply(r, width = list(-500, -1), FUN = VaRfun),
> it outputs a vector of NAs and I don't know why.
> Thank you for your help!
>         [[alternative HTML version deleted]]
> ______________________________________________
> R-help at r-project.org mailing list -- To UNSUBSCRIBE and more, see
> https://stat.ethz.ch/mailman/listinfo/r-help
> PLEASE do read the posting guide http://www.R-project.org/posting-guide.html
> and provide commented, minimal, self-contained, reproducible code.

Statistics & Software Consulting
GKX Group, GKX Associates Inc.
tel: 1-877-GKX-GROUP
email: ggrothendieck at gmail.com

More information about the R-help mailing list