<< . .

( 20)

. . >>


int main(){
for (int n=1;n<6;n++){
cout << " 2^" << n << " = " << power(2,n) << endl;

Code 1.1: A complete program

When compiled, linked and run, the program will provide the following output

2^1 = 2

2^2 = 4
2^3 = 8
2^4 = 16
2^5 = 32

1.2.8 Namespaces

To help in building large programs, the concept of a namespace was introduced. Namespaces are a means
of keeping the variables and functions de¬ned local to the context in which they are used. For now it
is necessary to know that any function in the standard C++ library lies in its own namespace, called the
standard namespace. To actually access these library functons it is necessary to explicitly specify that one
wants to access the standard namespace, by the statement

using namespace std;

Instead of such a general approach, one can also specify the namespace on an element by element basis, but
this is more a topic for specialized C++ texts, for the current purposes we will allow all routines access to
the whole standard namespace.

1.3 Extending the language, the class concept.

One of the major advances of C++ relative to other programming languages is the programmers ability to
extend the language by creating new data types and de¬ning standard operations on these data types. This
ability is why C++ is called an object oriented programming language, since much of the work in programming
is done by creating objects. An object is best though of as a data structure with operations on it de¬ned.
How one uses an object is best shown by an example.

1.3.1 date, an example class

Consider the abstract concept of a date. A date can be speci¬ed in any number of ways. Let us limit
ourselves to the Gregorian calendar. 12 august 2003 is a common way of specifying a date. However, it
can also be represented by the strings: “2003/8/12”, “12/8/2003” and so on, or by the number of years
since 1 january 1900, the number of months since January, and the day of the month (which is how a UNIX
programmer will think of it).
However, for most people writing programs the representation of a date is not relevant, they want to be able
to enter dates in some abstract way, and then are conserned with such questions as:

• Are two dates equal?
• Is one date earlier than another?
• How many days is it between two dates?

A C++ programmer will proceed to use a class that embodies these uses of the concept of a date. Typically
one will look around for an extant class which has already implemented this, but we will show a trivial such
date class as an example of how one can create a class.
A class is de¬ned in a header ¬le, as shown in code 1.2. A number of things is worth noting here. As internal
representation of the date is chosen the three integers day , month and year . This is the data structure
which is then manipulated by the various functions de¬ned below.
The functions are used to

• Create a date variable: date(const int& d, const int& m, const int& y);
• Functions outputting the date by the three integer functions day(), month() and year().

#include <string>
using namespace std;

class Date {
int year ;
int month ;
int day ;
date(const int& d, const& int m, const& int y);

int day() const;
int month() const;
int year() const;

void set day (const int& day );
void set month (const int& month );
void set year (const int& year );

date operator ++(); // pre¬x
date operator ++(int); // post¬x
’’(); //
date operator pre¬x
date operator // post¬x

bool operator == (const date&, const date&); // comparison operators
bool operator != (const date&, const date&);
bool operator < (const date&, const date&);
bool operator > (const date&, const date&);
bool operator <= (const date&, const date&);
bool operator >= (const date&, const date&);

Code 1.2: De¬ning a date class

• Functions setting the date set day(int), set month(int) and set year(int), which are used by
providing an integer as arguments to the function.

• Increment and decrement functions ++ and --
• Comparison functions <, <=, >, >=, == and !-.

After including this header ¬le, programmers using such a class will then treat an object of type date just
like any other.
For exmple,

date d(1,1,2001);

would result in the date object d containing the date 2 january 2001.
Any C++ programmer who want to use this date object will only need to look at the header ¬le to know
what are the possible functions one can use with a date object, and be happy about not needing to know
anything about how these functions are implemented. This is the encapsulation part of object oriented
programming, all relevant information about the date object is speci¬ed by the header ¬le. This is the only
point of interaction, all details about implementation of the class objects and its functions is not used in
code using this object.

1.4 Const references

Consider two alternative calls to a function, de¬ned by function calls:

some_function(double r);
some_function(const double& r);

They both are called by an argument which is a double, and that argument is guaranteed to not be changed
in the calling function, but they work di¬erently. In the ¬rst case a copy of the variable referenced to in the
argument is created for use in the function, but in the second case one uses the same variable, the argument
is a reference to the location of the variable. The latter is more e¬cient, in particular when the argument
is a large class. However, one worries that the variable referred to is changed in the function, which in most
cases one do not want. Therefore the const quali¬er, it says that the function can not modify its argument.
The compiler will warn the programmer if an attempt is made to modify such a variable.
For e¬ciency, in most of the following routines arguments are therefore given as as constant references.

Chapter 2

The value of time
2.1 Present value. . . . . . . . . .......... . . . . . . . . .......... . . 11
2.2 Internal rate of return. . . . .......... . . . . . . . . .......... . . 12
2.2.1 Check for unique IRR . . ........... . . . . . . . . ........... . . 15
2.3 Bonds . . . . . . . . . . . . . .......... . . . . . . . . .......... . . 16
2.3.1 Bond Price . . . . . . . . ........... . . . . . . . . ........... . . 16
2.3.2 Yield to maturity. . . . . ........... . . . . . . . . ........... . . 17
2.3.3 Duration. . . . . . . . . . ........... . . . . . . . . ........... . . 19

Finance as a ¬eld of study is sometimes somewhat ¬‚ippantly said to deal with the value of two things: time
and risk. While this is not the whole story, there is a deal of truth in it. These are the two issues which is
always present. We start our discussion by ignoring risk and only considering the implications of the fact
that anybody prefers to get something earlier rather than later, or the value of time.

2.1 Present value.

The calculation of present value is one of the basics of ¬nance. The present value is the current value of a
stream of future payments. Let Ct be the cash ¬‚ow at time t. Suppose we have N future cash ¬‚ows that
occur at times t1 , t2 , · · · , tN .

C1 C2 CN
0 t1 t2 tN

To ¬nd the present value of these future cash ¬‚ows one need a set of prices of future cash ¬‚ows. Suppose Pt
is the price one would pay today for the right to recive one dollar at a future date t. If one knows this set
of prices one would calculate the present value as the sum of the preent values of the di¬erent elements.
PV = Pti Cti

Ct1 Ct2 CtN
0 1 2 t

Pt1 Ct1 '
t2 t2


However, knowing the set of prices of all future dates is not always feasible. As a ¬rst approximation we
assume that there is one interest rate which is used for discounting, (this is termed a ¬‚at term structure),

and the prices of future payments Pt , which is also called a discount factor , is calculated from this interest
The best known example, known as discrete compounding, is calculated as
Pt = ,
(1 + r)t

In this case one would calculate the present value as
PV =
(1 + r)t

The implementation of this calculation is shown in code 2.1

#include <cmath>
#include <vector>
using namespace std;

double cash ¬‚ow pv discrete(const vector<double>& c¬‚ow times,
const vector<double>& c¬‚ow amounts,
const double& r){
double PV=0.0;
for ( int t=0; t<c¬‚ow times.size();t++) {
PV += c¬‚ow amounts[t]/pow(1+r,c¬‚ow times[t]);
return PV;

Code 2.1: Present value with discrete compounding

However, such discrete compounding is not the only alternative way to approximate the discount factor.
The discretely compounded case assumes that interest is added at discrete points in time (hence the name).
However, an alternative assumption is to assume that interest is added continously. If compounding is
continous, and r is the interes rate, one would calculate the current price of reciving one dollar at a future
date t as

Pt = e’rt ,

which implies the following present value calculation:
e’rti Cti
PV =

This calculation is implemented as shown in code 2.2. In much of what follows we will work with this
continously compounded case. There is a number of reasons why, but a prime reason is actually that it is
easier to use continously compounded interest than discretely compounded, because it is easier to deal with
uneven time periods. Discretely compounded interest is easy to use with evenly spaced cash ¬‚ows (such as
annual cash ¬‚ows), but harder otherwise.

2.2 Internal rate of return.

The internal rate of return of a set of cash ¬‚ows is the interest rate that makes the present value of the cash
¬‚ows equal to zero. Finding an internal rate of return is thus to ¬nd a root of of the equation

P V (C, t, r) = 0

#include <cmath>
#include <vector>
using namespace std;

double cash ¬‚ow pv( const vector<double>& c¬‚ow times,
const vector<double>& c¬‚ow amounts,
const double& r){
double PV=0.0;
for (int t=0; t<c¬‚ow times.size();t++) {
PV += c¬‚ow amounts[t] * exp(’r*c¬‚ow times[t]);
return PV;

Code 2.2: Present value calculation with continously compounded interest

As any textbook in basic ¬nance, such as Brealey and Myers [1996] or Ross et al. [1996] or will tell, there is
a number of problems with using the IRR, most of them stemming from the possibility for more than one
interest rate being de¬ned.
If we know that there is one IRR, the following method is probably simplest, bisection. It is an adaption
of the bracketing approach discussed in Press et al. [1992], chapter 9. Note that this approach will only
¬nd one interest rate, if there is more than one irr, the simplest is always to graph the PV as a function of
interest rates, and use that to understand when an investment is a good one.

#include <cmath>
#include <algorithm>
#include <vector>
using namespace std;
#include "fin_recipes.h"

const double ERROR=’1e30;

double cash ¬‚ow irr(const vector<double>& c¬‚ow times,
const vector<double>& c¬‚ow amounts) {
// simple minded irr function. Will ¬nd one root (if it exists.)
// adapted from routine in Numerical Recipes in C.
if (c¬‚ow times.size()!=c¬‚ow amounts.size()) return ERROR;
const double ACCURACY = 1.0e’5;
const int MAX ITERATIONS = 50;
double x1=0.0;
double x2 = 0.2;

// create an initial bracket, with a root somewhere between bot,top
double f1 = cash ¬‚ow pv(c¬‚ow times, c¬‚ow amounts, x1);
double f2 = cash ¬‚ow pv(c¬‚ow times, c¬‚ow amounts, x2);
int i;
for (i=0;i<MAX ITERATIONS;i++) {
if ( (f1*f2) < 0.0) { break; }; //
if (fabs(f1)<fabs(f2)) {
f1 = cash ¬‚ow pv(c¬‚ow times,c¬‚ow amounts, x1+=1.6*(x1’x2));
else {
f2 = cash ¬‚ow pv(c¬‚ow times,c¬‚ow amounts, x2+=1.6*(x2’x1));
if (f2*f1>0.0) { return ERROR; };
double f = cash ¬‚ow pv(c¬‚ow times,c¬‚ow amounts, x1);
double rtb;
double dx=0;
if (f<0.0) {
rtb = x1;
else {
rtb = x2;
dx = x1’x2;
for (i=0;i<MAX ITERATIONS;i++){
dx *= 0.5;
double x mid = rtb+dx;
double f mid = cash ¬‚ow pv(c¬‚ow times,c¬‚ow amounts, x mid);
if (f mid<=0.0) { rtb = x mid; }
if ( (fabs(f mid)<ACCURACY) | | (fabs(dx)<ACCURACY) ) return x mid;
return ERROR; // error.

Code 2.3: Estimation of the internal rate of return

2.2.1 Check for unique IRR

If you worry about ¬nding more than one IRR, the code shown in code 2.4 implements a simple check for
that. It is only a neccesary condition for a unique IRR, not su¬cient, so you may still have a well-de¬ned
IRR even if this returns false.
The ¬rst test is just to count the number of sign changes in the cash ¬‚ow. From Descartes rule we know that
the number of real roots is one if there is only one sign change. If there is more than one change in the sign
of cash ¬‚ows, we can go further and check the aggregated cash ¬‚ows for sign changes (See Norstrom [1972],
or Berck and Syds¦ter [1995]).

#include <cmath>
#include <vector>
using namespace std;

inline int sgn(const double& r){ if (r>=0) {return 1;} else {return ’1;}; };

bool cash ¬‚ow unique irr(const vector<double>& c¬‚ow times,
const vector<double>& c¬‚ow amounts) {
int sign changes=0; // ¬rst check Descartes rule
for (int t=1;t<c¬‚ow times.size();++t){
if (sgn(c¬‚ow amounts[t’1]) !=sgn(c¬‚ow amounts[t])) sign changes++;
if (sign changes==0) return false; // can not ¬nd any irr
if (sign changes==1) return true;

double A = c¬‚ow amounts[0]; // check the aggregate cash ¬‚ows, due to Norstrom
sign changes=0;
for (int t=1;t<c¬‚ow times.size();++t){
if (sgn(A) != sgn(A+=c¬‚ow amounts[t])) sign changes++;
if (sign changes<=1) return true;
return false;

<< . .

( 20)

. . >>

Copyright Design by: Sunlight webdesign