goldb.org home

AS OF MAY 2008, THIS BLOG IS NO LONGER BEING UPDATED.
Visit the new blog at: http://coreygoldberg.blogspot.com



 Friday, September 14, 2007

Python - Stock Quote Module

I just wrote a tiny Python module for programmatically retrieving stock quotes from Google Finance:

The module:


import urllib
import re

def get_quote(symbol):
    base_url = 'http://finance.google.com/finance?q='
    content = urllib.urlopen(base_url + symbol).read()
    m = re.search('class="pr".*?>(.*?)<', content)
    if m:
        quote = m.group(1)
    else:
        quote = 'no quote available for: ' + symbol
    return quote


Sample usage:


#!/usr/bin/env python

import stockquote

print stockquote.get_quote('goog')


Output:


>> 529.56
#    Comments [8] |
Friday, September 14, 2007 4:18:21 PM (Eastern Standard Time, UTC-05:00)
Not working for me. The regular expression isn't correct I think . . .

In [1]: import urllib

In [2]: import re

In [3]: base_url = 'http://finance.google.com/finance?q='

In [4]: symbol = 'goog'

In [5]: content = urllib.urlopen(base_url + symbol).read()

In [6]: m = re.search('(.*?)<', content)

In [7]: m
Out[7]: <_sre.SRE_Match object at 0x7fd4dd20>

In [8]: m.group(1)
Out[8]: ''
Saturday, September 15, 2007 8:42:37 AM (Eastern Standard Time, UTC-05:00)
fixed.
Saturday, September 15, 2007 11:37:06 AM (Eastern Standard Time, UTC-05:00)
Cool, works nicely now.
Saturday, September 15, 2007 7:38:39 PM (Eastern Standard Time, UTC-05:00)
How about:

http://finance.yahoo.com/d/quotes.csv?s=GOOG&f=sl1d1t1c1ohgv&e=.csv

then you don't need to use regular expressions.
Vitaliy
Sunday, September 16, 2007 5:02:09 AM (Eastern Standard Time, UTC-05:00)
Yes, I was going to say the same thing. A lot of the financial data from Yahoo Finance is available in plain CSV-format. And it doesn't require an API key to use it. And you don't have to worry about regular expressions.
K
Sunday, September 16, 2007 5:07:40 AM (Eastern Standard Time, UTC-05:00)
I found some documentation about this at http://www.gummy-stuff.org/Yahoo-data.htm You could always just do a search on the site and look at the "download" link to see the parameters, but this might be easier.

I also found a Python module at http://www.freenet.org.nz/python/yahooquote/apidoc/ but I don't know if it is updated.
K
Sunday, September 16, 2007 7:11:17 PM (Eastern Standard Time, UTC-05:00)
@Vitaliy
@K

thanks for the tip about yahoo finance offering data in CSV. I think I am going to write a larger module so we have a Python API for all sorts of stock data.

-Corey
Monday, September 17, 2007 2:20:21 PM (Eastern Standard Time, UTC-05:00)
just created a new module based on Yahoo Finance date:
http://www.goldb.org/ystockquote.html
Comments are closed.