Skip to content

Instantly share code, notes, and snippets.

@ericjang
Created September 7, 2014 03:38
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save ericjang/f58300d89022c4e978d6 to your computer and use it in GitHub Desktop.
Save ericjang/f58300d89022c4e978d6 to your computer and use it in GitHub Desktop.
Dollar Cost Averaging reduces variance of returns. Thanks Ben!
ticker = 'USSPX'; % s&p500 index
periods = 1:100;
nP = numel(periods);
c = yahoo;
dates = {'Jan 1 2000','Sep 6 2014'};
prices = fetch(c,ticker,'Adj Close',dates{1},dates{2}); % should I use Close instead?
nDays = size(prices,1);
nTrials = 50;
returns = zeros(nTrials,nP);
tP = 50*nDays; % total principal invested over time
for t=1:50 % start on different day offsets
for i=1:nP
% buy at i-day intervals with available cash accumulated
buyprices = prices(t:i:end,2);
available_cash = 50 * i; % 50 dollars a day
shares = sum(available_cash ./ buyprices); % num shares bought each time
returns(t,i) = shares * prices(end,2) / tP;
end
end
plot(1:nP, returns);
ylabel(['returns from ' dates{1} '-' dates{2}]);
xlabel('Dollar Cost Averaging Period (days)');
mR = mean(mean(returns));
fprintf('Average return: %d USD\n', mR);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment