diff --git a/googlefinance/googlefinance.py b/googlefinance/googlefinance.py new file mode 100644 index 0000000..a74aecc --- /dev/null +++ b/googlefinance/googlefinance.py @@ -0,0 +1,72 @@ +''' +MIT License +''' + +from urllib2 import Request, urlopen +import json +import sys + +__author__ = 'hongtaocai on github' + +googleFinanceKeyToFullName = { + u'id' : u'ID', + u't' : u'StockSymbol', + u'e' : u'Index', + u'l' : u'LastTradePrice', + u'l_cur' : u'LastTradeWithCurrency', + u'ltt' : u'LastTradeTime', + u'lt_dts' : u'LastTradeDateTime', + u'lt' : u'LastTradeDateTimeLong', + u'div' : u'Dividend', + u'yld' : u'Yield' +} + +def buildUrl(symbols): + symbol_list = ','.join([symbol for symbol in symbols]) + # a deprecated but still active & correct api + return 'http://finance.google.com/finance/info?client=ig&q=' \ + + symbol_list + +def request(symbols): + url = buildUrl(symbols) + req = Request(url) + resp = urlopen(req) + content = resp.read().decode().strip() + content = content[3:] + return content + +def replaceKeys(quotes): + global googleFinanceKeyToFullName + quotesWithReadableKey = [] + for q in quotes: + qReadableKey = {} + for k in googleFinanceKeyToFullName: + qReadableKey[googleFinanceKeyToFullName[k]] = q[k] + quotesWithReadableKey.append(qReadableKey) + return quotesWithReadableKey + +def getRealtimeQuotes(symbols): + ''' + get real-time quotes (index, last trade price, last trade time, etc) for stocks, using google api: + http://finance.google.com/finance/info?client=ig&q=symbols + Unlike python package 'yahoo-finance', There is no delay for NYSE and NASDAQ stocks in googlefinance. + :param symbols: a list of stock symbols + :return: real-time quote + ''' + content = json.loads(request(symbols)) + return replaceKeys(content); + +if __name__ == '__main__': + try: + symbols = sys.argv[1] + except: + symbols = "GOOG,AAPL" + + symbols = symbols.split(',') + + try: + print json.dumps(getRealtimeQuotes(symbols), indent=2) + except: + print "Fail" + + diff --git a/setup.cfg b/setup.cfg new file mode 100644 index 0000000..b88034e --- /dev/null +++ b/setup.cfg @@ -0,0 +1,2 @@ +[metadata] +description-file = README.md diff --git a/setup.py b/setup.py new file mode 100644 index 0000000..ad26746 --- /dev/null +++ b/setup.py @@ -0,0 +1,13 @@ +from distutils.core import setup +setup( + name = 'googlefinance', + packages = ['googlefinance'], # this must be the same as the name above + version = '0.1', + description = 'Python module to get stock data from Google Finance API', + author = 'Hongtao Cai', + author_email = 'caiht.ht@gmail.com', + url = 'https://github.com/hongtaocai/googlefinance', # use the URL to the github repo + download_url = 'https://github.com/hongtaocai/googlefinance', # I'll explain this in a second + keywords = ['googlefinance', 'stock', 'price' , 'finance', 'google'], # arbitrary keywords + classifiers = [], +)