i'm just beginning to learn to code and i want to apologize in advance if this question is trivial.
ive been trying to find a way to feed stock market data into python real time and came across this blog http://www.quantatrisk.com/2015/05/07/hacking-google-finance-in-pre-market-trading-python/
Below is the script i copied and pasted.
import urllib2 # works fine with Python 2.7.9 (not 3.4.+)
import json
import time
def fetchPreMarket(symbol, exchange):
link = "http://finance.google.com/finance/info?client=ig&q="
url = link+"%s:%s" % (exchange, symbol)
u = urllib2.urlopen(url)
content = u.read()
data = json.loads(content[3:])
info = data[0]
t = str(info["elt"]) # time stamp
l = float(info["l"]) # close price (previous trading day)
p = float(info["el"]) # stock price in pre-market (after-hours)
return (t,l,p)
p0 = 0
while True:
t, l, p = fetchPreMarket("AAPL","NASDAQ")
if(p!=p0):
p0 = p
print("%s\t%.2f\t%.2f\t%+.2f\t%+.2f%%" % (t, l, p, p-l,
(p/l-1)*100.))
time.sleep(60)
it seems to be a great code except when i run it, i get the following error message
---------------------------------------------------------------------------
KeyError Traceback (most recent call last)
<ipython-input-11-012ec6dc7b0c> in <module>()
18 p0 = 0
19 while True:
---> 20 t, l, p = fetchPreMarket("AAPL","NASDAQ")
21 if(p!=p0):
22 p0 = p
<ipython-input-11-012ec6dc7b0c> in fetchPreMarket(symbol, exchange)
10 data = json.loads(content[3:])
11 info = data[0]
---> 12 t = str(info["elt"]) # time stamp
13 l = float(info["l"]) # close price (previous trading day)
14 p = float(info["el"]) # stock price in pre-market (after-hours)
KeyError: 'elt'
I tried modifying fetchPreMarket such that it just outputs info = data[0]
but when i tried 'print info', nothing came of it.
Thanks in advance
So... The Google Finance API has been discontinued. I am surprised that link works, but there is no "etl"
(or "el"
) key in the data.
And so, you'll get KeyError: 'elt'
at info["elt"]
For reference,
{
"id": "22144"
,"t" : "AAPL"
,"e" : "NASDAQ"
,"l" : "95.52"
,"l_fix" : "95.52"
,"l_cur" : "95.52"
,"s": "0"
,"ltt":"2:34PM EST"
,"lt" : "Feb 24, 2:34PM EST"
,"lt_dts" : "2016-02-24T14:34:54Z"
,"c" : "+0.83"
,"c_fix" : "0.83"
,"cp" : "0.88"
,"cp_fix" : "0.88"
,"ccol" : "chg"
,"pcls_fix" : "94.69"
}
You may have better luck with the googlefinance or yahoo-finance python modules rather than directly calling the API address.
It is worth noting that the Yahoo API is not "realtime", though. It is about a 15 minute delayed quote.