September 27, 2011

Python - Stock Quotes From Google Finance

Quick example of retrieving stock quotes from Google Finance in Python:

#!/usr/bin/env python

import json
import pprint
import urllib2


def get_stock_quote(ticker_symbol):   
    url = 'http://finance.google.com/finance/info?q=%s' % ticker_symbol
    lines = urllib2.urlopen(url).read().splitlines()
    return json.loads(''.join([x for x in lines if x not in ('// [', ']')]))


if __name__ == '__main__':
    quote = get_stock_quote('IBM')
    print 'ticker: %s' % quote['t']
    print 'current price: %s' % quote['l_cur']
    print 'last trade: %s' % quote['lt']
    print 'full quote:'
    pprint.pprint(quote)

* note: all values in the returned dict object are Unicode strings.

Output:

ticker: IBM
current price: 174.51
last trade: Sep 26, 4:00PM EDT
full quote:
{u'c': u'+5.17',
 u'ccol': u'chg',
 u'cp': u'3.05',
 u'div': u'0.75',
 u'e': u'NYSE',
 u'ec': u'0.00',
 u'eccol': u'chb',
 u'ecp': u'0.00',
 u'el': u'174.51',
 u'el_cur': u'174.51',
 u'elt': u'Sep 26, 6:07PM EDT',
 u'id': u'18241',
 u'l': u'174.51',
 u'l_cur': u'174.51',
 u'lt': u'Sep 26, 4:00PM EDT',
 u'ltt': u'4:00PM EDT',
 u's': u'2',
 u't': u'IBM',
 u'yld': u'1.72'}
 

2 comments:

Alex K. said...

Same thing only in Python3

import json
import pprint
import urllib.request

def get_stock_quote(ticker_symbol):
url = 'http://finance.google.com/finance/info?q={}'.format(ticker_symbol)
lines = urllib.request.urlopen(url).readlines()
lines_string = [x.decode('utf-8').strip('\n') for x in lines]
print(lines_string)

merged = ''.join([x for x in lines_string if x not in ('// [', ']')])
print("merged:{}".format(merged))
return json.loads(merged)


if __name__ == '__main__':
quote = get_stock_quote('IBM')
print( 'ticker: {}'.format(quote['t']))
print( 'current price: {}'.format(quote['l_cur']))
print('last trade: {}'.format(quote['lt']))
print( 'full quote:')
pprint.pprint(quote)

Martin said...

Thanks for the code.

I merged yahoo quotes and this function into one module and then cleaned up the code a bit and added nice field labels; the code is here: https://github.com/mdengler/stockquote

If you're not happy with me publishing it or anything let me know.