Carter Olk
Carter Olk

Reputation: 1

How to ignore "KeyError" in Python

I am trying to analyze stocks within python using the api "yfinance." I get the program to run just fine most of the time. However, when it is unable to 'find' one of the fields, it throughs up an error (KeyError). Here is a snippet of my code.

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

This was the error Traceback (most recent call last): line 29, in industry = stock.info['industry'] KeyError: 'industry'

My main question is how do I get the code to basically ignore the error and run the rest of the code?

Upvotes: 0

Views: 1097

Answers (1)

hc_dev
hc_dev

Reputation: 9377

Error Handling in Python

Like Nicolas commented already, you will find many tutorials, blog posts and videos in the web. Also some basic Python books that cover "Error Handling".

The control-structure in Python consists of at least 2 keywords try and except, often named try-except block. There are also 2 optional keywords else and finally.

How to wrap your failing statements

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

Upvotes: 1

Related Questions