Search code examples
pythonyahoo-financeyfinance

Skip over errors when looping throgh yahoo finance tickers with yfinance


I am downloading data from yahoo finance with yfinance in Python and looping through a few hundred tickers but randomly I get an error with some of the tickers which breaks the whole process.

Is there a way to kind of capture the exception and continue with the loop but just ignore that 'faulty' ticker when there is an error so I don't have to start from the beginning every time?

This is my code

stockslist = pd.read_csv('KuCoins.csv')

combined = yf.download("SPY", start ="2022-01-01", end="2022-01-02")
 
for index, row in stockslist.iterrows():
   ticker = (row['ticker'])
  
   
   data = yf.download(ticker, start ="2022-03-01", end=currentDate)

and this is the error I get:

** [100%**] 1 of 1 completed

1 Failed download:

  • KDON-USD: No data found, symbol may be delisted Traceback (most recent call last):

Exception: inputs are all NaN **


Solution

  • You can use try-except block to handle with that.

    for index, row in stockslist.iterrows():
        try:
            ticker = (row['ticker'])
            data = yf.download(ticker, start ="2022-03-01", end=currentDate)
        except Exception as e:
             print ("There is an issue with ticker: {} and we are passing it".format(ticker))
             pass