Fundamental Data

Hi,

I would like to get the code to compile the csv file about Fundamental Data, in the Unsupervised Learning in Trading course.

Hi Alessandro,



You can use the following code to get the fundamental data for the 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

Additionally, I recommend you go through the free course on Getting Market Data: Stocks, Crypto, News & Fundamental. This course will help you understand how to fetch various data like pricing data of stocks, fundamental data, tweets by keyword and news headlines data, etc.

And you can also give the following blog a read:
Stock Market Data: Obtaining Data, Visualization & Analysis in Python

I hope this was helpful. 

Hi,

The data is downloaded very slowly and after a certain number it stops giving an error message. When the download resumes some data is null.

Hi Alessandro,

It may be possible that some stocks that are currently a component of the S&P 500 index were not necessarily part of the index in the past. This could be the case especially when you are trying to the historical data for a period of 3+ years.



If you are facing this issue for a few stocks, you can use a try-except block for better exception handling.



On the other hand, if this problem persists for a significant number of stocks, then you can try experimenting with different data vendors for getting the fundamental data.



I hope this helps.