Search code examples
pythonnumpymathlinear-algebrafinance

Python CashFlow Calculator


I am trying to formulate an equation that can calculate the outstanding_balance in one go using python. It is quite simple using the iterative process. For example:

for month in range(1, self.amortMonths + 1):

        # Calculate intial and future interest payments

        interest = self.originalPrin * self.rate / 12

        # Calculate intial and future principal payments

        principal_pmt = self.pmt - interest

        # Outstanding balance is reduced by the principal_pmt

        self.originalPrin = self.originalPrin - principal_pmt

So self.amortMonths is basically the monthly duration at which the loan must be payed off and along with self.rate, they will determine the self.pmt variable which is the monthly amount the borrower has to pay inorder to reduce the self.oringalPrin value to 0 by the end of self.amortMonths.

Example:

Lets say I have a loan of $1000 (OutstandingPrin) with an interest rate of 10% then my interest payment for the first month is 1000 * 10% = $100. In order to find the self.pmt amount I used a numpy.pmt function which takes the outstandingPrin, rate, amortMonths as parameters to generate a monthly payment value that will reduce the OutstandingPrin to 0 by the end of the amortMonths. Lets say that self.pmt = $120 then the principal_pmt = 120 - 100 = $20. So the outstandingPrin for the next month is 1000-20=$980. Then this just becomes an iterative process.

So I actually need some help to determine an equation that can do this in one go without the need for an iterative process. Apparently, I need to use linear algebra but I don't come from a math background so I was wondering if anyone has any ideas?

EDIT:

So something like this:

Balance_i = Balance_i-1 - (pmt - Balance_i-1 * Rate).


Solution

  • Here is my solution.

    import numpy as np
    
    a = np.array([[1,0,0,0,0], [1.00583333,-1,0,0,-1], [0, 1.005833333, -1, 0, -1], [0,0,1.005833333, -1, -1],[0,0,0,1,0]])
    b = np.array([162000,0,0,0,0])
    x = np.linalg.solve(a, b)
    balance_arr = np.delete(x, -1)
    print(balance_arr)
    
    interest_arr = balance_arr * 0.07/12
    print(interest_arr)
    
    prin_payment = np.subtract(54631.22, interest_arr)
    prin_payment[-1] = 0
    print(prin_payment)
    
    np.allclose(np.dot(a,x), b)
    

    The array values I manually created them based on hand calculations. The next step would be for me to figure out how to generate them automatically given the term, original balance, and interest rate.