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
CodePudding user response:
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
CodePudding user response:
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.