Search code examples
pythondataframefor-loopcontinueyfinance

How to skip an iteration that is returning error message


Below is code to get stock options data based on the stock's specific ticker symbol from a list (ticker). It is also based on the stock option's expiration date. But I am getting this error: "ValueError: Expiration 2021-07-30 cannot be found. Available expiration are: [2022-01-21, 2023-01-20]". I believe that is because certain stock's do not have options that expire on 2021-07-30, but somehow got in my list. How would I incorporate a continue statement to skip the option ticker if it does not have the available expiration date: 2021-07-30?

opt_df = DataFrame()

for symbol in tickers:
    ticker = yf.Ticker(symbol)
    opt = ticker.option_chain('2021-07-30')
    opt_df.append(opt)

Solution

  • Try/except statement with ValueError exception?

    opt_df = DataFrame()
    
    for symbol in tickers:
        try:
            ticker = yf.Ticker(symbol)
            opt = ticker.option_chain('2021-07-30')
            opt_df.append(opt)
        except ValueError:
            continue