clear; clc; close all;

%% Load Data
%% Head 2
%% Head 3
% This is the first item.
%

load("assets_11.mat");

dates = data_pool.Date;
prices = data_pool.TWSE_Index;
prices2 = data_pool.SPX_Index;
prices3 = data_pool.JPY_Curncy;

mask = ~isnan(prices) & ~isnan(prices2) & ~isnan(prices3) & dates.Year == 2014;
prices = prices(mask);
prices2 = prices2(mask);
prices3 = prices3(mask);

dates = dates(mask);

figure; plot(dates, prices); grid on; hold on;
plot(dates, prices2);
% ma5 = movmean(prices, [4, 0]);
% plot(dates, ma5, ".--");

%

rr = diff(prices) ./ prices(1 : end - 1);
rr2 = diff(prices2) ./ prices2(1 : end - 1);
rdates = dates(2 : end);

figure;
plot(rdates, rr); grid on;

figure;
histogram(rr, 100); grid on; hold on;
histogram(rr2, 100);

mean(rr)
std(rr)
kstest(rr)
jbtest(rr)
ttest(rr)

%

figure; scatter(rr(1 : end - 1), rr2(2 : end)); grid on;
corr(rr(1 : end - 1), rr2(2 : end));

%

autocorr(rr);
acf = autocorr(rr)
parcorr(rr);

adftest(rr);

%

Y = [prices, prices2, prices3];

[h, ~, ~, ~, mles] = jcitest(Y, "model", "H1*", "lags", 0)
mles.r1.paramVals.A
beta = mles.r1.paramVals.B
c0 = mles.r1.paramVals.c0
z = beta' * Y' + c0;

figure;
for i = 1 : 3
    Y(:, i) = Y(:, i) / Y(1, i);
end
plot(dates, Y); grid on;
figure;
plot(dates, z); grid on;


