2015-11-19 80 views
0

由於某些未知原因,當我運行下面的腳本時,以下錯誤與所需的輸出一起返回。出於某種原因,昨天晚上這個工作沒有任何錯誤。 API輸出每分鐘都會改變,但我不希望返回KeyError。我只是不能準確判斷這個錯誤是來自:Python JSON KeyError for non missing key

[u'@AAPL 151204C00128000'] <----- What I want to see printed 

Traceback (most recent call last): 

File "Options_testing.py", line 60, in <module> 
main() 
File "Options_testing.py", line 56, in main 
    if quotes[x]['greeks']['impvol'] > 0: #change this for different greek vals 

KeyError: 'impvol' 

下面是數據的一個小片段:

{"results":{"optionchain":{"expire":"all","excode":"oprac","equityinfo":{"longname":"Apple Inc","shortname":"AAPL"},"money":"at","callput":"all","key":{"symbol":["AAPL"],"exLgName":"Nasdaq Global Select","exShName":"NGS","exchange":"NGS"},"symbolstring":"AAPL"},"quote":[{"delaymin":15,"contract":{"strike":108,"openinterest":3516,"contracthigh":6.16,"contractlow":0.02,"callput":"Put","type":"WEEK","expirydate":"2015-11-13"},"root":{"equityinfo":{"longname":"Apple Inc","shortname":"AAPL"},"key":{"symbol":["AAPL"],"exLgName":"Nasdaq Global Select","exShName":"NGS","exchange":"NGS"}},"greeks":{"vega":0,"theta":0,"gamma":0,"delta":0,"impvol":0,"rho":0} 

代碼:

#Options screener using Quotemedia's API 
import json 
import requests 
#import csv   

def main():   


    url_auth= "https://app.quotemedia.com/user/g/authenticate/v0/102368/XXXXX/XXXXX" 
    decode_auth = requests.get(url_auth)   

    #print decode_auth.json() 
    #print(type(decode_auth))   

    auth_data = json.dumps(decode_auth.json())   

    #Parse decode_auth, grab 'sid'   

    sid_parsed = json.loads(auth_data)["sid"] 
    #print sid_parsed   

    #Pass sid into qm_options 
    #Construct URL   

    symbol = 'AAPL' 
    SID = sid_parsed 
    url_raw = 'http://app.quotemedia.com/data/getOptionQuotes.json?webmasterId=102368' 


    url_data = url_raw + '&symbol=' + symbol + '&greeks=true' + '&SID=' + SID   

    #print url_data   

    response = requests.get(url_data) 
    #print response 
    data = json.dumps(response.json()) 
    #print data   

    #save data to a file    

    with open('AAPL_20151118.json', 'w') as outfile: 
     json.dumps (data, outfile)   

    #Turn into json object 
    obj = json.loads(data)   

    #slim the object 
    quotes = obj['results']['quote']   

    #find the number of options contracts 
    range_count = obj['results']['symbolcount']   

    #print all contracts with an implied vol > 0 
    for x in range(0,range_count): 
     if quotes[x]['greeks']['impvol'] > 0: #change this for different greek vals 
      print quotes[x]['key']['symbol']   

if __name__ == '__main__': 
    main() 

我可以提供,如果樣本數據必要。

+1

請你爲什麼要使用'response.json()格式化數據片斷是代碼視圖以及 – mmenschig

+0

'只是'數據= json.dumps(response.json())'和那麼'obj = json.loads(data)'又一次? –

+0

該數據片段不完整。至少,「報價」列表永遠不會終止。 –

回答

1
for x in range(0,range_count): 
    if quotes[x]['greeks']['impvol'] > 0: #change this for different greek vals 
     print quotes[x]['key']['symbol'] 

這個循環通過量多報價,因此也許有甚至只是一個不具有impvol財產。

您應該添加一些錯誤處理,以便您瞭解何時發生。事情是這樣的:

# no need to iterate over indexes, just iterate over the items 
for quote in quotes: 
    if 'greeks' not in quote: 
     print('Quote does not contain `greeks`:', quote) 
    elif 'impvol' not in quote['greeks']: 
     print('Quote does not contain `impvol`:', quote) 

    elif quote['greeks']['impvol'] > 0: 
     print quote['key']['symbol'] 
+0

我沒有想到這一點。這可能解釋了收市後和現在收益之間的差異。讓我試試看看會發生什麼。謝謝。 – user2578013

+0

你說得對。這就是發生了什麼事。有一些選擇合同沒有impvol。我猜我假設太多了。非常感謝 :) – user2578013