how to create a loop for rolling window returns?

Hi to all,
I do not know the MATLAB environment well, I wanted to ask if someone could tell me how to create a loop with the sample - out sample method. I would like to find the mean and the covariance of returns, as follows:
returns = rand(2013, 30);
I would like to find the mean from 1 to 500, from 21 to 521, etc.
I'll explain better: M1 = mean of RR 1->500; M2 = mean of RR 21->521; M3 = mean of RR 41->541; ...
With a step of 20 positions.I tried to follow these examples but I could not:
Thanks for your help.

 Respuesta aceptada

Geoff Hayes
Geoff Hayes el 15 de Jun. de 2018
Giorgio - rather than dynamically creating variables (never a good idea, see TUTORIAL: Why Variables Should Not Be Named Dynamically (eval)) consider using arrayfun to create a cell array of means. For example,
n = 2013;
m = 500;
returns = rand(n, 30);
returnsMeans = arrayfun(@(k)mean(returns(k:m+k-1,:)),1:20:(n-m+1),'UniformOutput',false);
The above should return the means for 76 blocks of size 500. You can probably do something similar using cov.

3 comentarios

That's true! Thank you so much!
BISWA BHUYAN
BISWA BHUYAN el 28 de Oct. de 2019
Sir, I wish to apply above code (returnsMeans = arrayfun(@(k)mean(returns(k:m+k-1,:)),1:20:(n-m+1),'UniformOutput',false); )to multiple column, then how can i modify the code? Please suggest

Iniciar sesión para comentar.

Más respuestas (0)

Categorías

Más información sobre Loops and Conditional Statements en Centro de ayuda y File Exchange.

Preguntada:

el 15 de Jun. de 2018

Comentada:

el 29 de Oct. de 2019

Community Treasure Hunt

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

Start Hunting!

Translated by