Path: blob/master/sandbox/RFinance2014/R/lwShrink.R
1433 views
lwShrink <- function(x, shrink=NULL){1# port of matlab code from http://www.econ.uzh.ch/faculty/wolf/publications.html#92# Ledoit, O. and Wolf, M. (2004).3# Honey, I shrunk the sample covariance matrix.4# Journal of Portfolio Management 30, Volume 4, 110-119.56# De-mean returns7n <- nrow(x)8p <- ncol(x)9meanx <- colMeans(x)10x <- x - matrix(rep(meanx, n), ncol=p, byrow=TRUE)1112# Compute sample covariance matrix using the de-meaned returns13sample <- (1 / n) * (t(x) %*% x)1415# Compute prior16var <- matrix(diag(sample), ncol=1)17sqrtvar <- sqrt(var)18tmpMat <- matrix(rep(sqrtvar, p), nrow=p)19rBar <- (sum(sum(sample / (tmpMat * t(tmpMat)))) - p) / (p * (p - 1))20prior <- rBar * tmpMat * t(tmpMat)21diag(prior) <- var2223if(is.null(shrink)){24# What is called pi-hat25y <- x^226phiMat <- t(y) %*% y / n - 2 * (t(x) %*% x) * sample / n + sample^227phi <- sum(phiMat)2829# What is called rho-hat30term1 <- (t(x^3) %*% x) / n31help <- t(x) %*% x / n32helpDiag <- matrix(diag(help), ncol=1)33term2 <- matrix(rep(helpDiag, p), ncol=p, byrow=FALSE) * sample34term3 <- help * matrix(rep(var, p), ncol=p, byrow=FALSE)35term4 <- matrix(rep(var, p), ncol=p, byrow=FALSE) * sample36thetaMat <- term1 - term2 - term3 + term437diag(thetaMat) <- 038rho <- sum(diag(phiMat)) + rBar * sum(sum(((1 / sqrtvar) %*% t(sqrtvar)) * thetaMat))3940# What is called gamma-hat41gamma <- norm(sample - prior, "F")^24243# Compute shrinkage constant44kappa <- (phi - rho) / gamma45shrinkage <- max(0, min(1, kappa / n))46} else {47shrinkage <- shrink48}49# Compute the estimator50sigma <- shrinkage * prior + (1 - shrinkage) * sample51out <- list(cov=sigma, prior=prior, shrinkage=shrinkage)52return(out)53}545556