I was trying to get market cap data of stocks using yfinance. Here is my code:
import yfinance as yf
import numpy as np
from pandas_datareader import data
import pandas as pd
import pandas_datareader as web
tickers=pd.read_excel('C:/Users/Administrator/Desktop/bse.xlsx')
UndervaluedCompanies=[]
market_cap_data = web.get_quote_yahoo(tickers)['marketCap']
# Get the P/E ratio directly
pe_data = web.get_quote_yahoo(tickers)['trailingPE']
# print stock and p/e ratio
for stock, pe in zip(tickers, pe_data):
print(stock, pe)
By using this code I get the following error:
*** IndexError: list index out of range
I attach screenshots of the error and also of the DataFrame
I referred to the url as specified below as to circumvent this issue.
Yfinance IndexError: list index out of range
The modified code made using the fix given in the above url is:
import yfinance as yf
import pandas as pd
import pandas_datareader as web
import pandas_datareader as pdr
from pandas_datareader import data
data =pd.read_excel('C:/Users/Administrator/Desktop/bse.xlsx')
ticker = data['Ticker']
rows = []
for ticker in ticker:
try:
market_data = data.get_quote_yahoo(ticker)['marketCap']
except IndexError as e:
print(f'{ticker}: {e}') # print the ticker and the error
print('\n')
By using the above code I am getting an error as described in the screenshot:
By using the code I am getting the following error:
KeyError: 'regularMarketPrice
The screenshot of the same is as shown:
On clicking on the file which is mentioned in error we can see that the error is caused by the function def_read_lines. The screenshot is attached below:
I did try using the yahooquery library but in the values dataframe all the values are populated as error values and not the actual market cap values as shown:
I am not understanding where am I going wrong. Any help will be appreciated
It could be that some of the ticker in your excel file aren't listed or there is some kind of naming issue.
So i solved using try to download the stocks one by one with data.get_quote_yahoo('ticker')
and then with pd.concat()
I obtained my dataframe.
import yfinance as yf
from pandas_datareader import data
tickers=pd.read_excel('C:/Users/Administrator/Desktop/bse.xlsx')
market_data=[]
for ticker in tickers:
print(ticker)
try:
market_data.append(data.get_quote_yahoo(ticker)['marketCap'])
except:
print('Error with: ', ticker)
df=pd.concat(market_data, axis=0)
display(df)