Search code examples
rmathannuity

Compute interest rate of monthly mortgage payments using R


I try to compute the interest rate of an annuity given the total mortgage, the duration, and the monthly payment.

The formula to calculate the monthly annuity:

              i
J = T * --------------
        1 - (1 + i)^-n

where T is the total mortgage, i the monthly interest, and J the annuity

Example:

library(purrr)
library(dplyr)

mortgage   <- 300000
#annualRate <- ??
duration   <- 360
#annuity
ann <- 1108.86

#Use brute force to find the interest rate
annuity <- function(annualRate, mortgage, duration) {
    monthRate <- annualRate / 12
    ann <- (monthRate / (1- ((1+monthRate)^(-duration)) )) * mortgage
    data.frame(rate = annualRate*100, ann = ann)
}

#Try some rates
checkRates <- seq(1,3,0.5)/100
res <- map(checkRates , annuity, mortgage, duration) %>% bind_rows()
res

#  rate       ann
#1  1.0  964.9186
#2  1.5 1035.3606
#3  2.0 1108.8584
#4  2.5 1185.3627
#5  3.0 1264.8121

Using this brute force technique the interest is 2.0%

Check solution:

annualRate <- 2/100

monthRate <- annualRate / 12
(monthRate / (1- ((1+monthRate)^(-duration)) )) * mortgage
#[1] 1108.858

However, I was wondering if it is possible to calculate the exact interest rate in R without using brute force.

# 1108.86          i
# ------- =  --------------
# 300000     1 - (1 + i)^-360

Is it possible to solve this equation using R? Any suggestion is appreciated.


Solution

  • I think you are looking for uniroot. Here is an example usage for your problem:

    mortgage   <- 300000
    duration   <- 360
    ann <- 1108.86
    uniroot(function(x) mortgage * x/12 / (1 - (1+x/12)^(-duration)) - ann,
        c(1e-6,1))$root * 100
    #[1] 2.000091