forked from burakbayramli/books
-
Notifications
You must be signed in to change notification settings - Fork 0
/
example3_4.m
67 lines (29 loc) · 2.35 KB
/
example3_4.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
67
clear; % make sure previously defined variables are erased.
[num, txt]=xlsread('IGE'); % read a spreadsheet named "IGE.xls" into MATLAB.
tday=txt(2:end, 1); % the first column (starting from the second row) contains the trading days in format mm/dd/yyyy.
tday=datestr(datenum(tday, 'mm/dd/yyyy'), 'yyyymmdd'); % convert the format into yyyymmdd.
tday=str2double(cellstr(tday)); % convert the date strings first into cell arrays and then into numeric format.
cls=num(:, end); % the last column contains the adjusted close prices.
[tday sortIndex]=sort(tday, 'ascend'); % sort tday into ascending order.
cls=cls(sortIndex); % sort cls into ascending order of dates.
dailyret=(cls(2:end)-cls(1:end-1))./cls(1:end-1); % daily returns
excessRet=dailyret - 0.04/252; % excess daily returns = strategy returns - financing cost, assuming risk-free rate of 4% per annum and 252 trading days in a year
sharpeRatio=sqrt(252)*mean(excessRet)/std(excessRet) % the output should be 0.7618
%%%%%%%%%%%%%%%%% Second part of example starts here %%%%%%%%%%%%%%%%%
[num, txt]=xlsread('SPY'); % read a spreadsheet named "SPY.xls" into MATLAB.
tday=txt(2:end, 1); % the first column (starting from the second row) contains the trading days in format mm/dd/yyyy.
tday=datestr(datenum(tday, 'mm/dd/yyyy'), 'yyyymmdd'); % convert the format into yyyymmdd.
tday=str2double(cellstr(tday)); % convert the date strings first into cell arrays and then into numeric format.
cls=num(:, end); % the last column is the adjusted close prices.
[tday sortIndex]=sort(tday, 'ascend'); % sort tday into ascending order.
cls=cls(sortIndex); % sort cls into ascending order of dates.
dailyretSPY=(cls(2:end)-cls(1:end-1))./cls(1:end-1); % daily returns
netRet=(dailyret - dailyretSPY)/2; % net daily returns (divide by 2 because we now have twice as much capital.)
sharpeRatio=sqrt(252)*mean(netRet)/std(netRet) % the output should be 0.7837
%%%%%%%%%%%%%%%%%% third part of example starts here %%%%%%%%%%%%%%%%%%
% calculation of maximum drawdown and maximum drawdown duration
cumret=cumprod(1+netRet)-1; % cumulative compounded returns
plot(cumret);
[maxDrawdown maxDrawdownDuration]=calculateMaxDD(cumret);
maxDrawdown % maximum drawdown. Output should be 0.1053
maxDrawdownDuration % maximum drawdown duration. Output should be 497