QuantLib provides a number of functions that calculate the NPV of a series of cash flows. These are defined as static methods inside the `CashFlows`

class. The simplest calculation of the NPV will take a constant interest rate over the period of the cash flows.

static Real npv(const Leg& leg, const InterestRate& yield, bool includeSettlementDateFlows, Date settlementDate = Date(), Date npvDate = Date()); static Real npv(const Leg& leg, Rate yield, const DayCounter& dayCounter, Compounding compounding, Frequency frequency, bool includeSettlementDateFlows, Date settlementDate = Date(), Date npvDate = Date());

The first function takes a `Leg`

of cash flows and an interest rate that defines the yield. The interest rate is passed using the InterestRate class. In short, `InterestRate `

contains information about interest rates such as the rate itself, the compounding rule, the frequency and a day counting convention. Note that this allows the `InterestRate`

class to calculate a discount factor for a given time interval. The settlement date can be passed as fourth argument. Only cash flows that occur on or after the settlement date will contribute to the NPV. The inclusion of cash flows on the settlement date is governed by the flag `includeSettlementDateFlows`

. As always the parameters are simply passed to the `hasOccured`

method of the cash flow to determine if the cash flow has already occurred. If the settlement date is not set the global evaluation date will be used. The last parameter can be used to specify a different date to which the cash flows are discount back to. This means that the discounting factor is calculated using `npvDate`

. If `npvDate`

is not set, the settlement date will be taken.

Note that the interest rate is calculated by compounding the factor calculated for the cash flow intervals. What this means is that the discount rate is calculated using the compounding rules defined in the `InteresRate yield`

object for the intervals between two cash flows. Let’s say that \(d_i\) and \(d_{i-1}\) are the dates of two successive cash flows, then the interval discount factor is calculated as a function of these two dates.

$$\mathrm{Discount Factor}_i = DInt_{i, i-1}(d_i, d_{i-1})$$

Here \(DInt\) is the discount rate calculated by the `InterestRate`

object and might use simple, continuous compounding or use a compounding discount factor with a frequency that does not necessarily match the frequency of the cash flows. To get the discount factor of a cash flow these interval discount factors are compounded by multiplying them together.

$$D_i = \prod_{i=1}^{N} DInt_{i, i-1}(d_i, d_{i-1})$$

The final net present value is then calculated using the individual discount factors.

$$\mathrm{NPV} = \sum_{i=1}^{N} D_i \times R_i$$

In many realistic cases, one won’t have a constant interest rate over the period of the cash flows. In this case the NPV of a `Leg`

has to be calculated using a yield curve. In QuantLib yield curves are represented by `YieldTermStructure`

.The `CashFlows`

class provides a static method for evaluating the NPV in this case.

Real npv(const Leg& leg, const YieldTermStructure& discountCurve, bool includeSettlementDateFlows, Date settlementDate = Date(), Date npvDate = Date());

As with the two methods described above, `includeSettlementDateFlows`

determines if cash flows on the settlement date are taken into account for the calculation. The date `settlementDate`

is the settlement date which enters into the `hasOccured`

method of the cash flows. Again, this means only cash flows on or after the settlement date are included in the calculation. The `npvDate`

is a date that the NPV is discounted back to. To understand what the function calculates, assume that \(D(d_i)\) is the discount factor returned by the yield curve for a given date \(d_i\). This discount factor is simply the return value of the `discount`

method of `YieldTermStructure`

. The NPV is then calculated using the formula

$$\mathrm{NPV} = \frac{\sum_{i=1}^{N} D(d_i) \times R_i}{D(\mathrm{npvDate})}$$

The last function for calculating the NPV takes the zero spread of the cash flows into account.

Real npv(const Leg& leg, const boost::shared_ptr<YieldTermStructure>& discount, Spread zSpread, const DayCounter& dayCounter, Compounding compounding, Frequency frequency, bool includeSettlementDateFlows, Date settlementDate = Date(), Date npvDate = Date());

This function uses the zero spread, given by `zSpread`

, the day counter, the compounding rule and the frequency to construct a modified yield curve. This modified yield curve is simply the original curve passed to the function with an added zero spread. The modified curve is then passed to the previous function for calculating the NPV.

`CashFlow`

class, typedef std::vector< boost::shared_ptr<CashFlow> > Leg;

The functions for analysing cash flows are, somewhat confusingly, defined as static member functions of a class called `CashFlows`

. Notice the plural **s** at the end and don’t confuse it with the `CashFlow`

class that holds information about a single cash flow event. Many methods assume that the cash flows in a leg are sorted by their date as given by `Event::date()`

. This will not be pointed out individually for the methods described below.

In this post I will be talking about some basic methods defined inside the `CashFlows`

. These methods can be used to obtain dates or amounts of specific cash flows. In subsequent posts will focus on the methods that evaluate the cash flows and calculate data such as the NPV.

You can find the start date and end date of a `Leg`

using the `startDate`

and `endDate`

methods. The method `isExpired`

will return true when the leg is expired and false if it isn’t.

static Date startDate(const Leg& leg); static Date maturityDate(const Leg& leg); static bool isExpired(const Leg& leg, bool includeSettlementDateFlows, Date settlementDate = Date());

`startDate`

will find and return the earliest date in `leg`

. For most cash flows, the dates are taken from the `date`

method of the `Event`

class. For `Coupon`

cash flows, on the other hand, the start date of the accrual period is obtained by calling the `accrualStartDate`

method. Similarly `maturityDate`

will return the latest cash flow in the leg. For `Coupon`

cash flows the `accrualEndDate`

is taken to be the relevant date, for all other cash flows the normal date returned by `date`

is used.

The method `isExpired`

will query all cash flows if they have occurred. If all cash flows return `true`

then the leg is expired and `isExpired`

returns true. If one of the cash flows returns `false`

when queried via the `hasOccured`

method then `isExpired`

will return `false`

. The `settlementDate`

and `includeSettlementDateFlows`

parameters are simply passed on to the `hasOccured`

method in the `Event`

class. If the settlement date is not specified then the `Settings::evaluationDate`

will be used. An empty leg is considered expired.

static Leg::const_reverse_iterator previousCashFlow(const Leg& leg, bool includeSettlementDateFlows, Date settlementDate = Date()); static Leg::const_iterator nextCashFlow(const Leg& leg, bool includeSettlementDateFlows, Date settlementDate = Date()); static Date previousCashFlowDate(const Leg& leg, bool includeSettlementDateFlows, Date settlementDate = Date()); static Date nextCashFlowDate(const Leg& leg, bool includeSettlementDateFlows, Date settlementDate = Date()); static Real previousCashFlowAmount(const Leg& leg, bool includeSettlementDateFlows, Date settlementDate = Date()); static Real nextCashFlowAmount(const Leg& leg, bool includeSettlementDateFlows, Date settlementDate = Date());

The method `previousCashFlow`

will return the last cash flow on or before a given date while `nextCashFlow`

will return the next cash flow after a given date. The methods use the `hasOccured`

method of the `Event`

class to decide if a cash flow has occurred. As with `isExpired`

, the `settlementDate`

and `includeSettlementDateFlows`

parameters are passed on to `hasOccured`

and an empty settlement date will mean that the global evaluation date is used.

`previousCashFlow`

will return a reverse iterator pointing to the last cash flow that has occurred while `nextCashFlow`

will return a forward iterator to the first cash flow that has not occurred. If no cash flow was found that matches the critetria then `previousCashFlow`

will return `leg.rend()`

while `nextCashFlow`

will return `leg.end()`

. The advantage of returning a reverse iterator from `previousCashFlow`

is that you can easily iterate over all cash flows that have already occurred.

The other four methods are convenience methods that return the date or amount of the cash previous or next cash flow. `previousCashFlowDate`

calls `previousCashFlow`

and returns the date of the cash flow, and similarly `nextCashFlowDate`

calls `nextCashFlow`

and returns the date. In both cases a null `Date`

is returned if no cash flow was found.

`previousCashFlowAmount`

and `nextCashFlowAmount`

will return the amount of the previous or next cash flow. Again the cash flows are found by calling `previousCashFlow`

or `nextCashFlow`

. If there are multiple cash flows that occur at the same date then all their amounts are added together. If no cash flow is found a value of zero is returned.

QuantLib defines many different types of cash flows and, using polymorphism, a `Leg`

array can hold objects of different cash flow classes. However, in some cases one might be interested only in cash flows of a single type. Specifically, there are many cases in which only the `Coupon`

cash flows should be taken into account. The `CashFlows`

class defines a number of methods that only consider coupons within a cash flow and return `Coupon`

related information. In this section I will discuss only the functions that return basic information about coupon dates and periods. The functions that perform calculations on coupons are dealt with in a future post.

static Date accrualStartDate(const Leg& leg, bool includeSettlementDateFlows, Date settlDate = Date()); static Date accrualEndDate(const Leg& leg, bool includeSettlementDateFlows, Date settlementDate = Date()); static Date referencePeriodStart(const Leg& leg, bool includeSettlementDateFlows, Date settlDate = Date()); static Date referencePeriodEnd(const Leg& leg, bool includeSettlementDateFlows, Date settlDate = Date()); static Time accrualPeriod(const Leg& leg, bool includeSettlementDateFlows, Date settlementDate = Date()); static BigInteger accrualDays(const Leg& leg, bool includeSettlementDateFlows, Date settlementDate = Date()); static Time accruedPeriod(const Leg& leg, bool includeSettlementDateFlows, Date settlementDate = Date()); static BigInteger accruedDays(const Leg& leg, bool includeSettlementDateFlows, Date settlementDate = Date()); static Real accruedAmount(const Leg& leg, bool includeSettlementDateFlows, Date settlementDate = Date());

If you look at the documentation of coupons, you will notice that these methods are direct mirror images of the methods defined by the `Coupon`

class. All these methods will find the first `Coupon`

cash flow in the leg that has not yet occurred. Then they call the respective method on that coupon.

For example the method `accruedPeriod`

defined within `CashFlows`

will first find the first `Coupon`

object in leg that occurred after `settlementDate`

. Once a coupon, let’s call it `cp`

, is found the method will return `cp.accruedPeriod`

. If no coupon is found a sensible default value will be returned, in this case a period of 0.0. In all methods that return a numerical value the default is zero, for methods that return a date the default is an empty `Date`

object. As in `nextCashFlow`

, if the settlement date is not specified then the `Settings::evaluationDate`

will be used. The `hasOccurred`

method is called, with the settlement date and the `includeSettlementDate`

parameter, to find the cash flow that has not yet occurred.

Two Coupon related function behave slightly differently to the functions above.

static Rate previousCouponRate(const Leg& leg, bool includeSettlementDateFlows, Date settlementDate = Date()); static Rate nextCouponRate(const Leg& leg, bool includeSettlementDateFlows, Date settlementDate = Date());

The function will return the coupon rate of the previous or the next coupon in the leg, with respect to the settlement date. In some cases the leg might contain multiple coupons for the same date. If this is the case then an aggregate rate will be calculated for all coupons that occur on the same date. This aggregate rate is simply the sum of all the rates of the coupons on that date. However, for the calculation to be successful all coupons on that date must have the same nominal value, accrual period and must be using the same day counter.

]]>The constructor of the base class **Dividend** takes only the payment date of the dividend.

Dividend(const Date& date);

The date is stored in the **Dividend** object and can be inspected by the **date()** method.

Date date() const;

This method also implements the **Event** interface which **CashFlow** inherited from.

virtual Real amount() const = 0; virtual Real amount(Real underlying) const = 0;

The **amount()** method is re-declared from the **CashFlow** class and another amount method is added which takes the value of an underlying entity. Both method are abstract and are implemented by the **FixedDividend** and the **FractionalDividend** class.

virtual void accept(AcyclicVisitor&);

The **accept()** method allows visitation by the acyclic visitor.

The **FixedDividend** class implements a dividend with a fixed amount that is paid out at the specified date. The constructor takes the dividend amount and the date.

FixedDividend(Real amount, const Date& date)

Once the **FixedDividend** object is created, the values cannot be modified. The class implements the two **amount()** methods.

virtual Real amount() const; virtual Real amount(Real) const;

Both versions of **amount()** return the amount passed to the object in the constructor. The value of an underlying is ignored.

A global utility function lets you quickly create an stl:: vector of fixed dividends from a vector of dates and a vector of amounts.

std::vector<boost::shared_ptr<Dividend> > DividendVector(const std::vector<Date>& dividendDates, const std::vector<Real>& dividends);

This method will construct **FixedDividend** objects and store them in a vector of pointers to dividends. Each date is paired with an amount. The two vector containing the dates and values have to contained the same number of elements, otherwise an exception is thrown.

The **FractionalDividend** implements dividend cash flows that amount to a given fraction of the value of an underlying entity. They can be constructed by specifying the rate and the cash flow date, or by additionally specifying a nominal value of the underlying.

FractionalDividend(Real rate, const Date& date); FractionalDividend(Real rate, Real nominal, const Date& date);

The nominal does not have to be specified if the amount is always calculated using the value of the underlying. Note that, once the object has been created, the object is immutable. In particular, the nominal value cannot be set or changed. The two **amount()** methods are also implemented.

virtual Real amount() const; virtual Real amount(Real underlying) const;

The first version uses the nominal value and returns *rate * nominal*. This version actually implements the **CashFlow** interface. If the nominal value has not been set in the constructor then an exception is thrown. The second version returns* rate * underlying* and ignores the nominal value.

Two inspection methods return the values of the rate and the nominal value respectively.

Real rate() const; Real nominal() const;

In the following code we construct an array of **Dividend** cash flows from data contained in a file and then write out the data.

std::ifstream input("dividends.txt"); int day, month, year; int fixed; Real value; Real rate, nominal; typedef boost::shared_ptr<Dividend> pCashFlow; std::list<pCashFlow> dividends; input >> day >> month >> year >> fixed; while (input) { // convert number into a month Date d = Date(day,January,year) + (month-1)*Months; if (fixed== 1) { input >> value; pCashFlow dividend(new FixedDividend(value, d)); dividends.push_back(dividend); } else { input >> rate >> nominal; pCashFlow dividend(new FractionalDividend(rate, nominal, d)); dividends.push_back(dividend); } input >> day >> month >> year >> fixed; } BOOST_FOREACH(pCashFlow cashFlow, dividends) { std::cout << cashFlow->date() << " " << cashFlow->amount() << std::endl; }

In the example code **Dividend** objects are read from a data file and inserted into a list of **CashFlow** objects. The first three columns in the input file specify the payment date of the dividend. The fourth column is a flag that specifies if the dividend is fixed or fractional. For a fixed dividend only one more value is read and stored in the dividend amount. For fractional dividends twovalues are read from the file and passed to the FractionalDividend as rate and nominal value. After reading the data, all the cash flow amounts are written to the console using a loop over the list. Assume that the file dividends.txt contained the following ficticious data

15 1 2013 0 0.09 100.0 15 4 2013 0 0.10 100.0 15 7 2013 0 0.11 100.0 15 10 2013 1 20.0

This produces the output

January 15th, 2013 9 April 15th, 2013 10 July 15th, 2013 11 October 15th, 2013 20

]]>

Coupons are initialised by passing the appropriate values to the constructor

Coupon(const Date& paymentDate, Real nominal, const Date& accrualStartDate, const Date& accrualEndDate, const Date& refPeriodStart = Date(), const Date& refPeriodEnd = Date());

The parameters are pretty self explanatory, **paymentDate** is the payment date of the coupon and **nominal** is the nominal value of the coupon. The start and end of the accrual period are passed in the variables **accrualStartDate** and **accrualEndDate**. The ISMA variant of the Actual/Actual day counter will take into account a reference period to calculate the fraction of a year, which is needed to evaluate the accrued amount. This reference period is specified by **refPeriodStart** and **refPeriodEnd**. These do not have to be specified if not needed and their default values are empty **Date** objects.

Since **Coupon** indirectly inherits from the **Event** class it has to implement the **date()** method, which returns the payment date. A list of all methods allowing to read the properties are given here.

Date date() const; Real nominal() const; const Date& accrualStartDate() const; const Date& accrualEndDate() const; const Date& referencePeriodStart() const; const Date& referencePeriodEnd() const;

The **nominal()** method returns the nominal value of the coupon. The two methods **accrualStartDate()** and **accrualEndDate()** return the start date and the end date of the accrual period respectively. The reference period start date and end date are returned by the two methods **refPeriodStart()** and **refPeriodEnd()**. The **Coupon **also defines three abstract virtual methods.

virtual Real rate() const = 0; virtual DayCounter dayCounter() const = 0; virtual Rate accruedAmount(const Date&) const = 0;

The **rate()** method is intended to return the rate of the coupon and should be implemented by any concrete coupon type. The day counting convention associated with the coupon should be returned by the **dayCounter()** method. Finally, the amount accrued up to a given date should be returned by the **accruedAmount()** method.

The remainder of the methods are convenience methods that use the above methods to perform some calculations which are common to all coupons.

Time accrualPeriod() const; BigInteger accrualDays() const; Time accruedPeriod(const Date&) const; BigInteger accruedDays(const Date&) const;

All four methods use the day counter to calculate either a fraction of a year or the number of days between certain dates. The **accrualPeriod()** method gives the fraction of the year of one accrual period, i.e. between the accrual start date and the accrual end date. Similarly, the **accrualDays()** method returns the number of days in the accrual period. The **accruedPeriod()** and the **accruedDays()** methods return the fraction of a year and the number of days, respectively, between the accrual start date and the date passed as argument. If the date passed to either function does not lie within the accrual period, the functions will return zero.

**CashFlow** inherits from the **Event** interface. The **Event::date()** method is still left as an abstract method. The method **hasOccured()** is changed so that the global setting is taken into account. The **Settings** singleton defines a method

boost::optional &Settings::includeTodaysCashFlows();

If set, this setting overrides any **includeRefDate** parameter passed to the **hasOccurred()** method.

The method that has been added to the **CashFlow** interface is the **amount()** method. The declaration is

virtual double amount() = 0;

This method should be implemented by a cash flow class to return the cash flow amount.

In addition to the above, the **CashFlow** class implements the Visitability concept. This means it has a method called **accept()** which accepts an **AcyclicVisitor**.

virtual void accept(AcyclicVisitor &v);

The visitability concept is dealt with in a separate article. Here we will only state that the **accept()** method attempts to convert the visitor into the **Visitor<CashFlow>** type using a dynamic typecast. If the cast is successful, the **visit** method of the visitor class is called.

The file **cashflow.hpp** also includes a type definition for **Leg**, a collection of cash flows.

typedef std::vector > Leg;

As an example consider the simplest cash flow class **SimpleCashFlow**. This class represents a fixed cash flow at a specific date. The constructor of this class takes a date and the amount and these values are stored internally.

SimpleCashFlow(Real amount, const Date& date);

The **date() **method is implemented to return the specified date, and the** amount() **method is implemented to return the specified amount.

Two more cash flows exist that inherit from **SimpleCashFlow** without adding any more functionality. These are the classes **Redemption** and **AmortizingPayment**.

The reason for defining these two cash flows is for visitors to distinguish between different types of cash flows. Visitation is dealt with in a separate post and an example involving these cash flows is given there. Suffice to say here that these two cash flows re-implement the **accept()** method which attempts to call the appropriate function of the visitor passed to them.