FMP

FMP

Enter

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

May 14, 2024 11:41 AM - Sanzhi Kobzhan

The easiest way to calculate stock’s target price and why the target price is important.

A stock's target price, also known as its fair value, is an indication of what a share can cost based on the company’s forecasted financial statements. It is important to know a stock's fair value to find undervalued stocks with great growth potential. Let's consider how investment analysts calculat...

blog post title

May 24, 2024 9:30 AM - Rajnish Katharotiya

How to Access and Analyze Earnings Call Transcripts

Earnings call transcripts are invaluable resources for investors, analysts, and financial enthusiasts. They provide insights into a company's performance, strategy, and future outlook, making them essential for making informed investment decisions. With Financial Modeling Prep, Earnings Call Transcr...

blog post title

May 27, 2024 3:30 PM - Rajnish Katharotiya

The best 5 GPU stocks other than NVDA

In the ever-evolving world of technology, certain sectors have consistently demonstrated exceptional growth and innovation. The graphics processing units (GPUs) industry is one such sector, offering investors a golden opportunity for potentially high returns. In this blog, we'll delve into why inves...

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