% SP500.mat is a MATLAB data set with 2 columns. First is closing price
% (adjusted for splits and dividends) from 1/4/1988 - 6/10/2020.
% the S&P 500 index from 01.03.1950 - 09.22.2011.

load SP500.mat;
data = SP500;
p = data(:,1);

p_0 = p(2:end,1);
p_1 = p(1:end-1,1);
r = log (p_0./p_1);
n = size(r,1);
t = (1:1:n);

alpha = .05;
x0=[0;1;4];
[phat pci]= mle(r,'distribution','tlocationscale','start',x0,'alpha',1-alpha);

phat(1)
pci(:,1)

phat(2)
pci(:,2)

phat(3)
pci(:,3)

pd = makedist('tlocationscale','mu',phat(1),'sigma', phat(2),'nu',phat(3));
[h,p,ksstat,cv] = kstest(r,pd,alpha);

% If h=1 reject normality and h=0 accept
h

% p-value
p;

% Value of the Kolmogorov-Smirnoff statistic
ksstat

% cut-off value
cv


% Forecast

EP_hat = p_1(1)*( 1+t*(phat(1)+0.5*(phat(2)^2)*(phat(3)/(phat(3)-2))     )   +(phat(1)^2)*0.5*t.^2   );

% Figure plots daily returns on the S&P 500

figure(1)
plot(t,r)
box off
grid off
xlabel('Time Index (days)')
ylabel('Log returns')
title('Log-returns on S&P500 from 01.04.1988 - 06.10.2020')

figure(2)
qqplot(r)
grid on
box off

figure(3)

plot(t,EP_hat,t,p_1)
box off
grid off
xlabel('Time Index (days)')
ylabel('Forecast of Expected Price')
title('Forecasted Price Series')
