jkndrkn jkndrkn - 1 year ago 138
Ruby Question

Looking for Accurate Ruby, Javascript, or R Excel RATE() or IRR() Function Implementation

I'm currently looking for working and accurate implementations of Excel's

. I am coding in Javascript targeting modern browsers and Ruby 2.0.0 within Rails 4. My goal is to be able to calculate APR within a responsive Javascript application with a Rails back-end.

I've looked at and rejected the following options:

Finance Gem: No
appears to hang for many test vectors.

Formula.js: No working
does not work for many test vectors.

PHPExcel: Has a working
function that I converted to Ruby. This failed to work exactly like the PHP version and failed for important test vectors. This likely does have an
function but I have not yet tested it. I am not hopeful that I will find one that works but I will test it regardless.

I'm not interested in writing my own implementation from mathematical formulas. I prefer code that appears to have been soundly tested.


I have found a procedure for performing
using R that may be accurate enough for our purposes: https://stat.ethz.ch/pipermail/r-help/2008-August/169619.html I will evaluate this solution over the next day or so and update my question if I feel satisfied by it.

Answer Source

After some testing, I am comfortable with this implementation of IRR() in R:


Here it is in the form of a script runnable via the Rscript command:

args <- commandArgs(TRUE)

periods = as.numeric(args[1])
payment = as.numeric(args[2])
value = as.numeric(args[3])
monthsInYear = 12

timeline <- (0:periods)
payments <- payment + (0 * timeline)
payments[1] <- value

f <- function(r) sum(payments * exp(-r * timeline))
irr <- function(f) uniroot(f, c(0, 1))$root

irr(f) * monthsInYear
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download