0

This is my first experience in Python and Stackoverflow :) I try to update my xls file with Portfolio using Yfinance. I'm interested in two parameters on each stock : current price and sector. I try to update my Pandas DataFrame using the code below. It works fine for the "Price" but I can't extract "Sector" - get an error below.

What I'm doing wrong here?

Well, there is a "sector" key in the dictionary for each stock. I try to update the Excel file, so there isn't much code

---------------------------------------------------------------------------
KeyError                                  Traceback (most recent call last)
Cell In[271], line 7
      5 stock_info = yf.Ticker(ticker).info
      6 price = stock_info['regularMarketPrice']
----> 7 sector = str(stock_info['sector'])
      8 ibkr.loc[i, ['Price of share']] = price
      9 ibkr.loc[i, ['Sector']] = sector

KeyError: 'sector'

The code:

import yfinance as yf
import pandas as pd
import numpy as np <br/>  ibkr = pd.read_excel("BKR_WISHLIST.xlsx") <br/> ibkr.columns = ['Company_name', 'Symbol', 'Number of shares', 'Price of share', 'Total_value_share, USD'] <br/> ibkr.dropna(subset=['Total_value_share, USD', 'Number of shares'], inplace=True) <br/> ibkr.insert(2, "Sector", "XXX") <br/> ibkr.reset_index(drop = True, inplace = True) <br/>  my_tickers = ibkr["Symbol"].tolist()
tickers = yf.Tickers(my_tickers)
# i = 0
for ticker in my_tickers:
    stock_info = yf.Ticker(ticker).info
    # price = stock_info['regularMarketPrice']
    # sector = stock_info['sector']
    ibkr.loc[i, 'Price of share'] = stock_info['regularMarketPrice']
    #ibkr.loc[i, 'Sector'] = stock_info["sector"]
    i += 1
    my_tickers = ibkr["Symbol"].tolist()
tickers = yf.Tickers(my_tickers)
i = 0
for ticker in my_tickers:
    stock_info = yf.Ticker(ticker).info
    price = stock_info['regularMarketPrice']
    sector = stock_info['sector']
    ibkr.loc[i, ['Price of share']] = price
    ibkr.loc[i, ['Sector']] = sector
    i = I+1
Alef
  • 11
  • 3
  • Can you try like this ```for ticker in my_tickers: stock_info = yf.Ticker(ticker).info ibkr.loc[i, "Sector"] = stock_info["sector"] ibkr.loc[i, "Price"] = stock_info["regularMarketPrice"] i += 1``` – twister_void Jan 01 '23 at 21:54
  • Thanks for your reply. But wha't the principal difference? The code is better but it still gives the same error : --------------------------------------------------------------------------- KeyError Traceback (most recent call last) Cell In[272], line 9 6 # price = stock_info['regularMarketPrice'] 7 # sector = stock_info['sector'] 8 ibkr.loc[i, 'Price of share'] = stock_info['regularMarketPrice'] ----> 9 ibkr.loc[i, 'Sector'] = stock_info["sector"] 10 i += 1 KeyError: 'sector' – Alef Jan 01 '23 at 22:05
  • Basically, Keyerror states it is not able to find the sector. Can you share a bit more of your code? Or can you check when you are debugging is it able find sector ? – twister_void Jan 01 '23 at 22:11
  • Well, there is a "sector" key in the dictionary for each stock. – Alef Jan 01 '23 at 22:18
  • @twister_void I think that "sector" may be missing in one of the enquiries (I have quite a lot tickers). How can I can skip NA (or fill in with NaN) in my loop? – Alef Jan 01 '23 at 23:01
  • @twister_void I meant for Sector. If it's NaN (no value in the string) then fill with "Undefined". – Alef Jan 01 '23 at 23:19
  • @twister_void or maybe there isn't even a key "sector" for some of the tickers. Is it possible to skip or fill the gap? – Alef Jan 01 '23 at 23:32
  • i added answer to reduce lot of comments hope answer helps if yes then please accept as answer – twister_void Jan 01 '23 at 23:35

4 Answers4

1

Thank you guys for your help! I don't know how to @ you here, but I hope you will this post.

The problem was that the stock_info for some objects (ETF) did not have a "sector" key. So with help of @Damian Satterthwaite-Phillips and @twister_void this code did work:

my_tickers = ibkr["Symbol"].tolist()
tickers = yf.Tickers(my_tickers)
i = 0
for ticker in my_tickers:
    stock_info = yf.Ticker(ticker).info
    ibkr.loc[i, 'Sector'] = stock_info.get('sector', 'NA')
    ibkr.loc[i, "Price of share"] = stock_info["regularMarketPrice"]
    i += 1
Alef
  • 11
  • 3
0

There might be a problem with the value in the sector that's why KeyError is raised because the value is not found in some case you can handle with loop

for ticker in my_tickers:
    stock_info = yf.Ticker(ticker).info
    ibkr.loc[i, "Sector"] = stock_info["sector"]  
    if stock_info["sector"] is None or stock_info["sector"] == "":
        ibkr.loc[i, "Sector"] = "NA"
    ibkr.loc[i, "Price"] = stock_info["regularMarketPrice"]
    i += 1



twister_void
  • 1,377
  • 3
  • 13
  • 31
0

The stock_info object does not have a sector key: For example,

yf.Ticker('MSFT').info

returns

{'regularMarketPrice': None, 'preMarketPrice': None, 'logo_url': ''}

It looks like it might have had sector at one point (e.g.: How to get Industry Data from Yahoo Finance using Python?), but it may be that Yahoo Finance no longer publishes these data.

0

The API seems to be broken. I have tried upgrading yfinance from 1.86 all the way up to 2.x. Whether I put in a stock ticker or a fund ticker or ETF, I only get back the 3 keys: {'regularMarketPrice': None, 'preMarketPrice': None, 'logo_url': ''}. I don't think this is a "sector" problem at all... it seems more like a Yahoo problem... noworky.

  • Hello! No, it works just fine. You can check it here: https://github.com/AlefTester/Yfiance_portfolio Note that there is problem with yFinance and `Ticker` : it doesn't work if yFinance not updated to 0.2.4! update it with `pip install yfinance==0.2.4` – Alef Jan 23 '23 at 20:44