【问题标题】:Calculate EWMA covariances and correlations in R计算 R 中的 EWMA 协方差和相关性
【发布时间】:2016-03-21 13:07:38
【问题描述】:

你知道我可以在哪个包中找到在http://faculty.washington.edu/ezivot/econ589/econ589multivariateGarch.r for R 中使用的 cov.EWMA 和/或 covEWMA 函数吗?

谢谢。

【问题讨论】:

  • 安装列出的包并使用getAnywhere()
  • 谷歌一下! This is what I found
  • 来源:source("covEWMA.r")。你需要...... aaaaw,Jilber 打败了我。
  • @Jilber 请将此作为答案发布(包括代码以防止删除链接仅答案:))。

标签: r package correlation covariance


【解决方案1】:

在网上搜索我在 R-Forge 上找到了这段代码。

covEWMA <- function(factors, lambda=0.96, return.cor=FALSE) {
## Inputs:
## factors    N x K numerical factors data.  data is class data.frame
##            N is the time length and K is the number of the factors.  
## lambda     scalar. exponetial decay factor between 0 and 1. 
## return.cor Logical, if TRUE then return EWMA correlation matrices
## Output:  
## cov.f.ewma  array. dimension is N x K x K.
## comments:
## 1. add optional argument cov.start to specify initial covariance matrix
## 2. allow data input to be data class to be any rectangular data object


if (is.data.frame(factors)){
  factor.names  = colnames(factors)
  t.factor      = nrow(factors)
  k.factor      = ncol(factors)
  factors       = as.matrix(factors)
  t.names       = rownames(factors)
} else {
  stop("factor data should be saved in data.frame class.") 
}
if (lambda>=1 || lambda <= 0){
  stop("exponential decay value lambda should be between 0 and 1.")
} else {
  cov.f.ewma = array(,c(t.factor,k.factor,k.factor))
  cov.f = var(factors)  # unconditional variance as EWMA at time = 0 
  FF = (factors[1,]- mean(factors)) %*% t(factors[1,]- mean(factors))
  cov.f.ewma[1,,] = (1-lambda)*FF  + lambda*cov.f
  for (i in 2:t.factor) {
    FF = (factors[i,]- mean(factors)) %*% t(factors[i,]- mean(factors))
    cov.f.ewma[i,,] = (1-lambda)*FF  + lambda*cov.f.ewma[(i-1),,]
  }

}
  # 9/15/11: add dimnames to array
  dimnames(cov.f.ewma) = list(t.names, factor.names, factor.names)

  if(return.cor) {
   cor.f.ewma = cov.f.ewma
   for (i in 1:dim(cor.f.ewma)[1]) {
    cor.f.ewma[i, , ] = cov2cor(cov.f.ewma[i, ,])
   }
   return(cor.f.ewma)
  } else{
      return(cov.f.ewma)  
  }
}

【讨论】:

  • 谢谢!当我搜索该主题时,我看到了这一点,但没有尝试。我还是 R 的新手。我犯了太多错误。它现在工作得很好。非常感谢!
猜你喜欢
  • 1970-01-01
  • 2021-01-03
  • 2019-04-15
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多