Book a Demo!
CoCalc Logo Icon
StoreFeaturesDocsShareSupportNewsAboutPoliciesSign UpSign In
braverock
GitHub Repository: braverock/portfolioanalytics
Path: blob/master/sandbox/RFinance2014/R/lwShrink.R
1433 views
1
lwShrink <- function(x, shrink=NULL){
2
# port of matlab code from http://www.econ.uzh.ch/faculty/wolf/publications.html#9
3
# Ledoit, O. and Wolf, M. (2004).
4
# Honey, I shrunk the sample covariance matrix.
5
# Journal of Portfolio Management 30, Volume 4, 110-119.
6
7
# De-mean returns
8
n <- nrow(x)
9
p <- ncol(x)
10
meanx <- colMeans(x)
11
x <- x - matrix(rep(meanx, n), ncol=p, byrow=TRUE)
12
13
# Compute sample covariance matrix using the de-meaned returns
14
sample <- (1 / n) * (t(x) %*% x)
15
16
# Compute prior
17
var <- matrix(diag(sample), ncol=1)
18
sqrtvar <- sqrt(var)
19
tmpMat <- matrix(rep(sqrtvar, p), nrow=p)
20
rBar <- (sum(sum(sample / (tmpMat * t(tmpMat)))) - p) / (p * (p - 1))
21
prior <- rBar * tmpMat * t(tmpMat)
22
diag(prior) <- var
23
24
if(is.null(shrink)){
25
# What is called pi-hat
26
y <- x^2
27
phiMat <- t(y) %*% y / n - 2 * (t(x) %*% x) * sample / n + sample^2
28
phi <- sum(phiMat)
29
30
# What is called rho-hat
31
term1 <- (t(x^3) %*% x) / n
32
help <- t(x) %*% x / n
33
helpDiag <- matrix(diag(help), ncol=1)
34
term2 <- matrix(rep(helpDiag, p), ncol=p, byrow=FALSE) * sample
35
term3 <- help * matrix(rep(var, p), ncol=p, byrow=FALSE)
36
term4 <- matrix(rep(var, p), ncol=p, byrow=FALSE) * sample
37
thetaMat <- term1 - term2 - term3 + term4
38
diag(thetaMat) <- 0
39
rho <- sum(diag(phiMat)) + rBar * sum(sum(((1 / sqrtvar) %*% t(sqrtvar)) * thetaMat))
40
41
# What is called gamma-hat
42
gamma <- norm(sample - prior, "F")^2
43
44
# Compute shrinkage constant
45
kappa <- (phi - rho) / gamma
46
shrinkage <- max(0, min(1, kappa / n))
47
} else {
48
shrinkage <- shrink
49
}
50
# Compute the estimator
51
sigma <- shrinkage * prior + (1 - shrinkage) * sample
52
out <- list(cov=sigma, prior=prior, shrinkage=shrinkage)
53
return(out)
54
}
55
56