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 = '' % 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:'

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


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'}


Alex K. said...

Same thing only in Python3

import json
import pprint
import urllib.request

def get_stock_quote(ticker_symbol):
url = '{}'.format(ticker_symbol)
lines = urllib.request.urlopen(url).readlines()
lines_string = [x.decode('utf-8').strip('\n') for x in lines]

merged = ''.join([x for x in lines_string if x not in ('// [', ']')])
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:')

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:

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