1+ import pandas as pd
2+
3+ def payment (principal : float , interest_rate : float , payments : int ) -> float :
4+ """
5+ Calculate the monthly payment for a loan.
6+
7+ Parameters
8+ ----------
9+ principal : float
10+ The amount of the loan.
11+ interest_rate : float
12+ The annual interest rate for the loan.
13+ years : int
14+ The term of the loan in years.
15+
16+ Returns
17+ -------
18+ float
19+ The monthly payment for the loan.
20+
21+ Examples
22+ --------
23+ >>> payment(1000, 0.1, 1)
24+ 1099.9999999999995
25+ """
26+ payment = principal * interest_rate / (1 - (1 + interest_rate ) ** - payments )
27+
28+ return payment
29+
30+ def amortization_table (principal : float , interest_rate : float , years : int ) -> pd .DataFrame :
31+ """
32+ Create an amortization table for a loan.
33+
34+ Parameters
35+ ----------
36+ principal : float
37+ The amount of the loan.
38+ interest_rate : float
39+ The annual interest rate for the loan.
40+ years : int
41+ The term of the loan in years.
42+
43+ Returns
44+ -------
45+ pd.DataFrame
46+ The amortization table for the loan.
47+
48+ Examples
49+ --------
50+ >>> amortization_table(1000, 0.1, 1)
51+ Payment Principal Interest Remaining
52+ 0 0.00 0.00 0.00 1000.00
53+ 1 87.92 79.58 8.33 920.42
54+ 2 87.92 80.25 7.67 840.17
55+ 3 87.92 80.91 7.00 759.26
56+ 4 87.92 81.59 6.33 677.67
57+ 5 87.92 82.27 5.65 595.40
58+ 6 87.92 82.95 4.96 512.45
59+ 7 87.92 83.65 4.27 428.80
60+ 8 87.92 84.34 3.57 344.46
61+ 9 87.92 85.05 2.87 259.41
62+ 10 87.92 85.75 2.16 173.66
63+ 11 87.92 86.47 1.45 87.19
64+ 12 87.92 87.19 0.73 0.00
65+ """
66+ payments = years * 12
67+ interest_rate /= 12
68+ payment_amount = payment (principal , interest_rate , payments )
69+ df = pd .DataFrame (index = range (0 , payments + 1 ), columns = ["Payment" , "Principal" , "Interest" , "Remaining" ], dtype = "float" , data = 0 )
70+
71+ df ["Payment" ][1 :] = payment_amount
72+ df ["Remaining" ][0 ] = principal
73+ for i in range (1 , payments + 1 ):
74+ df ["Interest" ][i ] = df ["Remaining" ][i - 1 ] * interest_rate
75+ df ["Principal" ][i ] = df ["Payment" ][i ] - df ["Interest" ][i ]
76+ df ["Remaining" ][i ] = df ["Remaining" ][i - 1 ] - df ["Principal" ][i ]
77+ df = df .round (2 )
78+ df = df .abs ()
79+
80+ return df
81+
82+
83+
84+ if __name__ == "__main__" :
85+ import doctest
86+
87+ doctest .testmod ()
0 commit comments