我刚刚开始学习编码,如果这个问题很简单,我想提前道歉。
我一直试图找到一种方法将股票市场数据实时提供给python,并且遇到了这个博客 http://www.quantatrisk.com/2015/05/07/hacking-google-finance-in-pre-market-trading-python/
以下是我复制并粘贴的脚本。
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)
它似乎是一个很棒的代码,除非我运行它,我收到以下错误消息
---------------------------------------------------------------------------
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'
我尝试修改fetchPreMarket以便它只输出info = data[0]
但是当我尝试'打印信息'时,没有任何结果。
提前致谢
答案 0 :(得分:2)
所以... Google财经API has been discontinued。我很惊讶链接有效,但数据中没有"etl"
(或"el"
)键。
因此,您将KeyError: 'elt'
info["elt"]
供参考,
{
"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"
}
您可能会更好地使用googlefinance或yahoo-finance python模块,而不是直接调用API地址。
值得注意的是,Yahoo API并非“实时”。这是一个约15分钟的延迟报价。