Question

I have the following code to read off time series data (contained in sheets 5 to 19 in an excel workbook). Each worksheet is titled "TS" followed by the number of the time series. The process works fine apart from one thing- when I study the returns I find that all the time series are shifted along by 5. i.e. TS 6 becomes the 11th column in the "returns" data and TS 19 becomes the 5th column, TS 15 becomes the 1st column etc. I need them to be in the same order that they are read- such that TS 1 is in the 1st column, TS 2 in the 2nd etc. This is a problem because I read off the titles of the worksheets ("AssetList") which maintain their actual order throughout subsequent codes. Therefore when I recombine the titles and the returns I find that they do not match. This complicates further manipulation when, for example column 4 is titled "TS 4" but actually contains the data of TS 18. Is there something in this code that I have wrong?

XL='TimeSeries.xlsx';

formatIn = 'dd/mm/yyyy';
formatOut = 'mmm-dd-yyyy';


Bounds=3;
[Bounds,~] = xlsread(XL,Bounds);

% Determine the number of worksheets in the xls-file:

FirstSheet=5;
[~,AssetList] = xlsfinfo(XL);
lngth=size(AssetList,2);
AssetList(:,1:FirstSheet-1)=[];

% Loop through the number of sheets and RETRIEVE VALUES

merge_count = 1; 

for I=FirstSheet:lngth



    [FundValues, ~, FundSheet] = xlsread(XL,I);

% EXTRACT DATES AND DATA AND COMBINE % (TO REMOVE UNNECCESSARY TEXT IN ROWS 1 TO 4)

Fund_dates_data = FundSheet(4:end,1:2);
FundDates = cellstr(datestr(datevec(Fund_dates_data(:,1),...
                                    formatIn),formatOut));
FundData = cell2mat(Fund_dates_data(:,2));
% CREATE TIME SERIES FOR EACH FUND

    Fundts{I}=fints(FundDates,FundData,['Fund',num2str(I)]);

    if merge_count == 2
        Port = merge(Fundts{I-1},Fundts{I},'DateSetMethod','Intersection');
    end
    if merge_count > 2
        Port = merge(Port,Fundts{I},'DateSetMethod','Intersection');
    end
    merge_count = merge_count + 1;

end

% ANALYSE PORTFOLIO

Returns=tick2ret(Port);
q = Portfolio;
q = q.estimateAssetMoments(Returns)
[qassetmean, qassetcovar] = q.getAssetMoments
Was it helpful?

Solution

This is probably due to merge. By default, it sorts columns alphabetically. Unfortunately, as your naming pattern is "FundN", this means that, for example, Fund10 will normally be sorted before Fund9. So as you're looping over I from 5 to 19, you will have Fund10, through Fund19, followed by Fund4 through Fund9.

One way of solving this would to be always use zero padding (Fund01, Fund02, etc) so that alphabetical order and numerical order are the same. Alternatively, force it to stay in the order you read/merge the data by setting SortColumns to 0:

Port = merge(Port,Fundts{I},'DateSetMethod','Intersection','SortColumns',0);

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top