Contents

Cover

Half Title page

Title page

Copyright page

Chapter 1: Executive Overview of this Book

1.1 What is this book?

1.2 What’s special about this book?

1.3 Who is this book for?

1.4 Software requirements

1.5 The structure of this book

1.6 Pedagogical approach

1.7 What this book is not

1.8 Source code on the CD

Part I: Template Programming in C++

Chapter 2: A Gentle Introduction to Templates in C++

2.1 Introduction and objectives

2.2 Motivation and background

2.3 Defining a template

2.4 Template instantiation

2.5 Function templates

2.6 Default values and typedefs

2.7 Guidelines when implementing templates

2.8 Conclusions and summary

Chapter 3: An Introduction to the Standard Template Library

3.1 Introduction and objectives

3.2 A Bird’s-eye view of STL

3.3 Sequence containers

3.4 Associative containers

3.5 Iterators in STL

3.6 Algorithms

3.7 Using STL for financial instruments

3.8 Conclusions and summary

Chapter 4: STL for Financial Engineering Applications

4.1 Introduction and objectives

4.2 Clever data structures

4.3 Set theory and STL

4.4 Useful algorithms

4.5 STL adaptor containers

4.6 Conclusions and summary

Chapter 5: The Property Pattern in Financial Engineering

5.1 Introduction and objectives

5.2 The Property pattern

5.3 An example

5.4 Extending the Property pattern: property sets and property lists

5.5 Properties and exotic options

5.6 Conclusions and summary

Part II: Building Block Classes

Chapter 6: Arrays, Vectors and Matrices

6.1 Introduction and objectives

6.2 Motivation and background

6.3 A layered approach

6.4 The Array and Matrix Classes in Detail

6.5 The vector and Numeric Matrix classes in detail

6.6 Associative arrays and matrices

6.7 Conclusions and summary

Chapter 7: Arrays and Matrix Properties

7.1 Introduction and objectives

7.2 An overview of the functionality

7.3 Software requirements

7.4 The core processes

7.5 Other function categories

7.6 Using the functions

7.7 An introduction to exception handling

7.8 Conclusions and summary

Chapter 8: Numerical Linear Algebra

8.1 Introduction and objectives

8.2 An introduction to numerical linear algebra

8.3 Tridiagonal systems

8.4 Block tridiagonal systems

8.5 What requirements should our matrix satisfy?

8.6 Conclusions and summary

Chapter 9: Modelling Functions in C++

9.1 Introduction and objectives

9.2 Function pointers in C++

9.3 Function objects in STL

9.4 Some function types

9.5 Creating your own function classes

9.6 Arrays of functions

9.7 Vector functions

9.8 Real-valued functions

9.9 Vector-valued functions

9.10 Conclusions and summary

Chapter 10: C++ Classes for Statistical Distributions

10.1 Introduction and objectives

10.2 Discrete and continuous probability distribution functions

10.3 Continuous distributions

10.4 Discrete distributions

10.5 Tests

10.6 Conclusions and summary

Part III: Ordinary and Stochastic Differential Equations

Chapter 11: Numerical Solution of Initial Value Problems: Fundamentals

11.1 Introduction and Objectives

11.2 A Model Problem

11.3 Discretisation

11.4 Common Schemes

11.5 Some Theoretical Issues

11.6 Fitting: Special Schemes for Difficult Problems

11.7 Non-Linear Scalar Problems and Predictor—Corrector Methods

11.8 Extrapolation Techniques

11.9 C++ Design and Implementation

11.10 Generalisations

11.11 Conclusions and Summary

Chapter 12: Stochastic Processes and Stochastic Differential Equations

12.1 Introduction and Objectives

12.2 Random Variables and Random Processes

12.3 An Introduction to Stochastic Differential Equations

12.4 Some Finite Difference Schemes

12.5 Which Scheme to Use?

12.6 Systems of Sdes

12.7 Conclusions and Summary

Chapter 13: Two-Point Boundary Value Problems

13.1 Introduction and Objectives

13.2 Description of Problem

13.3 (Traditional) Centred-Difference Schemes

13.4 Approximation of the Boundary Conditions

13.5 Exponentially Fitted Schemes and Convection—Diffusion

13.6 Approximating the Derivatives

13.7 Design Issues

13.8 Conclusions and Summary

Chapter 14: Matrix Iterative Methods

14.1 Introduction and Objectives

14.2 Iterative Methods

14.3 The Jacobi Method

14.4 Gauss-Seidel Method

14.5 Successive Overrelaxation (SOR)

14.6 Other Methods

14.7 The Linear Complementarity Problem

14.8 Implementation

14.9 Conclusions and Summary

Part IV: Programming the Black-Scholes Environment

Chapter 15: An Overview of Computational Finance

15.1 Introduction and Objectives

15.2 The Development Life Cycle

15.3 Partial Differential Equations

15.4 Numerical Approximation of PDEs

15.5 The Class of Finite Difference Schemes

15.6 Special Schemes for Special Problems

15.7 Implementation Issues and the Choice of Programming Language

15.8 Origins and Application Areas

15.9 Conclusions and Summary

Chapter 16: Finite Difference Schemes for Black—Scholes

16.1 Introduction and Objectives

16.2 Model Problem: The One-Dimensional Heat Equation

16.3 The Black—Scholes Equation

16.4 Initial Conditions and Exotic Options Payoffs

16.5 Implementation

16.6 Method of Lines: A Whirlwind Introduction

16.7 Conclusions and Summary

Chapter 17: Implicit Finite Difference Schemes for Black—Scholes

17.1 Introduction and Objectives

17.2 Fully Implicit Method

17.3 An Introduction to the Crank—Nicolson Method

17.4 A Critique of Crank—Nicolson

17.5 Is There Hope? The Keller Scheme

17.6 Conclusions and Summary

Chapter 18: Special Schemes for Plain and Exotic Options

18.1 Introduction and Objectives

18.2 Motivating Exponentially Fitted Schemes

18.3 Exponentially Fitted Schemes for Parabolic Problems

18.4 What Happens When the Volatility Goes to Zero?

18.5 Exponential Fitting With Explicit Time

18.6 Exponential Fitting and Exotic Options

18.7 Some Final Remarks

Chapter 19: My First Finite Difference Solver

19.1 Introduction and Objectives

19.2 Modelling Partial Differential Equations in C++

19.3 Finite Difference Schemes as C++ Classes, Part I

19.4 Finite Difference Schemes as C++ Classes, Part II

19.5 Initialisation Issues

19.6 Interfacing with Excel

19.7 Conclusions and Summary

Chapter 20: An Introduction to ADI and Splitting Schemes

20.1 Introduction and Objectives

20.3 Motivation and History

20.4 Basic ADI Scheme for the Heat Equation

20.5 Basic Splitting Scheme for the Heat Equation

20.6 Approximating Cross-Derivatives

20.7 Handling Boundary Conditions

20.8 Algorithms and Design Issues

20.9 Conclusions and Summary

Chapter 21: Numerical Approximation of Two-Factor Derivative Models

21.1 Introduction and Objectives

21.2 Two-Factor Models in Financial Engineering

21.3 Finite Difference Approximations

21.4 ADI Schemes for Asian Options

21.5 Splitting Schemes

21.6 Conclusions and Summary

Part V: Design Patterns

Chapter 22: A C++ Application for Displaying Numeric Data

22.1 Introduction and Objectives

22.2 Input Mechanisms

22.3 Conversion and Processing Mechanisms

22.4 Output and Display Mechanisms

22.5 Putting it All Together

22.6 Output

22.7 Other Functionality

22.8 Using Excel and Property Sets

22.9 Extensions and the Road to Design Patterns

22.10 Conclusions and Summary

Chapter 23: Object Creational Patterns

23.1 Introduction and Objectives

23.2 The Singleton Pattern

23.3 The Prototype Pattern

23.4 Factory Method Pattern (Virtual Constructor)

23.5 Abstract Factory Pattern

23.6 Applications to Financial Engineering

23.7 Conclusions and Summary

Chapter 24: Object Structural Patterns

24.1 Introduction and Objectives

24.2 Kinds of Structural Relationships Between Classes

24.3 Whole—Part Pattern

24.4 The Composite Pattern

24.5 The FaçAde Pattern

24.6 The Bridge Pattern

24.7 Conclusions and Summary

Chapter 25: Object Behavioural Patterns

25.1 Introduction and Objectives

25.2 Kinds of Behavioural Patterns

25.3 Iterator Pattern

25.4 The Visitor Pattern

25.5 Notification Patterns

25.6 Conclusions and Summary

Part VI: Design and Deployment Issues

Chapter 26: An Introduction to the Extensible Markup Language

26.1 Introduction and Objectives

26.2 A Short History of XML

26.3 The XML Structure

26.4 Document Type Definition

26.5 Extensible Stylesheet Language Transformation (XSLT)

26.6 An Application of XML: Financial Products Markup Language

26.7 Conclusions and Summary

Chapter 27: Advanced XML and Programming Interface

27.1 Introduction and Objectives

27.2 XML Schema

27.3 Accessing XML Data: The Document Object Model

27.4 DOM and C++: The Essentials

27.5 DOM, Entities and Property Sets

27.6 XML Structures for Plain and Barrier Options

27.7 Conclusions and Summary

Chapter 28: Interfacing C++ and Excel

28.1 Introduction and Objectives

28.2 Object Model in Excel: An Overview

28.3 Under the Bonnet: Technical Details of C++ Interfacing to Excel

28.4 Implementing the Core Process

28.5 Extensions

28.6 Application Areas

28.7 Conclusions and Summary

Chapter 29: Advanced Excel Interfacing (Daniel Duffy and Robert Demming)

29.1 Introduction and Objectives

29.2 Status Report and New Requirements

29.3 A Gentle Introduction to Excel Add-Ins

29.4 Automation Add-in in Detail

29.5 Creating A COM Add-in

29.6 Future Trends

29.7 Conclusions and Summary

Chapter 30: An Extended Application: Option Strategies and Portfolios

30.1 Introduction and Objectives

30.2 Spreads

30.3 Combinations: Straddles and Strangles

30.4 Designing and Implementing Spreads

30.5 Delta Hedging

30.6 An Example

30.7 Tips and Guidelines

Appendix I: My C++ Refresher

A1.1 Summary

A1.2 What is C++ and Why is it Important?

A1.3 The Datasim C++ Self-Test

A1.4 The Essentials of a C++ Class: The Canonical Header File

A1.5 An Overview of Object-Oriented Programming in C++

A1.6 The European Option in C++: The Details

Appendix II: Dates and Other Temporal Types

A2.1 Summary

A2.2 The Date Class

A2.3 The Time Class

A2.4 Extensions

A2.5 A Simple Example

References

Index

Financial Instrument Pricing Using C++

Wiley Finance Series

Hedge Funds: Quantitative Insights

François-Serge L’habitant

A Currency Options Primer

Shani Shamah

New Risk Measures in Investment and Regulation

Giorgio Szegö (Editor)

Modelling Prices in Competitive Electricity Markets

Derek Bunn (Editor)

Inflation-Indexed Securities: Bonds, Swaps and Other Derivatives, 2nd Edition

Mark Deacon, Andrew Derry and Dariush Mirfendereski

European Fixed Income Markets: Money, Bond and Interest Rates

Jonathan Batten, Thomas Fetherston and Peter Szilagyi (Editors)

Global Securitisation and CDOs

John Deacon

Applied Quantitative Methods for Trading and Investment

Christian L. Dunis, Jason Laws and Patrick Naïm (Editors)

Country Risk Assessment: A Guide to Global Investment Strategy

Michel Henry Bouchet, Ephraim Clark and Bertrand Groslambert

Credit Derivatives Pricing Models: Models, Pricing and Implementation

Philipp J. Schönbucher

Hedge Funds: A Resource for Investors

Simone Borla

A Foreign Exchange Primer

Shani Shamah

The Simple Rules: Revisiting the Art of Financial Risk Management

Erik Banks

Option Theory

Peter James

Risk-adjusted Lending Conditions

Werner Rosenberger

Measuring Market Risk

Kevin Dowd

An Introduction to Market Risk Management

Kevin Dowd

Behavioural Finance

James Montier

Asset Management: Equities Demystified

Shanta Acharya

An Introduction to Capital Markets: Products, Strategies, Participants

Andrew M. Chisholm

Hedge Funds: Myths and Limits

François-Serge L’habitant

The Manager’s Concise Guide to Risk

Jihad S. Nader

Securities Operations: A Guide to Trade and Position Management

Michael Simmons

Modeling, Measuring and Hedging Operational Risk

Marcelo Cruz

Monte Carlo Methods in Finance

Peter Jäckel

Building and Using Dynamic Interest Rate Models

Ken Kortanek and Vladimir Medvedev

Structured Equity Derivatives: The Definitive Guide to Exotic Options and Structured Notes

Harry Kat

Advanced Modelling in Finance Using Excel and VBA

Mary Jackson and Mike Staunton

Operational Risk: Measurement and Modelling

Jack King

Interest Rate Modelling

Jessica James and Nick Webber

© 2004 Daniel J Duffy
Published by John Wiley & Sons, Ltd

Registered office
John Wiley & Sons Ltd, The Atrium, Southern Gate, Chichester, West Sussex, PO19 8SQ, United Kingdom

For details of our global editorial offices, for customer services and for information about how to apply for permission to reuse the copyright material in this book please see our website at www.wiley.com.

All rights reserved. No part of this publication may be reproduced, stored in a retrieval system, or transmitted, in any form or by any means, electronic, mechanical, photocopying, recording or otherwise, except as permitted by the UK Copyright, Designs and Patents Act 1988, without the prior permission of the publisher.

Wiley publishes in a variety of print and electronic formats and by print-on-demand. Some material included with standard print versions of this book may not be included in e-books or in print-on-demand. If this book refers to media such as a CD or DVD that is not included in the version you purchased, you may download this material at http://booksupport.wiley.com. For more information about Wiley products, visit www.wiley.com.

Designations used by companies to distinguish their products are often claimed as trademarks. All brand names and product names used in this book are trade names, service marks, trademarks or registered trademarks of their respective owners. The publisher is not associated with any product or vendor mentioned in this book.

Limit of Liability/Disclaimer of Warranty: While the publisher and author have used their best efforts in preparing this book, they make no representations or warranties with the respect to the accuracy or completeness of the contents of this book and specifically disclaim any implied warranties of merchantability or fitness for a particular purpose. It is sold on the understanding that the publisher is not engaged in rendering professional services and neither the publisher nor the author shall be liable for damages arising herefrom. If professional advice or other expert assistance is required, the services of a competent professional should be sought.

Library of Congress Cataloging-in-Publication Data

Duffy, Daniel J.
Designing and implementing financial instruments in C++ / Daniel J. Duffy.
p. cm.
ISBN 0-470-85509-6
1. Investments – Mathematical models. 2. Financial engineering. 3. C++
(Computer program language) I. Title
HG4515. 2. D85 2004
332.6_0285_5133 – dc22

2004008925

A catalogue record for this book is available from the British Library.

ISBN 978-0-470-85509-6 (HB)

Chapter 1

Executive Overview of this Book

1.1 WHAT IS THIS BOOK?

The goal of this book is to model financial instruments, such as options, bonds and interest-rate products by partial differential equations, finite differences and C++. It is intended for IT and quantitative finance professionals who know this material and wish to deepen their knowledge and for those readers who use techniques such as Monte Carlo, Fourier transform methods, stochastic differential equations and lattice methods (for example, the binomial method) for instrument pricing.

We integrate a number of well-known areas to create a traceable and maintainable path from when a financial engineer proposes a new model to when he or she codes the resulting equations in C++. When viewed as a black box, the core process in this book is to produce C++ classes and code for financial engineering applications. Furthermore, we give lots of examples of code that developers can use without much hassle. The accompanying CD contains all the source code in this book. We provide guidelines, algorithms and reusable code to help the reader to achieve these ends. The main activities that realise the core process are:

Activity 1: Map the financial model to a partial differential equation (PDE)

Activity 2: Approximate the PDE by the finite difference method (FDM)

Activity 3: Implement the FDM using C++ and design patterns.

In this book we shall concentrate on Activities 2 and 3. Since this is a book on the application of C++ to financial engineering we concentrate on mapping the numerical algorithms from Activity 2 to robust and flexible C++ code and classes. However, we shall provide sufficient motivation and background information to help the reader to understand the complete ‘instrument life cycle’. This life cycle describes the processes, activities, decisions and alternatives that describe how to program models for financial instruments in C++.

The topics in this book relate to finance, partial differential equations, numerical schemes and C++ code, and for this reason we use the term Computational Finance to sum up these related activities (see Seydel, 2003, where the same phrase is used). The foundations for partial differential equations and finite difference schemes for financial engineering applications are discussed in Duffy (2004b).

1.2 WHAT’S SPECIAL ABOUT THIS BOOK?

This book is part of a larger, ongoing project. It is the outcome of one part of this project and concentrates on showing how to program finite difference schemes in C++. Our approach is novel in a number of respects.

1. We use modern object-oriented and generic design patterns in C++ to solve a range of partial, stochastic and ordinary differential equations in financial engineering. Traditionally, engineers have used packages such as Matlab, Maple, the C language or other specialised libraries. Each alternative solution has its own benefits of course, but using C++ means that your code is portable, flexible and future-proof (C++ will still be used 20 years from now). Using C++ means that you are not tied into one vendor or operating system.

2. We give a thorough introduction to finite difference methods, how to apply them to Black – Scholes type equations and how to map them to C++ code. We avoid glib recipe-type schemes that work well for toy problems but do not always scale to real-life problems. In particular, we show how to program the famous Crank – Nicolson scheme and discuss when it breaks down, especially in applications with small volatility, discontinuous payoff functions or non-linearities. We propose new schemes that overcome these problems and produce uniformly good approximations to the delta of an option. The book discusses finite difference schemes for both one-factor and two-factor problems.

3. Successful software always needs to be adapted and extended, and to this end we design our classes and applications so that they can easily be modified. Our book is novel in the sense that we apply the powerful and proven design patterns (see Gamma et al., 1995; Buschmann et al., 1996) to help us to produce applications that can be extended or adapted to different organisational, hardware and software Contexts.

4. Last, but not least, it is vital that our software artefacts are well documented. We document these artefacts at the design level and, in particular, we use the de-facto Unified Modeling Language (UML) to visually display the structural, functional and behavioural relationships between the classes and objects in our applications.

In short, this book describes in a step-by-step manner how to create ‘good’ software for financial engineering applications; it also integrates established techniques from fluid mechanics, numerical analysis and software design to produce a coherent and seamless approach to the design and implementation of financial models in C++.

1.3 WHO IS THIS BOOK FOR?

This book is meant for IT and quantitative finance professionals (risk managers, product development and derivatives research groups) who work in financial institutions and software companies and are involved in designing and implementing pricing models in C++. This book deals with fundamental issues such as C++ design and implementation, design patterns, finite difference methods and advanced software environments. Thus, it is of value to financial engineers (‘Quants’), software developers and financial modellers.

We feel that the book is useful for universities and other educational institutes that deliver financial courses. This is not a book on instrument theory as such, and we assume that the reader has knowledge of option theory as presented in books by Hull (2000) and Wilmott (1998), for example. We also assume that the reader has had some exposure to differential equations, differential and integral calculus and matrix algebra. Finally, the reader should have a working knowledge of C++.

As we have already mentioned in this chapter, the book is suited not only to those readers from a partial differential equation (PDE) background but also to those who use techniques such as Monte Carlo, Fourier transform methods, stochastic differential equations (SDEs) and the binomial method for instrument pricing. We do our best to show that finite differences compare well with, and even outperform, these former methods, especially for complex and non-linear one-factor and two-factor Black – Scholes models.

Finally, the real option theory is emerging and many of the techniques in this book can be used in decision support systems in the oil, gas and energy industries. Thus, the book is also of interest to engineers, scientists and financial engineers in these fields.

1.4 SOFTWARE REQUIREMENTS

We have written this book from a number of viewpoints that have to do with what we call software quality. In general, we adopt the ISO 9126 quality characteristics (see Kitchenham and Pfleeger, 1996) as our working model. ISO 9126 describes how good a software product is. It consists of six top-level characteristics:

Functionality: The ability of the software to satisfy stated or implied customer needs.

Reliability: Does the software maintain its level of performance for a stated period of time?

Usability: Is the software easy to understand, learn or integrate with other applications?

Efficiency: Describes the response times in the application and the corresponding re\-sources that are needed.

Maintainability: How easy is it to modify, adapt and test the application? How stable is the application under Change?

Portability: The ease with which the application can be adapted to work in some new software or hardware environment.

Any one (or all) of the above requirements may be important for your new or existing software project. In general, the more requirements your applications must satisfy the more time it will take to satisfy them. In this book we classify applications into three broad categories, depending on the level of flexibility that they must have:

Low flexibility: These are either throwaway prototypes or simple programs in order to test a piece of code or check the validity of some new model

Medium flexibility: The code and classes in this category can be customised (by changing its source code if necessary) and used in your own applications

High flexibility: The code in this category can be used in your applications without any Changes.

It is important to know at the outset how flexible our solutions must be; on the one hand, we do not want to ‘over-engineer’ our application, but nor do we want to produce code that is difficult to maintain, understand or falls apart when we modify it. This book will provide you with guidelines to help you to produce good designs for financial engineering applications.

We layer the software in this book by examining it at four different levels:

Foundation classes and building blocks: Reusable components for vectors, lists, matrices and other containers. We make ample use of the Standard Template Library (STL).

Mechanisms: Tightly coupled groups of generic functions that are related to a specific piece of functionality. An example is a set of functions for Date manipulations (cash flows, interest rate Curves).

Half-products: Ready-to-use libraries that you can use as part of your own applications. We can place these half-products in assemblies and DLLs.

Applications: Dedicated applications for the user (not the developer). These applications are usually executables.

There are many advantages associated with taking this layered approach to software development, as we shall see in this book.

1.5 THE STRUCTURE OF THIS BOOK

This book is partitioned into six major parts, each of which deals with a major topic and consists of a number of chapters. These chapters deal with techniques that help to achieve the goals of each part.

Part I This part is an introduction to C++ template classes. We define what templates are, how to create them and how to use them in financial engineering applications. We give an overview of the Standard Template Library (STL). This is a C++ library consisting of template classes for a wide range of data containers, algorithms and functionality for navigating in these containers. We develop a number of template classes based on STL that we can use in financial engineering applications.

Part II In this part we create classes and code that will be used when approximating partial differential equations by finite difference methods. First, we create template classes for arrays, vectors and matrices as well as the corresponding mathematical operations on them. Furthermore, we introduce several classes that solve linear systems of equations. These classes implement direct and iterative matrix solvers in numerical linear algebra. Second, we create a number of other foundation classes that we need in numerical differentiation and integration. Finally, some useful classes for statistics are introduced.

Part III This part represents the start of the book as far as the mathematical core is concerned. We motivate the finite difference method by applying it to a simple first-order ordinary differential equation in Chapter 11. This chapter discusses the most important ideas and schemes that will serve us well in later chapters. Continuing from Chapter \chapr{11, we introduce stochastic differential equations and the finite difference schemes needed in order to approximate them. We also propose several schemes to approximate two-point boundary value problems. Special attention is paid to the Crank – Nicolson scheme and why it fails to approximate the solution of the convection-diffusion equation in certain circumstances. It is in this part of the book that we introduce the class of exponentially fitted schemes and explain how they resolve the spurious oscillation problems associated with Crank – Nicolson.

Part IV In this part we introduce the one-factor and two-factor Black – Scholes equations and devise appropriate finite difference schemes for them. Before we reach this level of Nirvana, we begin with the one-dimensional heat equation and discuss explicit and implicit finite difference schemes to approximate its solution. The schemes are extensions of the time-independent schemes that we introduced in Part III. Slightly increasing the level of difficulty, we discuss the Crank – Nicolson and fully implicit schemes for the one-dimensional convection-diffusion equation (and its specialisation, the Black – Scholes equation). We analyse the schemes in some detail, discussing why they work, when they do not work and how to produce fitted schemes that approximate the solution and the delta of the Black – Scholes equation.

Proceeding to two-factor problems, we propose Alternating Direction Implicit (ADI) and splitting methods and compare their relative merits.

Part V: In this part we give an introduction to design patterns. Design is about alternatives and we have many choices when designing a system as the choices are determined by the software requirements. We begin with an introduction to some general design principles. In particular, we focus on templates and inheritance and why they are competitors. We also introduce the important notion of delegation whose understanding is fundamental to design patterns.

The main objective in Part V is to show how the famous design patterns of GOF (see Gamma et al., 1995) are applied to financial engineering applications. We pay special attention to choosing appropriate examples and to a discussion of the advantages of design patterns in this particular context. Three chapters are devoted to the Creational, Structural and Behavioural patterns.

Part VI This part contains a number of chapters that are of particular interest to financial engineers and IT personnel who write financial engineering applications. First, we give an introduction to the Extensible Markup Language (XML), a W3C standard for interoperable data representation. We also describe how it is used in option pricing applications in this book. XML will become more important in the financial world in the coming years as evidenced by the work seen with FpML and FIX. We also discuss classes and code that allow C++ code to communicate with Excel. Finally, we introduce a number of design patterns that are very useful for the current work.

1.6 PEDAGOGICAL APPROACH

In general, our approach is incremental in the sense that we begin with simple examples to illustrate the theory and progress to larger problems and examples. This approach applies to the theory of finite differences for partial differential equations as well as the C++ code and design patterns. For example, our main objective is to model one-factor and two-factor Black – Scholes equations using finite differences. The main ‘flow’ in this case is:

Finite differences for scalar, linear first-order ordinary differential equations (ODEs).

Finite differences for stochastic differential equations (SDEs).

Two-point boundary value problems (special case: stationary convection-diffusion).

Explicit and implicit finite difference schemes for the heat equation.

Crank – Nicolson and fitting schemes for the one-factor Black – Scholes equation.

Approximating the Greeks.

Alternating Direction Implicit (ADI) and splitting schemes for two-factor Black – Scholes equations.

In a similar vein, we build up C++ expertise as follows:

The C++ template Class.

The Standard Template Library (STL) and its applications to financial engineering.

The Property pattern and the modelling of financial instruments.

C++ classes for ODEs and SDEs.

C++ foundation classes: vectors, matrices and statistics.

C++ classes for the heat equation.

Modelling Black – Scholes with C++.

C++ for ADI and splitting methods.

In short, we adopt the following rule-of-thumb:

1. Get it working.

2. Then get it right.

3. Then get it optimised.

One step at a time!

1.7 WHAT THIS BOOK IS NOT

First, this is not an introductory book on C++. We assume that the reader has a working knowledge of this language. Second, this book assumes that the reader knows what an option is, what Black – Scholes is, and so on. Finally, this is not a book on the theory of partial differential equations and their approximation using finite differences, but is rather a book that motivates finite difference schemes and applies them to financial engineering applications using C++.

1.8 SOURCE CODE ON THE CD

You can use the source code on the accompanying CD free of charge in your applications provided you acknowledge the author:

© Datasim Education BV 2004

Each source file has this copyright statement. Any questions or suggestions should be sent to Daniel Duffy at info@datasim.nl.

Part I

Template Programming in C++

Chapter 2

A Gentle Introduction to Templates in C++

2.1 INTRODUCTION AND OBJECTIVES

This is the first chapter in Part I of this book. The main goal of Part I is to introduce the reader to generic programming in C++ by discussing template classes and function templates. We also give a fairly detailed introduction to the Standard Template Library (STL), which provides us with a ready-to-use set of data structures and algorithms that we can apply to financial applications. Furthermore, we define our own data structures that model European option attributes. In short, Part I is the foundation upon which we build all future classes and software systems in this book.

In Appendix 1 we give a review of the main features in C++ which you should read if your knowledge of C++ is a bit rusty, but experienced C++ developers can pass it.

In this chapter we give a detailed introduction to how C++ supports the notion of generic programming in the form of so-called templates. Just as a class can be seen as a factory or ‘cookie-cutter’ for objects, so too can we see a C++ template as a factory for normal C++ classes. This feature leads to massive reusability in C++ software applications. For example, the STL (see Musser and Saini, 1996) contains C++ templates for a wide range of data containers such as vectors, lists and sets as well as various kinds of algorithms that operate on these containers. For example, STL has a C++ template for vectors. A vector is an indexible array of objects to which new objects can be added. The objects in the vector are generic and the programmer can then ‘instantiate’ the generic underlying type by replacing it by a concrete type. Some examples of instantiated template classes are:

vector<double>   (an array of doubles)
vector<EuropeanOption>   (an array of European options)
vector <int>   (an array of integers)

Please note that each of the above examples represents a class and that no new member functions need to be written because they are generated as it were from the corresponding template. Thus, we only have to write the template once and we instantiate its generic underlying types to give us a class. The following example shows us how templates, classes and objects are related:

Lesen Sie weiter in der vollständigen Ausgabe!

Lesen Sie weiter in der vollständigen Ausgabe!

Lesen Sie weiter in der vollständigen Ausgabe!

Lesen Sie weiter in der vollständigen Ausgabe!

Lesen Sie weiter in der vollständigen Ausgabe!

Lesen Sie weiter in der vollständigen Ausgabe!

Lesen Sie weiter in der vollständigen Ausgabe!

Lesen Sie weiter in der vollständigen Ausgabe!

Lesen Sie weiter in der vollständigen Ausgabe!

Lesen Sie weiter in der vollständigen Ausgabe!

Lesen Sie weiter in der vollständigen Ausgabe!

Lesen Sie weiter in der vollständigen Ausgabe!

Lesen Sie weiter in der vollständigen Ausgabe!

Lesen Sie weiter in der vollständigen Ausgabe!

Lesen Sie weiter in der vollständigen Ausgabe!

Lesen Sie weiter in der vollständigen Ausgabe!

Lesen Sie weiter in der vollständigen Ausgabe!

Lesen Sie weiter in der vollständigen Ausgabe!

Lesen Sie weiter in der vollständigen Ausgabe!

Lesen Sie weiter in der vollständigen Ausgabe!

Lesen Sie weiter in der vollständigen Ausgabe!

Lesen Sie weiter in der vollständigen Ausgabe!

Lesen Sie weiter in der vollständigen Ausgabe!

Lesen Sie weiter in der vollständigen Ausgabe!

Lesen Sie weiter in der vollständigen Ausgabe!

Lesen Sie weiter in der vollständigen Ausgabe!

Lesen Sie weiter in der vollständigen Ausgabe!

Lesen Sie weiter in der vollständigen Ausgabe!

Lesen Sie weiter in der vollständigen Ausgabe!

Lesen Sie weiter in der vollständigen Ausgabe!

Lesen Sie weiter in der vollständigen Ausgabe!

Lesen Sie weiter in der vollständigen Ausgabe!

Lesen Sie weiter in der vollständigen Ausgabe!

Lesen Sie weiter in der vollständigen Ausgabe!

Lesen Sie weiter in der vollständigen Ausgabe!

Lesen Sie weiter in der vollständigen Ausgabe!

Lesen Sie weiter in der vollständigen Ausgabe!

Lesen Sie weiter in der vollständigen Ausgabe!