I want to find the internal rate of return (IRR), basically the 'rate' that makes my NPV function go to zero, using the optim
function.
My current code for the NPV function (which works) is:
npv <- function(rate, cf){
r_v <- rep (rate,length (cf))
t_v <- as.numeric (seq(1:length (cf)))
pv <- cf * exp (-t_v*r_v)
sum (pv)
}
I tried using the following optim
function:
InternalRateReturn <- optim(c(0,1), npv, cf = testcf2, gr = NULL, method = "L-BFGS-B", lower = -Inf, upper = Inf,control=list(), hessian = FALSE)
but it is not coming back with the correct answer for InternalRateReturn$par
as opposed to using the uniroot
method below.
May I ask how to modify this code (to reiterate, I just want to optimize the rate in the npv
function such that the npv
function equals zero)?
The IRR function using uniroot
is as per below:
irr1 <- function(cf) {
uniroot(npv, c(0, 1), cf=cf)$root
}