0
$\begingroup$

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!

$\endgroup$
  • $\begingroup$ 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. $\endgroup$ – SRKX Nov 7 '16 at 2:59
  • $\begingroup$ @BobJansen: I tried to add the matlab tag but the system won't let me - do you have an explanation? $\endgroup$ – vonjd Nov 7 '16 at 11:13
  • 1
    $\begingroup$ 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. $\endgroup$ – Bob Jansen Nov 7 '16 at 11:15
1
$\begingroup$

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
$\endgroup$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.