Credits calculations

Start using basic Python to simplify your everyday life. Such as calculating a mortgage payment. What’s the point of building own functions for such purposes, anyway? Let’s find out.

Examples of formulas for calculating loan installments are available on banks websites with it product offers, theme search engines and credit calculators published on populist dailies.

The most popular formula to calculate the monthly equal loan installment:

where:
R is the monthly installment,
P is the loan amount,
r is the monthly interest rate (annual interest rate divided by 12),
n is the number of installments (loan period in months).

Let’s try at first with simple variables and basic code in Python.

Example for:
Loan amount: 100 000
Annual interest rate: 5%,
Loan period: 30 years.
Formula: = P*r*(1+r)**n/(1+r)**n -1

Annual_interest_rate = 0.05 #Annual interest rate 5%
Years = 30#Loan period

r = Annual_interest_rate/12
n = Years*12
P = 100000
print(P,round(r,4),n) #output: 100000 0.0042 360
R = P*r*(1+r)**n/(1+r)**n-1
print(round(R,2)) #output:415.67

Looks way too perfect, I asked AI to to the same, and it was the answer:

source:chatgpt.com/c/1ec3a627-f305-4663-9b48-f3b1bc5574a2

So, I tried to spread the values in 2 separeted mini-formulas:

V1 = r*(1+r)**n
V2 = (1+r)**n -1

R = P*(V1/V2)
print(round(R,2)) #output 536.82

Now, it is the same result as from ChatGPT source.

Now as define function:

def loan_payment(loan_amount, annual_interest_rate, 
                 loan_period_years):
    #basics calcs:
    P = loan_amount
    r = annual_interest_rate / 12
    n = loan_period_years * 12

    # formula
    R = P * (r * (1 + r) ** n) / ((1 + r) ** n - 1)

    return round(R,2)

How to use:

option1 – call function knowing it variables:

monthly_installment = loan_payment(100000, 0.05, 30)
print(monthly_installment) #output 536.82

option2 – using input method:

loan_input = int(input("loan_amount: "))
rate_input = float(input("annual_interest_rate: "))
years_input = int(input("loan_period_years: "))

print(loan_payment(loan_input, rate_input, years_input))

Let’s try with decreasing payments.

The formula for a decreasing installment:

Where:
C is the fixed capital part:P/n
P is the loan amount,
t is the month number (from 1 to n),
r is the monthly interest rate,
n is the number of installments (loan period in months)

def dec_loan_payment(loan_amount, annual_interest_rate, 
                     loan_period_years):
    #basics calcs:
    P = loan_amount
    r = annual_interest_rate / 12
    n = loan_period_years * 12
    C = P/n

    # formula: R=C+(P−(t−1)⋅C)⋅r
    R = []
    for t in range(1, n + 1):
        R_t = C + (P - (t - 1) * C) * r
        R.append(R_t)

    return R
monthly_installment = dec_loan_payment(100000, 0.05, 30)
first_six_payments = monthly_installment[:6]
print(first_six_payments)

for x in first_six_payments:
    print(round(x,2))

AI show me also a different example for decreasing loan calculations, but something went wrong here:

def decreasing_installments(capital,
                            interest_rate,
                            period_months):
    installment = []
    for month in range(1, period_months + 1):
        monthly_installment = \
            (capital * (1 + interest_rate)**(month / 12) * 
             interest_rate) / ((1 + interest_rate)**(month/12)-1)
        installment.append(monthly_installment)
    return installment

loan_principal = 100000 # Loan amount in PLN
interest_rate = 0.05 # Annual interest rate (5%)
loan_period = 30 * 12 # Loan period in months (30years* 12months)

decreasing_loan_installments = \
    decreasing_installments(loan_principal,
                            interest_rate, loan_period)

for month, installment in enumerate(decreasing_loan_installments,
                                    start=1):
    print(f"Month {month}: {installment:.2f} PLN")

There is an error in this expression:

monthly_installment = (capital * (1 + interest_rate)(month / 12) * interest_rate) / ((1 + interest_rate)(month / 12) – 1)

Lack of fixed capital part value, therefore the result is as follows:

After modifications it can work properly:

def decreasing_installments(capital,
                            annual_interest_rate,
                            period_months):
    fixed_capital_part = capital / period_months
    interest_rate = annual_interest_rate/12

    installment = []
    for month in range(1, period_months + 1):
        monthly_installment = fixed_capital_part + \
                              (capital - (month - 1) * 
                               fixed_capital_part) *\
                              interest_rate
        installment.append(monthly_installment)
    return installment


loan_principal = 100000  
annual_interest_rate = 0.05 
loan_period = 30 * 12 

decreasing_loan_installments = \
    decreasing_installments(loan_principal, 
                            annual_interest_rate, loan_period)

for month, installment in enumerate(decreasing_loan_installments,
                                    start=1):
    print(f"Month {month}: {installment:.2f} PLN")

but I am still more convinced of the first version I present with define variables: C,P,n,r

Loops for lists, tuples, dicts

Tpl = (1,8,2,4,3,5,7,6,9,0)
Lst = [1,2,2,3,3,3,1.1,2.1,3.1]
Dct1 = dict(name = "Aga", age = 35, year = 1989, hobby = "dance")
Dct2 = {'zodiac': "Cancer",'hair': "brown",'sex': "woman"}

for x in Tpl:
    print(x)
for x in sorted(Lst):
    print(x)
for item in Dct1:
    print(item)
for val in Dct1.values(): 
    print(val)

#Tuples

def calcs(a,b,c):
    return a+b, a**a, b/a, b**c
print(calcs(1,2,3))

names = ("Peter", "Cassandra", "April")
ages = (22, 47, 89)
for name, age in zip(names,ages):
    print(f"{name} is {age} years old")

t_array = ((1,2),(3,4),(5,6))

for in_tuple in t_array:
    for item in in_tuple:
        print(item, end = "::")
    print()

even_numbers = sorted(tuple(num for num in Tpl if num % 2 == 0))
squared_numbers = tuple(num ** 2 for num in Tpl)
print(even_numbers)
print(squared_numbers)

# A dictionary with tuple keys
points = {
    (1, 2): 'low',
    (3, 4): 'medium',
    (5, 6): 'high'
}

# Iterate through the dictionary items
for coordinates, label in points.items():
    print(f"Point {coordinates} is a {label} score")

#Dictionaries and lists


Lst = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]

# Dictionary to hold even and odd numbers
categorized_numbers = {"even": [], "odd": []}

# Loop through each number in the list
for number in Lst:
    # Check if the number is even
    if number % 2 == 0:
        categorized_numbers["even"].append(number)
    else:
        categorized_numbers["odd"].append(number)

# Print the categorized numbers
print(categorized_numbers)

#Calculates the average grade for each worker

workers = {
    "Peter": [5, 4, 5],
    "Cassandra": [3, 4, 4],
    "April": [2, 1, 3]
}

# Dictionary to hold the average grades and pass/fail status
workers_score = {}

# Loop through each student in the dictionary
for student, grades in workers.items():
    # Calculate the average grade
    average_grade = round((sum(grades) / len(grades)),2)

    # Determine if the student passed
    if average_grade >= 3.5:
        status = "Passed"
    else:
        status = "Failed"

    # Store the result in the dictionary
    workers_score[student] = {"average": average_grade, \
                              "status": status}

# Print the student results
print(workers_score)

#Example from AI – manages an inventory of items

inventory = {
    "apples": 10,
    "bananas": 5,
    "oranges": 8
}

sales = {
    "apples": 4,
    "oranges": 2
}

restocks = {
    "bananas": 10,
    "oranges": 5
}

# Update inventory based on sales
for item, quantity_sold in sales.items():
    if item in inventory:
        inventory[item] -= quantity_sold

# Update inventory based on restocks
for item, quantity_restocked in restocks.items():
    if item in inventory:
        inventory[item] += quantity_restocked
    else:
        inventory[item] = quantity_restocked

# Print the updated inventory
print(inventory)