Hi,
when I run this code to get the fundamental data for the S&P500 stocks:
# Import libraries
import yfinance as yf
import pandas as pd
# List of all S&P500 tickers
tickers = pd.read_html(
'https://en.wikipedia.org/wiki/List_of_S%26P_500_companies')[0]
# Variable 'stocks' to store the list of all ticker names
stocks = tickers.Symbol
# Uncomment the below line to test on a smaller list of stocks
#stocks = ["AAPL", "MSFT", "AMZN"] # Feel free to add more
# Create a dataframe called 'data' with column stock
data = pd.DataFrame(columns=['Stock'])
# A loop that iterates through each ticker in the list passed earlier
# Here, we get the data for ticker i and store it in respective variables
for i in stocks:
# Note: In the below code, we have first converted i to yf.Ticker object
profitMargins = yf.Ticker(i).get_info()['profitMargins']
revenueGrowth = yf.Ticker(i).get_info()['revenueGrowth']
returnOnEquity = yf.Ticker(i).get_info()['returnOnEquity']
# Print the ticker name and fundamental attributes at each iteration
print(i, profitMargins, revenueGrowth, returnOnEquity)
# Add the new data to the dataframe 'data'
data = data.append({'Stock': i, 'profitMargins': profitMargins,
'revenueGrowth': revenueGrowth, 'returnOnEquity': returnOnEquity}, ignore_index=True)
# Display the dataframe
data
I read this error:
KeyError Traceback (most recent call last) <ipython-input-1-e503ae675393> in <module> 20 for i in stocks: 21 # Note: In the below code, we have first converted i to yf.Ticker object ---> 22 profitMargins = yf.Ticker(i).get_info()['profitMargins'] 23 revenueGrowth = yf.Ticker(i).get_info()['revenueGrowth'] 24 returnOnEquity = yf.Ticker(i).get_info()['returnOnEquity'] KeyError: 'profitMargins'