%=========================================================
clear all
%=============
%Read the data
%=============
data_2006prog
[T,NoH]=size(data_2006);

% for i=1:NoH
%     plot(data_2006(:,i))
%     pause
% end

%====================
%Read the datafactors
%====================
datafactors_2006prog
[T,plithosfactors]=size(datafactors_2006);
maxplithosfactors=plithosfactors+1;

% for i=1:plithosfactors
%     plot(datafactors_2006(:,i))
%     pause
% end
% corrcoef(datafactors_2006)

%================================
%Make data: First Y, then Factors
%================================
% NoH=31;
% plithosfactors=9;

for i=1:NoH
    alldata=[]; yhelp=[]; xhelp=[];
    yhelp=data_2006(:,i);
    xhelp=datafactors_2006;
    alldata=[yhelp xhelp];
    ahfr{i}=alldata;
end
%================================


%=========================================================
for i=1:NoH
    pinakasdata=ahfr{i};
    data=pinakasdata(:,1);
    absdata=abs(data);
    sqrdata=data.^2;
    %calculate Ljung-Box statistic for the return series
    [Hd(i),Pd(i),Qd(i),CVd(i)]=lbqtest(data,12);
    %calculate Ljung-Box statistic for the absolute returns
    [Habs(i),Pabs(i),Qabs(i),CVabs(i)]=lbqtest(absdata,12);
    %calculate Ljung-Box statistic for the squared returns
    [Hsqr(i),Psqr(i),Qsqr(i),CVsqr(i)]=lbqtest(sqrdata,12);
    [i Hd(i) Habs(i) Hsqr(i)]
%     autocorr(data,12)
%     pause
%     autocorr(absdata,12)
%     pause
%     autocorr(sqrdata,12)
%     pause
end
[sum(Hd) sum(Habs) sum(Hsqr)]/NoH
% 0.0968    0.4839    0.5484
%=========================================================


%=========================================================
%Run the CLASSICAL APPROACH
STEP_keep=zeros(NoH,maxplithosfactors);

for i=1:NoH
    i
    pinakasdata=[];   
    pinakasdata=ahfr{i};    
    
    data=pinakasdata(:,1);  
    datafactors=pinakasdata(:,2:end);
    
    %====== STEP ======
    [B,SE,PVAL,INMODEL,STATS,NEXTSTEP,HISTORY]=stepwisefit(datafactors,data,'display','off')
    stepmodelhelp=zeros(1,maxplithosfactors);
    for ii=1:plithosfactors
        if (INMODEL(ii)==1)
            stepmodelhelp(ii)=ii;
        end
    end
    stepmodelhelp(stepmodelhelp==0)=[];
    stepmodel=zeros(1,maxplithosfactors);
    stepmodel(1:size(stepmodelhelp,2))=stepmodelhelp
    %==================
   
    STEP_keep(i,:)=stepmodel
    pause
end
%=========================================================
