Computing Bond Yield with Newton’s Method

In fixed income analysis it is often required to calculate the yield of some coupon paying instrument, for example a bond. Very simply, an yield of a bond is defined as a single rate of return. Under continuous compounding, given a set of interest rates $\{r_{T_1}, r_{T_2}, ..., r_{T_n}\}$, the yield $y$ equates the present value of the bond computed under a given set of rates. In other words:

$\sum_{i=1}^{n}exp(-r_{T_i}T_i) C_{T_i}=\sum_{i=1}^{n}exp(-yT_i) C_{T_i}$

where $C_{T_i}$ is a coupon paid out at time $T_i$. Usually, one solves for $y$ using some iterative guess-work, e.g. goal seek. In this post I will show you a well-know Newton’s recursive method that can be used to base such goal seek on.

The Newton’s Method

The Newton’s method is based on a recursive approximation formula:

$x_{i+1}=x_i-\frac{f(x_i)}{f'(x_i)}$

Let $B=\sum_{i=1}^{n}exp(-yT_i) C_{T_i}$ be the price(or present value) of the bond expressed via its yield. Then, taking $x$ to represent interest rate, we have:
$f(x) = \sum_{i=1}^{n}exp(-x_{T_i}T_i) C_{T_i} - B = 0$ and $f'(x)=-\sum_{i=1}^{n}T_i C_{T_i} exp (-x_{T_i}T_i)$

The recursive formula to solve for yield becomes:

$x_{i+1}=x_i+\frac{\sum_{i=1}^{n}exp(-x_{T_i}T_i) C_{T_i} - B}{\sum_{i=1}^{n}T_i C_{T_i} exp (-x_{T_i}T_i)}$

Goal Seek in C#

Now let’s take a look at an example implementation. The while loop in CalculateYield method implements the goal seek. This is a very simple example, and we pretend to have the bond price.

using System;
using System.Collections.Generic;
using System.Linq;

namespace YieldCalculator
{
class EntryPoint
{
static void Main(string[] args)
{
// use some numbers to illustrate the point
// maturities in months
int[] maturities = { 6, 12, 18, 24, 30, 36 };
double[] yearFrac = maturities.Select(i => i / 12.0).ToArray();
// bond principle
double P = 100;
// bond price
double B = 108;
double couponRate = 0.1;
// calculate future cashflows
double[] cashflows = maturities.Select(i => (P * couponRate) / 2.0).ToArray();
cashflows[cashflows.Count() - 1] = P + cashflows[cashflows.Count() - 1];

double initialGuess = 0.1;
Console.WriteLine(CalculateYield(initialGuess, cashflows, yearFrac, B));
}

static double CalculateYield(double initialGuess, double[] cashflows, double[] yearFrac, double B)
{
double error = 0.000000001;
double x_i = initialGuess-1.0;
double x_i_next = initialGuess;

double numerator;
double denominator;

while (Math.Abs(x_i_next - x_i) > error)
{
x_i = x_i_next;
// linq's Zip is handy to perform a sum over expressions involving several arrays
numerator = cashflows.Zip(yearFrac, (x,y) => (x * Math.Exp(y *-1*x_i))).Sum();
denominator = yearFrac.Zip(cashflows, (x,y) => (x*y*Math.Exp(x*-1*x_i))).Sum();
x_i_next = x_i + (numerator - B) / denominator;
}
return x_i_next;
}
}
}


Note how handy is LINQ’s Zip function to calculate a sum over an expression involving two arrays.

And now to the burning question – why the picture of a cat? The answer is even simpler than this post: It is a cute cat, so, why not?

Abstract Class vs. Interface and when to Use Both

I have recently come across a puzzling code example in one book. Here is a snapshot of the code:

public interface ITwoFactorPayoff
{ // The unambiguous specification of two-factor payoff contracts

// This interface can be specialized to various underlyings
double payoff(double factorI1, double factorII);
}
public abstract class MultiAssetPayoffStrategy: ITwoFactorPayoff
{

public abstract double payoff(double S1, double S2);
}


Can you see why I was puzzled? The web is full of advice for when to choose abstract class vs. interface and the other way around. Take for example, this MSDN link or this stackoverflow Q&A. Anyone who is not lazy has written something about this already. However, a discussion on when one would want to use both is somewhat lacking. And rightly so, you may say. The above code introduces a redundancy with no apparent benefit. Here, inheriting from MultiAssetPayoffStrategy class still requires to implement the payoff method. So, why not just use the interface? I would agree with you that the example is poorly designed (in spite of the fact that the book it comes from is an expensive one!). Nevertheless, it got me thinking – when would one actually want to have abstract classes implementing interfaces. Here are the reasons I have come up with. Would be interested to know if you can add anything to this.

Reason 1 – Tidy Code

This is the simplest reason, and the first one that came to my mind. Imagine you have 10 or more interfaces that, a class hierarchy you are working on requires to implement. That is, class A must implement interface1, interface2, …, interfaceN; class B also must implement these interfaces. In other words, a situation that looks like this:


public interface Interface1
{
void method_interface1();
}

public interface Interface2
{
void method_interface2();
}
...
public class A: Interface1, Interface2
{
void method_interface1() {...}
void method_interface2() {...}
...

}

public class B: Interface1, Interface2
{
void method_interface1() {...}
void method_interface2() {...}
...

}


A way to simplify the code is to introduce either another interface that inherits from all 10 interfaces or simply an abstract class that does the same. Then, class A and class B just need to inherit from a single abstract class or a single interface.

Reason 2 – Providing Default Implementation for Some but Not Other Members

An abstract class could provide a default behavior for some methods. I admit, this is different to the book’s example since that method is an abstract one. But we all know that an abstract class can have non-abstract methods. The derived class then has an option on which methods it needs to implement. Here is a simple example (note that default implementation is decorated as virtual):

namespace OOPDesign
{
public interface IPrice
{
double Price(double strike);
}

public interface IPrintPrice
{
void PrintPrice(double price);
}

public abstract class Pricer: IPrice, IPrintPrice
{
public abstract double Price(double strike);

public virtual void PrintPrice(double price)
{
Console.WriteLine(price);
}
}

internal sealed class OptionPricer: Pricer
{
public override double Price(double strike)
{
return strike + 15;
}

}

class EntryPoint
{
static void Main(string[] args)
{
double strike = 20;
OptionPricer op = new OptionPricer();
op.PrintPrice(op.Price(strike));
}
}
}


Reason 3 – Combining Class Hierarchy with Contracts

This is probably the most obvious reason for choosing abstract classes together with interfaces. An abstract class can serve as a design summary of what all derived classes should do. This can aid in implementing a well-known visitor pattern. To give some credit to the mentioned book, it eventually evolves the example code to be based on this design pattern. If you are not familiar with the visitor pattern, I suggest you google it. Below I am providing a C# implementation based on the Java example one can find in Wikipedia (although it is not a one-for-one translation, as I have simplified the code a bit). This visitor pattern example can be summed-up as follows. We start off with three contracts: 2 interfaces and one abstract class. The abstract class is here to tell all its concrete classes to implement one of the interfaces (the accept method). The other interface is for the “visiting” classes. These visiting classes don’t really know what they are visiting, as long as the concrete class can accept them (which is guaranteed since the concrete classes are of the parent type and implement the accept functionality.

namespace VisitorExample
{
public interface ICarElementVisitor
{
void visit(CarBodyPart part);
}

public interface ICarElement
{
void accept(ICarElementVisitor visitor);
}

public abstract class CarBodyPart: ICarElement
{
public abstract void accept(ICarElementVisitor visitor);
public abstract string Name { get;  }
public abstract string Action { get;  }
}

public sealed class Wheel: CarBodyPart
{
private string name;
private string action;

public Wheel(string name, string action)
{
this.name = name;
this.action = action;
}

public override void accept(ICarElementVisitor visitor)
{
visitor.visit(this);
}

public override string Name
{
get
{
return this.name; ;
}
}

public override string Action
{
get
{
return this.action; ;
}
}

}

public sealed class Engine : CarBodyPart
{

private string name;
private string action;

public Engine(string name, string action)
{
this.name = name;
this.action = action;
}

public override void accept(ICarElementVisitor visitor)
{
visitor.visit(this);
}

public override string Name
{
get
{
return this.name; ;
}
}

public override string Action
{
get
{
return this.action; ;
}
}
}

public sealed class Body : CarBodyPart
{

private string name;
private string action;

public Body(string name, string action)
{
this.name = name;
this.action = action;
}

public override void accept(ICarElementVisitor visitor)
{
visitor.visit(this);
}

public override string Name
{
get
{
return this.name; ;
}
}

public override string Action
{
get
{
return this.action; ;
}
}
}

public sealed class Car : CarBodyPart
{
ICarElement[] elements;
private string name;
private string action;

public Car()
{
this.name = "car";
this.action = "driving ";

this.elements = new ICarElement[]
{   new Wheel("front left wheel", "Kicking my "),
new Wheel("front right wheel", "Kicking my "),
new Wheel("back left wheel", "Kicking my ") ,
new Wheel("back right wheel", "Kicking my "),
new Body("Body", "Moving my "),
new Engine("Engine", "Starting my ")
};
}

public override void accept(ICarElementVisitor visitor)
{
foreach(ICarElement elem in elements)
{
elem.accept(visitor);
}
visitor.visit(this);
}

public override string Name
{
get
{
return this.name; ;
}
}

public override string Action
{
get
{
return this.action; ;
}
}
}

sealed class CarElementPrintVisitor:ICarElementVisitor
{
public void visit(CarBodyPart part)
{
Console.WriteLine("Visiting " + part.Name);
}
}

sealed class CarElementActionVisitor:ICarElementVisitor
{
public void visit(CarBodyPart part)
{
Console.WriteLine(part.Action + part.Name);
}
}

class EntryPoint
{
static void Main(string[] args)
{
ICarElement car = new Car();
car.accept(new CarElementPrintVisitor());
car.accept(new CarElementActionVisitor());