使用异常来避免yahoofinance错误

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

Using Exception to avoid yahoofinance error

问题

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

import yfinance as yf

stcks = ['AXSM', 'FB', 'AAPL']
for i in stcks:
    try: 
        sec = yf.Ticker(i).info['sector']
    except yf.exceptions.HTTPError as err:
        print('error')
        continue
    else: 
        print('hi')

修正后的代码应该输出:

hi
error
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:

stcks = ['AXSM', 'FB', 'AAPL']
   for i in stcks:
        try: 
            sec = yf.Ticker(i).info['sector']
        except yf.utils.exceptions.HTTPError as err:
            print('error')
            continue
        else: 
            print('hi')

Output

hi
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:

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

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?:

hi
hi

答案1

得分: 1

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

import requests

stcks = ['AXSM', 'FB', 'AAPL']
for i in stcks:
    try: 
        sec = yf.Ticker(i).info['sector']
    except requests.HTTPError as err:
        print('error')
        continue
    else: 
        print('hi')

输出:

hi
error
hi
英文:

Use requests exception to catch missing tickers (HTTPError):

import requests

stcks = ['AXSM', 'FB', 'AAPL']
for i in stcks:
    try: 
        sec = yf.Ticker(i).info['sector']
    except requests.HTTPError as err:
        print('error')
        continue
    else: 
        print('hi')

Output:

hi
error
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:

确定