US Treasury notes and QuantLib

Here, we deal with US debt securities, and more specifically with US Treasury notes. Before turning to the C++/QuantLib code itself, we remind the reader with some bond-related terminology. And, we will conclude with short comments on our code.

Bond terminology refresh

Principal or face value: the amount invested in the bond.

Coupon: the periodic payment until the bond expires. It is a financial flow from the issuer toward the holder of the bond. The payments can occur at different time interval, it is generally annual or semi annual coupon. And, a bond can pay a fixed coupon or much less frequently a variable coupon.

Redemption value: a bond can be repurchased by the issuing company before expiration. That is redemption. And, the redemption value often is equal to the bond principal, but not always.

Clean price: the bond quoted without any accrued interest.

Accrued interest: the amount of interest built up since the last coupon payment.

Dirty price: it equals clean price + accrued interest. It is the actual payment received by the bond holder.

C++/QuantLib code

We now turn to the code.
__________________________
US Treasury security type:    note
Principal:                                            100
Issuing date:                                     January 27th, 2011
Settlement:                                       January 28th, 2011
Maturity:                                            August 31th, 2020
Coupon rate:                                    3,625%
Yield:                                                     3,4921%
________________________________

#include <ql/quantlib.hpp>
#include <iostream>
#include <iomanip>

#include <boost/timer.hpp>
using namespace QuantLib;

#if defined(QL_ENABLE_SESSIONS)
namespace QuantLib {
Integer sessionId() { return 0; }
}
#endif

int main(int, char* []) {

    try {

    boost::timer timer;
    std::cout << std::endl; 

	// date set up
	Calendar calendar = TARGET();

	Date settlementDate(28, January, 2011);
	// the settlement date must be a business day
	settlementDate = calendar.adjust(settlementDate);

	// Evaluation date
	Integer fixingDays = 1;
	Natural settlementDays = 1;
	Date todaysDate = calendar.advance(settlementDate, -fixingDays, Days);
	Settings::instance().evaluationDate() = todaysDate;

	// bond set up	
	Real faceAmount = 100.0;
	Real redemption = 100.0;
	Date issueDate(27, January, 2011);
	Date maturity(31, August, 2020);
	Real couponRate = 0.03625;
	Real yield = 0.034921;

	RelinkableHandle<YieldTermStructure> discountingTermStructure;
	boost::shared_ptr<YieldTermStructure> flatTermStructure(
	new FlatForward(
		settlementDate,
		yield,
		ActualActual(ActualActual::Bond),
		Compounding::Compounded,
		Semiannual));
	discountingTermStructure.linkTo(flatTermStructure);

	// Pricing engine
	boost::shared_ptr<PricingEngine> bondEngine(
		new DiscountingBondEngine(discountingTermStructure));

	 // Rate
	Schedule fixedBondSchedule(
		issueDate,
		maturity,
		Period(Semiannual),
		UnitedStates(UnitedStates::GovernmentBond),
		BusinessDayConvention::Unadjusted,
		BusinessDayConvention::Unadjusted,
		DateGeneration::Rule::Backward,
		false);

	FixedRateBond fixedRateBond(
		settlementDays,
		faceAmount,
		fixedBondSchedule,
		std::vector<Rate>(1, couponRate),
		ActualActual(ActualActual::Bond),
		BusinessDayConvention::Unadjusted,
		redemption,
		issueDate);

	fixedRateBond.setPricingEngine(bondEngine);

	std::cout << "Principal: " << faceAmount << std::endl;
	std::cout << "Issuing date: " << issueDate << std::endl;
	std::cout << "Maturity: " << maturity << std::endl;
	std::cout << "Coupon rate: " << std::setprecision (4) << io::percent(couponRate) << std::endl;
	std::cout << "Yield: " << std::setprecision (4) << io::percent(yield) << std::endl << std::endl;
	std::cout << "Net present value: " << std::setprecision (4) << fixedRateBond.NPV() << std::endl;
	std::cout << "Clean Price: " << std::setprecision (4) << fixedRateBond.cleanPrice() << std::endl;
	std::cout << "Dirty price: " <<  std::setprecision (4) << fixedRateBond.dirtyPrice() << std::endl;
	std::cout << "Accrued coupon: " <<  std::setprecision (4) << fixedRateBond.accruedAmount() << std::endl << std::endl;
	system("pause");
	return 0;

    } catch (std::exception& e) {
        std::cerr << e.what() << std::endl;
        return 1;
    } catch (...) {
        std::cerr << "unknown error" << std::endl;
        return 1;
    }
}



QuantLib has powerful tools to handle dates (date calculations, formatting, …) . A simple example in our code is :

Date settlementDate(28, January, 2011);
// the settlement date must be a business day
settlementDate = calendar.adjust(settlementDate);

settlementDate will be adjusted to the appropriate near business day according to the given convention, thanks to calendar.adjust(settlementDate).
Thus, QuantLib allows to value ‘for real’ in this case a US Treasury note. That implies it requires a precise knowledge of convention dates. How does the US Treasury cope with bank holidays ?

The reader may have noticed the try,  catch and throw statements that we introduced in a recent post. Here, the exception mechanism doesn’t actually do a great deal for us. But, coding exception mechanisms is a good practice to make.

Finally, we introduced the RelinkableHandle handles, even if we don’t take much advantage of them in this code example. One benefit is that values  passed in relinkable handles can then be relinked to some other data source later on.

14 pensamientos en “US Treasury notes and QuantLib

    1. édouard Autor de la entrada

      Besides the various industry standard calendars it includes (ISDA, ISMA, US Treasury bonds … ) , QuantLib allows to take into account other special calendar conventions (at the firm-level, for example).

      To understand how this part of the code works, consider these following lines :

      date settlementDate(28, January, 2011); // settlement date

      Date todaysDate = calendar.advance(settlementDate, -fixingDays, Days); // special date convention at the level of the firm

      Settings::instance().evaluationDate() = todaysDate; // all that is passed to todaysDate that is eventually is the date at wich the bond value is calculated

      Now, the ActualActual(ActualActual::Bond) declaration tells the program to use the US treasury bond calendar.

      Responder
  1. Newbie

    Thanks for the very helpful posts. I am new to quantlib, have played around a little with it.
    Most examples that I have seen are around building a yield curve from discount rates and other parameters.
    I have to build a spot yield curve from a given Yield to maturity curve. I will be grateful for any help on how this can be done with quantlib.

    Thanks

    Responder
  2. raj

    converted to C# (quantlib V 0.9.9)

    // date set up
    Calendar calendar = new TARGET();

    Date settlementDate = new Date(14, Month.July, 2011);
    // the settlement date must be a business day
    settlementDate = calendar.adjust(settlementDate);

    // Evaluation date
    Integer fixingDays = 1;
    Natural settlementDays = 1;
    Date todaysDate = calendar.advance(settlementDate, -fixingDays, TimeUnit.Days);
    Settings.instance().setEvaluationDate(new Date(14, Month.July, 2011));

    // bond set up
    Real faceAmount = 100.0;
    Real redemption = 100.0;
    Date issueDate = new Date(15, Month.July, 2011);
    Date maturity = new Date(30, Month.June, 2016);
    Real couponRate = 0.015;
    Real yield = 0.0148;

    YieldTermStructure flatTermStructure = new FlatForward(settlementDate, yield, new ActualActual(ActualActual.Convention.Bond), Compounding.Compounded, Frequency.Semiannual);
    YieldTermStructureHandle discountingTermStructure = new YieldTermStructureHandle(flatTermStructure);

    PricingEngine bondEngine = new DiscountingBondEngine(discountingTermStructure);

    // Rate
    Schedule fixedBondSchedule = new Schedule(issueDate, maturity,
    new Period(Frequency.Semiannual),
    new UnitedStates(UnitedStates.Market.GovernmentBond),
    BusinessDayConvention.Unadjusted,
    BusinessDayConvention.Unadjusted, DateGeneration.Rule.Backward, false);

    FixedRateBond fixedRateBond = new FixedRateBond(settlementDays, faceAmount, fixedBondSchedule, new DoubleVector(new Rate[] { couponRate }), new ActualActual(ActualActual.Convention.Bond),
    BusinessDayConvention.Unadjusted, redemption, issueDate);

    fixedRateBond.setPricingEngine(bondEngine);

    /*Clean price: the bond quoted without any accrued interest.

    Accrued interest: the amount of interest built up since the last coupon payment.

    Dirty price: it equals clean price + accrued interest. It is the actual payment received by the bond holder.
    *
    */

    Debug.WriteLine(“Principal: ” + faceAmount);
    Debug.WriteLine(“Issuing date: ” + issueDate.__str__());
    Debug.WriteLine(“Maturity: ” + maturity.__str__());
    Debug.WriteLine(“Coupon rate: ” + couponRate);
    Debug.WriteLine(“Yield: ” + yield);
    Debug.WriteLine(“Net present value: ” + fixedRateBond.NPV());
    Debug.WriteLine(“Clean Price: ” + fixedRateBond.cleanPrice());
    Debug.WriteLine(“Dirty price: ” + fixedRateBond.dirtyPrice());
    Debug.WriteLine(“Accrued coupon: ” + fixedRateBond.accruedAmount());

    Responder
    1. édouard Autor de la entrada

      Hello. Thank you for posting your code in C#.
      I would be keen to share ideas, codes and so on.
      If you have your own blog site feel free to advertise here🙂
      Cheers.
      Édouard

      Responder
  3. lesleyedwardsud

    Hello,

    I am trying to learn QuantLib by following each of your post, now I come to this US treasury notes example.
    When I try to compile this example, there`s error like:

    US_Treasury_Notes.cpp:52: error: ‘Compounding’ is not a class or namespace
    US_Treasury_Notes.cpp:66: error: ‘BusinessDayConvention’ is not a class or namespace
    US_Treasury_Notes.cpp:67: error: ‘BusinessDayConvention’ is not a class or namespace
    US_Treasury_Notes.cpp:68: error: ‘struct QuantLib::DateGeneration::Rule’ is not a class or namespace
    US_Treasury_Notes.cpp:77: error: ‘BusinessDayConvention’ is not a class or namespace

    I tried to find these classes like “Compounding” in this QuantLib online document:
    http://quantlib.sourcearchive.com/documentation/1.0.1/annotated.html

    But I failed. Is this a problem about different versions of QuantLib? If so, how could I modified your code in this part?

    Best Regards
    Lesley

    Responder
  4. lesleyedwardsud

    Hi, Edouard,

    Maybe there is a type here, just write here for reference:
    When you use following kind of code:

    boost::shared_ptr flatTermStructure(
    new FlatForward(
    settlementDate,
    yield,
    ActualActual(ActualActual::Bond),
    Compounding::Compounded,
    Semiannual));

    At lease in GNU on my MAC, “Compounding::Compounded” will receive a warning, “Compounding:: is not a class”. This bothers me a while, finally I realize, using the scope resolution operator:: on enums is a compiler-specific extension, not standard C++.

    Hopefully others will not have this problem. Please accept my sincere apology if this is a stupid post!

    Responder
    1. édouard Autor de la entrada

      Hi lesleyedwardsud. Thank you for your comment. I posted the code above as I compiled it. And, I don’t not remember problems of this kind occurred then at compilation-time.
      Best,
      Édouard

      Responder
      1. lesleyedwardsud

        Hi edouard,

        Sure I understand. Just a remark for others who may have similar problem🙂
        I really enjoy your blog. As a newbie to QuantLib I learned a lot here! Thanks!

  5. Thomas Materna

    Hi. QL’s very own example (in bonds.cpp) use ModifiedFollowing for the paymentConvention argument to the FixedRateBond constructor. I suspect that is right as I don’t see the Treasury paying a coupon e.g. on a Sunday. Am I right to think that you use the Unadjusted convention to price the bond from the “street convention” yield rather than the true yield (which would have to take holidays/weekend into account) ?

    Responder
    1. édouard Autor de la entrada

      Hi Thomas, thanks for visiting my blog.

      Please consider, the example code in this post as a demo code. Anyway, you are right unadjusted is certainly not the right business day convention.

      I am not sure, but I think that the right convention in the case of U.S. Treasury notes is following business day.

      I don’t think it is modified following.

      Best,
      Édouard

      Responder

Responder

Por favor, inicia sesión con uno de estos métodos para publicar tu comentario:

Logo de WordPress.com

Estás comentando usando tu cuenta de WordPress.com. Cerrar sesión / Cambiar )

Imagen de Twitter

Estás comentando usando tu cuenta de Twitter. Cerrar sesión / Cambiar )

Foto de Facebook

Estás comentando usando tu cuenta de Facebook. Cerrar sesión / Cambiar )

Google+ photo

Estás comentando usando tu cuenta de Google+. Cerrar sesión / Cambiar )

Conectando a %s