
% housekeeping:
clear all
addpath('./market-data-functions-master');

%Chose Asset:
initDate = '1-Jan-2006';
%initDate = '1-Jan-1987';
symbol = '^HSI';
name = 'Hang Seng';
symbol = '0939.HK';
name = 'China Construction Bank';
%symbol = '0729.HK';
%name = 'FDG Electric Vehicles';

% Scrape Yahoo and Plot Price Series
symbol = getMarketDataViaYahoo(symbol, initDate);
symbol = timeseries([symbol.Close], datestr(symbol(:,1).Date));
figure(1);
plot(symbol);
xtickformat('yyyy');
ylabel(name);
title( sprintf('%s 2006 - Present' , name) );
box off

%Make Return Series and Print Statistics
display('Return Statistics');
ret = (symbol.Data(2:end) - symbol.Data(1:end-1)) ./ (symbol.Data(1:end-1));
summaryStats(ret);
display('\n Log Return Statistics');
logRet = log(symbol.Data(2:end) ./ symbol.Data(1:end-1));
summaryStats(logRet);

%Correlogram Returns
%Price Returns
[acf,lags,bounds] = autocorr(ret);
figure(2);
autocorr(ret);
mx = max(acf(2:end));
ylim([-2*mx 2*mx]);
title( sprintf('%s Price Returns Correlogram' , name) );
% Robust Intervals
adj = [];
for k = 1:20
    T = length(ret);
    retSq = ret .^2;
    num = (retSq(1+k:end).* retSq(1:end-k));
    numm = sqrt(T*sum(num));
    den = sum(retSq);
    adj(k) = 1.96 * numm / (den*sqrt(T));
end
hold on;
plot(adj, 'color','g','LineWidth',1);
plot(-adj, 'color','g','LineWidth',1);
title( sprintf('%s Correlogram With Robust Intervals' , name) );
hold off;

%Log Returns
[acf,lags,bounds] = autocorr(ret);
figure(3);
autocorr(ret);
mx = max(acf(2:end));
ylim([-2*mx 2*mx]);
title( sprintf('%s Log Returns Correlogram' , name) );

% Histogram of returns
figure(4);
hist(logRet*100,1000);
title('Price Returns of Hang Seng 1987 - Present');
xlabel('% Return');
ylabel('');
set(gca,'ytick',[]);
box off;

% regression
regressionTest(ret, 5);
regressionTest(logRet, 5);

%Correlogram Square Returns
[acf,lags,bounds] = autocorr(ret.*ret);
figure(5);
autocorr(ret.*ret);
mx = max(acf(2:end));
%ylim([-2*mx 2*mx]);
title( sprintf('%s Square Returns Correlogram' , name) );

%Ljung-Box test
[h,pValue,stat,cValue] = lbqtest(ret, 'lags',20)

% Function to perform robust regression on lags of univariate series
function out = regressionTest(ret, lags)
    lags = 5;
    Y = ret(1+lags:end);
    X = [ret(1:end-lags)];
    for k = 2:lags;
        X = [X ,[ret(k:end-lags+k-1)]];
    end
    fitlm(X,Y,'linear','RobustOpts','on')
end

%Function to Print Summary Statistics
function out = summaryStats(ret)
    fprintf('Mean    %.3f\n' , mean(100*ret));
    fprintf('StdDev  %.3f\n' , std(100*ret));
    fprintf('Kurt    %.3f\n' , kurtosis(100*ret));
    fprintf('Skew    %.3f\n' , skewness(100*ret));
    warning off;
    [h, p, jbstat] = jbtest(ret);
    warning on;
    fprintf('JBstat  %.0f\n' , jbstat);
end




