2

I have this function which calculates internal rates of returns for non-periodic cashflows..

xirr <- function(cf, t) {
    npv <- function(cf, t, r) sum(cf/((r)^(t/365.25)))
    irr <- uniroot(f=npv, interval=c(0,10), cf=cf, t=t, maxiter=100)$root - 1
    return(irr)
}

The problem is, the mathematical assumptions of this formula are not satisfied if the return on the cashflows are less than -100%. I need the function to NOT STOP (throw an error) even if these assumptions aren't fulfilled. I need it to return 0 or something when this happens. At present..

 mycashflow <- c(2000, 2000, 3000,4000, -10000)
 mydates <-as.integer( c(0,101,200,300,400))

 xirr(mycashflow, mydates)

..it throws the error :

Error in uniroot(f = npv, interval = c(0, 10), cf = cf, t = t, maxiter = 100) : f.lower = f(lower) is NA

4

3 に答える 3

4

Try catching the error and return directly:

xirr <- function(cf, t) {
    npv <- function(cf, t, r) sum(cf/((r)^(t/365.25)))
    tryCatch(
      irr <- uniroot(f=npv, interval=c(0,10), cf=cf, t=t, maxiter=100)$root - 1, 
      error=return(0)
    )
    return(irr)
}
于 2013-01-15T10:40:11.037 に答える
2

You could try:

irr <- NA  

try(irr <- uniroot(f=npv, interval=c(0,10), cf=cf, t=t, maxiter=100)$root - 1, silent=T)

if(is.na(irr)) irr <- 0

which will try to calulate the irr and assign it to 0 if the unirott function fails.

于 2013-01-15T10:35:22.100 に答える
0

The problem lies with using uniroot itself to find the IRR. You are limiting the solution between a fixed interval of 0% and 1000%

It would be better if you programmed the code to find the XIRR rather than rely on a built-in function to find internal rate of return for irregular cash flows


After reading a comment from OP, I am editing this reply to show why you do not need to specify a lower and upper bound to locate a root.

f(i) = 2000 + 2000(1+i)^-0.277 + 3000(1+i)^-0.548 + 4000(1+i)^-0.822 - 10000(1+i)^-1.096
f'(i) = - 553.425(1+i)^-1.277 - 1(1+i)^-1.548 - 3(1+i)^-1.822 + 10(1+i)^-2.096

i(N-1) ############## f(x) ############# f'(x) ############ i(N-1) - f(x)/f'(x)
0 ################### 1000 ############# 5473.97260274 #### -0.182682682683
-0.182682682683 #### -287.317250921 #### 9015.5263858 ##### -0.150813522899
-0.150813522899 #### -13.1104684396 ##### 8209.8448578 #### -0.149216602535
-0.149216602535 #### -0.0301760416678 ### 8172.09143372 ### -0.149212909962
-0.149212909962 #### -1.60673153005E-7 ## 8172.00440952 ### -0.149212909943

IRR = -14.921%

As you can see, the XIRR calculation does not make use of any specific interval in which to locate or find the root of the function.

于 2013-01-15T16:19:50.557 に答える