# How to efficiently get covariance matrices from a rolling window in Matlab?

I'am trying to produce a rolling window to estimate a covariance matrix using a for-loop. I have my returns under the variable returns_sec and I have 260 observations stored under N_ret.

I now want to produce a covariance matrix estimate based on ten return series at a time and obtain one big variable with all covariance matrices in it (Top lines: Matrix1, below Matrix2 and so on).

I could to this by hand by writing:

kov_test=cov(returns_sec(1:10,:));
kov_test2=cov(returns_sec(11:21,:));  ...


and copy all results in one variable. But I think there should also be a more effective and easy way using a for-loop.

Would be great if anyone of you could help me out!

• This is almost purely a programming question, might be more suited for Stack Overflow... Also, have you already tried something? You should have and you should have added your attempts in the question. – SRKX Nov 7 '16 at 2:59
• @BobJansen: I tried to add the matlab tag but the system won't let me - do you have an explanation? – vonjd Nov 7 '16 at 11:13
• Weird, I've added the tag without problem. If it happens again I guess it's a bug in the Stack Exchange software. Edit: and then it doesn't appear. I'll follow up on this with Stack Exchange. – Bob Jansen Nov 7 '16 at 11:15

I would recommend you to use rolling overlapping window (1st implementation) instead of non-overlapping (your example - 2nd implementation)

% overlapping rolling covariance
[n,m] = size(returns_sec); % n-> number of dates, m->number of assets
rolling_window = 10;
cov_test = nan(m*(n - rolling_window + 1),m);
for i = rolling_window:n
start_index = m*(i - rolling_window) + 1; % aggregate covariance matrix start index
end_index = m*(i - rolling_window +1); % aggregate covariance matrix end index
covariance_mtx = cov(returns_sec(i-rolling_window +1:i,:));
cov_test(start_index:end_index,:) = covariance_mtx;
end

% non-overlapping rolling covariance
[n,m] = size(returns_sec); % n-> numberg of dates, m->number of assets
rolling_window = 10;
num = floor(n/rolling_window); % number of non-overllaping intervals
cov_test = nan(m*num,m);
for i = 1:num
start_index = m*(i - 1) + 1; % aggregate covariance matrix start index
end_index = m*i; % aggregate covariance matrix end index
covariance_mtx = cov(returns_sec(rolling_window*(i - 1) + 1: rolling_window*i,:));
cov_test(start_index:end_index,:) = covariance_mtx;
end

• If I may make a further suggestion about the internal workings here, with $n$ stocks, the covariance matrix estimate suggested above involves $n(n+1)/2$ free parameters and presumably handles time-variation in conditional correlations in an ad hoc fashion. It has the advantage of both speed and simplicity, but the OP might want to think about modeling the dynamic of conditional correlations explicitly. There is a not-so-obvious to resolve trade-off between variance and bias here. – Stéphane Mar 18 at 19:18