I am making a request to yfinance to get data for a specific stock ticker and I want to handle the case that an invalid stock ticker has been entered. I tried the standard try and except duo but because yfinance automatically handles these cases it won’t let me handle it myself. Essentially the code continues on as if nothing happened I want to do something specific if this occurs.
import yfinance as yf
ticker = yf.Ticker("ABCDE")
try:
info = ticker.info
print(info)
except KeyError:
print(f"Cannot get info of {ticker}, it probably does not exist")
The above code results in this printed out:
yfinance.Ticker object
404 Client Error: Not Found for url: https://query2.finance.yahoo.com/v10/finance/quoteSummary/ABCDE?modules=financialData%2CquoteType%2CdefaultKeyStatistics%2CassetProfile%2CsummaryDetail&corsDomain=finance.yahoo.com&formatted=false&symbol=ABCDE&crumb=w1YRj9yLL98
{‘trailingPegRatio’: None}
Obviously the except is never called but I would really like it to. I appreciate any help 🙂