Calculating a Mortgage Payment and Future Balance using Ruby

Because it seems as if I continually revisit these formulas, and have to re-figure them out each time, I’m putting them here for reference.


# Calculation based on formula found at http://www.financeformulas.net/Loan_Payment_Formula.html
#
# Calculate a payment given:
#
# rate - annual percentage rate, not decimal
# bal - loan balance
# term - term of the loan in months
#
def payment(rate, bal, term)
  # Convert annual rate to monthly and make it decimal.
  r = rate / 1200

  # Numerator
  n = r * bal

  # Denominator
  d = 1 - (1 + r)**-term

  # Calc the monthly payment.
  pmt = n / d
end


# Calculation based on formula found at http://www.financeformulas.net/Remaining_Balance_Formula.html
#
# Calculate a future balance given:
#
# rate - annual percentage rate, not decimal
# bal - current loan balance
# term - term of the loan in months
# num_payments - return the current loan balance after this many monthly payments have been made.
#
def future_balance(rate, bal, term, num_payments)
  p = payment(rate, bal, term)

  # Convert annual rate to monthly and make it decimal.
  r = rate / 1200

  # Numerator
  n = (1 + r)**num_payments - 1

  # Denominator is simply the monthly rate.
  d = r

  # Calc the future balance.
  fb = bal * (1 + r)**num_payments - (p * (n / d) )
end

Using the methods:

Given a balance of $100,000 with a rate of 4.5% for 360 months (30 years), my payment is?


[42] pry(main)> payment(4.5, 100000, 360)
=> 506.6853098258858

#  $506.69

If I’ve made payments for 12 years (144 months), my current balance is?


[43] pry(main)> future_balance(4.5, 100000, 360, 144)
=> 74917.47372509036

#  $74,917.47