Hi I am new to R and I cannot get my function to work. I need to use the Newton Method to estimate IRR of a bond portfolio. The Newton Method equation we are supposed to use is below!
D is duration, P is principle, c is coupon and y is yield/IRR, which is guessed.
The initial for loop is the Newton Method loop, attempting to loop through the final equation.
The other loops (in order) are supposed to calculate the total price of the bonds, then the duration (the price/the total price equals the weight, then the weight* the time of payment equals the duration for that payment, then sum up all those durations for the total duration). Finally, the last for loop is supposed to determine the summnation in the JPEG equation, and finally add up all the info as displayed in the image.
I have no idea what is going wrong, but I could really use some help, as my knowledge of R syntax/formatting is nonexistent, and thus I am not sure what error I am making.
NewtonMethodIrr <- function(C,P,n) {
iterations<- 20
y<-0
for (j in length(iterations)) {
price<-0
for (i in length(n-1)) {
price <- price + C*exp(-y*i)
}
totalPrice<- price + C*P*exp(-y*n)
durationPart1<-0
for (f in length(n-1)) {
weight <- (C*exp(-y*j))/totalPrice
durationPart1 <- weight*f + durationPart1
}
totalDuration <- durationPart1 + n*(C*P*exp(-y*n)/totalPrice)
denominator<-0
for (q in length(n)) {
denominator <- denominator + q*exp(-y*q)
}
finalBottom <- denominator*C
y <- y + (1/totalDuration) - (P/finalBottom)
}
return(y)
}