mat=readmat('data.txt');
rmat=diff(log(mat(180:1000,633:668)));
%rmat=rmat(find(rmat));
rmat = delzeros(rmat);
rmat=flipud(rmat);
 Pmat0 = zscore(rmat);
 [tt,l] = size(Pmat0); 
 tt = 1/tt;
 [Wmat0,Pval0]=eig(tt*Pmat0'*Pmat0);
% %Wmat = fliplr(Wmat);
 Pmat1 = Pmat0*Wmat0;
 ii=1;
 for k=49:length(rmat)-50
 t= corrcoef(rmat(k:k+50,1:end));
 mCor(ii)=t(1,2);
 ii=ii+1
end
x3 = [1+50:ii-1+50]
x0 = [1:length(rmat)];
%subplot(2,1,1);plot(x3,mCor, '-');
%subplot(2,1,2);plot(x0,rmat, '-');

%principal component analysis
% [Wmat1,Pval1]= eig(rmat'*rmat);
% Pmat1= rmat* Wmat1
%principal component from matlab
%[Wmat,SCORE,latent,tsquare] = princomp(rmat);
%Pmat = SCORE*Wmat
%mStdv= std(rmat);
%initialize the first column
%col2 = Pmat(1:end,1);
%[Coeff,Errors,LLF,Innovations,Sigmas,Summary] = garchfit(col2);
%s= garchfit(col2);
%h=250;
%futmat=garchpred(s, col2, h);
%n=2


i=1
for col2= Pmat1
%col2= Pmat1(1:end,1);
    [Coeff,Errors,LLF,Innovations,Sigmas,Summary] = garchfit(col2);
    s= garchfit(col2);
    h=250;
    future=garchpred(s, col2, h);
    x2=[length(col2)+1:length(col2)+h];
    futmat(1:length(future),i) = future;

    x1=[1:length(col2)];
    %garchplot(Sigmas,col2);
    %plot(Sigmas);
    %subplot(2,2,i);plot(x1,Sigmas,'-',x1,Pmat1,'-',x2,future,'-');    
    
    %correlations forecast
    %Diagmat1(i,i)=future(1);
    %Diagmat(i,i)=future(1)*future(1);
    %Covforecast=Wmat*Diagmat*Wmat';
    i=i+1;
end
[m,n] = size(Wmat0)
for i=1:m
    for j=1:n
        A(i,j)=Wmat0(i,j)*std(rmat(1:end,i));
    end
end
%Diagmat 
%loop on all the k= forcasts
for k=1:h
    Diagmat1(i,i)=futmat(k,i);
    Diagmat(i,i)=futmat(k,i)*futmat(k,i);
    
    %Covforecast=Wmat0*Diagmat*Wmat0';
    
    Covforecast=A*Diagmat*A';
    [m,n] = size(Covforecast)
    for i=1:m
        for j=1:m
            Corforecast(i,j)=Covforecast(i,j)/(sqrt(Covforecast(i,i))*sqrt(Covforecast(j,j)));
        end
    end
    vecorr(k)=Corforecast(1,2);
    vecorr1(k)=Corforecast(1,3);
    vecorr2(k)=Corforecast(1,4);
    vecorr3(k)=Corforecast(2,3);
end
meshc(1:m,1:m,Corforecast);
%plot(x1,rmat,'-',x2,vecorr,'-');

%plot(Sigmas);
%plot(x1,Sigmas,'-',x1,Pmat,'-',x2,future,'-');