Search code examples
pythonpython-3.xpandasyahoo-financeyfinance

when there is no data available on yahoo finance, is it possible to return N/A instead of there being an error?


I'm trying to collect several pieces of data for a company at one time, yet one piece being missing results in an error. Is it possible to prevent this by returning 'N/A' instead?

import yfinance as yf
import pandas
comp = yf.Ticker("ERO")
print(comp.info['industry'], comp.info['sector'], 
comp.info['currentPrice'],comp.info['targetMeanPrice'])

this returns the error

"print(comp.info['industry'], comp.info['sector'], 
comp.info['currentPrice'],comp.info['targetMeanPrice'])
KeyError: 'targetMeanPrice'"

is it possible to return N/A (there is no target price available on yahoo finance) and the 3 other pieces of data, rather than there being an error?


Solution

  • def get_target_price(comp):
        try: 
            return yf.Ticker(comp).info['targetMeanPrice']
        except:
            return pandas.NA
    
    get_target_price('AAPL') # 188.47
    get_target_price('ERO') # <NA>