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

Sep 11, 2023 5:49 PM - Rajnish Katharotiya

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

Sep 11, 2023 1:38 PM - Rajnish Katharotiya

P/E Ratios Using Normalized Earnings

Price to Earnings is one of the key metrics use to value companies using multiples. The P/E ratio and other multiples are relative valuation metrics and they cannot be looked at in isolation. One of the problems with the P/E metric is the fact that if we are in the peak of a business cycle, earni...

blog post title

Oct 17, 2023 3:09 PM - Davit Kirakosyan

VMware Stock Drops 12% as China May Hold Up the Broadcom Acquisition

Shares of VMware (NYSE:VMW) witnessed a sharp drop of 12% intra-day today due to rising concerns about China's review of the company's significant sale deal to Broadcom. Consequently, Broadcom's shares also saw a dip of around 4%. Even though there aren’t any apparent problems with the proposed solu...

blog post title

Oct 30, 2023 4:30 AM - Parth Sanghvi

How to Invest in Growth Stocks

Growth stocks are stocks of companies that are expected to grow at a faster rate than the overall market. These companies are typically smaller and newer than established companies, and they may be operating in new or emerging industries. Growth stocks can be a great way to generate h...

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