p = csvread('stocks.csv',1,0);
p = p(:,[1,2]); % consider first two stocks
y = diff(log(p))*100; % convert prices to returns
y(:,1)=y(:,1)-mean(y(:,1)); % subtract mean
y(:,2)=y(:,2)-mean(y(:,2));
T = length(y);
using CSV, Statistics, DataFrames;
p = CSV.read("stocks.csv", DataFrame);
y1 = diff(log.(p[:,1])).*100; # consider first two stocks
y2 = diff(log.(p[:,2])).*100; # convert prices to returns
y1 = y1 .- mean(y1); # subtract mean
y2 = y2 .- mean(y2);
y = hcat(y1,y2); # combine both series horizontally
T = size(y,1); # get the length of time series
%% create a matrix to hold covariance matrix for each t
EWMA = nan(T,3);
lambda = 0.94;
S = cov(y); % initial (t=1) covar matrix
EWMA(1,:) = S([1,4,2]); % extract var and covar
for i = 2:T % loop though the sample
S = lambda*S+(1-lambda)* y(i-1,:)'*y(i-1,:);
EWMA(i,:) = S([1,4,2]); % convert matrix to vector
end
EWMArho = EWMA(:,3)./sqrt(EWMA(:,1).*EWMA(:,2)); % calculate correlations
## create a matrix to hold covariance matrix for each t
EWMA = fill(NaN, (T,3))
lambda = 0.94
S = cov(y) # initial (t=1) covar matrix
EWMA[1,:] = [S[1], S[4], S[2]] # extract var and covar
for i in 2:T # loop though the sample
S = lambda*S + (1-lambda)*y[i-1,:]*(y[i-1,:])'
EWMA[i,:] = [S[1], S[4], S[2]] # convert matrix to vector
end
EWMArho = EWMA[:,3]./sqrt.(EWMA[:,1].*EWMA[:,2]); # calculate correlations
[par, Ht] = o_mvgarch(y,2, 1,1,1);
Ht = reshape(Ht,4,T)';
%% Ht comes from o_mvgarch as a 3D matrix, this transforms it into a 2D matrix
OOrho = Ht(:,3) ./ sqrt(Ht(:,1) .* Ht(:,4));
%% OOrho is a vector of correlations
## No OGARCH code available in Julia at present
%%The function 'dcc' in MFE toolbox currently cannot work in MATLAB R2022a.
%%The function 'dcc' use one MATLAB Optimization toolbox function 'fmincon'.
%%The changes of 'fmincon' cause this problem.
%%This block can work on Optimization 8.3
[p, lik, Ht] = dcc(y,1,1,1,1);
Ht = reshape(Ht,4,T)';
DCCrho = Ht(:,3) ./ sqrt(Ht(:,1) .* Ht(:,4));
%% DCCrho is a vector of correlations
using ARCHModels, Plots;
## Multivariate models in ARCHModel package
dcc = fit(DCC{1, 1, GARCH{1, 1}}, y; meanspec = NoIntercept);
## Access covariances
H = covariances(dcc);
## Getting correlations
DCCrho = [correlations(dcc)[i][1,2] for i = 1:T];
plot(DCCrho, title = "Correlations", legend = false)
plot([EWMArho,OOrho,DCCrho])
legend('EWMA','DCC','OGARCH','Location','SouthWest')
## No OGARCH code available in Julia at present