Yahoo Finance - get sector data for dynamic list of tickers

949 Views Asked by At

I am trying to get the sectors for a list of tickers and add them to a list. I pull the list of tickers from a workbook stored on my computer which is updated at the end of each trading day, so I don't want to hard-code the tickers.

All the tickers taken from the workbook are stored in ticker_list. I use a loop to iterate through the list and retrieve the sector for each ticker:

import yfinance as yf
sector_list=[]

for tik in ticker_list:
    ticker=yf.Ticker(tik)
    sector=ticker.info['sector']
    sector_list.append(sector)
    
sector_list

This throws an error:

KeyError: 'sector'

This code works for other Yahoo Finance attributes, such as 'beta'. Anyone know why it isn't working as written above for the sector attribute?

1

There are 1 best solutions below

1
On

The following codes will work for you.

import yfinance as yf
ticker_list = ["AAPL", "GOOG", "MSFT"]

sector_list=[]

for tik in ticker_list:
    ticker=yf.Ticker(tik)
    sector=ticker.info['sector']
    sector_list.append(sector)
    
sector_list

Output:

['Technology', 'Communication Services', 'Technology']