Reputation: 9
I need help with a function which can calculate mortgage annuity amortization table with output in cols and rows of payment amount, principal payment, Interest payment, etc. sorted by each month like in link below: Output example
The output file format should be .cvs. At the moment I am stuck with this witch is still far away from result:
var i = 5/100;
var loanAmount = 15000;
var m = 12;
var monthlyPayment = loanAmount*(i/12)*Math.pow((1+i/12), m) / (Math.pow((1+i/12), m)-1)
var currentBalance = loanAmount;
var paymentCounter = 1;
var totalInterest = 0;
monthlyPayment = monthlyPayment;
while(currentBalance > 0) {
//this calculates the portion of your monthly payment that goes towards interest
towardsInterest = (i/12)*currentBalance;
if (monthlyPayment > currentBalance){
monthlyPayment = currentBalance + towardsInterest;
}
towardsBalance = monthlyPayment - towardsInterest;
totalInterest = totalInterest + towardsInterest;
currentBalance = currentBalance - towardsBalance;
}
Would really appreciate any help on this.
Upvotes: 0
Views: 1003
Reputation: 1599
Try something like this:
const annuity = (C, i, n) => C * (i/(1-(1+i)**(-n)));
const balance_t = (C, i, P) => {
const period_movements = {
base: C
}
period_movements.interest = C*i;
period_movements.amortization = P - (C*i);
period_movements.annuity = P;
period_movements.final_value = Math.round((C - period_movements.amortization)*100)/100;
return period_movements;
}
const display_mortgage = (C, i, n) => {
const payements = annuity(C, i, n);
let movements = balance_t(C, i, payements);
while (movements.final_value>-.01){
console.log(movements);
movements = balance_t(movements.final_value, i, payements);
}
}
display_mortgage(20000, 0.05, 4);
Output:
{ base: 20000,
interest: 1000,
amortization: 4640.236652069255,
annuity: 5640.236652069255,
final_value: 15360 }
{ base: 15360,
interest: 768,
amortization: 4872.236652069255,
annuity: 5640.236652069255,
final_value: 10488 }
{ base: 10488,
interest: 524.4,
amortization: 5115.836652069255,
annuity: 5640.236652069255,
final_value: 5372 }
{ base: 5372,
interest: 268.6,
amortization: 5371.6366520692545,
annuity: 5640.236652069255,
final_value: 0 }
Upvotes: 0