% Example of How to Import Stock Statistics from Web into Matlab % --- This example retrieves trailing P/E ratio from Yahoo! Finance % LuminousLogic.com % Initialize Workspace function trailing_pe = get_trailing_pe(stock_symbol) stock_symbol = upper(stock_symbol); % Open connection to Yahoo! Finance statistics page fprintf(1,'Retrieving trailing P/E ratio for %s...', stock_symbol); url_name = strcat('http://finance.yahoo.com/q/ks?s=', stock_symbol); url = java.net.URL(url_name); % Construct a URL object is = openStream(url); % Open a connection to the URL isr = java.io.InputStreamReader(is); br = java.io.BufferedReader(isr); % Cycle through the source code until we find trailing P/E... while 1 line_buff = char(readLine(br)); ptr = strfind(line_buff, 'Trailing P/E'); % ...And break when we find it if length(ptr) > 0,break; end % Handle the case where either data not available or no trailing PE no_data = strfind(line_buff, 'There is no'); if length(no_data) > 0, fprintf(1,'Yahoo! Finance does not currently have trailing P/E for %s.\n',stock_symbol); trailing_pe = NaN; return; end end % Just to make it easier, strip off all the preceeding stuff we don't want line_buff = line_buff(ptr:end); % Extract the trailing P/E ptr_gt = strfind(line_buff,'>'); ptr_lt = strfind(line_buff,'<'); trailing_pe = str2num(line_buff(ptr_gt(2)+1:ptr_lt(3)-1)); if length(trailing_pe) == 0 fprintf(1,'N/A\n'); else fprintf(1,' = %3.2f\n', trailing_pe); end