python - Python:如何使用此 JSON API 捕获 404 错误?
问题描述
我正在编写一些使用此 API 的脚本:http ://www.robin-stocks.com/en/latest/functions.html
在我的一个模块中,我尝试运行以下函数来获取一堆 JSON 响应并将它们存储在一个文件中。
import robin_stocks as r
def getAllOptions(symbol):
jsonAllOptions = r.options.find_tradable_options(symbol, expirationDate=None, strikePrice=None, optionType=None, info=None)
with open('allOptions.json', 'w') as json_allop:
json.dump(jsonAllOptions, json_allop)
unfilteredOptions = pd.read_json (r'allOptions.json')
allOptions = unfilteredOptions.loc[unfilteredOptions['rhs_tradability'] == 'untradable']
return allOptions
和
def storeEachOption(allOptions):
pathPrefix = "data/stockData/availableOptions/"
pathSuffix = ".json"
for sID in allOptions['id'].tolist():
jsonCurrentOption = r.options.get_option_market_data_by_id(sID,info=None)
fullPath = pathPrefix + sID + pathSuffix
print('Writing....' + fullPath)
with open(fullPath, 'w') as json_oplist:
json.dump(jsonCurrentOption, json_oplist)
pdCurrentOption = pd.DataFrame(jsonCurrentOption, index=[0])
然后我打电话给他们:
storeEachOption(getAllOptions('TSLA'))
我的其他模块通常会提取这些 JSON 文件并将它们转换为 Pandas DataFrames 来操作它们。问题是我从 Robin Hood 的 API 中得到了一堆 404。我认为这与我的代码有关,但显然每当您尝试通过其 API 获取可用选项列表时,它都会返回一些无效的选项 ID,因此会返回 404。
我正在寻找一种方法来捕获这些 404 并将它们发送到 /dev/null。最好这会在它被保存到 JSON 文件之前发生,但如果不是这样也可以。当我在 storeEachOption() 中调用这行代码时,我的控制台开始出现 404 错误(由 robin_stocks 输出):
jsonCurrentOption = r.options.get_option_market_data_by_id(sID,info=None)
控制台输出:
404 Client Error: Not Found for url: https://api.robinhood.com/marketdata/options/b81b5b6c-3f2b-45f2-a5cf-fdf44e1fed85/
下面我列出了 404 和正常响应的示例 JSON 响应(以及每个文件中存储的内容)。
404 响应:
{"adjusted_mark_price": "", "ask_price": "", "ask_size": "", "bid_price": "", "bid_size": "", "break_even_price": "", "high_price": "", "instrument": "", "last_trade_price": "", "last_trade_size": "", "low_price": "", "mark_price": "", "open_interest": "", "previous_close_date": "", "previous_close_price": "", "volume": "", "chance_of_profit_long": "", "chance_of_profit_short": "", "delta": "", "gamma": "", "implied_volatility": "", "rho": "", "theta": "", "vega": "", "high_fill_rate_buy_price": "", "high_fill_rate_sell_price": "", "low_fill_rate_buy_price": "", "low_fill_rate_sell_price": ""}
正常反应:
{"adjusted_mark_price": "0.010000", "ask_price": "0.620000", "ask_size": 110, "bid_price": "0.000000", "bid_size": 0, "break_even_price": "4.990000", "high_price": null, "instrument": "https://api.robinhood.com/options/instruments/00b70671-97d2-44cf-ad30-278f1c84ed1e/", "last_trade_price": null, "last_trade_size": null, "low_price": null, "mark_price": "0.310000", "open_interest": 0, "previous_close_date": "2020-07-01", "previous_close_price": "0.010000", "volume": 0, "chance_of_profit_long": "0.020993", "chance_of_profit_short": "0.979007", "delta": "-0.010636", "gamma": "0.011169", "implied_volatility": "0.806188", "rho": "-0.000126", "theta": "-0.000823", "vega": "0.000878", "high_fill_rate_buy_price": "0.450000", "high_fill_rate_sell_price": "0.020000", "low_fill_rate_buy_price": "0.210000", "low_fill_rate_sell_price": "0.270000"}
任何帮助将不胜感激。
解决方案
理想情况下,API 应该返回 404。解决方法可能是检查响应的字段:
def storeEachOption(allOptions):
pathPrefix = "data/stockData/availableOptions/"
pathSuffix = ".json"
for sID in allOptions['id'].tolist():
jsonCurrentOption = r.options.get_option_market_data_by_id(sID,info=None)
allEmpty = True
for key, value in jsonCurrentOption.items():
if(value!=""):
allEmpty = False
if(allEmpty is False):
fullPath = pathPrefix + sID + pathSuffix
print('Writing....' + fullPath)
with open(fullPath, 'w') as json_oplist:
json.dump(jsonCurrentOption, json_oplist)
pdCurrentOption = pd.DataFrame(jsonCurrentOption, index=[0])
else:
print('404 ERROR! :(')
pass