Rich Newman

August 8, 2011

A Beginner’s Guide To Credit Default Swaps (Part 4)


This post continues the discussion of changes in the credit default swap (CDS) since 2007.  Part 2 and part 3 of this series of articles discussed changes in the mechanics of CDS trading.  This part will discuss changes around how credit events are handled, and future changes in the market.

Changes in the CDS Market re Credit Events Since 2007

  • Determination committees (DCs) have been set up to work out if a credit event has occurred, and to oversee various aspects of dealing with a credit event for the market.  A ‘determination committee’ is simply a group of CDS traders of various kinds, although overseen by ISDA (the standards body). The parties to one of the new standard contracts agree to be bound by the committee’s decisions.
  • Auctions are now conducted to determine the price to cash-settle credit default swaps when there is a credit event.  For this we need to determine the current price of the bonds in default.  To do this we get a group of dealers to quote prices at which they are prepared to trade the bonds (and may have to), and then calculate the price via an averaging process.  This can get quite complicated.  The determination committees oversee these auctions.
  • Classes of events that lead to credit events have been simplified.  In particular whether ‘restructuring’ is a credit event has been standardized (although the standards are different in North America, Asia and Europe).  ‘Restructuring’ means such things as changing the maturity of a bond, or changing its currency.
  • There is now a ‘lookback period’ for credit events regardless of when a CDS is traded.  What this means is that credit events that have happened in the past 60 days (only) can trigger a contract payout.  This simplifies things because the same CDS traded on different days is now treated identically in this regard.

Terminology and a Little History

The changes described so far in this article were introduced in 2009.  For North America, which went first, this was known as ‘CDS Big Bang’.  The standard contract terms thus introduced were known as the ‘Standard North American CDS Contract’ or ‘SNAC’ (pronounced ‘snack’).  The later changes in Europe were known as the ‘CDS Small Bang’The final standardization of Asian contracts occurred later still.

Much more detail on all of this can be found on the links to the excellent MarkIt papers above.

Future Changes

Further standardization in the credit default swap market will occur as a result of the Dodd-Frank Act in the USA. This mandates that standard swaps (such as standard CDS) be traded through a ‘swap execution facility’ (SEF). It further mandates that any such trades be cleared through a central clearing house.  Europe is likely to impose a similar regulatory regime, but is behind the United States.  More detail on SEFs and clearing houses is below.

The primary aims of these changes are:

1/ Greater transparency of trading. Currently many swaps are traded over-the-counter with no disclosure other than between the two counterparties. This makes it different to assess the size of the market, or the effects of a default.

2/ Reduced risk in the market overall from the bankruptcy of one participant.

The exact details of these changes are still being worked on by the regulators.

Swap Execution Facilities (SEFs)

At the time of writing it’s not even clear exactly what a ‘SEF’ is.  The Act defines a SEF as a “facility, trading system or platform in which multiple participants have the ability to execute or trade Swaps by accepting bids and offers made by other participants that are open to multiple participants”. That is, a SEF is a place where any participant can see and trade on current prices. There are some additional requirements of SEFs relating to providing public data relating to price and volume, and preventing market abuses.

In many ways a SEF will be very similar to an existing exchange. As mentioned the exact details are still being worked on.

A number of the existing electronic platforms for the trading of CDS are likely to become SEFs.

Clearing Houses

Central clearing houses are another mechanism for reducing risk in a market.

When a trade is done both parties to the trade can agree that it will be cleared through a clearing house.  This means that the clearing house becomes the counterparty to both sides of the trade: rather than bank A buying from bank B, bank A buys from the clearing house, and bank B sells to the clearing house.

Obviously the clearing house has no risk from the trades themselves.  The clearing house is exposed to the risk that either bank A or bank B goes bankrupt and thus can’t pay its obligations from the trade.  To mitigate this the clearing house will demand cash or other assets from both banks A and B.  This is known as ‘margin’.

The advantage of this arrangement is that the clearing house can guarantee that bank A will be unaffected even if bank B goes bankrupt.  The only counterparty risk for bank A is that the clearing house itself goes bankrupt.  This is unlikely since the clearing house will have no market risk, be well capitalized, and demands margin for all transactions.

Clearing houses and exchanges are often linked (and may be the same entity), but they are distinct concepts: the exchange is the place where you go to get prices and trade, the clearing house deals with the settlement of the trade. Usually clearing houses only have a restricted number of ‘members’ who are allowed to clear trades. Anyone else wanting clearing services has to get them indirectly through one of these members.

At the time of writing there are already a few central clearing houses for credit default swaps in operation, and more are on the way.


Since 2007 contracts for credit default swaps have been standardized.  This has simplified the way in which the market works overall: it’s reduced the scope for difficulties when a credit event happens, simplified the processing of premium payments, and allowed similar CDS contracts to be netted together more easily.  At the same time it has made understanding the mechanics of the market more difficult.

Further changes are in the pipeline for the CDS market to use ‘swap execution facilities’ and clearing houses.

August 4, 2011

A Beginner’s Guide to Credit Default Swaps (Part 3)


Part 1 of this series of articles described the basic mechanics of a credit default swap.

Part 2 started to describe some of the changes in the market since part 1 was written.  This part will continue that description by describing the upfront fee that is now paid on a standard CDS contract, and the impact of the changes on how CDS are quoted in the market.

Standard Premiums mean there is a Fee

Part 1 discussed how CDS contracts have been standardized.  One of the ways in which they have been standardized is that there are now standard premiums.

Now consider the case where I buy protection on a five-year CDS.  I enter into a standard contract with a premium of 500 basis points (5%).  It may be that the premium I would have paid under the old nonstandard contract for the same dates and terms would have been 450 basis points.  However, now I’m paying 500 basis points.

Clearly I need to be compensated for the 50 bps difference or I won’t want to enter into the trade under the new terms.

As a result an upfront fee is paid to me when the contract is started.  This represents the 50 basis points difference over the life of the trade, so that I am paying the same amount overall as under the old contract.

Note that in this case I (the protection buyer) am receiving the payment, but it could easily be that I pay this upfront fee (if, for example, the nonstandard contract would have traded at 550 bps).

Upfront Fee Calculation

The calculation of the fee from the ‘old’ premium (spread) is not trivial.  It takes into account discounting, and also the possibility that the reference entity will default, which would mean the premium would not be paid for the full life of the trade.  However, this calculation too has been standardized by the contracts body (ISDA).  There is a standard model that does it for us.

The Full First Coupon means there is a Fee

In the example in part 1 I discussed how I might pay for a full three months protection at the first premium payment date for a CDS trade, even though I hadn’t had protection for three months.

Once again I need compensation for this or I will prefer to enter into the old contract.  So once again there is a fee paid to me when I enter into the trade.

This is known as an ‘accrual payment’ because of the similarity to accrued interest payment for bonds.  Here the calculation is simple: it’s the premium rate applied to the face value of the trade for the period from the last premium payment date to the trade date.

That is, it’s the amount I’ll be paying for protection that I haven’t received as part of the first premium payment.  Note no discounting is applied to this.

Upfront Fee/Accrual Payment

So in summary the new contract standardization means that a payment is now always made when a standard CDS contract is traded.

Part of the payment is the upfront fee that compensates for the difference between the standard premium (100 or 500 bps in North America) and the actual premium for the trade.  This can be in either direction (payment from protection buyer to seller or vice versa).  Part of the payment is the accrual payment made to the protection buyer to compensate them for the fact that they have to make a full first coupon payment.

How CDS are Quoted in the Market

Prior to these changes CDS were traded by simply quoting the premium that would be paid throughout the life of the trade.
With the contract standardization clearly the premium paid through the life of the trade will not vary with market conditions (it will always be 100 or 500 bps in North America, for example), so quoting it makes little sense.

Instead the dealers will quote one of:

a) Points Upfront
‘Points upfront’ or just ‘points’ refer to the upfront fee as a percentage of the notional.  For example, a CDS might be quoted as 3 ‘points upfront’ to buy protection.  This means the upfront fee (excluding the accrual payment) is 3% of the notional.  ‘Points upfront’ have a sign: if the points are quoted as a negative then the protection buyer is paid the upfront fee by the protection seller.  If the points are positive it’s the other way around.

b)  Price
With price we quote ‘like a bond’. We take price away from 100 to get points:
That is, points = 100 – price.  So in the example above where a CDS is quoted as 3 points to buy protection, the price will be 97.   The protection buyer still pays the 3% as an upfront fee of course.

c)  Spread
Dealers are so used to quoting spread that they have carried on doing so in some markets, even for standard contracts that pay a standard premium.  That is they still quote the periodic premium amount you would have been paying if you had bought prior to the standardization.  As already mentioned, there is a standard model for turning this number into the upfront fee that actually needs to be paid.


This part concludes the discussion of the changes in the mechanics of CDS trading since 2007.  As you can see, in many ways the standardization of the CDS market has actually made it more complicated.  The things to remember are that premiums, premium and maturity dates, and the amounts paid at premium dates have all been standardized in a standard contract.  This has meant there is an upfront fee for all standard CDS, and that they are quoted differently in the market from before.  It has also meant that CDS positions can be more easily netted against each other, and that the mechanics of calculating and settling premiums have been simplified.

Part 4 of this series will examine some of the other changes since 2007, and changes that are coming.

July 19, 2011

A Beginner’s Guide to Credit Default Swaps (Part 2)


Part 1 of the ‘Beginner’s Guide to Credit Default Swaps’ was written in 2007. Since that time we have seen what many are calling the greatest financial crisis since the Great Depression, and a global recession.

Rightly or wrongly, some of the blame for the crisis has been attributed to credit derivatives and speculation in them.  This has led to calls for a more transparent and better regulated credit default swap (CDS) market. Furthermore the CDS market has grown very quickly, and by 2009 it had become clear that some simple changes to operational procedures would benefit everyone.

As a result many changes in the market have already been implemented, and more are on the way. This article will discuss these changes.  It will focus primarily on how the mechanics of trading a credit default swap have changed, rather than the history of how we got here or why these changes have been made. I’ll also briefly discuss the further changes that are on the way.

Overview of the Changes

The first thing to note is that nothing has fundamentally changed from the description of a credit default swap in part 1. A credit default swap is still a contract that provides a kind of insurance against a company defaulting on its bonds. If you have read and understood part one then you should understand how a credit default swap works.

The main change that has happened is that credit default swap contracts have been standardized. This standardization falls into three broad categories:

  1. Changes to the premium, premium and maturity dates, and premium payments that simplify the mechanics of CDS trading.
  2. Changes to the processes around identifying whether a credit event has occurred.
  3. Changes to the processes around what happens when a credit event has occurred.

Items 2 and 3 are extremely important, and have removed many of the problems that were discussed in part 1 relating to credit events. However, they don’t affect the way credit default swaps are traded as fundamentally as item 1, and are arguably more boring, so we’ll start with item 1.

The Non-Standard Nature of Credit Default Swaps Previously

If I buy 100 IBM shares and then buy 100 more I know that I have a position of 200 IBM shares.  I can go to a broker and sell 200 IBM shares to get rid of (close out) this position.

One of the problems with credit default swaps (CDS) as described in part 1 of this series of articles is that you couldn’t do this.  Every CDS trade was different, and it was consequently difficult to close out positions.

Using the description in part 1, consider the case where I have some senior IBM bonds.  I have bought protection against IBM default using a five year CDS.  Now I decide to sell the bonds and want to close out my CDS.  It’s difficult to do this by selling a five year CDS as described previously.  Even if I can get the bonds being covered, the definition of default, the maturity date and all the premium payment dates to match exactly it’s likely that the premiums to be paid will be different from those on the original CDS.  This means a calculation has to be done for both trades separately at each premium payment date.


To address this issue a standard contract has been introduced that has:

1.  Standard Maturity Dates

There are four dates per year, the ‘IMM dates’ that can be the maturity date of a standard contract: 20th March, 20th June, 20th September, and 20th December.  This means that if today is 5th July 2011 and I want to trade a standard five-year CDS I will normally enter into a contract that ends 20th September 2016.  It won’t be a standard CDS if I insist my maturity date has to be 5th July 2016.

2.  Standard Premium Payment Dates

The same four dates per year are the dates on which premiums are paid (and none other).  As a result three months of premium are paid at every premium payment date.

Note that the use of IMM dates for CDS maturity and premium payment dates was already common when I wrote part 1 of the article.

3.  Standard Premiums

In North America, standard contracts ONLY have premiums of 100 or 500 basis points per annum (1% or 5%).  In Europe, Asia and elsewhere a wider range of premiums is traded on standard contracts, although this is still restricted.  How this works in practice will be explained in part 3.

4.  Payment of Full First Coupon

Standard contracts pay a ‘full first coupon’.  What this means is that if I buy a CDS midway between the standard premium payment dates I still have to pay a full three months’ worth of premium at the next premium date.  Note that ‘coupon’ here means ‘premium payment’.

For example, if I enter into a CDS with face value $100m on 5th July 2011 with a premium of 5% I will have to pay 3 months x 5% x 100m on the 20th September.  This is in spite of the fact that I have not been protected against default for the full three months.

Note that for the standard premiums and the payment of full first coupon to work we now have upfront fees for CDS.  Again this will be explained in more detail in part 3.

Impact of these Changes

What all this means is that we have fewer contract variations in the market.  The last item in particular means that a position in any given contract always pays the same amount at every premium date: we don’t need to make any adjustments for when the contract was traded.

In fact, in terms of the amount paid EVERY contract with the same premium (e.g. 500 bps) pays the same percentage of face value at a premium date, regardless of reference entity.  This clearly simplifies coupon processing.  It also allows us to more easily net positions in credit default swaps in our systems.


One of the major changes in the CDS market since part 1 was written is that contracts have been largely standardized.  More detail on this and other changes will be given in part 3.

January 28, 2008

Problems with Using xsd.exe to Generate .NET Classes from the FpML XSD Schema (Introduction to using FpML with .NET Tools Part 4)


Part 3 of this series of articles showed how we can generate .NET classes from the FpML XSD schema using xsd.exe. It showed how we can then use standard .NET serialization syntax to populate the classes from FpML documents, and vice versa.

However, as mentioned in part 3, xsd.exe generates buggy code when used with the FpML XSDs. This article will go through some of the problems with this code and describe how to fix them.

Corrected .NET Classes

Corrected generated classes, which are the end result of the work in this article, are available. This code has been corrected such that it appears to work in most circumstances. However we cannot be certain that it is free of all bugs.

The corrected code is based on FpML 4.2. The main aim of this article is to give you a starting point if you are trying to generate .NET code from other versions of the specification.

Please note also that this article was written using the xsd.exe supplied with Visual Studio 2005 Service Pack 1. Different versions of Visual Studio, or Visual Studio 2005 without the service pack applied, may give different results. See the discussion in the Comments for this article for more details.

Generating the Code

Part 3 of this series of articles described how to use xsd.exe to generate C# code from the FpML schemas. This gave us a file called fpml-main-4-2_xmldsig-core-schema.cs, which contains a Document class which should be the root class for our serialization. Unfortunately if we attempt to create an XmlSerializer object using this code we get exceptions.

Problem 1: Substitution Groups and Extension

The most fundamental problem with our generated code is that xsd.exe has got confused about the substitution groups and associated extension that were discussed in some detail in part 2 of this series of articles.

In particular it has not decorated the Product property of our Trade class correctly to allow it to deal with all the possible products correctly.

In part 2 we saw that the product element in the FpML is replaced with various individual product types using the substitutionGroup syntax. The product element is a sub-element of the trade element in the XML. As a result in our C# code we have a Trade class which contains a data member of type Product and a public property that gets and sets this. Excerpts from our generated code are as below:

[System.CodeDom.Compiler.GeneratedCodeAttribute("xsd", "2.0.50727.42")]
public partial class Trade {
    private Product productField;
    public Product product {
        get {
            return this.productField;
        set {
            this.productField = value;

The problem with this code is that, as we saw in part 2, we need to be able to put a Swap object (for example) in to our Product data member. We have a Swap class in our code, and this inherits Product, as we’d expect. So we can store a Swap object in our Product data member.

However, .NET doesn’t know how to serialize or deserialize a swap element in the XML into our product property without being told. In particular, if the deserializer finds an element called ‘swap’ where it’s expecting ‘product’ it doesn’t know that it should deserialize into a Swap object. As we saw in part 2, in <a href=" there is a ‘swap’ element where you might expect a ‘product’ element.

This is very easily fixed in this case. We simply decorate the Product property with an XmlElementAttribute that tells the serializer what to do:

    [System.Xml.Serialization.XmlElementAttribute("swap", typeof(Swap))]
    public Product product {
        get {
            return this.productField;
        set {
            this.productField = value;

This does solve the problem for swap. However, there are multiple other product types that need the XmlElementAttribute added to Product to get the serialization to work (there are over twenty in fact). Also it turns out that this problem isn’t limited to Product. There are other elements that use the substitution group and extension property in this way and have the same problem

At first glance it appears there is no easy solution to this: we are going to have to go through all the possible places where there might be errors and correct the code by hand. However, there’s a much easier solution.

Problem 1 Solution

For simple examples of this problem xsd.exe will correctly generate the required XmlElementAttribute. It’s not immediately obvious why it fails to do so with the full FpML schemas.

It turns out that the reason xsd.exe gets this wrong is because the FpML schemas are spread across multiple files. If we create one big xsd file containing all of the FpML schema files and then run xsd.exe on this the problem goes away. I’ll leave you to draw your own conclusions about the quality of the xsd.exe code.

So to fix the problem we can cut and paste all of the FpML xsd files into one file, removing the include statements that become redundant. An example of this is available. We then use xsd.exe as described in part 3 to create our C# classes.

Problem 2: RoutingIds

If we fix problem 1 as above, we still get an error when we try to create our XmlSerializer object. The error message says ‘Connot convert type ‘RoutingId[]’ to ‘RoutingId’’.

This exception arises because xsd.exe has got an XmlArrayItemAttribute wrong in class RoutingIdsAndExplicitDetails. The generated code for the routingIds property in this class is as below:

    [System.Xml.Serialization.XmlArrayItemAttribute("routingId", typeof(RoutingId), IsNullable=false)]
    public RoutingId[][] routingIds {
        get {
            return this.routingIdsField;
        set {
            this.routingIdsField = value;

The XmlArrayItemAttribute says that the property relates to an array of type RoutingId. However, the property (correctly) is of type RoutingId[][] which is an array of arrays of type RoutingId. So the XmlArrayItemAttribute should be changed as below:

    [System.Xml.Serialization.XmlArrayItemAttribute("routingId", typeof(RoutingId[]), IsNullable=false)]
    public RoutingId[][] routingIds {
        get {
            return this.routingIdsField;
        set {
            this.routingIdsField = value;

Testing the Generated Classes

The two fixes above appear to make the generated classes work correctly. With these changes we can deserialize our ird_ex01_vanilla_swap.xml FpML document into the classes. We can then serialize it back into XML, and we end up with the same document we started. We saw this in one of our code examples from part 3. It’s not easy to test this code is working in all cases however. One approach is to take all the sample FpML files provided with the FpML download and attempt to deserialize them and reserialize them. The code is working if the final document is the same as the original one.

Testing Program

A testing program that does this is available. This contains the code we have seen before (in part 3) for serialization and deserialization.

It also contains a basic class for comparing the original and final FpML documents and outputting any differences. It does this simply by iterating through the lines in the two files and comparing them. This may not be the best way to do this as it is quite difficult with XML.

It is difficult because there can be valid differences between the files that are hard to deal with. For example we have a ‘difference’ where the original line is:


After deserialization and reserialization this becomes:


These are clearly the same thing but our file comparer has to be able to deal with it. It does so in a very basic way by hard-coding such differences to be ignored in method ‘CompareLines’.

Extent of Testing of Generated Code

Because of the difficulties described above the testing program has only been used to test that the generated code works with the interest rate derivatives and credit derivatives sample files.

Usefulness of Generated Classes

In the last two articles we have demonstrated that we can generate C# classes based on the FpML XSD specification, and with a little work can deserialize FpML documents into this object model, manipulate the objects, and serialize back into FpML.

However, my personal opinion is that we need to think carefully as to whether we want to use these classes. FpML has a very hierarchical structure, and as a result in the generated code we have very many classes interacting to represent even a simple trade. Our object model is not very easy to understand or use as a result.

For example, suppose we want to change the notional on the fixed leg of our interest rate swap (ird_ex01_vanilla_swap.xml) once we have it in the object model. Starting with the top-level Document object that we have deserialized, the syntax is as below:

        private void ChangeNotional(Document document)
            DataDocument dataDocument = (DataDocument)document;
            Trade trade = (Trade)dataDocument.Items[0];
            Swap swap = (Swap)trade.Item;
            InterestRateStream interestRateStream0 = swap.swapStream[0];
            InterestRateStream interestRateStream1 = swap.swapStream[1];
            Calculation calculation1 = (Calculation)interestRateStream1.calculationPeriodAmount.Item;
            Notional notional = (Notional)calculation1.Item;
            notional.notionalStepSchedule.initialValue = 1000000;

In fact, I don’t think this routine is complex enough, since it should really check which of interestRateStream0 and interestRateStream1 is the fixed leg.

A code example incorporating this code is available.

It’s hard to argue that this code is straightforward: for instance we have a number of ‘Item’ properties referenced that can be of various types. We have to know which type we want. In addition we have the issue that we are not entirely sure that the code generated by xsd.exe is free of bugs, even after the work we have done to patch it up.

As a result in a current project I am working on we have decided not to use the classes generated by xsd.exe, but instead to deserialize into flatter structures of our own design.


This article has shown that it is possible to fix the code generated by xsd.exe from the FpML schemas such that we can deserialize/serialize FpML documents into/out of the object model. We have also shown that it is difficult to test that this will work correctly in all cases, and that the resulting object model is not all that easy to use.

Licensing of FpML Specifications

The FpML Specifications of this document are subject to the FpML Public License (the “License”); you may not use the FpML Specifications except in compliance with the License. You may obtain a copy of the License at
The FpML Specifications distributed under the License are distributed on an “AS IS” basis, WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License for the specific language governing rights and limitations under the License.
The Licensor of the FpML Specifications is the International Swaps and Derivatives Association, Inc. All Rights Reserved.

January 27, 2008

Generating .NET Classes from the FpML XSD Schema (Introduction to using FpML with .NET Tools Part 3)


Part one of this series of articles looked at how we can use Visual Studio to examine the FpML XML schema documents (XSDs), and the associated example XML instance documents.

Part two of the series looked in some detail at the structure of an FpML trade XML document, and showed how to investigate its validation against the schemas using Visual Studio.

This article will show how to generate .NET classes in C# from the XML schema documents. These classes can in theory be used to load FpML documents into objects. These objects can then be manipulated by the code and saved out as FpML. However, there are some problems with the Microsoft tools for doing this, as we shall see.


FpML is a powerful way of representing financial products in a standard way. It can be used to pass trade data between financial institutions in an XML format that both parties can understand. It can also be used to pass trade data between computer systems within a financial institution. If all systems know about FpML then we have a standard platform-independent human-readable representation of our data that everyone can use.

Clearly there are some disadvantages to using FpML in this way (it’s very verbose, and we will probably need to modify it for our own needs anyway, in which case it stops being standard). However there’s a prevailing view that FpML is a good place to start when defining what trade data and messages we will pass around in a service-oriented architecture in a bank.

However if we want to use trade data passed to us as FpML we need to get it into a format we can program against. Obviously if we are programming in .NET languages we want to have objects, or even DataSets. Furthermore we’d like to be able to modify those objects or DataSets and then turn them back into valid FpML documents.

The XML Schema Definition Tool (xsd.exe)

Microsoft have provided an ‘XML Schema Definition Tool’ called xsd.exe that purports to allow us to do this. It claims to be able to turn XSDs into classes. These classes can then be used to automatically load associated XML instance documents into objects, and back into XML again after manipulation. xsd.exe is also capable of creating DataSets from XSD files.

Obviously loading XML instance documents into objects is XML deserialization, and turning them back into XML is serialization. Once we have the classes we can use .NET’s standard serialization mechanisms for this.

As we shall see, this doesn’t work particularly well with the FpML schemas.

Generating C# Classes from FpML Schemas

To use xsd.exe to generate C# classes is relatively straightforward:

  1. 1. Start a Visual Studio command prompt (this is under ‘Microsoft Visual Studio/Visual Studio Tools’ on your start menu).
  2. Navigate to a folder where the FpML XSD files are. If you created the console application used in parts 1 and 2 of this series of articles navigate to the project folder (which has the XSDs in it).
  3. Run the command below:
    xsd /c fpml-main-4-2.xsd xmldsig-core-schema.xsd
    This generates a file called fpml-main-4-2_xmldsig-core-schema.cs which contains the classes we need.

Note that the /c parameter asks xsd to generate classes. There is also a /d parameter that asks xsd to generate DataSets. We will discuss this option later.

Note also that we only need reference the root schema file (fpml-main-4-2.xsd) for this to work: the other schema files are referenced from this file (with include statements) and xsd can work this out. However xsd can’t work out what to do with the xmldsig-core-schema.xsd file unless we tell it to process it. This is because only the namespace is referenced in the schema files, not the file itself.

Using the Generated C# Classes

If we look at the fpml-main-4-2_xmldsig-core-schema.cs file we see that we have nearly 37,000 lines of code, including over 650 classes. As you’d expect these classes use .NET’s XML serialization attributes throughout, so we can serialize into and deserialize from XML correctly. The root class is Document.

To use these classes we need to create an XmlSerializer object based on the root Document in code. This is standard .NET serialization code:

        XmlSerializer xmlSerializer = new XmlSerializer(typeof(Document));

Then in theory we should be able to deserialize any FpML document into these classes using the XmlSerializer. The syntax we’d use for this is as below:

        internal Document DeserializeXMLToDocument(FileInfo inputXMLFile)
            using (FileStream fileStream = File.OpenRead(inputXMLFile.FullName))
                return (Document)xmlSerializer.Deserialize(fileStream);

Once we’ve deserialized into objects based on our classes, we should be able to serialize those back into XML. Clearly the final XML should be the same as the initial XML. The syntax for the serialization is as below:

        internal void SerializeDocumentToXML(Document document, FileInfo outputXMLFile)
            using (FileStream outFileStream = new FileStream(outputXMLFile.FullName, FileMode.Create))
                xmlSerializer.Serialize(outFileStream, document);

This is all standard .NET XML serialization code.

First Attempt to Use the Generated Classes

We can write a basic harness that uses our generated classes and the code above to attempt to deserialize and serialize FpML files.

A version of this is available. It tries to deserialize the ird_ex01_vanilla_swap.xml that was examined in part 2 of this series of articles.

Unfortunately the classes generated by xsd.exe have a number of problems, and unless we correct these the basic harness will not work. In fact we can’t even create the XmlSerializer object successfully with the generated code.

Part four of this series of articles will examine the various problems with the code that xsd.exe has generated, and will discuss how to correct them.

Corrected Generated Classes and a Working Harness

Corrected generated classes are available. As will be discussed in part four this code has been corrected such that it appears to work in most circumstances. However we cannot be certain that it is free of all bugs.

A version of the harness that uses the corrected code is also available. As you can see if you run it, this does correctly deserialize and then reserialize ird_ex01_vanilla_swap.xml.


This article has shown that in theory we can generate classes from the FpML XSDs using xsd.exe. We should then be able to deserialize FpML documents into these classes, manipulate the resulting objects, and then reserialize back into valid FpML documents. However, xsd.exe has some problems that prevent this from working correctly.

Part four of this series of articles will look in more detail at the problems in the generated code, and how to fix them.

Licensing of FpML Specifications

The FpML Specifications of this document are subject to the FpML Public License (the “License”); you may not use the FpML Specifications except in compliance with the License. You may obtain a copy of the License at
The FpML Specifications distributed under the License are distributed on an “AS IS” basis, WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License for the specific language governing rights and limitations under the License.
The Licensor of the FpML Specifications is the International Swaps and Derivatives Association, Inc. All Rights Reserved.

January 20, 2008

How FpML Validates a Basic Trade Document (Introduction to using FpML with .NET Tools Part 2)


Part 1 of this series of articles gave a general introduction to using Microsoft .NET tools to investigate FpML XSD schemas.

This article will focus more closely on the FpML itself, by looking at the structure of an FpML trade XML document in some detail. It will explain how the FpML schemas fit together to validate such a document. In particular it will examine the use of base and extension types, and of substitution groups, in the XSDs.

As mentioned in part 1, FpML is complex and there’s little documentation. This article will attempt to redress this by explaining how it works assuming only that you know the basics of how an XSD works.

These articles assume you understand the basics of XML Schema Definition language. If you don’t there are a number of good tutorials available on the internet. For example there’s quite a good one at These articles will reference the tutorial for the less obvious XSD structures.

The fpml-main Schema

In part one of this series of articles we showed that the file ird_ex01_vanilla_swap.xml is a valid document in accordance with the FpML schemas. ird_ex01_vanilla_swap.xml is an example file provided with the FpML download that represents a simple interest rate swap. However, at first glance it’s not entirely clear how the large number of XSD files that define the FpML schema fit together to validate this XML document.

The first thing to notice is that the XML document references the main root schema fpml-main-4-2.xsd in namespace FpML puts all its definitions in one namespace, which for the version we are using is

If we look at file fpml-main-4-2.xsd and collapse it to an appropriate level we see something as below. I’ve moved the schema attributes onto multiple lines for clarity:


As we can see, this XSD defines a number of namespaces, sets our targetNamespace for the schema, and includes a number of other XSDs from the set of FpML XSDs. It defines one complex type, ValuationDocument. Remember that complex types only have to appear in the XML if they are referenced as the type of an element: ValuationDocument does not have to appear in any XML just by virtue of being in this document.

The schema finally defines the one mandatory top-level element in this document, which is an element called ‘FpML’ which is of type ‘Document’. If we expand the FpML element definition we find it just contains an annotation (comment). So in effect all this schema is saying is that our root element for an FpML document must be called ‘FpML’ and it must be a Document.

Schemas Needed to Validate an Interest Rate Swap

It’s also worth noting here that we don’t need all the XSDs that are imported here to validate the interest rate swap successfully. In fact we can comment them all out apart from fpml-ird-4-2.xsd, provided we add an import for fpml-doc-4-2.xsd (which is included in fpml-valuation-4-2.xsd). We need to comment out the ValuationDocument complex type as well if we do this.

Note you can use the usual comment out/uncomment buttons in Visual Studio to comment XML (and hence XSD) code.

So the ird_ex01_vanilla_swap.xml file will validate with fpml-main changed as below. This makes it clear that we are only using a subset of our XSD files to validate an interest swap, which is what you’d expect. Note that fpml-ird-4-2.xsd itself includes a number of other FpML schemas, so we are not JUST validating with the two included below:


Document Type

We can now navigate to the Document complex type, which is in file fpml-doc-4-2.xsd. Remember that to do this in Visual Studio all we need do is right-click “Document” and select “Go to definition” (or hit F12). We see that Document is defined as ‘abstract’. This is equivalent to a class being abstract in C#. It means we can’t use Document directly as the type of an element, but have to derive from it first. Document also contains an attributeGroup that references StandardAttributes.atts. This has one mandatory attribute ‘version’ (which applies to the FpML element), and can have value “4-0”, “4-1”, or “4-2”.

So now we need to know what complex types derive from the Document type. The easiest way to find this out using Visual Studio is to search our project for “Document” (in quotes), since any extension has to use the extension syntax which looks like:

<xsd:extension base="Document">

If we do this we find there are two types that extend Document: “DataDocument” and “Message”. Obviously the ‘Message’ type of document is used for messaging. Here we are only looking at trade representations in XML, which use the DataDocument type of Document.

The XML Document

If we now look at our instance XML document we see that, as expected, it starts with an FpML tag, which has a version attribute. It then uses the xsi:type attribute to specify that we are using a DataDocument.

Most FpML trade documents will have the general structure below, as we shall see. That is, the root FpML element will contain a trade element and a number of party elements. The trade element will contain a tradeHeader element, and an element that represents a specific product, in this case swap. For other product types the swap element will be substituted directly with some other product element.



We saw above that our FpML element is of type DataDocument. The DataDocument definition is in fpml-doc-4-2.xsd, and a summarized version is below. If we look at the full version we can see there is a comment that says that the data document is intended to ‘contain sets of data without expressing any processing intention’:


As expected this extends Document. It adds a sequence, starting with a Validation.model group. The element in this group is optional, so it doesn’t don’t appear in our XML at all.

The next item in our schema is a choice between a sequence of trade and portfolio elements, or of an event element. Our XML uses the trade and portfolio choice. Note that both of these are optional (minOccurs = 0), and our XML has no portfolio element. We examine the Trade element in more detail below.

Finally in our sequence we can have multiple (or zero) elements called ‘party’. These are intended to identify any parties to the trade (see the comments in the full version of the XSD). They are of type Party: this has an ‘id’ attribute, a required ‘partyId’ element, and optional partyName and account elements. If you look again at our XML you can see that we have two ‘party’ elements defined, with just the id attribute and mandatory partyId provided.


So in an FpML document we have a root element called ‘FpML’ that has to be of type Document. Document is abstract, and one extension is DataDocument, which can contain an element called ‘trade’ of type Trade.

The XSD definition of the Trade complex type is below:


The first thing to notice is that everything is optional (minOccurs=0) apart from the tradeHeader element, and the referenced product element. These two elements are the only ones that appear in our sample XML (although indirectly in the case of product, as we shall see below).


By now you’ve probably got the idea of how this works and how to use Visual Studio to navigate through the schema and find out what needs to be where in the XML. As a result we won’t go into how the tradeHeader element is constructed, which is straightforward. The comment on the TradeHeader complex type says ‘a type defining trade related information which is not product specific’, which is self-explanatory.

It’s interesting to note that the ONLY information relating to a trade that is not ‘product specific’ here is the trade date and at least one trade ID (along with whose ID it is). If you are constructing a base trade class for a hierarchy of trade types this is really the only data you can meaningfully put in it.

Product and Swap

The product element is a little more complex. If we look again at our sample XML we see that we have a ‘swap’ element in the XML where we expect the ‘product’ element to be.

If we go to the definition of the referenced product element we find that it is of complex type Product, is abstract, and is defined in fpml-shared-4-2.xsd.

However, in spite of the product element (and its associated type Product) being abstract the schemas are not using straightforward extension here. Hence there is no ‘xsi:type’ attribute in our XML instance document. Instead we are using substitution groups.

If we locate the definition of ‘swap’ in fpml-ird-4-2.xsd we see that it is an element of type Swap with substitutionGroup of product. This means it can be substituted directly for the product element in our final XML (as can any other element tagged in this way):

  <xsd:element name="swap" type="Swap" substitutionGroup="product">
      <xsd:documentation xml:lang="en">A swap product definition.</xsd:documentation>

The substitution group syntax on its own means that element swap and type Swap need have no relation to type Product. Swap could be a completely new type with no reference to the base Product type. We can substitute whatever we like for the product element.

However, in the FpML schemas complex type Swap also extends type Product, which means this element has to take account of the definition of the Product complex type.

So, to summarize, we have a ‘swap’ element in our XML document where there is a ‘product’ element in the XSD. We can put the swap element in there because of the substitution group syntax: we just substitute the swap element for the product element. However, the swap element is also of type Swap which extends type Product, so it must take account of the Product definition as well.

This is certainly difficult to understand.

Product itself is abstract, has an id attribute and contains a named group called ‘Product.model’. However, all of this is optional and does not consequently appear in our sample instance XML.

Difficulties with Substitution Groups for product in the FpML

As explained above, the use of both substitution groups and extension to replace product elements in the FpML schemas is confusing.

In my opinion even if we ignore the use of extension the use of substitution groups is confusing for developers. Most XSD constructs map to object oriented concepts. However, because we are using substitution groups here we are effectively saying that absolutely any type can be a member of our parent trade type at this point in the schema. It’s like including a generic object data member in a class that can be used to contain ANY other class. In OO terms we have no idea what interface this object will implement. It’s hard to represent this in UML as well: see Finally, as we shall see in part 3, the Microsoft tool for creating classes from schemas (xsd.exe) struggles with the combination of extension and substitution groups used in the FpML schemas.


The Swap complex type is again fairly straightforward. Everything is optional except for at least one element called swapStream, of type InterestRateStream. Clearly these represent the swap legs for our interest rate swap, and consequently we have two of them in our sample instance XML. As mentioned above you’ve probably got the idea of how this all fits together by now, and how to investigate further, so we’ll leave the schemas at this point.


This article has attempted to show how validation using the FpML schemas works, and to give an idea of the structure of a trade XML document in FpML.

Part three of this series of articles will examine how we can generate .NET classes from these schemas using xsd.exe, and will look at some of the problems associated with doing this.

Licensing of FpML Specifications

The FpML Specifications of this document are subject to the FpML Public License (the “License”); you may not use the FpML Specifications except in compliance with the License. You may obtain a copy of the License at
The FpML Specifications distributed under the License are distributed on an “AS IS” basis, WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License for the specific language governing rights and limitations under the License.
The Licensor of the FpML Specifications is the International Swaps and Derivatives Association, Inc. All Rights Reserved.

December 29, 2007

Introduction to using Financial Products Markup Language (FpML) with Microsoft .NET Tools (Part 1)


This short series of articles will attempt to show how Microsoft’s standard .NET tools (Visual Studio and xsd.exe) can be used to investigate and use Financial products Markup Language (FpML).

This first article gives an overview of how we can use Visual Studio to examine the FpML XSDs, and use it to validate the XML examples that are provided in the FpML download.

Part 2 of the series will examine how the FpML XSDs fit together for basic trade types.

These articles assume you understand the basics of XML Schema Definition language. If you don’t there are a number of good tutorials available on the internet. For example there’s quite a good one at These articles will reference the tutorial for the less obvious XSD structures.


Financial products Markup Language is intended as an industry-standard method of representing financial products using XML. Details can be found at

The XML representations of financial products are defined using XML Schema Definition (XSD). These can be downloaded from the site.

FpML is Complex

The FpML XSDs are intended to define XML for a very wide range of financial products. They are also intended to be easily extensible for any new products. To achieve this products are built up from small building blocks into a complex structure. This means the XML is very hierarchical (it has many layers of tags).

An alternative approach would be to represent financial products in as flat a structure as possible. By ‘flat’ we mean a simple series of name-value pairs (with associated types for the values), and no hierarchy. Even quite complex derivatives products can be represented by a flat schema (obviously such things as basket products are an exception to this). A flat structure is easier to understand, and can be easier to handle in code. It also leads to less verbose XML, and hence smaller message sizes.

However, this is not the approach FpML takes for good reasons: whilst it’s easier to deal with a flat structure, it’s hard to extend as you cannot easily re-use blocks of tags in a new structure.

As well as defining formats for a wide range of trade types, the FpML XSDs define message formats for standard trade events (e.g. confirmations, credit event notifications). They also define standard enumerations for such things as day count conventions.

As a result all this FpML is inevitably complex and difficult to understand. Furthermore there’s little free documentation available.

Visual Studio Support for XSDs

Visual Studio (combined with C#) has good support for XML and XSD. As you may know, we can load XSDs into it and it will automatically check that they are internally consistent. We can then load XML into it and validate that XML against the XSDs on the fly at design-time.

As we shall show the .NET languages also have support for validating XML using XSDs at run-time.

In addition there is an ‘XML Schema Definition Tool’ called xsd.exe that ships with Visual Studio. We can use this to automatically generate classes in a .NET language of our choice based on the XSDs. We can then load the XML data into those classes (at run-time obviously). If we don’t like the classes it’s very easy to manually tweak them to do what we want. In fact, as we shall see, xsd.exe is far from perfect and we may well need to tweak the classes to get them to work properly.

We can even usually use xsd.exe to generate DataSets from the XSDs and populate those from the XML. Of course, DataSets give us some disadvantages (e.g. speed) over plain old classes, but they allow us to track changes, and easily bind our data into grids for display and editing.

This series of articles will take us through all of the scenarios outlined above. However, as we shall see, the complexity of the FpML schemas (and some Microsoft bugs) can make handling FpML in Visual Studio challenging.

Initially we will work with Visual Studio 2005 (and .NET 2.0). Later on we’ll have a look at changes in Visual Studio 2008.

Getting Started with FpML and Visual Studio

The first thing to do if you want to learn about FpML is to download the schemas. This can be done from, although you will need to register with the site. For this article I have used the FpML 4.2 Recommendation in Zip format, which you can download via the ‘Specifications’ tab.

Once you have downloaded and extracted this, create a console application project in Visual Studio. Add ALL of the XSDs found in the xml folder from your download to this project (using the Project/Add Existing Item… menu).


We are going to start with interest rate swaps. The details of these are defined in file fpml-ird-4-2.xsd. Right-click this file in Solution Explorer and select View Code. DON’T just ‘Open’ it as the default is to open with a DataSet Editor, which gives a graphical view. Note that you can change the default if you right-click/Open With. If you select the XML Editor as the default you will get the code view when you double-click in future.

You should now have the raw XSD in the document window. It’s a bit daunting, so right-click in the document window, and select Outlining/Toggle All Outlining. This collapses the XSD entirely. If you now expand it once (by clicking the ‘+’ sign) you will see that the XSD includes some other schemas, then defines some complex types, then some elements and some groups. One of the elements is called ‘swap’, which is encouraging. This is of type ‘Swap’ which we can see defined as a complex type. However it’s not clear how we get from this to XML for an interest rate swap.

Note here that Visual Studio validated the schema when you displayed it. You can see this if you deliberately break the schema. Try changing the type of the swap element mentioned above to ‘notSwap’. If you now look at the Warnings in the Error List (menu View/Error List) you’ll see Visual Studio is telling you that ‘Type ‘; is not declared.’ It’s also telling you the line number and the file, and you can as usual double-click the error to go to it.


Note also that Visual Studio only validates the schema when the schema file is open in the document window (try saving it and closing it with the error still in there: the warning disappears). Visual Studio will quite happily validate all of the FpML XSDs if you open them individually however.


Now we will add an XML file representing an interest rate swap to our project, and get the XSDs to validate it. Our original download contains XML examples in the subfolders of the xml folder referred to above. In particular, there is a folder called interest-rate-derivatives that contains a file called ird_ex01_vanilla_swap.xml. This XML file references the XSD files we have already examined using the schemaLocation attribute. However the schemaLocation attribute says that the schemas are in a folder at a level above the XML file.

So create a folder in your solution (right-click the solution in Solution Explorer and select Add…/New Folder). Then right-click the folder, choose Add/Existing Item…, and add the ird_ex01_vanilla_swap.xml file into this folder.

Now if you open the file in Visual Studio it should validate correctly straight away: there should be no errors or warnings in the Error List. Again you can see this is working if you manually edit the XML: try changing the partyReference element near the top to ‘notpartyReference’. You will get a warning the notpartyReference is an invalid child element and ‘partyReference’ is expected.


Visual Studio and XML: Navigation and Outlining

We have already seen that we can use Visual Studio’s outlining (collapsible regions) in the usual way with XSD files, and the same is true of XML files.

We can also use Visual Studio’s standard ‘Go To Definition’ functionality with both XSD and XML files. Put your cursor inside partyReference in the XML and hit F12 (or right-click, Go To Definition). Visual Studio will show the place in the XSD where partyReference is defined (which is inside file fpml-doc-4-2.xsd).

This shows that partyReference is an element in complex type TradeIdentifier. It is itself of type ‘PartyReference’. If you right-click ‘PartyReference’ and Go To Definition in the same way you can navigate within the XSD: you can see that PartyReference is an extension of base type ‘Reference’, and if you go to the definition of that you can see that it is an abstract complex type with one attribute called ‘href’ of type IDREF.

You can then navigate back through the items you’ve visited as usual in Visual Studio using the Navigate Backward toolbar button, or hitting Control + – (minus key).

It’s worth noting that the normal toolbar Comment/Uncomment buttons work fine with XML and XSD, including commenting sensibly across several lines: you don’t have to type ‘<!–‘ and ‘–>’. Also there’s good intellisense support if you are entering XML or XSD code, including code snippets on the context menu.

Finally if you load all of your XSDs into a project as described above you can (obviously) use Visual Studio’s normal Find in Files functionality (Ctrl-Shift-F) to locate items anywhere in the XSDs.

Validation in Code

We have seen how we can use Visual Studio to validate that a schema is correctly formed, and to validate an XML instance document against a schema. We can also do this validation in C# code.

Validation of a Schema in Code

To validate a schema we can load it into an XmlSchemaSet and compile it as below. Put this code in the Main method of the C# console application created above to see this working:

            XmlSchemaSet xmlSchemaSet = new XmlSchemaSet();
            xmlSchemaSet.Add("", @"..\..\fpml-main-4-2.xsd");

If the schemas are not properly formed you will get an error when you attempt to compile them.

Validation of XML Against a Schema in Code

To validate an XML instance document against the schema we use an XmlReader in association with a ValidationEventHandler as below. The code below goes in Main:

            XmlReaderSettings xmlReaderSettings = new XmlReaderSettings();
            xmlReaderSettings.ValidationType = ValidationType.Schema;
            xmlReaderSettings.ValidationEventHandler += new ValidationEventHandler(xmlReaderSettings_ValidationEventHandler);
            XmlReader xmlReader = XmlReader.Create(@"..\..\XML\ird_ex01_vanilla_swap.xml", xmlReaderSettings);
            while (xmlReader.Read()) { };
            Console.WriteLine("Validation complete");

Additionally we need a ValidationEventHandler method: this will be called if there are any errors:

        static void xmlReaderSettings_ValidationEventHandler(object sender, ValidationEventArgs e)
            if (e.Severity == XmlSeverityType.Warning)
                Console.Write("WARNING: ");
            else if (e.Severity == XmlSeverityType.Error)
                Console.Write("ERROR: ");

The code for this example is available. To test these try deliberately breaking both the schemas and the XML and ensure you get appropriate error messages. Note that this code is based on Microsoft’s own help examples at

Note on Visual Studio 2008

The above discussion used Visual Studio 2005. Visual Studio 2008 behaves in the same way except:

  1. Visual Studio 2008 defaults to the XML Editor as the editor for XSD files, which is more sensible than the default DataSet Editor in Visual Studio 2005.
  2. Visual Studio 2008 automatically references xmlsig.xsd in Microsoft’s own schemas folder (normally c:\Program Files\Microsoft Visual Studio 9.0\xml\Schemas). xmlsig.xsd is the standard XML Signature namespace. However, the FpML files are referencing their own version of this schema, which is called xmldsig-core-schema.xsd. As a result if you open fpml-main-4-2.xsd in the designer, for instance, you get warnings about types in this schema being defined twice.To fix this bring up the Properties window for the fpml-main-4-2.xsd file, and click in the Schemas property. Click the button that appears. The screen that comes up lets you select the schemas that are automatically used for the file. Find xmlsig.xsd and in the ‘Use’ column set it to ‘Do not use this schema’ (which gives it a red cross as below). This will get rid of the warnings.



This article has looked at some of Visual Studio’s functionality for handling XSDs and the associated FpML. Part 2 of this series will examine how the FpML fits together for a basic trade XML document.

Licensing of FpML Specifications

The FpML Specifications of this document are subject to the FpML Public License (the “License”); you may not use the FpML Specifications except in compliance with the License. You may obtain a copy of the License at
The FpML Specifications distributed under the License are distributed on an “AS IS” basis, WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License for the specific language governing rights and limitations under the License.
The Licensor of the FpML Specifications is the International Swaps and Derivatives Association, Inc. All Rights Reserved.

December 9, 2007

A Beginner’s Guide to Credit Default Swaps (Part 1)


On our team at work we occasionally employ developers who know nothing about derivatives. It usually falls to me to give these guys a general introduction to the credit derivatives business. As part of that we usually have a session on what a credit default swap is and why it’s important. This article is based on what I say in that session, and as such is an attempt to explain the product to someone who knows very little about the financial services industry.

Government Bonds

It isn’t really possible to understand a credit default swap without having a basic understanding of bonds, so we’ll start with a discussion of what bonds are and why someone might invest in one.

Imagine I have some cash and I want to invest it for a long period. Furthermore assume that interest rates are high and I want to ensure I get a high rate of interest for the period. I would ideally like a fixed interest rate. One way of doing this would be to go to my bank and see what they have on offer. However, most banks don’t offer very generous fixed rate deposits, especially over long periods. They prefer to offer you a variable rate.

An alternative is to buy a bond from the government. To raise money almost all governments periodically issue these bonds. The way they work is that you give your money to the government. The government then pays a fixed rate of interest periodically (usually every six months) on the money you give them. The government does this for a fixed period, usually of several years. At the end of the fixed period they will give you your money back. The end of the fixed period is called the ‘maturity’ of the bond. The amount they pay interest on is called the ‘face value’, the ‘notional value’ or the ‘principal’ of the bond.

What makes this even more attractive as an option is the fact that there is a ‘secondary market’ for bonds. What that means is that there is someone who will buy the bond from me should I not want to hold it to maturity. This is like the stock market. You can buy stocks from individual companies when they issue them, and then (usually) sell them on a stock exchange when you no longer wish to hold the stock. In both cases the price you get will depend on market conditions at the time. Clearly the current level of interest rates will have a major impact on the price you can get when you come to sell your bond. Of course you can buy your bond in the secondary market in the first place, rather than buying it directly from the government.

Should you actually want to do this most of the major stockbrokers will also allow you to trade government bonds, although some cheap online brokers won’t.

So for example, if I look on the US TreasuryDirect site right now I can see that on the 15th August 2007 the US government issued a bond that has a maturity of 15th May 2037 with an interest rate of 5% per year. This is paid every six months (so I get 2.5% of the face value of the bond every six months).

Note that in the United States government bonds issued with a period to maturity of between ten and thirty years are called ‘Treasury bonds’, whilst government bonds issued with a period to maturity of two to ten years are called ‘Treasury notes’. However, these instruments all behave as described above, and are often just referred to as ‘government bonds’.

Corporate Bonds

It’s not only governments that issue bonds, companies do so as well. This is a way of raising money for them, the other alternative being to issue stock. These corporate bonds are typically very like the government bonds discussed above: the company will pay you a fixed interest rate on your money for a fixed period. There’s also a secondary market for these bonds as described above for government bonds.

If you are given the choice between a 10-year corporate bond issued by, say, General Motors (a car company) and a US government bond, which one would you prefer? If the interest rates were the same you’d be wise to go for the US government bond. This is because there’s almost no chance that the US government won’t pay you back your money. It’s going to take a world war or something similar for the US government to be in such trouble that it can’t repay (and in that case you’d probably have bigger worries than your bonds). However, companies can get into financial trouble, even big ones (think of WorldCom, or Enron). If a company goes bankrupt there’s a chance you won’t get all the money you’ve given them for the bond back.

For this reason companies are forced to pay a higher rate of interest on their bonds than the US government. Otherwise no-one will give them the money for their bonds. How much bigger the rate of interest has to be depends on how risky the company is perceived to be.

For example General Motors has issued a bond that matures on the 15th July 2033 paying 8.375%. Whilst this interest rate isn’t directly comparable with that on the US Treasury bond discussed above, if you do work out the numbers you will find that you are getting much more interest from the General Motors bond. This article isn’t going to go into the details of how to do this, as it isn’t strictly relevant to understanding credit default swaps.

Further Reading on Bonds

The sections above have given a very simple overview of bonds. These sections have not described how the secondary markets work, how we price bonds, what a yield is or what yield curves are. If you are interested in such things there are some more details at the links below:

Credit Default Swaps (CDS)

Suppose that we have invested in the General Motors bond mentioned above. Suppose our investment is $10,000,000. Suppose also that we have become worried that General Motors may be getting into financial trouble. What can we do about it? Obviously we could just sell our bond position in the secondary market. However, we can also enter into a credit default swap. The easiest way to think of a credit default swap is as an insurance contract. We are insuring against the possibility that a company might get into financial trouble and cause us to lose money on our bond position.

To enter into this insurance contract we have to find someone prepared to insure us. Note that this is NOT General Motors. The big banks are usually the people to go to.

What we can do is to pay the bank a periodic small amount of money known as a ‘premium’ (which is like an insurance premium). This is calculated as a percentage of the face value of the bond we are insuring against, which is $10m in our case. This amount (the $10m) is known as the ‘notional principal’. The premium is paid every few months (usually every three or six months) throughout the life of the contract.

In return for the premium the bank does nothing unless General Motors gets into financial difficulty. In that case the bank will pay us an amount equal to the amount we have lost on our bond position. This is likely to be a big sum relative to the small premiums that we will pay. Once this happens the contract will terminate. Otherwise the contract carries on for an agreed period (usually five years). In picture form this looks a bit as below:


Here the Big Bank is the ‘protection seller’: it’s receiving money in return for providing protection against our bonds falling in value. Similarly we are ‘protection buyers’.

Clearly there are a few things that need to be sorted out before we enter into this contract. Since the Big Bank is going to make us a large payment if General Motors gets into financial difficulty we’d better define what ‘financial difficulty’ means very clearly. We’d also better sort out exactly how we’re going to calculate the amount that will be paid.

Physical Settlement and Cash Settlement

The amount to be paid is slightly the easier of the two to define. We know which bond we want insurance on (the one we are holding), and we know we want to get the reduction in its value as a result of General Motors getting into trouble. There are two ways of handling this. The first is known as ‘physical settlement’. Here we give the bond to the Big Bank, and the Big Bank gives us the full face value of the bond in return (i.e. the amount that was originally paid to General Motors for it). The bank will then try to dispose of the bond in the market. Note that it will be worth much less than the full face value. This is because General Motors is in difficulty and hence unlikely to pay back the full face value at maturity. So from our point of view we’ve given up our bond but been paid face value for it: we’ve been compensated for the reduction in the value.

The second method is known as ‘cash settlement’. Here we try to work out the reduction in value of the bond, and this is just paid from the Big Bank to us in cash. To work out the reduction in value usually a ‘calculation agent’ is appointed in the CDS contract. The calculation agent will go into the market and get a selection of quotes for the bond from which a price for settlement will be calculated in an agreed way. Often the calculation agent is the seller of protection (the Big Bank in our example).

Credit Events

Defining ‘financial difficulty’ is more problematic, and indeed has led to several lawsuits already. We don’t usually call it ‘financial difficulty’, by the way. It’s referred to as a ‘credit event’, or a ‘default’. We say a credit default swap contract is ‘triggered’ if a credit event occurs, meaning the Big Bank has to pay up in our example.

There are three broad categories of credit events that are put into the documentation of credit default swap contracts:

  1. Bankruptcy
    If a company goes into Chapter 11 (in the US) then that is a clear indicator that the company is in serious financial difficulty and that the bondholders may not get all their money back. This is an obvious thing to have trigger the payment in a CDS contract.
  2. Failure to Pay
    If a company fails to make payments it should be making, including coupon payments on the bonds, then this can be documented as a credit event.
  3. Restructuring
    This is where a company changes the payment schedules it makes on its bonds, usually with the agreement of the bondholders. It’s usually not to the bondholders advantage when this happens, and hence CDS contracts can be documented to cover this kind of restructuring as a credit event.

Of these, restructuring is the one that has proved the most problematic for the market. There are now four separate standard definitions for restructuring that can be used in CDS contracts.

Size of Premium Payment is Bigger if the Company is More Likely to Default

One question that has been asked is how large the premium will be in general (see the comments).

The Big Bank in our example is providing us with protection against the default of a company (General Motors).  We are paying them the premium for this protection.  Clearly if the company being referred to is more likely to default the Big Bank will want us to pay them more money.  So the premium rate is higher for riskier companies than for safe ones.

The Big Bank will decide which companies it thinks are risky, and hence what premium it should charge, based on a number of factors.  However, there’s already a market that reflects how risky a company is.  This is the bond market as described earlier in this article.  In the example there General Motors had to pay a higher interest rate on its bonds than the US Government because of the risk that the investor wouldn’t get their money back if General Motors defaulted.

Size of Premium Payment and How it Relates to Bond Prices 

Now consider the case where we buy a General Motors bond.  We then enter into a credit default swap to the maturity of the bond as well.  This acts as insurance against General Motors defaulting on the bond.  We receive interest from the General Motors bond, but pay some of it away in insurance on the credit default swap.

In simple terms we now have overall a bond position where we don’t lose anything if General Motors defaults.  If a default occurs we get our money back from the credit default swap.  We can then invest in another bond.

We can think of this as a risk-free bond position.  This is in many ways equivalent to a position in US Government bonds (which we can assume won’t default at all).  We’d expect our overall interest rate to be similar to that of a US Government bond.  Our overall interest rate is the rate on the General Motors bond less the premium on the credit default swap.

Now suppose the interest rate on a US Government bond is 5% and the interest rate on a General Motors bond of the same maturity is 8%.  We’d expect the premium on a credit default swap on General Motors for the same period to be about 3%.  Note that the 3% premium is also called the ‘spread’ on a credit default swap, since it is the spread between the government bond and the corporate bond interest rates.

Note that this is a very simplistic analysis.  It is broadly accurate but there are reasons why it doesn’t work exactly in practice.

Some Other Terminology Relating to Credit Default Swaps

(i) Reference Entity and Reference Obligation

Note above that General Motors is not directly involved in the credit default swap contract. General Motors as a company will not even know the contract exists. The contract is between us and the Big Bank. General Motors is just an entity that is referred to in the contract, and hence is known as the ‘reference entity’.

Similarly the contract refers to the specific bond we are insuring (General Motors 8.375% maturing 15th July 2033 in our example). However the bond isn’t directly involved in the contract. Indeed if the contract is cash settled we don’t even have to be holding the bond at any time: we can just enter into the CDS contract without it. The bond is just an obligation being referred to in the contract, and hence is known as the ‘reference obligation’.

You should know that, at least in technology, everyone’s favourite interview question about credit default swaps is ‘what’s the difference between a reference entity and a reference obligation?’

(ii) Bond Seniority

Bonds have a hierarchy of importance when a company is unable to pay its debts. Some bondholders will get their money back before others. (They ALL get their money back before the shareholders.) The exact place in the pecking order depends on the documentation of the bonds. Typically bonds are classified according to ‘seniority’. They are assigned to one of senior secured, senior unsecured, senior subordinated, subordinated and junior subordinated seniority categories. The list is in order of seniority: senior secured is the highest, junior subordinated the lowest. This means if we hold a senior secured bond we are more likely to get our money back if the company goes bankrupt than if we hold a junior subordinated bond.

When a company is being wound up the bondholders get paid in seniority order out of the cash that is remaining to the company. The bondholders with the highest seniority debt get paid first, then the bondholders with the next level of seniority debt, and so on. Bondholders will get paid in full in each seniority category until the money runs out. If at any stage the money is insufficient to pay the current seniority of bondholder in full, every bondholder of that seniority gets paid the same percentage of the face value of their bond.  So, for example, the most senior bondholders may get paid in full, one category of more junior bondholders will only get a percentage payout, and the most junior bondholders may get nothing.

(iii) Recovery Rates

The ‘recovery rate’ is the percentage of the face value of our bond that we get back if there’s a credit event. For example, suppose we hold $10m of bonds in a company, and it goes bankrupt. Assume we get $4m back for our bonds from the company after the bankruptcy. We would say our ‘recovery rate’ is 40% (4m/10m as a percentage).

Recovery rates are also one of the inputs into pricing a CDS contract (working out its value to either counterparty) prior to maturity. To price a CDS one of the things we need to know is how much the bond we are insuring will reduce in value if a credit event occurs. This is obviously important since it determines the size of the payment made as a result of the credit event. Clearly we can’t know exactly how much the bond will be worth after a credit event before the credit event has happened, so we estimate a recovery rate.

Most pricing methodologies estimate recovery rates in a very simplistic way: a percentage is assigned to the seniority of the debt of a company. So we might say General Motors Senior Unsecured debt has a recovery rate of 40%, and then use that number for pricing all GM senior unsecured credit default swaps.

Uses of Credit Default Swaps

As described above it sounds like the credit default swap is a very niche product since its primary use is to hedge bond positions against default. However, the credit default swap market has taken off and is huge. The reason is that there is a wide range of ways CDS can be used. In recent years pure speculation, largely by hedge funds, seems to have been the main driver of the market.

Geoff Chaplin’s excellent book ‘Credit Derivatives: Risk Management, Trading and Investing’ cites the following uses of CDS:

  • Directional Trading/Relative Trades (speculation on individual companies)
  • Debt Hedging (hedging bond positions as described above)
  • Sector/Portfolio Trades (speculation on groups of companies)
  • Income Generation (we can just sell protection and receive premium, provided we’re confident we won’t face defaults (credit events))
  • Regulatory Capital Reduction (if a bank has lent to a company that uses regulatory capital which can be reduced by buying CDS protection)


Below are a few further issues relating to credit default swaps:

  • The description of CDS as ‘insurance’ is not technically accurate. Insurance contracts are regulated in a different way, the documentation is different, and usually an insurance contract would require us to actually own the bond to be valid for a claim, which is not the case for a CDS.
  • As mentioned above, there’s no reason for either party to a CDS contract to actually be holding a bond (reference obligation) of the reference entity. CDS can be entered into purely as speculative positions. Even with physical settlement the buyer of protection can just go into the market and buy the appropriate bond at the time of a credit event, and doesn’t need to hold it through the life of the contract.
  • CDS contracts are usually not entered into with retail investors. You or I couldn’t actually execute a CDS on our bond position; we don’t have big enough positions to make it worthwhile in general. Hedge funds, pension funds, fund managers and insurance companies tend to be the counterparties to the banks on these contracts (as well as other banks).
  • Credit default swaps are usually documented such that a range of bonds can be ‘delivered’ (handed over in physical settlement or used to calculate losses in cash settlement). The text above implied that only one bond was ever relevant. The reference obligation cited in the contract simply defines the type of bond that can be delivered (its seniority). Usually any bond of the same seniority or higher seniority can be delivered. CDS can be traded without any reference obligation being cited: usually this means that any senior unsecured debt can be delivered.
  • This is a zero-cost instrument. The two parties to the contract just agree the details up front, and the contract starts without any initial payment being necessary. If you are a seller of protection you just get premium in without having to do anything, which can be attractive.


In summary, a credit default swap is a contract where one party to the contract pays a small periodic premium to the other, in return for protection against a credit event (financial difficulty) of a known reference entity (company).

This article was written in 2007.  Since then there have been a few developments in the credit default swap market.  A discussion of these developments can be found in part 2 of this series of articles.

July 14, 2007

An Introduction to the Smart Client Software Factory and Composite Application Block: Part 1 Modules and Shells


Microsoft’s Smart Client Software Factory (SCSF) and associated application blocks are excellent pieces of software. However, for a developer coming to them for the first time they can be extremely daunting. There are many things that can be confusing. Firstly we have modules, workitems, workspaces, and shells, all of which sound similar. Then there’s dependency injection, command patterns, event brokers, model-view-presenter patterns and other high-level concepts, none of which are easy to understand. There’s a load of other concepts as well, multiple example applications, and plenty of documentation. Microsoft’s documentation has a very steep learning curve indeed.

I’m going to write a series of short articles that assume you are a developer coming to this for the first time and are confused as I was. To do this I’m going to focus on one or two basic concepts in each article. There’s quite a lot of blogging about CAB/SCSF on the web, but I couldn’t find anything that gave me a quick, basic introduction with a gentle learning curve. This is what I will try to achieve here.

To start I’m going to look at the basic set up of modules and shells in the Composite Application Block. This is the starting point for most SCSF projects. I’m not going to cover WorkItems until my second article as I found them quite confusing initially.


For this example you only need download the code. This contains the CAB dlls it needs to run.

Composite Application Block

The starting point for many developers coming to the Composite Application Block (CAB) is the need to either

1. To design a complex user interface that has some kind of separate components that can be developed and released independently, or
2. To take several existing user interface applications and combine them in such a way that they can continue to be developed independently, but appear in the same window with common menus etc and can interoperate on some level.

This is certainly where I started. The key point in both cases is that if we want our components to be released independently then they can’t have direct references to each other. In short we want ‘applications’ or components that appear in the same user interface (same window) with common menus and some ability to talk to each other, but don’t directly reference each other.

The CAB allows us to do this. It clearly offers us a lot more than just this, but in this article I will show the basics.

Modules and Shells

The first concept you need to understand for this is that of a ‘module’. This is what I am referring to as a ‘application’ or ‘component’ in the paragraph above: a block of code, usually with a user interface that can be displayed in a common window, but which doesn’t reference other modules. In reality these are separate .NET projects within our solution that don’t reference each other.

The second concept is that of the ‘shell’. This is simply the ‘common window’ I’m referring to in the paragraph above. It will contain our modules, or at least the visual parts of them. In reality the shell is usually contained in its own .NET project, but one that doesn’t reference any of the modules, nor is referenced by them.

So, simplistically:

Module = standalone project to be used in a composite user interface
Shell = the host form for the composite user interface

Our Example

Let’s start with a really simple example. Assume we have a C# project that just displays a red form, and another separate project that just displays a blue form. These are going to be our two modules. Then we want a third project to contain a shell, which in this case will just be another form that we want displayed. To keep this example really simple we won’t try to display the red and blue forms actually inside the shell: this will be done in part 2.

The difficult bit is that although all these projects will be in the same solution, none of them will reference each other directly, yet all three forms will display at start up. Obviously we could do this fairly simply with reflection, but we will use the CAB to do it.

Naïve Application Example

The code for this example is available.

To implement the example:

1. We set up three projects (all Windows applications) in a solution. We’ll call these Red, Blue, and Shell. For the Red and Blue projects (which will be our modules) we simply change the BackColor property of the form to red and blue as appropriate.
2. We add references to the CAB dlls (Microsoft.Practices.CompositeUI.dll, .Practices.CompositeUI.WinForms.dll, and Microsoft.Practices.ObjectBuilder.dll) to all three of the projects. We also make sure all three build into the same build directory (via the Properties/Build tab). Shell is the startup project.
3. Now if we run the projects all three will build, but clearly only the form from the Shell project will get displayed, since that is the start up project. We need to tell the other modules to show their forms. To do this we change Program.cs in Shell (our start up code) to inherit from FormShellApplication<,> as below:

 using System;
 using Microsoft.Practices.CompositeUI.WinForms;
 using Microsoft.Practices.CompositeUI;       

 namespace Shell
     public class Program : FormShellApplication<WorkItem, Form1>
         static void Main()
             new Program().Run();

The two types passed in to FormShellApplication<,> both get instantiated when Program is instantiated and .Run() is called (this calls into the base classes clearly). Form1 is our shell form and gets displayed, WorkItem I will discuss in part 2. After this change the application will still only display the MDI form, but the .Run() call will enable us to show the other two screens with some other simple changes.

4. In fact the application is now looking for an XML file telling it what other modules to load. Again this happens as a result of the call to .Run(). The XML file has to be called ProfileCatalog.xml, has to be copied always into the output directory, and has to look like the XML below:

<?xml version="1.0" encoding="utf-8" ?>
<SolutionProfile xmlns="">
    <ModuleInfo AssemblyFile="Red.exe" />
    <ModuleInfo AssemblyFile="Blue.exe" />

We add this file to the Shell project. Now if you get the names of the modules wrong and then run the application it will throw an exception, showing that it’s trying to find the relevant files.

5. Finally we need something in the Red and Blue projects that will actually run as a result of this (the CAB doesn’t just call the usual start up code). We can do this by adding a class that inherits from Microsoft.Practices.CompositeUI.ModuleInit and overrides its Load() method. The CAB code will call this Load method from the .Run() call above:

using Microsoft.Practices.CompositeUI;
namespace Blue
    public class BlueModuleInit : ModuleInit
        public override void Load()
            Form1 form = new Form1();

That’s it: if we put the code above in the Blue project, and the equivalent in the Red project, the three forms will now load and we have our first composite application. None of the three separate projects has a direct reference to any other.


The difficult thing to understand when you see this for the first time is that the CAB is doing a lot of work for us when we call that .Run() method on a FormShellApplication class. It’s instantiating and showing our Form1 (our shell). It’s checking for an XML file called ProfileCatalog.xml. If it finds ProfileCatalog.xml, it is loading the assemblies it finds listed in there. It’s then looking for any ModuleInit classes in them, and calling .Load if it finds them. None of that’s too complicated, but it can feel a bit like smoke and mirrors are being used.

This article is continued in part 2, where I explain WorkItems, and part 3 where I will explain dependency injection, and show how we can get the two forms in the Red and Blue projects in our example to be MDI children in the shell.

June 24, 2007

A Beginner’s Guide to the Black-Scholes Option Pricing Formula (Part 1)

Black-Scholes Call on European Stock
Black-Scholes d1 d2

Firstly let me apologize to the .NET developers perusing this blog, as this article is a little off-topic. However, my interests range over both .NET and derivatives, and I will be posting on both topics in the future.


The Black-Scholes model for pricing stock options was developed by Fischer Black, Myron Scholes and Robert Merton in the early 1970’s. It is arguably the most important result in financial engineering, and is certainly a rich source of interview questions in the financial services industry.

I was recently asked by a friend if I could provide a written explanation in layman’s terms of how the Black-Scholes options pricing formula works. This isn’t necessarily all that easy as the formula involves some relatively complex mathematics. However, I think it is possible to get an intuitive understanding of what the various parts of the formula mean. This article is an attempt to explain that.

Note that to keep things simple here I am only going to discuss European call options on non-dividend paying stock. It doesn’t matter for the purposes of this article if you don’t know what that means.

What is an Option?

Firstly a reminder of what a European call option is. If I ask this in an interview I usually get the textbook answer: ‘the right but not the obligation to buy an asset at a predetermined price at a predetermined date’. My next question is always ‘what does that actually mean?’

Consider a European call option on a Microsoft share (the ‘asset’), with a strike of 30 (the ‘predetermined price’) and maturity of one year from today (the ‘predetermined date’). If I pay to enter into this contract I have the right but not the obligation to buy one share at 30 in a year’s time. Whether I actually exercise my right clearly depends on the share price in the market at that date:

– If the share price is above 30, say at 35, I can buy the share in the contract at 30 and sell it immediately at 35, making a profit of 5. Similarly if the share price is 40 I make a profit of 10.
– If the share price is below 30, say at 25, the fact that I have the right to buy at 30 is worthless: I can buy more cheaply in the open market.

Thus we get the classic ‘hockey stick’ payoff diagram as below. This shows how the amount of money I make on my contract varies with the value of Microsoft stock at the end of the year.

Call Option Payoff Diagram

So if I enter into this contract I make money if the stock price finishes above 30, but don’t lose anything if it finishes below 30. Because I can’t lose, I have to pay to enter into the contract (this is the price of the contract, or the ‘premium’). This premium is usually paid upfront at the start of the contract. The question is how much this premium is going to be?

The Basic Idea

So we’re trying to find the value today of a contract whose ultimate value depends on the value of the Microsoft stock price in one year’s time. Furthermore, the contract has different values depending on whether that stock price goes up or goes down: the payoff curve above is not symmetrical.

So intuitively we are going to need some measure, or measures, of the probabilities of the stock price ending up at various values after one year.

If we have that it may be possible to apply an expected value calculation to get to a price for the contract. This is explained further in part 2.

Older Posts »

Create a free website or blog at