Python For Finance

How to Use Python to Build a Cash Flow Model?

Python is excellent for building complex financial models. The language can form recursive functions, unlike spreadsheets like Ms. Excel. You also get version control and peer review with a Python cash flow model. Again something that Excel can’t provide. Plus Python is also one of the easiest programming languages because it was designed to mimic plain English. Hence switching to Python for financial modeling is an excellent choice. I’ll demonstrate how by explaining how you can create a Python cash flow model. 

The tools you need

You’ll need colaboratory, or colab for short, is a free Python interpreter. Colab uses cells that contain code, images, and other data. Colab also stores your code as you write, which makes it easier to catch mistakes as you write. So it’s a great interpreter. 

We’ll use Colab to build a model for an amortized loan with scheduled periodic payments to both the loan’s interest and principal. The loan also has a fixed installment for each payment, and the interest component of the loan decreases over time. 

Python libraries 

You need these three Python libraries: 

  • numpy-financial==1.0.0
  • pandas==1.2.3
  • matplotlib==3.2.2

How to install Python libraries

colab has the Pandas and Matplotlib packages by default, so you’ll only need to install the NumPy financial library. Thankfully, you can do that directly from colab with the following code: 

  • # initial set-up
  • !pip install numpy_financial
  • import pandas as pd
  • import numpy_financial as npf
  • import matplotlib.pyplot as plt
  • from collections import namedtuple

This code also imports the other 2 libraries. Just open colab and open a new colab notebook from the File menu. Then paste the above code into the first code cell.

Note: numpy-financial’s name has a hyphen(-), but you have to use an underscore(_) when you import it. 

NumPy is also written as np, and Pandas as pd. These are predefined aliases that improve readability. 

Using Python libraries to set up the problem

NumPy is one of Python’s most popular libraries. It has both multidimensional array support and a large collection of mathematical functions for arrays. 

The numpy financial library includes the most commonly used financial functions. 

The PMT, IPMT, and PPMT functions are relevant to us. 

PMT 

This function calculates the fixed loan installment for paying the full loan over a number of payments. 

IPMT 

This function calculates the interest payments of the loan over a number of payments. 

PPMT

This function calculates the principal payments of the loan over an over-number of payments.

The IPMT and PPMT functions can provide values for a single period or multiple ones, depending on the period input. For this example, we’ll use the full life of the loan as the period input. 

We’ll use vector arrays with the interest in principal payments each period of the loan: 

  • # loan characteristics
  • original_balance = 750_000
  • interest rate = 0.16
  • term = 60
  • # payments
  • periods = range(1, term+1)
  • interest_payment = npf.ipmt(rate=interest rate / 12, per=periods, nper=term, pv=-original_balance)
  • principal_payment = npf.ppmt(rate=interest rate / 12, per=periods, nper=term, pv=-original_balance)

The above code only sets the loan information to complete the rest of the exercise. 

Creating a chart on python

It’s best to visualize the output, like a stack plot, for increased clarity. 

We’ll create a stack plot with plt, the pyplot collection of functions in the matplotlib library. 

We’ll add a legend to the top left corner and title the x and y-axis. 

And finally, we’ll also set the margins to 0 since we don’t need an internal border. 

Do all this by inserting the following code in another code cell: 

  • plt.stackplot(periods, interest_payment, principal_payment, labels=[‘Interest’, ‘Principal’])
  • plt.legend(loc=’upper left’)
  • plt.xlabel(“Period”)
  • plt.ylabel(“Payment”)
  • plt.margins(0, 0)

The stack plot shows the interest and loan balance decrease over time. The only way to maintain the fixed installment is to increase the loan’s principal component. 

Creating a table to show cash flows

We’ll use the Pandas package to create a Python cash flow model since it has fast and expressive data structures. 

Insert the following code to generate a table that contains both the interest and principal components of the payment along with the original and ending loan balances for each payment. 

  • _# pandas float formatting_
  • pd.options.display.float_format = ‘{:,.2f}’.format
  • _# cash flow table_
  • cf_data = {‘Interest’: interest_payment, ‘Principal’: principal_payment}
  • cf_table = pd.DataFrame(data=cf_data, index=periods)
  • cf_table[‘Payment’] = cf_table[‘Interest’] + cf_table[‘Principal’]
  • cf_table[‘Ending Balance’] = original_balance –           cf_table[‘Principal’].cumsum()
  • cf_table[‘Beginning Balance’] = [original_balance] + list(cf_table[‘Ending Balance’])[:-1]
  • cf_table = cf_table[[‘Beginning Balance’, ‘Payment’, ‘Interest’, ‘Principal’, ‘Ending Balance’]]
  • cf_table.head(10)

The first line of code makes the table more readable with display formatting rules

The second section of the code tells Colab to include the interest payment, principal payment, starting and ending balances for each payment. 

You should receive the following table: 

Cash Flow Model built using Python

Congratulations, you’ve just learned to build a Python Cash Flow Model. Don’t stop here, there’s lots more you can do with Python for finance, like modeling loans with variable interest rates. 

Author: Ramish Kamal Syed | Editor: Syed Hamza Ali | SEO Editor: Muhammad Waqas Aslam