Calculating Bond Duration with for loops

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)
}

if any other infomation is needed to understand this problem, please let me know, im not sure how much of this finance stuff is known

I think you misunderstand the in construct. Look at these adapted versions of your function :

NewtonMethodIrr <- function(C,P,n) {
  iterations<- 20
  y<-0
  cat('one\n')
  print(length(iterations))
  for (j in length(iterations)) {
    cat('two\n')
    print(j)
  }
  # return(y)
}

NewtonMethodIrr()
#> one
#> [1] 1
#> two
#> [1] 1

NewtonMethodIrr2 <- function(C,P,n) {
  iterations<- 20
  y<-0
  cat('one\n')
  for (j in 1:iterations) {
    cat('two\n')
    print(j)
  }
  # return(y)
}

NewtonMethodIrr2()
#> one
#> two
#> [1] 1
#> two
#> [1] 2
#> two
# ...
# you get the idea so I deleted some lines
# ...
#> two
#> [1] 20

Created on 2020-10-20 by the reprex package (v0.3.0)

This topic was automatically closed 21 days after the last reply. New replies are no longer allowed.

If you have a query related to it or one of the replies, start a new topic and refer back with a link.