Write a date loop in matlab
조회 수: 4 (최근 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] ;
참고 항목
카테고리
Help Center 및 File Exchange에서 Calendar에 대해 자세히 알아보기
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!