Loan Calculation Using Python: A Step-by-Step Guide

Joseph bwalya - Feb 24 - - Dev Community

Image descriptionIn today's world, loans are an integral part of personal and business finance. Whether you're buying a home, financing a car, or starting a business, understanding how loans work is crucial. One of the most important aspects of a loan is the amortization schedule, which breaks down each payment into principal and interest components. In this blog post, we'll explore how to calculate loan amortization using Python and an API. We'll also create a dynamic table to display the results.

Understanding Loan Amortization
Before diving into the code, let's briefly discuss what loan amortization is. Amortization is the process of spreading out a loan into a series of fixed payments over time. Each payment consists of two parts:

Principal: The amount of the loan that is being paid off.

Interest: The cost of borrowing the money.

The amortization schedule is a table that shows the breakdown of each payment, including the remaining balance after each payment.

Setting Up the Environment
To get started, you'll need Python installed on your machine. You'll also need to install the requests library, which allows you to make HTTP requests in Python. You can install it using pip:

pip install requests

Making the API Request
We'll be using the Loan Amortization Calculator API from RapidAPI to calculate the loan schedule. The API requires the following parameters:

loan_amount: The total amount of the loan.

annual_interest_rate: The annual interest rate (in percentage).

num_payments: The number of payments.

extra_payment: Any extra payment made (default is 0).

frequency: The frequency of payments (e.g., monthly, quarterly).

Here's how you can make a POST request to the API using Python:

import requests

url = "https://loan-amortization-calculator1.p.rapidapi.com/api/calculate/amortization"

payload = {
    "loan_amount": 10000,
    "annual_interest_rate": 7,
    "num_payments": 3,
    "extra_payment": 0,
    "frequency": "monthly"
}

headers = {
    'Content-Type': 'application/json',
    'x-rapidapi-host': 'loan-amortization-calculator1.p.rapidapi.com',
    'x-rapidapi-key': 'cee0d12e3dmshd8cc8a3c884fcbdp1c2d92jsnd916f6092b82'
}

response = requests.post(url, json=payload, headers=headers)

if response.status_code == 200:
    data = response.json()
    print(data)
else:
    print(f"Error: {response.status_code}")
Enter fullscreen mode Exit fullscreen mode

Parsing the API Response
The API response will be in JSON format, which we can easily parse in Python. Here's a sample response:

{
    "data": {
        "loan_amount": 10000,
        "payments": [
            {
                "closing_balance": 6686.04,
                "interest": 58.33,
                "opening_balance": 10000,
                "payment": 3372.3,
                "period": 1,
                "principal_payment": 3313.96
            },
            {
                "closing_balance": 3352.74,
                "interest": 39.0,
                "opening_balance": 6686.04,
                "payment": 3372.3,
                "period": 2,
                "principal_payment": 3333.3
            },
            {
                "closing_balance": 0.0,
                "interest": 19.56,
                "opening_balance": 3352.74,
                "payment": 3372.3,
                "period": 3,
                "principal_payment": 3352.74
            }
        ],
        "periodic_payment": 3372.3,
        "total_amount": 10116.89,
        "total_interest": 116.89
    },
    "message": "Loan Schedule",
    "status": 200,
    "success": true
}
Enter fullscreen mode Exit fullscreen mode

Creating a Dynamic Table for Results
To display the loan schedule in a user-friendly format, we'll create a dynamic table using Python's tabulate library. First, install the library:

pip install tabulate
Enter fullscreen mode Exit fullscreen mode

Now, let's create a function to display the loan schedule:

from tabulate import tabulate

def display_loan_schedule(data):
    payments = data['data']['payments']
    table = []

    for payment in payments:
        row = [
            payment['period'],
            payment['opening_balance'],
            payment['payment'],
            payment['principal_payment'],
            payment['interest'],
            payment['closing_balance']
        ]
        table.append(row)

    headers = ["Period", "Opening Balance", "Payment", "Principal", "Interest", "Closing Balance"]
    print(tabulate(table, headers, tablefmt="pretty"))

# Assuming 'data' is the API response
display_loan_schedule(data)
Enter fullscreen mode Exit fullscreen mode

Putting It All Together
Now that we have all the pieces, let's put them together in a single script:

import requests
from tabulate import tabulate

def calculate_loan_schedule():
    url = "https://loan-amortization-calculator1.p.rapidapi.com/api/calculate/amortization"

    payload = {
        "loan_amount": 10000,
        "annual_interest_rate": 7,
        "num_payments": 3,
        "extra_payment": 0,
        "frequency": "monthly"
    }

    headers = {
        'Content-Type': 'application/json',
        'x-rapidapi-host': 'loan-amortization-calculator1.p.rapidapi.com',
        'x-rapidapi-key': 'cee0d12e3dmshd8cc8a3c884fcbdp1c2d92jsnd916f6092b82'
    }

    response = requests.post(url, json=payload, headers=headers)

    if response.status_code == 200:
        data = response.json()
        display_loan_schedule(data)
    else:
        print(f"Error: {response.status_code}")

def display_loan_schedule(data):
    payments = data['data']['payments']
    table = []

    for payment in payments:
        row = [
            payment['period'],
            payment['opening_balance'],
            payment['payment'],
            payment['principal_payment'],
            payment['interest'],
            payment['closing_balance']
        ]
        table.append(row)

    headers = ["Period", "Opening Balance", "Payment", "Principal", "Interest", "Closing Balance"]
    print(tabulate(table, headers, tablefmt="pretty"))

if __name__ == "__main__":
    calculate_loan_schedule()
Enter fullscreen mode Exit fullscreen mode

Running the Script
When you run the script, it will make a POST request to the Loan Amortization Calculator API, retrieve the loan schedule, and display it in a dynamic table. Here's what the output will look like:

+---------+-----------------+----------+------------+----------+-----------------+
| Period  | Opening Balance | Payment  | Principal  | Interest | Closing Balance |
+---------+-----------------+----------+------------+----------+-----------------+
|    1    |     10000.0     | 3372.3   |  3313.96   |  58.33   |     6686.04     |
|    2    |     6686.04     | 3372.3   |  3333.3    |   39.0   |     3352.74     |
|    3    |     3352.74     | 3372.3   |  3352.74   |  19.56   |       0.0       |
+---------+-----------------+----------+------------+----------+-----------------+
Enter fullscreen mode Exit fullscreen mode

In this blog post, we've explored how to calculate loan amortization using Python and an API. We've also created a dynamic table to display the loan schedule in a user-friendly format. This approach can be easily extended to handle more complex loan scenarios, such as variable interest rates or additional payments.

Understanding loan amortization is essential for making informed financial decisions. By leveraging Python and APIs, you can automate the calculation process and gain deeper insights into your loan repayment strategy.

Happy coding!

.