FMP

FMP

Enter

Price-to-Earnings ratio is a relative valuation tool. It is used by investors to find great companies at low prices. In this post, we will build a Python script

What is Price To Earnings Ratio and How to Calculate it using Python

-

twitterlinkedinfacebook
blog post cover photo

Image credit: Job Savelsberg

Price-to-Earnings ratio is a relative valuation tool. It is used by investors to find great companies at low prices. In this post, we will build a Python script to calculate Price Earnings Ratio for comparable companies.

Photo by Skitterphoto on Pexels

Price Earnings Ratio and Comparable Companies

Comparable companies are companies operating in the same sector and with similar market capitalisation. They are very useful when we use multiples, such as the price earnings ratio, for valuation purposes.

In this post, we will start by identifying all comparable companies trading in the NASDAQ stock exchange. Then, we will filter out companies in the technological sector and with a market capitalisation between $10 and $100 billions.

Then, we will build a Python function to obtain each of the companies Price Earnings (PE) ratio.

What is Price to Earnings Ratio?

Price to Earnings (P/E) ratio is a ratio often used to value companies. It is a relative valuation measure in terms that it should be used only to compare similar companies. Alternatively, it the PE ratio can also be used to value a company based on its past performance.

How is the Price to Earnings Ratio Calculated?

P/E is calculated by dividing the market capitalisation of a company by its net income. P/E ratios may be calculated in two ways:

  • On one hand, we can calculate them using historical data, what is called, trailing PE ratio.

  • On the other hand, we could also use analysis forecast on future earnings to calculate the forward P/E ratio.

For this post, we will be computing trailing P/E ratios working with historical data.

What the Price To Earnings Ratio tell us?

The P/E ratio is telling us how many times earnings we need to pay in order to get a stock of the company.

For instance, if the P/E ratio of Apple is 5, it means that we need to pay 5 times the earnings reported by Apple (if using trailing PE ratio) in order to buy a stock of Apple in the market.

Enough theory, let's start building the tool.

How to find Comparable Companies with Python?

First, we will make a request to get 1000 symbols of companies listed in the NASDAQ stock exchange.

Next, we will store the results in a variable named contains a list of dictionaries. Each dictionary contains the symbol and name of the company as shown below.

import requests

demo = 'YOUR API KEY'

querytickers = requests.get(f'https://fmpcloud.io/api/v3/search?query=&exchange=NASDAQ&limit=500&apikey={demo}')

querytickers = querytickers.json()

list_500 = querytickers

print(list_500)

How to Calculate Price Earnings with Python?

Next, we will build a function to calculate the Price-to-Earnings ratio (P/E). Therefore, we need two elements to compute a company's Price-to-Earnings ratio. First, Market Capitalisation and second Net Income.

Lets then extract this information for each of the companies included in our variable. As we did before, we will use a financialmodelingprep to extract income statement data and company profiles. Below getPricetoEarnings function will do the work for us.

The function will compute the Price-to-Earnings ratio. It will also add the result to a dictionary named PtoE. The key of the dictionary will be the name of the company:

def getPricetoEarnings(stock):

PtoE = {}

IS = requests.get(f'https://financialmodelingprep.com/api/v3/income-statement/{stock}?apikey={demo}')

IS = IS.json()

earnings = float(IS[0]['netIncome'])

company_info = requests.get(f'https://financialmodelingprep.com/api/v3/company/profile/{stock}?apikey={demo}')

company_info = company_info.json()

market_cap = float(company_info['profile']['mktCap'])

PtoEarnings = market_cap/earnings

PtoE[stock] = PtoEarnings

return PtoE

#Example of new function for Apple

getPricetoEarnings('AAPL')

Calculating P/E for Comparable Companies

Now that we have our list of companies and the PE function built, we can move forward. We will use the getPricetoEarnings function to calculate Price-to-Earning ratio for each of the companies.

Before applying the function, we need to extract the company symbol for each company out of the variable. We will iterate trough the list of companies. Then extract the symbol to finally append it to a list named :

stocks = []

count = 0

for item in list_500:

count = count +1

#Stop after storing 500 stocks

if count < 500:

stocks.append(item['symbol'])

Having now the symbol or ticker of all companies, it would be interesting to find out which of these companies are really comparable. For example, we should not compare ratios between companies operating in different sectors. Neither, compare companies having different sizes.

In order to find out real comparable companies, we will filter companies which meet below two conditions:

  • The sector of the company will be Technology.

  • And companies should have a Market Capitalisation between $10 and $100 billions.

Let's translate these two conditions into Python. We can do this with below code. First, we iterate through each of the companies in our list. Then, we make an API request for each of the stocks in order to extract sector and market capitalisation information.

Finally, we use if-statements and getPricetoEarnings function if both the sector of the stock is Technology and the market capitalisation is between $10 and $100 billions.

result = []

for item in stocks:

profile = requests.get(f'https://financialmodelingprep.com/api/v3/company/profile/{item}?apikey={demo}')

profile = profile.json()

try:

sector = profile['profile']['sector']

mktcap = profile['profile']['mktCap']

mktcap = float(mktcap)/1000

if ((sector == 'Technology') & (10000 <= mktcap <= 100000)):

try:

result.append(getPricetoEarnings(item))

except:

pass

except:

pass

Wrapping Up

One of the pitfalls of the P/E ratio is that if we are in the peak or bottom of the business cycle, we are going to get distorted P/E ratios.

The tool that we have built is super powerful and facilitates the search of relatively cheap stocks. From the resulting 10 stocks, we can select the most attractive and perform additional financial analysis. For instance, we could calculate the Price to Book Value or the Return on Equity with Python to gather additional insights.

Similarly, we could value a company using Price to Sales ratio with Python.

Other Blogs

Nov 25, 2023 6:39 AM - Parth Sanghvi

DCF Valuation vs. Comparable Companies Analysis: Choosing the Right Valuation Method

Choosing the Right Valuation Method: DCF vs. Comparable Companies Analysis Introduction: Valuation methods play a pivotal role in determining the fair value of a company, aiding investors in making informed investment decisions. Two commonly used methods, DCF Valuation and Comparable Companies A...

blog post title

Dec 25, 2023 2:31 AM - Parth Sanghvi

Decoding the Discounted Cash Flow (DCF) Model: A Comprehensive Guide for Strategic Investment Analysis

Introduction: The Discounted Cash Flow (DCF) model stands as a cornerstone in investment analysis, offering a robust framework for estimating the intrinsic value of an investment. In this comprehensive guide, we delve into the fundamentals of DCF analysis, providing step-by-step instructions, key...

blog post title

Jan 4, 2024 1:56 AM - Parth Sanghvi

Optimizing DCF Model Accuracy: Advancements through Big Data and AI Integration

The Discounted Cash Flow (DCF) model remains a cornerstone in financial analysis, offering a strategic way to assess the intrinsic value of an investment. With advancements in technology, the integration of Big Data and Artificial Intelligence (AI) presents a transformative approach to enhance the p...

blog post title
FMP

FMP

Financial Modeling Prep API provides real time stock price, company financial statements, major index prices, stock historical data, forex real time rate and cryptocurrencies. Financial Modeling Prep stock price API is in real time, the company reports can be found in quarter or annual format, and goes back 30 years in history.
twitterlinkedinfacebookinstagram
2017-2024 © Financial Modeling Prep