Home > database >  Matlab - Nested for loop doesn't run till end
Matlab - Nested for loop doesn't run till end

Time:11-04

I want to multiply the returns and the expected returns for each firm for the respective earnings date, e.g. Return(30-Jan-2017)*Return(31-Jan-2017)*Return(01-Feb-2017) [the same for the next earnings date and so on]

see pic1

My Code is as follows:

firms = unique(T.Ticker(:,:))
for i = 1:length(firms)
    idx = firms(i);
    Dates = T.EarningsDate(T.Ticker == idx,:);
    ERDates=unique(Dates);
    for n = 1:length(ERDates)
        x = strcmpi(Dates,ERDates(n));
        T.ret(x) = prod(T.Return(x))
    end
end

However I get all the correct calculated values for APPL (the first 60 rows) but then the loop stops somehow and I only receive 0.

see pic2

Does anybody has some hint, what I can do?

CodePudding user response:

Frame change: you don't need to use a nested loop if you use findgroups to identify the unique groupings by Ticker and EarningsDate, then just do a single loop over these.

First, a minimal example data set:

% Set up some example data
T = table();
rng(0);
T.Ticker = repelem( ["AAPL"; "AMGN"], 6, 1 );
T.EarningsDate = repelem( datetime(2022, randi(12,4,1), randi(28,4,1)), 3, 1 );
T.Date = T.EarningsDate   repmat( [-1;0;1], 4, 1 );
T.Return = rand(height(T),1)-0.5;
T.ExpectedReturn = T.Return .* rand(height(T),1)*2;

Then a simple loop, see comments for details:

% Get groups for each unique combination of Ticker and EarningsDate
grp = findgroups( T.Ticker, T.EarningsDate );
% Loop over the groups and get the product for each one
T.ret(:) = NaN;
for igrp = 1:max(grp)
    idx = (grp == igrp); % Rows which match this group
    % Assign all group rows a "ret" value equal to their "Return" product
    T.ret( idx ) = prod( T.Return(idx) ); 
end
  • Related