 Contributor:
TheAutomatic.net
Visit: TheAutomatic.net Blogger, TheAutomatic.net, and Senior Data Scientist

In this post we will explore how to download fundamentals data with Python. We’ll be extracting fundamentals data from Yahoo Finance using the yahoo_fin package. For more on yahoo_fin, including installation instructions, check out its full documentation here.

Getting started

Now, let’s import the stock_info module from yahoo_fin. This will provide us with the functionality we need to scrape fundamentals data from Yahoo Finance. We’ll also import the pandas package as we’ll be using that later to work with data frames.

import yahoo_fin.stock_info as si
import pandas as pd

Next, we’ll dive into getting common company metrics, starting with P/E ratios.

How to get P/E (Price-to-Earnings) Ratios

There’s a couple ways to get the current P/E ratio for a company. First, we can use the get_quote_table method, which will extract the data found on the summary page of a stock (see here).

quote = si.get_quote_table(“aapl”)

Next, let’s pull the P/E ratio from the dictionary that is returned.

quote[“PE Ratio (TTM)”] # 22.71

A company’s P/E ratio can also be extracted from the get_stats_valuation method. Running this method returns a data frame of the “Valuation Measures” on the statistics tab for a stock.

val = si.get_stats_valuation(“aapl”)

val = val.iloc[:,:2]

val.columns = [“Attribute”, “Recent”]

Next, let’s extract the P/E ratio.

float(val[val.Attribute.str.contains(“Trailing P/E”)].iloc[0,1])

How to get P/S (Price-to-Sales) Ratios

Another popular metric is the P/S ratio. We can get the P/S ratio, along with several other other metrics, using the same get_stats_valuation method. Let’s use the object we pulled above, currently stored as val.

Then, we can get the Price/Sales ratio like below.

Getting fundamentals stats for many stocks at once

Now, let’s get the Price-to-Earnings and Price-to-Sales ratios for each stock in the Dow. We could also do this for a custom list of tickers as well.

# get list of Dow tickers
dow_list = si.tickers_dow()

# Get data in the current column for each stock’s valuation table
dow_stats = {}
for ticker in dow_list:
temp = si.get_stats_valuation(ticker)
temp = temp.iloc[:,:2]
temp.columns = [“Attribute”, “Recent”]

dow_stats[ticker] = temp

# combine all the stats valuation tables into a single data frame
combined_stats = pd.concat(dow_stats)
combined_stats = combined_stats.reset_index()

del combined_stats[“level_1”]

# update column names
combined_stats.columns = [“Ticker”, “Attribute”, “Recent”]