-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathcointRolling.m
66 lines (51 loc) · 1.75 KB
/
cointRolling.m
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
tic;
w = 252; % window length
nAssets = size(prices,2); % number of assets
totDays = size(prices,1);
nDays = totDays - w; % number of days out of sample
maxCoint = (nAssets^2 - nAssets)/2; % max number of coint pairs
spreads = zeros(nDays,maxCoint);
logPrices = log(prices);
coint = zeros(maxCoint,4);
k = 0;
for d=w+1:totDays
disp([num2str((d-w)/nDays * 100) '%']);
cMat = zeros(nAssets,nAssets);
logPricesRolling = logPrices(d-w:d,:);
for i=1:nAssets
for j=i+1:nAssets
tmpPrices = [logPricesRolling(:,i) logPricesRolling(:,j)];
[h,~,~,~,reg] = egcitest(tmpPrices, 'alpha', 0.99);
if (h==1)
cMat(i,j) = reg.coeff(2);
cMat(j,i) = cMat(i,j);
nr = find((coint(:,1) == i) & (coint(:,2) == j));
if isempty(nr)
k = k + 1;
coint(k,:) = [i j reg.coeff(1) reg.coeff(2)];
c0 = coint(k,3);
beta = [1; -coint(k,4)];
s = zscore(tmpPrices*beta - c0);
spreads(d,k) = s(end);
else
coint(nr,:) = [i j reg.coeff(1) reg.coeff(2)];
c0 = coint(nr,3);
beta = [1; -coint(nr,4)];
s = zscore(tmpPrices*beta - c0);
spreads(d,nr) = s(end);
end;
end;
end;
end;
end;
%%
positions = positionPair(spreads);
pl = profitAndLosses(positions, prices, coint);
totRets = sum(pl,2);
cumRets = cumprod(totRets + 1);
%%
cumProfits = [];
for i=1:maxCoint
cumProfits(:,i) = cumprod(1+pl(:,i));
end;
toc;