%==================
%Matlab Code for GARCH models

%Load Data – Summary Statistics
load CSFBCompEx_new.txt
data=CSFBCompEx_new;
load datafanalyse_new.txt
datafactors=datafanalyse_new;
[T,plithosmet]=size(data)
[T,plithosfactors]=size(datafactors)
%==================
%plot of the data
plot(data)
pause
hist(data)
pause

%calculate summary statistics
[mean(data) std(data) median(data) kurtosis(data) skewness(data)]

%check for autocorrelation for the data
autocorr(data,24)
pause
%calculate Ljung-Box statistic for the return series
[Hd,Pd,Qd,CVd]=lbqtest(data,24)
pause
%help lbqtest
%calculate Ljung-Box statistic for the absolute returns
autocorr(abs(data),24)
pause
[Habs,Pabs,Qabs,CVabs]=lbqtest(abs(data),24)
pause
%calculate Ljung-Box statistic for the squared returns
autocorr(data.^2,24)
pause
[Hsqr,Psqr,Qsqr,CVsqr]=lbqtest(data.^2,24)
pause

%==================
%RUN SIMPLE GARCH MODEl
speck=garchset('P',1,'Q',1,'display','off');
Coeff=[]; Errors=[]; LLF=[]; Innovations=[]; Sigmas=[]; Summary=[];
[Coeff,Errors,LLF,Innovations,Sigmas,Summary]=garchfit(speck,data); 

subplot(2,1,1)
plot(data)
subplot(2,1,2)
plot(Sigmas)

autocorr(Innovations,24)
pause
[Hr,Pr,Qr,CVr]=lbqtest(Innovations,24)

autocorr(abs(Innovations),24)
pause
[Har,Par,Qar,CVar]=lbqtest(abs(Innovations),24)

%==================
%RUN SIMPLE GARCH MODEl
speck=garchset('P',1,'Q',1,'Distribution','T','display','off');
Coeff=[]; Errors=[]; LLF=[]; Innovations=[]; Sigmas=[]; Summary=[];
[Coeff,Errors,LLF,Innovations,Sigmas,Summary]=garchfit(speck,data); 

subplot(2,1,1)
plot(data)
subplot(2,1,2)
plot(Sigmas)

autocorr(Innovations,24)
pause
[Hr,Pr,Qr,CVr]=lbqtest(Innovations,24)

autocorr(abs(Innovations),24)
pause
[Har,Par,Qar,CVar]=lbqtest(abs(Innovations),24)


%RUN REGRESSION GARCH MODEL
model=[1 2 3 4];
factors_used=[];
factors_used=datafactors(:,model);
numfactors=length(model);
    
speck=garchset('P',1,'Q',1,'Regress',[1:numfactors],'display','off');
Coeff=[]; Errors=[]; LLF=[]; Innovations=[]; Sigmas=[]; Summary=[];
[Coeff,Errors,LLF,Innovations,Sigmas,Summary]=garchfit(speck,data,factors_used); 
%==================
%BEST STEP MODEL
[B,SE,PVAL,INMODEL,STATS,NEXTSTEP,HISTORY]=stepwisefit(datafactors,data,'display','off');
stepmodelhelp=zeros(1,plithosfactors);
for i=1:plithosfactors
    if (INMODEL(i)==1)
        stepmodelhelp(i)=i;
    end
end
stepmodelhelp(stepmodelhelp==0)=[];
stepmodel=zeros(1,plithosfactors);
stepmodel(1:size(stepmodelhelp,2))=stepmodelhelp
%==================

