Write a date loop in matlab
28 次查看(过去 30 天)
显示 更早的评论
Hello all,
I am very new to Matlab so I hope you guys can help me out.
The thing is,
I have to create a loop which calculate portfolio means on an annual basis. The assets in the portfolio are mkt, hml and mom. The starting date is 19261103(yyyymmdd), ending date is 20121231 (yyyymmdd). So from 19271103 onwards, I need to retrieve the means per asset.
My problem is that I am just not able to create a loop that proceeds onwards, because not every year November 3rd, is a trading day (it can be a Saturday or a Sunday). How can I avoid this problem and retrieve annual 1x3 matrices from 1927 till 2012?
Hope I formulated this problem well.
Thank you very much in advance.
Kevin
2 个评论
Jan
2013-4-23
You have explained, what is not working as wanted: You want a loop over dates, but some dates are not valid. But you did not explain, what shgould happen instead: When a specific date is not wanted, which date should be used instead? How can the validity be determined automatically? Is it only the weekend, or are there more exceptions? If you calculate the values on an "annual basis", why do certain days matter? I though this would concerns complete years only.
采纳的回答
Azzi Abdelmalek
2013-4-23
d1=datenum('1926-11-03','yyyy-mm-dd'),
d2=datenum('2012-12-31','yyyy-mm-dd'),
d=d1:d2
for k=1:numel(d)
%do
end
3 个评论
Azzi Abdelmalek
2013-4-23
Jan, it was not my intention to give a complete answer, because it was not completly clear for me. I gave a hint that could help.
更多回答(1 个)
Andrei Bobrov
2013-4-23
编辑:Andrei Bobrov
2013-4-23
d = [19261103; 20121231];
ddte = datenum(num2str(d),'yyyymmdd');
ndte = (ddte(1):ddte(2))';
t = weekday(ndte);
ndte = ndte(t ~= 1 & t ~= 7);
yourdata = [ndte, randi(125,numel(ndte),3)]; % create your data as
% yourdata = [date,mkt,hml,mom]
[yy,mm,dd] = datevec(yourdata(:,1));
ymd = [yy,mm,dd];
im = mm == 11 & dd >= 3;
ii = strfind([~im(1),im(:)'],[0 1]);
sb = zeros(numel(ndte),1);
sb(ii) = 1;
sbc = cumsum(sb);
t = sbc > 0 & sbc ~= max(sbc);
sbb = sbc(t);
sb1 = find(sb(t));
wdta = yourdata(t,:);
[r, c] = ndgrid(sbb,1:size(wdta,2)-1);
out1 = accumarray([r(:) c(:)],reshape(wdta(:,2:4),[],1),[],@mean);
out = [ymd(ii(1:end-1),:),out1] ;
另请参阅
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!