llamallama101092030
llamallama101092030

Reputation: 81

Method to Skip Errors in For Loop python

I am writing a for loop in Python that iterates over a list of the NASDAQ ticker symbols. Each symbol is within a column, tickers['Stock Symbol'], and I am using the yfinance package to retrieve price information. To simplify the example, let's say I just want the price date for 01-01-2018. My code then looks like:

import yfinance as yf
tickers = pd.read_csv("/nasdaq.csv")

tickerData = []
for i in range(1114): 
  price = yf.download(tickers[i], 
                      start='2018-01-01', 
                      end='2018-01-01', 
                      progress=False)
  tickerData.append(price)

The issue I have with dates I am working with is that some of the companies were not around or public on the specific date, and therefore generate an error message. I was wondering if there is a python function which will simply skip over those stocks that generate errors in this?

I am still new to Python, so I am sorry about any formatting issues here. I appreciate your feedback!

Upvotes: 2

Views: 1980

Answers (2)

M.qaemi Qaemi
M.qaemi Qaemi

Reputation: 97

following answer of Afeef janjua. you can log this errors to a file to know if only this error happens or how many companies did not have data and so on like this:

import logging    
logging.basicConfig(filename='example.log',level=logging.DEBUG)

for i in range(1114): 
   try:
      price = yf.download(i, start='2018-01-01', end='2018-01-01', progress=False)
      tickerData.append(price)
    except Exception as e:
      logging.debug("company number {} did not have data. error:{}".format(i, e))

Upvotes: 0

Afeef Janjua
Afeef Janjua

Reputation: 659

The simplest thing you can do is to add a try/except block like this

for i in range(1114): 
    try:
        price = yf.download(i, start='2018-01-01', end='2018-01-01', progress=False)
        tickerData.append(price)
    except Exception:
        pass

In the code above I am catching a generic exception since I don't know the error you are receiving. You have to replace Exception with the type of exception you are receiving

Upvotes: 3

Related Questions