【问题标题】:subscript out of boundaries when trying to fill matrix with values in r尝试用 r 中的值填充矩阵时下标超出边界
【发布时间】:2014-05-21 05:14:24
【问题描述】:

我试图在我的时间序列上针对不同的 alpha 值运行 VaR 模型,当我尝试以具有不同 p 值的矩阵形式获得我的结果。如果我只使用一个for 和一个固定值p 运行模型,我会收到正确的结果。为什么我会收到这个错误,我在阅读的许多线程中都没有找到关于这个主题的解决方案!我模拟了我的时间序列,以便重现!谢谢

#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)

【问题讨论】:

  • 我很难理解这里应该发生什么,但我认为你想用VaRhistorical 的输出填充你的 4500 行乘 2 列矩阵。 estperiod:lenght(ret)的长度不是= 4501吗?是这个问题吗?
  • 感谢您的回复,错误不再出现!但是我的矩阵没有填充VaRhistorical 的值,我现在只收到NA 的矩阵。让我解释一下我的意图:假设 ret 是一个时间序列,我想获取前 500 个观察值并在 501 处预测 VaRhistrocial。然后将窗口滚动一步并做同样的事情。为了加快这个过程,我想对很多 p 值执行相同的过程,因此矩阵。我在代码中编辑了另一个错误,因为无法比较 VaRhs[4501] 因为没有 ret of 5001

标签: r matrix subscript


【解决方案1】:

我将代码更改如下: 我删除了seqvseq,因为它们不需要。我将estperiod 重新定义为窗口的长度。内部循环(带有j 的循环)被删除并替换为sapply,它一次计算所有p 的值,然后放入正确的行。您应该检查数学以确保我将 ret 的正确部分输入到每个预测的 VaRhistorical 函数中。

#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)

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2018-04-30
    • 2013-12-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-09-08
    • 1970-01-01
    • 2015-02-08
    相关资源
    最近更新 更多