Calculating Return on Equity with Python

One of Warren Buffet’s favourite metrics is Return on Equity. He uses ROE as part of his investment decision process. Return on Equity indicates how much net income a company generates with the money invested by shareholders. During this story, we are going to calculate Return on Equity with Python for any stock of your interest.

Python for Finance: Calculating Return on Equity with Python
Photo by NeONBRAND on Unsplash

How we calculate Return on Equity?

Return on Equity is calculated as net income available to common shareholders divided by the average book value of common equity over the period.

Calculate Return on Equity with Python
Return on Equity

Net Income represents the net income available to common shareholders. While book value of equity is the value of firm’s assets minus liabilities. Instead of using the average book value of common equity in the denominator, we could also use the book value at the beginning of the period. However, the average book value of a period is most appropriate if the book value of common equity it is very changeable from period to period. For our example, we will use the average book value.

How to interpret ROE?

Higher ROE is viewed as a positive sign in the investment world. However, we need to be cautious on how firms are increasing ROE. If a firm takes on more debt, the ROE will increase since the firm may be reducing equity (i.e. buying their own equity) by issuing debt. This will lead to a higher risk, and consequently, ROE will increase.

On the other side, if a firm increases net income without taking addittional debt, then the ROE increase will be a very good sign.

Calculate Return on Equity with Python

Now that we understand why ROE is so important, let’s build a Python a script to automatically calculate the ROE of any company that we are interested in.

It is super easy. We will be using a free API, Financialmodelingprep, to retrieve financial statement and stock data. We will make a get request to the API end point to retrieve the financial statements and we will parse the values that we need to compute ROE.

First of all, we need to import the only library that we will need to build our Python script:

import requests

Since we would like to reuse the code to calculate the ROE for different companies, we will build a function call getROE. getROE will take a company ticker as an argument that will be passed as a parameter of the url:

UPDATE DEC 2020: Since a few months back, 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.

api_key = 'your api key '
def getROE(stock,api_key):
    income_statement = requests.get(f"{stock}?period=quarter&limit=400&apikey={api_key}").json()

Within our getROE function, we will make a get request to the Financialmodelingprep API end point to extract first income statement quarterly information. Then, we convert the response into a json object in order to be able to work with it.

If we now print our income statement, we will have a nice formatted dictionary that is easy to parse. Note that in the url, stock will be replaced by the company ticker passed as an argument, for example “AAPL“.


What we have now in the income_statement variable is a list of dictionaries. Each element in the list contains the income statement for a quarter in the form of a dictionary. The first element in the list is the latest available quarter (e.g. 28 Dec 2019).

Python for Finance - Income Statement
Income Statement with Python

Calculating Net Income

Now, we can easily extract the net Income of Apple by parsing the dictionary. Since we are interested in the latest quarter, we extract the first element of the list. Within the first element, we need to extract the value of the key Net Income Com:

    net_inc_common1 = float(income_statement[0]['netIncome'])

Retrieving Book value of Equity

Great, we have the numerator of our ROE. Next, we need to calculate the book value of equity. The book value of equity can be extracted by looking into the Balance Sheet in the financial reports.

Luckily, Python will do the work and extract the value for us. We will make a get request to the Financialmodelingprep API end point to extract Balance Sheet quarter data:

BS = requests.get(f"{stock}?period=quarter&limit=400&apikey={api_key}").json()

Our response looks like below.

Python Extracting Balance Sheet
Python Extracting Balance Sheet

As before, our response contains a list of dictionaries. The latest quarter is the first element in the list. We can now parse the dictionary to extract Total shareholders equity value:

tot_equity_now = float(BS[0]['totalStockholdersEquity'])

Since we need to calculate the average of the period, we also need to retrieve the equity book value from last year. That will be the fourth element in the list, i.e. four quarters ago:

tot_equity_previous = float(BS[4]['totalStockholdersEquity'])

Great, we can now compute the average equity and use it as the denominatior to get the ROE value.

Average_equity = (tot_equity_now + tot_equity_previous)/2

ROE = net_inc_common1/Average_equity

Putting our Python financial script together

We have built a very useful Python script to calculate Return on Equity with Python of any company. It is very easy to use, we only need to call the function and pass as an argument a company ticker. Then, our function will extract the needed financials and calculate the ROE for us.

See below the final code.

import requests

#Getting Income Statement and Balance Sheet Data
api_key='your api key'
def getROE(stock,api_key):
    income_statement = requests.get(f"{stock}?period=quarter&limit=10&apikey={api_key}").json()
    net_inc_common1 = float(income_statement[0]['netIncome'])

    BS = requests.get(f"{stock}?period=quarter&limit=10&apikey={api_key}").json()
    tot_equity_now = float(BS[0]['totalStockholdersEquity'])
    tot_equity_previous = float(BS[4]['totalStockholdersEquity'])
    Average_equity = (tot_equity_now + tot_equity_previous)/2

    ROE = net_inc_common1/Average_equity
    return ROE

If we now pass AAPL and MSFT as arguments of our getROE function, Python will calculate the ROE for Apple and Microsoft:

Apple = getROE('AAPL')
#Format number as percentage 
Apple = "{:.2%}".format(Apple)

MSFT = "{:.2%}".format(MSFT)

print('MSFT:', MSFT )
print('AAPL:', Apple )

That will give us a ROE of 11.5% for Microsoft and 21.44% for Apple. Apple has a higher ROE. It is due to a higher level of debt or to a higher net income? I will let you analyse this by yourself. Feel free to provide the answer to this question below!

If you have enjoyed the article, I would recommend you to have a look at my other blog entries on Python for Finance. And if you enjoy my blog on Python for Finance, I would appreciate if you can share in social media.