Making yfinance errors propagate

1k views Asked by At

I'm trying to build an application allowing the user to add stocks to a portfolio, then perform an analysis of this portfolio. It is essential that only existing stocks, those for which data is available, be added. If the user inputs an invalid stock symbol, this needs to be handled. The obvious choice is some kind of try-except structure. I have tried this, but cannot figure out where my approach fails. Note: I am using yfinance to download the stock data.

def getData(self, period):
    try:
        stock = yf.Ticker(self.ticker)
        data = stock.history(period = period)
        return data
    except Exception as exception:
        print(exception)
        raise Exception

Inside a Stock class I'm implementing a getData() function. Using yfinance I create a ticker object, called stock, then try to download historic market data. This works fine in some cases (AAPL, TSLA, ..., real stock symbols).

In the main application I have a label which is to be updated if a stock is valid:

def extendPortfolio():
        try:
            stock = st.Stock(stock_entry.get().upper())
            data = stock.getData("1mo")
            self.portfolio.append(stock)
            portfolioString.set(portfolioString.get() + "\n" + stock.__str__())
        except Exception as exception:
            print(exception)

Using the Stock class functionality, a stock object is created, its data dowloaded, and in the best of possible worlds -- added to a tk.StringVar portfolio string. My problem is this: Whatever nonsense I decide to type in the entry, it gets added to the portfolio string, and thus appears in the label.

A message is displayed in the terminal stating: - {some nonsense sequence}: No data found, symbol may be delisted This message is most probably from the yfinance library itself. But does this mean the error was handled, too early? How can I make these errors propagate further up in the program, to a place where they need to be handled?

I hope the question is clear, please ask for clarifications if not. Thanks in advance for any help!

1

There are 1 answers

0
ecoguy On BEST ANSWER

If yfinance is unable to download the data, it will not raise an exception -- it provides an empty data frame. To make sure only valid stocks get added, check if the provided data frame in empty or not.

def getData(self, period):
    try:
        stock = yf.Ticker(self.ticker)
        data = stock.history(period = period)
        if data.empty:
            raise Exception
    except:
        print("data is empty")
        raise Exception
    else:
        return data

This solves the issue. I hope this will help people in the future.