Google Groups no longer supports new Usenet posts or subscriptions. Historical content remains viewable.
Dismiss

How can I download stock data from the web and find the efficient frontier of the portfolio plus the allocation of each security according to the risk/return profile of each security?

103 views
Skip to first unread message

Ryan

unread,
Feb 1, 2015, 9:16:13 AM2/1/15
to
How can I download stock data from the web and find the efficient frontier of the portfolio plus the allocation of each security according to the risk/return profile of each security?

Here is a great link for building an optimized portfolio.
http://www.mathworks.com/help/finance/portfolio-optimization-examples.html

How can I use the downloaded data from the web as a data source? I don’t want to use the ‘BlueChipStockMoments.mat’ file, which is used in that example.

Here’s a function to download stock data from the web.
function data = getYahooDailyData(tickers, startDate, endDate, dateFormat)

% EXAMPLE:
% data = getYahooDailyData({'MSFT', 'ML.PA'}, ...
% '01/01/2010', '01/01/2013', 'dd/mm/yyyy');

%% 1. Input parsing
% Check to see if a single ticker was provided as a string; if so, make it
% a cell array to better fit the later logic.
if ischar(tickers)
tickers = {tickers};
end

% If dateFormat is provided, use it. Otherwise, assume datenums were
% given.
if nargin == 4
startDate = datenum(startDate, dateFormat);
endDate = datenum( endDate, dateFormat);
end

url1 = 'http://ichart.finance.yahoo.com/table.csv?s=';

[sY, sM, sD] = datevec(startDate);
[eY, eM, eD] = datevec(endDate);

url2 = ['&a=' num2str(sM-1, '%02u') ...
'&b=' num2str(sD) ...
'&c=' num2str(sY) ...
'&d=' num2str(eM-1, '%02u') ...
'&e=' num2str(eD) ...
'&f=' num2str(eY) '&g=d&ignore=.csv'];

% Determine if we're using tables or datasets:
isBeforeR2013b = verLessThan('matlab', '8.2');

%% 2. Load Data in a loop
h = waitbar(0, 'Getting daily data from Yahoo!');
for iTicker = 1:length(tickers)
try
str = urlread([url1 tickers{iTicker} url2]);
catch
% Special behaviour if str cannot be found: this means that no
% price info was returned. Error and say which asset is invalid:
close(h)
error('getYahooDailyData:invalidTicker', ...
['No data returned for ticker ''' tickers{iTicker} ...
'''. Is this a valid symbol? Do you have an internet connection?'])
end
c = textscan(str, '%s%f%f%f%f%f%f', 'HeaderLines', 1, 'Delimiter', ',');
if isBeforeR2013b
ds = dataset(c{1}, c{2}, c{3}, c{4}, c{5}, c{6}, c{7}, 'VarNames', ...
{'Date', 'Open', 'High', 'Low', 'Close', 'Volume', 'AdjClose'});
else
ds = table(c{1}, c{2}, c{3}, c{4}, c{5}, c{6}, c{7}, 'VariableNames', ...
{'Date', 'Open', 'High', 'Low', 'Close', 'Volume', 'AdjClose'});
end
ds.Date = datenum(ds.Date, 'yyyy-mm-dd');
ds = flipud(ds);
data.(genvarname(tickers{iTicker})) = ds;

waitbar(iTicker/length(tickers), h);
end

close(h)
0 new messages