Code covered by the BSD License  

Highlights from
View and add transaction to portfolios on Google Finance

image thumbnail

View and add transaction to portfolios on Google Finance

by

 

10 Jul 2011 (Updated )

View and add transactions to portfolios on Google Finance. A Google account will be required.

getGooglePortfolioHoldings(username,password,portfolioId)
function holdings= getGooglePortfolioHoldings(username,password,portfolioId)
% getGooglePortfolioHoldings retreives the virtual stock holdings
% in the given Google Finance Portfolio within Matlab.
% See accompanying example (googlePortfolioHoldingsExample.m) on how it can
% be used.

if nargin < 3
    display('requires 3 parameters! getPortfolioHoldings.m');
    return;
end

%import java stuff
import java.io.*;
import java.net.*;
import java.lang.*;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Date;

%initialize some 
holdings = [];


%get authorization token from google.
[authorized, aToken]=connectAndAuthorize(username, password, 'finance');

if (~authorized)    
    return;
end

success=false;
MAXITER=3;
%get portfolio info from google in xml format.
try
    % try to create new event
    safeguard=0;
    while (~success && safeguard<MAXITER)
        %get the portfolio info
        geturlString = ['http://finance.google.com/finance/feeds/default/portfolios/',num2str(portfolioId),'/positions'];

        url = URL( geturlString );
        con = url.openConnection();    
        con.setInstanceFollowRedirects(false);
        con.setRequestMethod( 'GET' );        
        con.setRequestProperty('content-type','application/atom+xml;charset=UTF-8');
        % stuff the Authorization request header
        con.setRequestProperty('Authorization',String('GoogleLogin ').concat(aToken));

        if con.getResponseCode() == 200,
            success = true;
            continue;
        else
            display(con.getResponseCode());
            con.disconnect();
            holdings =[];
            success=false;
            return;
        end
        safeguard = safeguard + 1;
    end
catch ME
    display(ME.message);
    success=false;
    return;
end

%read retrieved xml data.
xmlData=xmlread(con.getInputStream());
    %xmlstr = xmlwrite(xmlData) %show xml data.

%disconnect connection.
con.disconnect();

%get the number of entries in the xml data.
numChildNodes = xmlData.getElementsByTagName('entry').getLength;

%save ticker symbols and number of shares if there is any.
for count = 1:numChildNodes
    share = str2num(char(xmlData.getElementsByTagName('entry').item(count-1).getChildNodes.item(6).getAttribute('shares')));
    if share ~= 0,
    holding.symbol = char(xmlData.getElementsByTagName('entry').item(count-1).getChildNodes.item(7).getAttribute('symbol'));
    holding.share = share;
    holdings = [holdings, holding];
    end
end

Contact us