Search code examples
javascriptpythonjsonfinance

Python- Get Stock Information for a company for a range of dates


Trying to get more than just the stock information at the current time period, and I can't figure out if Google Finance allows for retrieving information for more than just one date. For example, if I wanted to find out the Google Stock value over the last 30 days and return that data as a list... how would I go about doing this?

Using the code below only gets me a single value:

class GoogleFinanceAPI:
    def __init__(self):
        self.prefix = "http://finance.google.com/finance/info?client=ig&q="

    def get(self,symbol,exchange):
        url = self.prefix+"%s:%s"%(exchange,symbol)
        u = urllib2.urlopen(url)
        content = u.read()

        obj = json.loads(content[3:])
        return obj[0]


c = GoogleFinanceAPI()
quote = c.get("MSFT","NASDAQ")
print quote

Solution

  • Here is a recipe to get a historical values from Google Finance:

    http://code.activestate.com/recipes/576495-get-a-stock-historical-value-from-google-finance/

    It looks like it returns the data in .csv format.

    Edit: Here is your script modified to get the .csv. It works for me.

    import urllib2
    import csv
    
    class GoogleFinanceAPI:
        def __init__(self):
            self.url = "http://finance.google.com/finance/historical?client=ig&q={0}:{1}&output=csv"
        def get(self,symbol,exchange):
            page = urllib2.urlopen(self.url.format(exchange,symbol))
            content = page.readlines()
            page.close()
            reader = csv.reader(content)
            for row in reader:
                print row
    
    c = GoogleFinanceAPI()
    c.get("MSFT","NASDAQ")