Inverse of a covariance matrix (loop)

10 次查看(过去 30 天)
Hi all,
I am stuck to create a loop which yields inverse of covariance matrices.
Data description:
I have the returns of three risky assets: mkt, hml and mom, from nov 3, 1926 up to dec 31, 2012.
For each year (so starting from Nov 3, 1927)I want the inverse covariance matrix for the three risky assets.
The dates are described (thanks Andrei) by the following code:
d = [19261103; 20121231];
ddte = datenum(num2str(d),'yyyymmdd');
ndte = (ddte(1):ddte(2))';
t = weekday(ndte);
ndte = ndte(t ~= 1 & t ~= 7);
yourdata = [date,mkt,hml,mom];
[yy,mm,dd] = datevec(yourdata(:,1));
ymd = [yy,mm,dd];
im = mm == 11 & dd >= 3;
ii = strfind([~im(1),im(:)'],[0 1]);
So I am stuck what do I have to add to retrieve the inverse covariance matrices per year.
Hopefully someone can help me out.
Thanks!
I adjusted the code with cov in it, but it does not yield the desired results:
d = [19261103; 20121231];
ddte = datenum(num2str(d),'yyyymmdd');
ndte = (ddte(1):ddte(2))';
t = weekday(ndte);
ndte = ndte(t ~= 1 & t ~= 7);
yourdata = [date,mkt,hml,mom];
[yy,mm,dd] = datevec(yourdata(:,1));
ymd = [yy,mm,dd];
im = mm == 11 & dd >= 3;
ii = strfind([~im(1),im(:)'],[0 1]);
sb = zeros(numel(ndte),1);
sb(ii) = 1;
sbc = cumsum(sb);
t = sbc > 0 & sbc ~= max(sbc);
sbb = sbc(t);
sb1 = find(sb(t));
wdta = yourdata(t,:);
[r, c] = ndgrid(sbb,1:size(wdta,2)-1);
out1 = accumarray([r(:) c(:)],reshape(wdta(:,2:4),[],1),[],@cov);
out = [ymd(ii(1:end-1),:),out1] ;
What do I do wrong?

采纳的回答

Andrei Bobrov
Andrei Bobrov 2013-4-25
Try this is code:
d = [19261103; 20121231];
ddte = datenum(num2str(d),'yyyymmdd');
ndte = (ddte(1):ddte(2))';
t = weekday(ndte);
ndte = ndte(t ~= 1 & t ~= 7);
yourdata = [ndte,mkt,hml,mom];
[yy,mm,dd] = datevec(yourdata(:,1));
ymd = [yy,mm,dd];
im = mm == 11 & dd >= 3;
ii = strfind([~im(1),im(:)'],[0 1]);
sb = zeros(size(yourdata,1),1);
sb(ii) = 1;
sbc = cumsum(sb);
t = sbc > 0 & sbc ~= max(sbc);
sb1 = diff(find([sb(t);1]));
wdta = yourdata(t,:);
s = size(wdta,2) - 1;
ydcell = mat2cell(wdta(:,2:end),sb1,s);
out = cellfun(@(x)cov(x)\eye(s),ydcell,'un',0);

更多回答(1 个)

Kevin van Berkel
Kevin van Berkel 2013-4-25
Andrei you are a legend. Works perfect, thank you very much!

类别

Help CenterFile Exchange 中查找有关 Structures 的更多信息

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!

Translated by