Python - How to avoid error (Exceptions) in Pandas while still getting data ?

帅比萌擦擦* 提交于 2019-12-24 16:42:59

问题


I'm currently using Pandas to get options data from yahoo. It works fine until there is a stock that does not have options, at which point the program crashes. I attempted to create exceptions and just have it pass but without luck. How can I have the program identify stocks with no options and just skip? Thanks.

The error I get is this: RemoteDataError: Data not available

Here's the code (I used a stock with no options to test--> 'GHC'):

from pandas_datareader.data import Options
import pandas as pd
from pandas import DataFrame
import datetime
import csv
import time
import sys

tickers = ['GHC']

for i in tickers:
option = Options(i,'yahoo')
data = option.get_all_data()

try:
    print data.head

except AttributeError:
    pass

except RemoteDataError:
    pass

回答1:


You can handle the RemoteDataError exception imported from pandas_datareader._utils:

from pandas_datareader._utils import RemoteDataError
from pandas_datareader.data import Options

tickers = ['GHC']

for i in tickers:
    try:
        option = Options(i, 'yahoo')
        data = option.get_all_data()
    except RemoteDataError:
        print("No information for ticker '%s'" % i)
        continue



回答2:


for i in tickers:
    try:
        option = Options(i,'yahoo')
        data = option.get_all_data()
    except RemoteDataError: # Add here correct expectation type...
        continue # What to do with 'i' and 'data', nulls?


来源:https://stackoverflow.com/questions/36249835/python-how-to-avoid-error-exceptions-in-pandas-while-still-getting-data

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!