Question

I am trying to run a VaR model on my time series for different alpha values and always come up with the error Error in[<-(tmp, i + seq[1], j, value = 0.09265792) : subscript out of bounds when i try to get my results in a matrix form with different p values. If i solely run the model with one for and a fixed value for p i receive correct results. Why do i get this error, i have not found a solution on this topic in the many threads read! I simulated my time series in order to be reproducible! Thanks

#HS VaR function
VaRhistorical <- function(returns, prob=.05) {
  ans <- -quantile(returns, prob)
  signif(ans, digits=7)
}

#Parameter specification
ret <- runif(5000,-0.1,0.1)
p <- c(0.05, 0.025)#, 0.01, 0.005, 0.001)
vseq <- -499:0 #VaR estimated from past 500 ret values change to -1999 for window of 2000 observations
#HS VaR Estimation with specified parameters
estperiod <- length(vseq)
VaRhs <- matrix(nrow=length(estperiod:(length(ret)-1)),ncol=length(p),byrow=T)
for (i in estperiod:(length(ret)-1)) {
  seq <- vseq + i
  for (j in p) {
  VaRhs[i+vseq[1],j] <- VaRhistorical(ret[seq],prob=j)
  }
}
act <- ret[(length(vseq)+1):length(ret)]
violationratio <- ifelse(act>=(-VaRhs),0,1)
sum(violationratio)
Was it helpful?

Solution

I changed the code as follows: I removed seq, and vseq as they were not needed. I redefined estperiod to just be the length of the window. The innner loop (the one with j) was removed and replaced with a sapply that calculates the values for all of your p's at once and puts then in the proper row. You should check the math to make sure I have the right part of ret going into the VaRhistorical function for each prediction.

#HS VaR function
VaRhistorical <- function(returns, prob=.05) {
  ans <- -quantile(returns, prob)
  signif(ans, digits=7) 
}

#Parameter specification
ret <- runif(5000,-0.1,0.1)
p <- c(0.05, 0.025)#, 0.01, 0.005, 0.001)
estperiod<-500  #now its the length of the window
VaRhs <- matrix(nrow=length(ret)-estperiod, ncol=length(p))

for (i in 1:nrow(VaRhs) ) {
   VaRhs[i,]<-  sapply(X=p, FUN=VaRhistorical,returns=ret[i:(estperiod+i-1)] )
}

act <- ret[(estperiod+1):length(ret)]
violationratio <- ifelse(act>=(-VaRhs),0,1)
sum(violationratio)
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top