"KeyError" в yfinance - PYTHON
Я пытаюсь анализировать акции в Python с помощью API "yfinance". Я заставляю программу работать нормально большую часть времени. Однако, когда не удается "найти" одно из полей, возникает ошибка (KeyError). Вот фрагмент моего кода.
import yfinance as yf
stock = yf.Ticker(stock)
pegRatio = stock.info['pegRatio']
print(pegRatio)
if pegRatio > 1:
print("The PEG Ratio for "+name+" is high, indicating that it may be overvalued (based on projected earnings growth).")
if pegRatio == 1:
print("The PEG Ratio for "+name+" is 1, indicating that it is close to fair value.")
if pegRatio < 1:
print("The PEG Ratio for "+name+" is low, indicating that it may be undervalued (based on projected earnings growth).")
Это была ошибка Traceback (последний вызов последним): строка 29, в файле industry = stock.info['industry'] KeyError: 'industry'
Мой главный вопрос: как заставить код игнорировать ошибку и запускать остальную часть кода?
1 ответ
Обработка ошибок в Python
Как уже прокомментировал Николас , вы найдете множество руководств, сообщений в блогах и видео в Интернете. Также несколько базовых книг по Python, посвященных «обработке ошибок».
Контрольная структура в Python состоит как минимум из двух ключевых слов.
try
а также
except
, часто называемый блоком try-except. Также есть 2 необязательных ключевых слова
else
а также
finally
.
Как обернуть ваши несостоятельные утверждения
import yfinance as yf
try: # st art watching for errors
stock = yf.Ticker(stock) # the API call may also fail, e.g. no connection
pegRatio = stock.info['pegRatio'] # here your actual exception was thrown
except KeyError: # catch unspecific or specific errors/exceptions
# handling this error type begins here: print and return
print "Error: Could not find PEG Ratio in Yahoo! Finance response!"
return
# the happy path continues here: with pegRatio
print(pegRatio)
if pegRatio > 1:
print("The PEG Ratio for "+name+" is high, indicating that it may be overvalued (based on projected earnings growth).")
if pegRatio == 1:
print("The PEG Ratio for "+name+" is 1, indicating that it is close to fair value.")
if pegRatio < 1:
print("The PEG Ratio for "+name+" is low, indicating that it may be undervalued (based on projected earnings growth).")