www.gusucode.com > GAVPai_Book_MathworksCntrlFileEx_May2019 > GAVPai_Book_MathworksCntrlFileEx_May2019/mean_covariance_extraction.m

    % To read the daily stock price time series data set and extract mean and
% covariance of daily returns (in percentage) after data preprocessing

% Note: The last trading day row and the row/col dimensions of  data have been
% provided within the function only for reasons of simplicity of
% demonstration. Users familiar with MATLAB are encouraged to improvise the
% code
%----------------------------------------------------------------------

function [mean_dat, covariance_dat]= mean_covariance_extraction(file_name, Asset)
last_trading_day_row = 900;
m = xlsread(file_name);
                                   
[~, cols]=size(Asset);
dat = m(1:last_trading_day_row, Asset);  % read the stock time series data set into the array 'dat'

% handling empty rows and missing data in the stock time series data set
j=1;
for i=1: last_trading_day_row
                 if  (sum(isnan(dat(i,:)))~= cols )  % handling  empty rows 
                     newdat(j,:) = dat(i,:);
                     j=j+1;
                 else
                    continue
                 end
end



[row_sourcedat, col_sourcedat] = size(newdat);

for j=1:cols 
    for i=1: row_sourcedat
                     if  isnan(newdat(i,j))         % handling missing data : copy last known price
                         newdat(i,j)= newdat(i-1,j);
                     end
    end
end

% compute daily returns (percentage) of the assets in the portfolio
for j=1: cols
    for i=1:(row_sourcedat-1)
        return_dat(i,j)=(( newdat(i+1,j)-newdat(i,j))/newdat(i,j))*100;
    end
end


% compute mean and covariance of daily returns (percentage) of assets in
% portfolio P
mean_dat= mean(return_dat);
covariance_dat = cov(return_dat);