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