I have an empty dictionary, and need to pull industry info base on ticker symbols. I would then like to add all tickers under the same industry in a list with the industry as the key.
For example, the end would look something like the below:
{'technology': ['AAPL', 'ADBE'], 'Consumer Cyclical': ['TSLA', 'UA']}
Here is what I’ve been working on with no success:
import yfinance as yf
tickers = ['AAPL', 'ADBE', 'AMD', 'AMAT', 'AMZN', 'ANF',
'APA', 'BA', 'BABA', 'BBY', 'BIDU', 'BMY', 'BRX', 'BZUN',
'C', 'CAT', 'CLF', 'CMCSA', 'CMG', 'COST', 'CRM', 'CVX',
'DE', 'EBAY', 'FB', 'FCX', 'FDX', 'FSLR',
'GILD', 'GM', 'GME', 'GOOG','GPRO', 'GS', 'HAL', 'HD',
'HIG', 'HON', 'IBM', 'JCPB', 'JD', 'JPM', 'LULU', 'LYG',
'MA', 'MCD', 'MDT', 'MS', 'MSFT','MU', 'NEM', 'NFLX',
'NKE','PBR', 'QCOM', 'SLB', 'SNAP', 'SPG', 'TSLA', 'TWTR',
'TXN', 'UA', 'UAL', 'V', 'VZ' 'X', 'XLNX', 'ZM']
sector_dict = dict()
for ticker in tickers:
try:
sector = yf.Ticker(ticker).info['sector']
sector_dict[sector].update(ticker)
except:
sector_dict.update({'no sector':[ticker]})
The below just gives me an empty dictionary. Does anybody see where the issue is?
2
Answers
You should always avoid catch-all exceptions.
Your original example was masking the fact that
update
isn’t a list method.When you subscript a python dictionary like
sector_dict[ticker]
, we’re now talking about the value associated with theticker
key. In this case a list.Also update isn’t used like that, so I think it was masking a second error. It’s usage is to update a dictionary with another dictionary or an iterable. Not to update an existing entry.
Finally, the
try
clause should be as small as possible, in order to be sure where the error is coming from or at least you can guarantee there won’t be conflicting exceptions such as this case.I think that’s why your list is returning with only the last ticker in my previous solution, as
yf.Ticker
causes aKeyError
and theKeyError
exception gets called instead of the last one.Here’s how I’d do it:
Assuming the information you need is returned from the API call – the code below may work for you.
output