pythonyfinance

How to check if a ticker is yfinance library


I'm trying to find some information on some tickers through yfinance. However, I run into an error whenever I try to search up information on a ticker that doesn't exist. For example, this is the code I had.

import yfinance as yf

with open("/2019.txt") as f:
    content = f.readlines()
# content is a list with all tickers in "/2019.txt"
content = [x.strip() for x in content] 

print(content)

for x in content:
    y = yf.Ticker(x)
    z = y.info['volume']
    print(x)
    print(z)

This is the error I received:

/usr/local/lib/python3.6/dist-packages/yfinance/base.py in _get_fundamentals(self, kind, proxy)
        338                 self._info.update(data[item])
        339 
    --> 340         self._info['regularMarketPrice'] = self._info['regularMarketOpen']
        341         self._info['logo_url'] = ""
        342         try:
    
    KeyError: 'regularMarketOpen'

To fix this I tried:

import yfinance as yf

with open("/2019.txt") as f:
    content = f.readlines()
# content is a list with all tickers in "/2019.txt"
content = [x.strip() for x in content] 

print(content)

for x in content:
    y = yf.Ticker(x)
    if(y==1):
      z = y.info['volume']
      print(x)
      print(z)
    elif(y==0):
      print(y)
      print( "does not exist")

But now it doesn't print anything except the tickers in the list.

Does anyone know how to approach this? Thanks!


Solution

  • Try to get the info of the ticker and if you get an exception you probably cannot do much more with it:

    import yfinance as yf
    
    for t in ["MSFT", "FAKE"]:
      ticker = yf.Ticker(t)
      info = None
    
      try:
        info = ticker.info
      except:
        print(f"Cannot get info of {t}, it probably does not exist")
        continue
      
      # Got the info of the ticker, do more stuff with it
      print(f"Info of {t}: {info}")
    

    See a demo on this colab.