Retrieve Financial Ratios with Python

Financial Ratios are very useful tools to check the attractiveness of public companies. It helps investors to answer key questions before deciding to buy or not stocks in a company. In this post we will retrieve Financial Ratios with Python. We will uncover here the basics that will let us explore more advance uses of Financial Ratios such as:

There are different types of financial ratios. Between the most used categories, we have operating, liquidity, solvency, profitability and valuation ratios.

Each of these ratio categories help investors, creditors, etc. to answer different questions across companies. For instance, solvency and liquidity ratios will let us know if a firm is able to meet short and long term obligations. On the other hand, profitability ratios show how profitable a company is, etc.

Financial Ratios Python
Photo by Markus Spiske on Unsplash

Financial ratios are not giving us much insights unless we use them to compare companies within an industry.

Obtaining data to compute financial ratios is not difficult. We just need to go to the public financial statements of any company to get the desired numbers. However, it may be a time consuming exercise due to the large number of data that we need to extract. On top of that, ideally, we would need to have data for a range of companies to perform a proper comparison.

The good news is that we can fully automate the computation of financial ratios using Python and a free Financialmodelingprep API to get the data. As you will see now, it is quite easy and quick to do it.

Note that I have also a video tutorial in Youtube explaining step by step what the code is doing. I recommend you to go through the video to understand each of the lines used in the script:

Building our script to Retrieve Financial Ratios with Python

Let’s start coding. First of all, we import all required modules and start making an API request to FinancialModellingPrep API to retrieve all financial ratios of any company that we pass into our financial ratios function.

Note that you need to sign up to financialmodelingprep in order to get an API key. You can get one for free with up to 250 API requests a month. If you opt to sign up for a paid subscription using my link, you will get a 25% discount.

We will use Pandas, Requests and Json libraries to work with the data.

import pandas as pd
import requests
import json

api_key='your api key'

def financialratios(quote):
   fr = requests.get(f"{quote}?apikey={api_key}")
fr = fr.json()

We store the API response in a variable call fr that will be converted to json so that we can work with it in Python.

After that, we store the first element of the list that was returned from the API end point. Note, that we only keep the first element of the array because it contains the latest available data. Then, we store each of the financial ratios categories in a variable to convert it later to a Pandas DataFrame:

  valuation = fr['ratios'][0]['investmentValuationRatios']
  profitability = fr['ratios'][0]['profitabilityIndicatorRatios']
  operating = fr['ratios'][0]['operatingPerformanceRatios']
  liquidity = fr['ratios'][0]['liquidityMeasurementRatios']
  debt = fr['ratios'][0]['debtRatios']
  valuation = pd.DataFrame(list(valuation.items()),columns=['Ratio', quote])
  profitability = pd.DataFrame(list(profitability.items()),columns=['Ratio', quote])
  operating = pd.DataFrame(list(operating.items()),columns=['Ratio', quote])
  liquidity = pd.DataFrame(list(liquidity.items()),columns=['Ratio', quote])
  debt = pd.DataFrame(list(debt.items()),columns=['Ratio', quote])

As a result, we have five Pandas DataFrames, that is, one Pandas DataFrame per financial ratio category. For example, in the variable debt, we have all debt financial ratios.

See below example of the content of debt when we pass ‘AAPL’ (i.e. ticker of Apple):

Financial Debt Ratios Apple — Python for Finance
Financial Debt Ratios Apple — Python for Finance

As next step, lets concatenate all financial ratio categories into a single Pandas DataFrame. First, we create a list containing each of the Pandas DataFrame. Then, by using pd.concat function, we can merge them into a single DataFrame stored in a variable named result.

Finally, as part of our function, we return the concatenated result.

  frames = [valuation,profitability,operating,liquidity,debt]
  result = pd.concat(frames)
  return result

Comparing Financial Ratios from different companies

Now we have all our ratios together in a single Pandas DataFrame. However, we cannot make any conclusion by looking into financial ratios of a single company. We need to compare them across companies within the same industry.

If we were to compare Facebook, Apple and Microsoft, we could just run our code three times for each of the companies and make the comparison this way ratio by ratio. However, there is a better and more efficient way to do it.

Let’s put together all financial ratios from different companies into a single data frame to enable better comparability. We can simply do that by looping through our list of stocks. Then, we merge each of the companies in our list to the initial Pandas DataFrame. And that is what we do in below lines of code. Feel free to add any other company of your interest!

listofstocks = ['AAPL','MSFT','FB','TSLA']
x = financialratios('GOOGL')

for item in listofstocks:
    y = financialratios(item)
    x = x.merge(y,on='Ratio')

Then in our x variable, we have a single Pandas DataFrame containing financial ratios of 5 different companies. Now, we can start looking and make some nice conclusions about these companies.

Hope you find this script useful for your analysis!

Check in below picture our Financial Ratio Pandas DataFrame. Very useful script to compare financial ratios across different companies.

Financial Ratios Across Companies — Python for Finance
Financial Ratios Across Companies

If something is unclear, I recommend you to watch above Youtube video where all code is explained line by line!

Subscribe to to see my latest posts.