[R-SIG-Finance] yield to maturity with optim?
Whit Armstrong
armstrong.whit at gmail.com
Fri Oct 24 21:59:02 CEST 2008
Thanks, Ajay.
Am I being dense? A bond trading a par should have ytm == coupon, right?
> ytm.ajay(6,20,1)
[1] 9.372377
>
So, I have slightly reworked version:
ytm <- function(price, cpn, term, freq, prin=100) {
npv <- function(yld, term, cpn, freq, prin) {
indx <- 1:(term*freq)
payment <- (cpn/freq)*prin
disc <- (1 + yld/freq)
sum(payment/disc^(indx)) + prin/(disc^(term*freq))
}
uniroot(function(yld) npv(yld, term, cpn, freq, prin) - price,
interval=c(0,100), tol=0.000001)$root
}
which gives:
> ytm(100,0.06,20,2)
[1] 0.05999979
>
Thanks for your help!
-Whit
On Fri, Oct 24, 2008 at 2:02 PM, Ajay Shah <ajayshah at mayin.org> wrote:
> On Fri, Oct 24, 2008 at 02:01:18PM -0400, Whit Armstrong wrote:
>> anyone using optim to solve for bond yields given price?
>>
>> I've anyone has any quick and dirty code, I would be grateful.
>
> You mean:
>
> ytm <- function(C, T, p) {
> npv <- function(C, T, r) {
> sum(C * (1 + (0.01*r))^-T)
> }
> uniroot(function(r) npv(C, T, r) - p, interval=c(-20,100), tol=0.0001)$root
> }
>
> ?
>
> --
> Ajay Shah http://www.mayin.org/ajayshah
> ajayshah at mayin.org http://ajayshahblog.blogspot.com
> <*(:-? - wizard who doesn't know the answer.
>
More information about the R-SIG-Finance
mailing list