clear all
% read data
load datafanalyse_new.txt
%or 
read_data
data=datafanalyse_new;
size(data)

%Summry statistics
%==================
%plot of the data
for i=1:size(data,2)
    plot(data(:,i))
    pause
    hist(data(:,i))
    pause
end

[mean(data); std(data); median(data); kurtosis(data); skewness(data)]

for i=1:size(data,2)
    %check for autocorrelation for the data
    %autocorr(data(:,i),12)
    %pause
    %calculate Ljung-Box statistic for the return series
    %[Hd(i),Pd(i),Qd(i),CVd(i)]=lbqtest(data(:,i),12)
    %pause
    [Habs(i),Pabs(i),Qabs(i),CVabs(i)]=lbqtest(abs(data(:,i)),12)
    pause
    autocorr(data(:,i).^2,12)
    pause
    [Hsqr(i),Psqr(i),Qsqr(i),CVsqr(i)]=lbqtest(data(:,i).^2,24)
    pause
end



%Make portfolios
%Model 1
m=mean(data);
covmat=cov(data);
[PortRisk1, PortReturn1, PortWts1]=portopt(m,covmat)
 
%Model 2: CCC
%==================
speck=garchset('P',1,'Q',1,'display','off');
mCCC=zeros(size(data,2),1);
d=zeros(size(data,2),1);
resids=zeros(size(data,1),size(data,2));
for i=1:size(data,2)
    i
    %RUN SIMPLE GARCH MODEl
    coeff=[]; Errors=[]; LLF=[]; Innovations=[]; Sigmas=[]; Summary=[];
    [Coeff,Errors,LLF,Innovations,Sigmas,Summary]=garchfit(speck,data(:,i));
    size(Innovations)
    mCCC(i)=garchget(Coeff,'C');
    a0=garchget(Coeff,'K');
    a1=garchget(Coeff,'ARCH');
    b1=garchget(Coeff,'GARCH');
    d(i)=sqrt(a0+a1*Innovations(end)^2+b1*Sigmas(end)^2);
    resids(:,i)=Innovations;
end
covmatCCC=diag(d)*corr(resids)*diag(d);
[PortRisk2, PortReturn2, PortWts2]=portopt(mCCC,covmatCCC)

[PortRisk1 PortRisk2 PortReturn1 PortReturn2 PortReturn1./PortRisk1 PortReturn2./PortRisk2]
