使用异常来避免yahoofinance错误

huangapple go评论124阅读模式
英文:

Using Exception to avoid yahoofinance error

问题

代码中的问题在于使用了错误的异常类。要获得期望的输出,你需要捕获 yf.utils.exceptions.HTTPError 异常,而正确的异常类应该是 yfinance.exceptions.HTTPError。以下是修正后的代码和期望的输出:

  1. import yfinance as yf
  2. stcks = ['AXSM', 'FB', 'AAPL']
  3. for i in stcks:
  4. try:
  5. sec = yf.Ticker(i).info['sector']
  6. except yf.exceptions.HTTPError as err:
  7. print('error')
  8. continue
  9. else:
  10. print('hi')

修正后的代码应该输出:

  1. hi
  2. error
  3. hi

这样,当无法获取列表中某个项目的数据时,代码将继续迭代处理下一个项目。

英文:

I'm simply trying to use an exception to handle HTTPErrors for items like 'FB' to continue iterating through the list but I can't seem to get around the issue. Code:

  1. stcks = ['AXSM', 'FB', 'AAPL']
  2. for i in stcks:
  3. try:
  4. sec = yf.Ticker(i).info['sector']
  5. except yf.utils.exceptions.HTTPError as err:
  6. print('error')
  7. continue
  8. else:
  9. print('hi')

Output

  1. hi
  2. HTTPError: 404 Client Error: Not Found for url: https://query2.finance.yahoo.com/v10/finance/quoteSummary/FB?modules=summaryProfile%2CfinancialData%2CquoteType%2CdefaultKeyStatistics%2CassetProfile%2CsummaryDetail&ssl=true

During handling of the above exception, another exception occurred:

  1. AttributeError
  2. Traceback (most recent call last)
  3. Cell In[243], line 5
  4. 3 try :
  5. 4 sec = yf.Ticker(i).info['sector']
  6. ----> 5 except yf.utils.exceptions.HTTPError as err:
  7. 6 print('error')
  8. 7 continue
  9. AttributeError: module 'yfinance.utils' has no attribute 'exceptions'

How can I get the desired output provided that I cannot get data for one of the items in the list?:

  1. hi
  2. hi

答案1

得分: 1

使用requests异常来捕获缺失的股票代码(HTTPError):

  1. import requests
  2. stcks = ['AXSM', 'FB', 'AAPL']
  3. for i in stcks:
  4. try:
  5. sec = yf.Ticker(i).info['sector']
  6. except requests.HTTPError as err:
  7. print('error')
  8. continue
  9. else:
  10. print('hi')

输出:

  1. hi
  2. error
  3. hi
英文:

Use requests exception to catch missing tickers (HTTPError):

  1. import requests
  2. stcks = ['AXSM', 'FB', 'AAPL']
  3. for i in stcks:
  4. try:
  5. sec = yf.Ticker(i).info['sector']
  6. except requests.HTTPError as err:
  7. print('error')
  8. continue
  9. else:
  10. print('hi')

Output:

  1. hi
  2. error
  3. hi

huangapple
  • 本文由 发表于 2023年6月26日 11:50:08
  • 转载请务必保留本文链接:https://go.coder-hub.com/76553415.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定