MatLab嵌套的for循环直到结束才运行

jk9hmnmh  于 2022-11-15  发布在  Matlab
关注(0)|答案(1)|浏览(280)

我想乘以每个公司在各自盈利日期的回报和预期回报,例如Return(30-Jan-2017)*Return(31-Jan-2017)*Return(01-Feb-2017)[下一个盈利日期也是如此,依此类推]

我的代码如下:

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

然而,我得到了APPL的所有正确计算值(前60行),但随后循环不知何故停止了,我只得到了0。

有谁能给我一些提示,我能做什么?

lskq00tm

lskq00tm1#

Frame Change:如果使用findgroups来标识Ticker和EarningsDate的唯一分组,则不需要使用嵌套循环,然后只需在这些分组上执行一次循环。
首先,一个最小的示例数据集:

% 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;

然后是一个简单的循环,有关详细信息,请参阅评论:

% 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

相关问题