Search code examples
pythonexceptionpandasdataframeyahoo-finance

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


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

Solution

  • 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