YFinance_Can't get data from dictionary_Python_Jupyter notebook
Question:
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
Answers:
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
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.
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
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.
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
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
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.
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
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.