Calculating Sharpe ratio with examples provided
Afficher commentaires plus anciens
I am trying to work through code from a book on Quantitative trading I am reading. The problem is that the code from the book is old and in some cases out of date.
I tried to re-create the code in R2020b however my result is not right according to the expected out put
my result - 8.3184
the expected result - 0.7618
Edit - I now know that my error is with this line
cls = sortrows(cls, 1); % Sort cls into ascending order of dates
Its suppose to match sort cls by the date column but instead it orders cls in ascending order. What is the way to create this association correctly?
Your help is must appreciated. (Spreadsheet attached)
Here is the OLD code from the book
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
Here is my code.
T = readtable("IGEv3.xlsx");
Warning: Column headers from the file were modified to make them valid MATLAB identifiers before creating variable names for the table. The original column headers are saved in the
VariableDescriptions property.
Set 'VariableNamingRule' to 'preserve' to use the original column headers as table variable names.
tday=T{2:end, 1}; %The First Columns (from second row)
tday.Format = 'yyyy-MMM-dd'; % Convert the format into yyymmdd
cls=T(:, end); % The last Column contains the adjusted close prices
[tday, sortIndex] = sort(tday, 'ascend'); % Sort tday into ascending Order
cls = sortrows(cls, 1); % 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 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
sharpeRatio =
8.3184
Réponse acceptée
Plus de réponses (0)
Catégories
En savoir plus sur Matrix Indexing dans Centre d'aide et File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!