[R] Code to calculate internal rate of return
Moshe Olshansky
m_olshansky at yahoo.com
Fri Aug 1 05:02:09 CEST 2008
You can use uniroot (see ?uniroot).
As an example, suppose you have a $100 bond which pays 3% every half year (6% coupon) and lasts for 4 years. Suppose that it now sells for $95. In such a case your time intervals are 0,0.5,1,...,4 and the payoffs are: -95,3,3,...,3,103.
To find internal rate of return you can do the following:
> tim <- (0:8)/2
> tim
[1] 0.0 0.5 1.0 1.5 2.0 2.5 3.0 3.5 4.0
> pay <- 3 + 0*tim
> pay[1] <- -95
> pay[9] <- 103
> pay
[1] -95 3 3 3 3 3 3 3 103
> f <- function(r) sum(pay*exp(-r*tim))
> z <- uniroot(f,c(0,1))
> z
$root
[1] 0.07329926
$f.root
[1] 0.01035543
$iter
[1] 5
$estim.prec
[1] 6.103516e-05
So the internal rate of return is 0.07329926 (z$root) = 7.33% (continuously compound).
--- On Fri, 1/8/08, Thomas E <thomas at elger.se> wrote:
> From: Thomas E <thomas at elger.se>
> Subject: [R] Code to calculate internal rate of return
> To: r-help at r-project.org
> Received: Friday, 1 August, 2008, 2:05 AM
> Hi all.
>
> I am an R newbie and trying to grasp how the simple
> optimization routines in
> R work. Specifically, I would like some guidance on how to
> set up a code to
> calculate the internal rate of return on an investment
> project
> (http://en.wikipedia.org/wiki/Internal_rate_of_return).
>
> My main problem (I think) is that I want a generic code
> where N (number of
> periods) can be easily changed and set within the code,
>
> Hope this makes sense - any help appreciated !!!
>
> Thomas
> --
> View this message in context:
> http://www.nabble.com/Code-to-calculate-internal-rate-of-return-tp18757967p18757967.html
> Sent from the R help mailing list archive at Nabble.com.
>
> ______________________________________________
> R-help at r-project.org mailing list
> https://stat.ethz.ch/mailman/listinfo/r-help
> PLEASE do read the posting guide
> http://www.R-project.org/posting-guide.html
> and provide commented, minimal, self-contained,
> reproducible code.
More information about the R-help
mailing list