FMP

FMP

Enter

In business, debt is an essential partner to investment from shareholders to finance business growth. If a company spots an opportunity in the market and needs

How to pull Financial Debt and Leverage Ratios using Python

Oct 26, 2023 4:41 PM - Rajnish Katharotiya

twitterlinkedinfacebook
blog post cover photo

Image credit: Alexander Schimmeck

In business, debt is an essential partner to investment from shareholders to finance business growth. If a company spots an opportunity in the market and needs money to go after it, they need to source this from creditors and investors. However, unlike investment from investors, debt is usually taken with an agreement to pay interest on the loaned amount and with the interest comes risk. In our education section, we've written two articles that explain how investors may use an understanding of a company's debt. In the first article, we explain what debt and leverage are in a business context. The next covers the ratios used to understand company debt and how to calculate them. In this article, we are going to show you how you can pull debt ratios directly from the FMP Financial Ratio API.

The 7 ratios we will investigate are:

  1. Debt/Equity Ratio
  2. Net Debt
  3. Debt Ratio
  4. Debt to Capitalization Ratio
  5. Interest Coverage Ratio
  6. Cash Flow to Debt Ratio
  7. Equity Multiplier

Step 1: Load FMP Developer API Docs Website

From this article go to the top right of the page, click “Developers” and then click "API Docs" from the list below. Make sure you are logged into your account. You should see this in the top right corner:

image

Otherwise, click login and enter your account credentials.

A key piece of information that'll want to write down in a safely secured location is your API Key. This is located in the second section of the API docs page which is called "Your Details". See in the example below, it should be a long series of letters and numbers. As with any key, this unlocks something and in this case it ensures that you have permission to access the API you are requesting. Make sure to keep your key private and safely secured if you are storing it somewhere on your computer. It is against our terms and conditions to share your API key with anyone - your account will be blocked and investigated if we suspect you are doing this.

Step 2: Copy the URL for the API you want to access

For this example, we are going to pull from the company profile API. So scroll down to the section that says Company Financial Ratios (You can also use the navigation bar on the left hand side of the screen) and you will see the following

image

Then right click on the box that contains something that looks like a condensed URL. In this case: api/v3/ratios/APPL?limit=40

Step 3: Open Your Python Environment and copy URL

Now you'll need to open up your Python environment to start writing code. To start with, create a variable called “URL” and give the string version of the URL you copied in step 2. You can simply use Ctrl + V (or cmd + V for mac users) to paste the url you copied.

ERROR ALERT: Make sure to add inverted commas (otherwise called quotation marks) around the copied URL to make the URL variable a string.

url = “https://financialmodelingprep.com/api/v3/ratios/AAPL?limit=40&apikey=demo”

If you're copying directly from this page you'll need to make sure that you replace the ‘demo' with your API key

Step 4: Write the Python code to access the Financial Statement

To learn more about exactly what all the following code means and why it works, visit out guide - How to call a Financial Modeling Prep API

try: # For Python 3.0 and later from urllib.request import urlopen except ImportError: # Fall back to Python 2's urllib2 from urllib2 import urlopen import json def get_jsonparsed_data(url): """ Receive the content of ``url``, parse it as JSON and return the object. Parameters ---------- url : str Returns ------- dict """ response = urlopen(url) data = response.read().decode("utf-8") return json.loads(data) url = ("https://financialmodelingprep.com/api/v3/ratios/AAPL?limit=40&apikey=demo") Ratios_APPL = get_jsonparsed_data(url)

The variable that we have created called Ratios_APPL will have all the financial ratios from the last 40 years of Apple Inc's financial statements in the JSON format.

Step 5: Pull out the individual debt ratios

The debt ratios listed at the beginning of this article aren't named exactly the same way in the JSON because we want to keep the code clean and we can't use spaces in python when naming individual variables and objects. The JSON format stores the data as a list of dictionaries for each year. Each dictionary is made up of keys and values. In this case, each key is a financial ratio and the value is the figure for that ratio. The key name of each debt ratio in the JSON file is as follows:

Debt Ratio Key Name
Debt to Equity Ratio 'debtEquityRatio'
Debt Ratio 'debtRatio'
Cash Ratio 'cashRatio'
Debt to Capitalization Ratio 'totalDebtToCapitalization'
Interest Coverage Ratio (ICR) 'interestCoverage'
Cash Flow to Debt Ratio 'cashFlowToDebtRatio'
Equity Multiplier 'companyEquityMultiplier'
Net Debt See Special Example

Let's say we want to pull out Apple's 2020 debt ratio. We would use the following code:

Ratios_APPL[0]['debtRatio']

It's important to note that the format of this data means that as you index higher, you'll go further back in time. Here's a little bit of code that will help you understand how to index for a specific year:

for i in range(0,len(Ratios_APPL)): print(i, Ratios_APPL[i]['date'])

This will return a print out of each index and its corresponding date taken:

image

Examples of how to pull Debt Ratios

Pooling Debt Ratios into a list

Firstly, it's useful to store the codified name of each of these ratios in their own list so that you can easily pull all the ratios quickly and loop through them.

debtRatios = [ 'debtEquityRatio', 'debtRatio', 'totalDebtToCapitalization', 'interestCoverage', 'cashFlowToDebtRatio', 'companyEquityMultiplier', ]

Pulling all debt ratios for one stock

Here's an example of how you would loop through all the debt ratios for Apple in 2018 using the index of 2.

APPL_2018_DebtRatios = [] #This is an empty list of that the next for loop will fill for i in range(0,len(debtRatios)): APPL_2018_DebtRatios.append(Ratios_APPL[2][debtRatios[i]]) #This adds the ratio i to the list of Apple's Debt ratios print(f"{debtRatios[i]} , {APPL_2018_DebtRatios[i]: .2f}"

Using the for loop and range function we can cycle through each debt ratio and print it out. The f string at the end has a neat :.2f to limit the output to two decimal places.

image

Function to pull historical debt ratio for a given number of years in the past

Here we're going to create a function that tell you what a specific debt ratio was in previous years:

def historical_ratio(ratioName, years): for i in range(0,years): print(f" {ratioName} on {Ratios_APPL[i]['date']} = {Ratios_APPL[i][ratioName]:.2f}")

image

From the output we can see that Apple's debt ratio has been consistently rising over the past 6 years.

Net Debt Special Example

Since net debt is more of a raw figure rather than a ratio, it is special in not being stored in the Financial Ratio API. Hence, to determine this ratio we will need to draw out the specific numbers required to calculate it from the balance sheet statement.

We know that

Net Debt = (Short Term Debt + Long Term Debt) - Cash and Cash Equivalents

So we need to pull in the balance sheet and then calculate the net debt from that.

To learn how to pull in a financial statement see this previous article.

This is how the terms are defined in the response from the API:

Short Term Debt = 'shortTermDebt'

Long Term Debt = 'longTermDebt'

Cash and Cash Equivalents = 'cashAndCashEquivalents'

So to determine net debt simply use a basic arithmetic with Python:

netDebt = ( balanceSheet_APPL[0]['shortTermDebt'] + balanceSheet_APPL[0][ 'longTermDebt']) - balanceSheet_APPL[0]['cashAndCashEquivalents']

This looks quite complicated but really it is just indexing into the balance sheet response to get each relevant figure for the calculation.

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

Sep 11, 2023 1:49 PM - Rajnish Katharotiya

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

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 Compa...

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
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