This repository has been archived by the owner on Jun 1, 2020. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 0
/
covCor.m
60 lines (45 loc) · 1.55 KB
/
covCor.m
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
function [sigma,shrinkage]=covCor(x,shrink)
% x (t*n): t iid observations on n random variables
% sigma (n*n): invertible covariance matrix estimator
%
% Shrinks towards constant correlation matrix
% if shrink is specified, then this constant is used for shrinkage
% The notation follows Ledoit and Wolf (2003, 2004)
% This version 02/2010
% de-mean returns
[t,n]=size(x);
meanx=mean(x);
x=x-meanx(ones(t,1),:);
% compute sample covariance matrix
sample=(1/t).*(x'*x);
% compute prior
var=diag(sample);
sqrtvar=sqrt(var);
rBar=(sum(sum(sample./(sqrtvar(:,ones(n,1)).*sqrtvar(:,ones(n,1))')))-n)/(n*(n-1));
prior=rBar*sqrtvar(:,ones(n,1)).*sqrtvar(:,ones(n,1))';
prior(logical(eye(n)))=var;
if (nargin < 2 | shrink == -1) % compute shrinkage parameters and constant
% what we call pi-hat
y=x.^2;
phiMat=y'*y/t - 2*(x'*x).*sample/t + sample.^2;
phi=sum(sum(phiMat));
% what we call rho-hat
term1=((x.^3)'*x)/t;
help = x'*x/t;
helpDiag=diag(help);
term2=helpDiag(:,ones(n,1)).*sample;
term3=help.*var(:,ones(n,1));
term4=var(:,ones(n,1)).*sample;
thetaMat=term1-term2-term3+term4;
thetaMat(logical(eye(n)))=zeros(n,1);
rho=sum(diag(phiMat))+rBar*sum(sum(((1./sqrtvar)*sqrtvar').*thetaMat));
% what we call gamma-hat
gamma=norm(sample-prior,'fro')^2;
% compute shrinkage constant
kappa=(phi-rho)/gamma;
shrinkage=max(0,min(1,kappa/t));
else % use specified constant
shrinkage=shrink;
end
% compute the estimator
sigma=shrinkage*prior+(1-shrinkage)*sample;