[R] Yield to maturity calculation - bndyield equivalent of MATLAB in R

Marc Schwartz marc_schwartz at me.com
Wed Apr 5 15:52:53 CEST 2017

> On Apr 5, 2017, at 8:00 AM, Tunga Kantarcı <tungakantarci at gmail.com> wrote:
> I have the MATLAB code pasted below that calculates yields to maturity.
> IRR = zeros(length(c),length(M))
> The ith row and jth column is the price of the bond with coupon c(i)
> and maturity M(j).
> for i = 1:3
>    for j = 1:3
>        if j == 1
>            IRR(i,j) =
> bndyield(mPricecon(i,j),c_org(i),'07-Apr-2016','07-Apr-2026');
>        elseif j == 2
>            IRR(i,j) =
> bndyield(mPricecon(i,j),c_org(i),'07-Apr-2016','07-Apr-2036');
>        elseif j == 3
>            IRR(i,j) =
> bndyield(mPricecon(i,j),c_org(i),'07-Apr-2016','07-Apr-2046');
>        end
>    end
> end;
> mPricecon represents the prices calculated from zero coupon bond
> prices, and c_org represents the coupon payments. This then gives IRR.
> I need to convert this MATLAB code to R code, and ideally one to one.
> The problem is that bndyield is a MATLAB function and there does not
> seem be an exact equivalent in R. What is the best way to go?


First, from a high-level view, you rarely want to convert code from another language to R on a one-to-one or line by line basis. R's underlying philosophy is to take a whole object approach to solving problems by using vectorized code, rather than loops, much less nested loops, albeit, sometimes there are exceptions.

An initial step would be to use Google or rseek.org <http://rseek.org/>, the latter being a dedicated R search resource, where you can use keywords such as " R Yield to Maturity" to identify possible solutions, CRAN packages that may make sense and prior discussions in the list archives.

I am not in finance, so would defer to others with specific knowledge in the domain, but another resource would be CRAN Task Views:

  https://cran.r-project.org/web/views/ <https://cran.r-project.org/web/views/>

where there are Econometrics and Finance views that have focused resources with links to CRAN packages that may be relevant (more so the latter view). From the latter view, the fBonds package on CRAN seems to be possibly relevant:

  https://cran.r-project.org/web/packages/fBonds/index.html <https://cran.r-project.org/web/packages/fBonds/index.html>

as does the jrvFinance package:


with some others having 'yield' as keyword in their descriptions.

Also, there are a number of domain specific R e-mail lists, including one for Finance:

  https://stat.ethz.ch/mailman/listinfo/r-sig-finance <https://stat.ethz.ch/mailman/listinfo/r-sig-finance>

and you would avail yourself of a focused audience in the domain using that list, as opposed to R-Help for these types of questions.

Hopefully this will get you moving forward.


Marc Schwartz

	[[alternative HTML version deleted]]

More information about the R-help mailing list