如何检查股票代码是否为 yfinance 库

问题描述 投票:0回答:4

我正在尝试通过 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")

但现在除了列表中的股票之外,它不会打印任何内容。

有谁知道如何解决这个问题?谢谢!

python yfinance
4个回答
2
投票

2/22/23 更新

info
库中使用
yfinance
方法的问题越来越多。最近的问题在这里讨论:https://github.com/ranaroussi/yfinance/issues/1407。对于那些想要检查的人,另一种方法是简单地使用
history
方法并检查是否有最近可用的数据。例如,以下是
yf.Ticker('SPY').history(period='7d', interval='1d')
的输出:

                                Open        High  ...  Stock Splits  Capital Gains
Date                                               ...                             
2023-02-10 00:00:00-05:00  405.859985  408.440002  ...           0.0            0.0
2023-02-13 00:00:00-05:00  408.720001  412.970001  ...           0.0            0.0
2023-02-14 00:00:00-05:00  411.239990  415.049988  ...           0.0            0.0
2023-02-15 00:00:00-05:00  410.350006  414.059998  ...           0.0            0.0
2023-02-16 00:00:00-05:00  408.790009  412.910004  ...           0.0            0.0
2023-02-17 00:00:00-05:00  406.059998  407.510010  ...           0.0            0.0
2023-02-21 00:00:00-05:00  403.059998  404.160004  ...           0.0            0.0

对于非交易资产(在本例中为

FAKENAME
),可以看到以下输出:

FAKENAME: No data found, symbol may be delisted

将其包装成一个给出

True/False
输出的简洁函数的方法如下:

def check_available(asset: str) -> bool:
    """
    Checks if an asset is available via the Yahoo Finance API.
    """
    info = yf.Ticker(asset).history(
        period='7d',
        interval='1d')
    # return == period value for more precise check but may
    # need more complex handling to take into account non-
    # trading days, holidays, etc.
    return len(info) > 0

本质上,这表示“如果最近有数据,则资产可用”,这可能并非在所有情况下都是如此,因此请记住这一点。


1
投票

尝试获取股票信息,如果出现异常,您可能无法用它做更多事情:

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

查看这个合作实验室的演示。


1
投票

检查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"

0
投票

我是用 PyCharm 做的...希望它有帮助,如果我错过了什么,请告诉我!

import yfinance as yf

stock_input = input('Please enter the stock symbol:\n')

ticker_info = yf.Ticker(stock_input).info
if len(ticker_info) <= 1:
    print("Please Try Again!\nEnsure to provide a valid stock ticker!")             
    # Ticker Wrong
elif len(ticker_info) > 1:
    print("Place code to Run Analysis")                                             
    # Ticker Right
else:
    print("Invalid Input!")

输出(右侧代码):

Please enter the stock symbol:
aapl
Ticker Correct!
Place code to Run Analysis

Process finished with exit code 0

输出(股票代码错误):

Please enter the stock symbol:
asdas
404 Client Error: Not Found for url: https://query2.finance.yahoo.com/v10/finance/quoteSummary/ASDAS?modules=financialData%2CquoteType%2CdefaultKeyStatistics%2CassetProfile%2CsummaryDetail&corsDomain=finance.yahoo.com&formatted=false&symbol=ASDAS&crumb=qfrN2%2FdMLos
Ticker Wrong! Please Try Again!
Ensure to provide a valid stock ticker!

Process finished with exit code 0
© www.soinside.com 2019 - 2024. All rights reserved.