summaryrefslogtreecommitdiff
path: root/mortgage.py
blob: 3b9b958450c4e2edec96ab85e57a9d637510c306 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
import argparse
import math
import sys
from tabulate import tabulate, SEPARATING_LINE


def calc_payments(principal, annual_interest, installments):
    p = principal
    i = annual_interest / 100 / 12 # Monthly equivalent.
    n = installments

    def fmt(x):
        return f"{math.ceil(x*100)/100:.2f}"

    table = [["Time", "Outstanding Debt", "Monthly Installment", "Interest Paid", "Amount Amortised"]]

    monthly_installment = p * (i * (1 + i)**n) / ((1 + i)**n - 1)
    debt = principal
    total_interest = 0
    total_amortised = 0

    for k in range(n):
        interest = i * debt
        amortised = monthly_installment - interest
        table.append([k] + [fmt(x) for x in [debt, monthly_installment, interest, amortised]])

        total_interest += interest
        total_amortised += amortised
        debt -= amortised

    total_interest_pct = total_interest / principal * 100

    table.append(SEPARATING_LINE)
    table.append(["Total", "", "Amount Paid", "Interest Paid", "Amount Amortised"])
    table.append(["", ""] + [
        fmt(monthly_installment * n),
        fmt(total_interest) + f" ({fmt(total_interest_pct)}%)",
        fmt(total_amortised)])
    return table


def main():
    parser = argparse.ArgumentParser()
    parser.add_argument("-p", "--principal", type=float, default=100000, help="Principal")
    parser.add_argument("-i", "--interest", type=float, default=5, help="Annual interest %")
    parser.add_argument("-n", "--installments", type=int, default=300, help="Number of installments")
    args = parser.parse_args()

    table = calc_payments(args.principal, args.interest, args.installments)
    print(tabulate(table))
    return 0


if __name__ == "__main__":
    sys.exit(main())