如何检查代码是否为 yfinance 库

How to check if a ticker is yfinance library

我正在尝试通过 yfinance 查找有关某些代码的信息。但是,每当我尝试搜索不存在的代码信息时,我 运行 就会出错。例如,这是我的代码。

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)

这是我收到的错误:

/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'

为了解决这个问题,我尝试了:

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")

但现在除了列表中的代码,它不会打印任何内容。

有谁知道如何处理这个问题?谢谢!

尝试获取自动收报机的信息,如果出现异常,您可能无法用它做更多事情:

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}")

查看 this colab 上的演示。

检查 ticker.info 是否可行对我不起作用。 我使用字典的“regularMarktPrice”索引解决了它,函数 ticker.info 返回:

相关 if 语句:

if (ticker.info['regularMarketPrice'] == None):
        raise NameError("You did not input a correct stock ticker! Try again.")

完整功能:

def pick_stock():
    ticker_input = input("Enter Stock-Ticker:")
    global ticker
    ticker = yf.Ticker(str(ticker_input))
    info = None
    if (ticker.info['regularMarketPrice'] == None):
        raise NameError("You did not input a correct stock ticker! Try again.")
    else:
        return "\n \nThe Ticker '" + ticker_input.upper() + "' was chosen \n \n"