Modeling Derivatives Applications in Matlab, C++, and Excel

NJ • New York • London • San Francisco • Toronto • Sydney Tokyo • Singapore • Hong Kong • Cape Town • Madrid Paris • Milan • Munich • Amsterdam . C++.Modeling Derivatives Applications in Matlab. and Excel Justin London An Imprint of PEARSON EDUCATION Upper Saddle River.

4. and Excel. Modeling Credit Derivatives. 2006 ISBN: 0-13-196259-0 Pearson Education LTD. p. Pearson Educati` n de Mexico.. Corporate and GovernmentSales. ISBN 0-13-196259-0 (hardback : alk. please contact International Sales at international@pearsoned.382-3419. 2. Ltd. Publishing as FT Press Upper Saddle River. Library of Congress Cataloging-in-Publication Data London. without permission in writing from the publisher. Inc.5’7–dc22 2006023492 .Vice President. Justin. No part of this book may be reproduced. please contact U. 2006 005. New Jersey 07458 FT Press offers excellent discounts on this book when ordered in quantity for bulk purchases or special sales. Editor-in-Chief: Tim Moore Executive Editor: Jim Boyd Editorial Assistant: Susie Abraham Development Editor: Russ Hall Associate Editor-in-Chief and Director of Marketing: Amy Neidlinger Cover Designer: Chuti Prasertsith Managing Editor: Gina Kanouse Senior Project Editor: Lori Lyons Copy Editor: Water Crest Publishing Indexer: Christine Karpeles Compositor: Lori Hughes Manufacturing Buyer: Dan Uhrig © 2007 by Pearson Education. o Pearson Education—Japan Pearson Education Malaysia. and Excel / Justin London. Pte. cm. Printed in the United States of America First Printing December. Pearson Education Singapore. in any form or by any means. corpsales@pearsontechgroup. Company and product names mentioned herein are the trademarks or registered trademarks of their respective owners.A. Pricing Models in Matlab. HF5548. 1-800. Limited. For sales outside the U. Pearson Education North Asia. paper) 1. S. I. Pearson Education Australia PTY. Pte. C++. Ltd. de C. For more information.S. Ltd. Ltd. 1968Modeling Derivatives Applications in Matlab. Pearson Education Canada.V. All rights reserved.

v To the memory of my grandparents. Milton and Evelyn London. Joanna. Leon and Leslie. and my sister. . my parents.


and DV01 Hedging Bond Portfolios 1.9 Bootstrapping in Excel 1.6 Term Structure of Rates 1.1 Eurodollar Futures 1.C ONTENTS Preface Acknowledgments About the Author 1 SWAPS AND FIXED INCOME INSTRUMENTS 1.4 Hedging Debt Positions Hedging a Future 91-Day T-Bill Investment with T-Bill Call Short Hedge: Managing the Maturity Gap Maturity Gap and the Carrying Cost Model Managing the Maturity Gap with Eurodollar Put Short Hedge: Hedging a Variable-Rate Loan 1.5 Bond and Swap Duration.12 Swap Valuation in C++ 1. Modified Duration.7 Bootstrap Method 1.8 Bootstrapping in Matlab 1.13 Bermudan Swaption Pricing in Matlab Endnotes xv xix xxi 1 2 3 6 7 10 11 11 12 14 14 15 18 20 24 25 28 30 33 43 45 50 61 65 vii .3 Computing Treasury Bill Prices and Yields in Matlab 1.11 Swap Pricing in Matlab Using Term Structure Analysis 1.2 Treasury Bills and Bonds Hedging with T-Bill Futures Long Futures Hedge: Hedging Synthetic Futures on 182-Day T-Bill 1.10 General Swap Pricing in Matlab Description 1.

Durrelman.1 Prepayment Models 3.10 Principal. and Roncalli Method e Mashal and Zeevi Method 2. Nikeghbali.5 MBS Pricing Using Monte Carlo in C++ 3.12 Dynamic Hedging of MBS The Multivariable Density Estimation Method Endnotes 4 COLLATERALIZED DEBT OBLIGATIONS 4.3 Archimedean Copulae 2.viii Contents 2 COPULA FUNCTIONS 2.2 Numerical Example of Prepayment Model 3.6 Matlab Fixed-Income Toolkit for MBS Valuation 3.2 Classes of Copula Functions Multivariate Gaussian Copula Multivariate Student’s T Copula 2.8 CMO Implementation in C++ 3.1 Structure of CDOs Cash Flow CDOs Market Value CDOs Balance Sheet Cash Flows CDOs Arbitrage CDOs Arbitrage Market Value CDOs 67 67 69 69 71 73 74 74 76 76 77 77 82 86 87 91 93 95 98 100 111 126 131 137 146 149 151 151 153 160 163 164 165 166 166 166 166 .4 Calibrating Copulae Exact Maximum Likelihood Method (EML) The Inference Functions for Margins Method (IFM) The Canonical Maximum Likelihood Method (CML) 2. Riboulet.1 Definition and Basic Properties of Copula Functions 2.6 Using Copulas in Excel Endnotes 3 MORTGAGE-BACKED SECURITIES 3.5 Numerical Results for Calibrating Real-Market Data Bouy` .9 Planned Amortization Classes (PACS) 3.and Interest-Only Strips 3.3 MBS Pricing and Quoting 3.4 Prepayment Risk and Average Life of MBS 3.7 Collateralized Mortgage Obligations (CMOs) 3.11 Interest Rate Risk 3.

3 5.4 5.Contents ix Arbitrage Cash Flow CDOs Credit Enhancement in Cash Flow Transactions Credit Enhancement in Market Value Transactions: Advance Rates and the Over-Collateralization Test Minimum Net Worth Test Transaction Characteristics 4.8 CDS Day Counting Conventions General Valuation of Credit Default Swaps Hazard Rate Function Poisson and Cox Processes Valuation Using a Deterministic Intensity Model Hazard Rate Function Calibration Credit Curve Construction and Calibration 167 167 167 169 171 171 177 179 181 181 186 186 187 188 189 193 196 197 197 199 208 216 216 218 220 223 224 226 226 228 229 232 235 248 4.5 5.9 4.3 4.6 4.12 CDO Tranche Pricing Pricing Equation Simulation Algorithm CDO Pricing in Matlab CDO Pricing in C++ CDO2 Pricing Fast Loss Calculation for CDOs and CDO2 s Fast Algorithm for Computing CDO Tranche Loss in Matlab Endnotes 5 CREDIT DERIVATIVES 5.2 Synthetic CDOs Fully Funded Synthetic CDOs Partially and Unfunded Funded Synthetic CDOs Balance Sheet Management with CDS The Distribution of Default Losses on a Portfolio CDO Equity Tranche CDO Equity Tranche Performance The CDO Embedded Option The Price of Equity Using Moody’s Binomial Expansion Technique to Structure Synthetic CDOs Correlation Risk of CDO Tranches 4.11 4.6 5.5 .4 4.2 5.1 Credit Default Swaps 5.7 5.7 4.8 4.10 4.

7 Pricing Weather Derivatives Model Framework Pricing a Heating Degree Day Option 6.8 Historical Burn Analysis 6.4 Parameter Estimation 6.10 5.9 5.1 Weather Derivatives Market 6.10 Pricing Weather Options in C++ Endnotes 7 ENERGY AND POWER DERIVATIVES 7.11 5.5 Volatility Estimation 6.12 Credit Basket Default Swaps Pricing Generation of Correlated Default Stopping Times Sampling from Elliptical Copulae The Distribution of Default Arrival Times Basket CDS Pricing Algorithm Credit Basket Pricing in Matlab Credit Basket Pricing in C++ Credit Linked Notes (CLNs) CLNs with Collateralized Loan or Bond Obligations (CLOs or CBOs) Pricing Tranched Credit Linked Notes Regulatory Capital Endnotes 249 250 250 252 252 255 264 291 295 296 296 297 299 300 303 303 306 308 309 310 310 311 312 312 313 316 318 328 330 333 334 336 336 337 340 341 342 6 WEATHER DERIVATIVES 6.9 Time-Series Weather Forecasting 6.x Contents 5.2 Weather Contracts CME Weather Futures 6.1 Electricity Markets 7.2 Electricity Pricing Models Modeling the Price Process One-Factor Model Estimating the Deterministic Component Estimation of the Stochastic Process for the One-Factor Models Two-Factor Model .3 Modeling Temperature Noise Process Mean-Reversion 6.6 Mean-Reversion Parameter Estimation 6.

5 7.15 7.12 7.14 7.9 7.3 7.10 7.16 Swing Options The Longstaff-Schwartz Algorithm for American and Bermudan Options The LSM Algorithm Extension of Longstaff-Schwartz to Swing Options General Case: Upswings.6 7.11 7.13 7. and Penalty Functions Swing Option Pricing in Matlab LSM Simulation Results Upper and Lower Boundaries Exercise Strategies The Threshold of Early Exercise Interplay Between Early Exercise and Option Value Pricing of Energy Commodity Derivatives Cross-Commodity Spread Options Model 1 Model 2 Model 3 Jump Diffusion Pricing Models Model 1a: Affine Mean-Reverting Jump-Diffusion Process Model 1b Model 2a: Time-Varying Drift Component Model 2b: Time-Varying Version of Model 1b Stochastic Volatility Pricing Models Model 3a: Two-Factor Jump-Diffusion Affine Process with Stochastic Volatility Model Parameter Estimation ML-CCF Estimators ML-MCCF Estimators Spectral GMM Estimators Simulation Parameter Estimation in Matlab Energy Commodity Models Natural Gas Natural Gas Markets Natural Gas Spot Prices Gas Pricing Models One-Factor Model Two-Factor Model Calibration 344 345 346 348 351 352 352 354 356 358 360 362 362 364 365 366 368 368 369 370 372 372 372 373 375 376 379 383 385 385 387 387 389 390 390 391 393 .7 7.Contents xi 7. Downswings.8 7.4 7.

4 Commercial Real Estate-Backed Securitization (CREBS)—Singapore’s Experience 9.10 Summary Endnotes References 9 COMMERCIAL REAL ESTATE ASSET-BACKED SECURITIES 9.2 Motivations for Asset-Backed Securitization 9.1 Introduction 8.18 One-Factor Model Calibration Two-Factor Model Calibration Natural Gas Pricing in Matlab Natural Gas and Electricity Swaps Generator End User Endnotes 393 394 398 398 400 401 402 8 PRICING POWER DERIVATIVES: THEORY AND MATLAB IMPLEMENTATION 8.4 Fundamentals-Based Models 8.5 The PJ Model—Overview 8.xii Contents 7.8 Option Valuation Methodology Splitting the (Finite) Difference: Daily Strike and Monthly Strike Options Matlab Implementation for a Monthly Strike Option Spark Spread Options Matlab Implementation of Spark Spread Option Valuation 8.6 Model Calibration 8.3 Traditional Valuation Approaches Are Problematic for Power 8.2 Power Markets 8.9 Results 8.1 Introduction 9.17 7.3 Concepts of Securitizing Real Estate Cash Flows 9.5 Structure of a Typical CREBS A CREBS Case by Visor Limited 407 407 409 410 413 415 419 423 423 423 424 424 424 426 434 434 439 443 443 445 447 447 449 450 452 456 457 .7 Using the Calibrated Model to Price Options Daily Strike Options Monthly Strike Options Spark Spread Options 8.

5 Matlab Excel Link Example A.Contents xiii 9.6 Two-Factor HJM Model Implementation in Matlab Endnotes B CHAPTER 7 CODE REFERENCES INDEX .6 9.1 BDT Modeling in Matlab A.7 9.10 Pricing of CREBS Swaps and Swaptions The Cash Flow Swap Structure for CREBS Valuation of CREBS Using a Swap Framework Basic Swap Valuation Framework Pricing of Credit Risks for CREBS Using the Proposed Swap Model Modeling Default Risks in the CREBS Swap Numerical Analysis of Default Risks for a Typical CREBS Monte Carlo Simulation Process Input Parameters Analysis of Results Matlab Code for the Numerical Analysis Summary Endnotes 459 459 459 460 460 461 461 463 463 464 465 467 470 470 473 473 478 486 490 492 493 493 493 494 497 500 501 503 543 555 A INTEREST RATE TREE MODELING IN MATLAB A.3 Black-Karasinski Trees in Matlab A.8 9.2 Hull-White Trees in Matlab A.9 9.4 HJM Pricing in Matlab Description Syntax Arguments Examples Creating an HJM Volatility and Pricing Model A.


power. In addition. Moreover. mortgagebacked securities (MBSs). as well as the code implementations. C++. the use of Excel is also important as many trading desks use Excel as a front-end trading application. hundreds of financial institutions now market these complex instruments and employ thousands of financial and technical professionals needed to model them accurately and effectively. The best way to learn is to follow the examples and run the code. xv . and Excel. the implementation of these models in C++ and Matlab (two widely used languages for implementing and building derivatives models) has made programming skills in these languages important for practitioners to have.P REFACE Given the explosive growth in new financial derivatives such as credit derivatives. numerous examples are given using Matlab. Readers will benefit from both the mathematical derivations of the models. credit default swaps and credit-linked notes). swaps. Examples using actual real-time Bloomberg data show how these models work in practice. Craig Pirrong. professor of finance and director of the Global Energy Management Institute at the University of Houston. Throughout this book. the theory underlying the models. Modeling Derivatives Applications in Matlab. asset-backed securities (ABSs). and increasingly important weather. The purpose of the book is to teach readers how to properly develop and implement derivatives applications so that they can adapt the code for their own use as they develop their own applications. and Excel. collateralized-debt obligations (CDOs). C++. and Excel is the first book to cover in detail important derivatives pricing models for credit derivatives (for example. fixed income securities. The chapters cover the following topics: • Chapter 1: Swaps and fixed income securities • Chapter 2: Copulas and copula methodologies • Chapter 3: Mortgage-backed securities • Chapter 4: Collateralized-debt obligations • Chapter 5: Credit derivatives • Chapter 6: Weather derivatives • Chapter 7: Energy and power derivatives • Chapter 8: Also covers model implementations for energy derivatives using Matlab. and energy derivatives using Matlab. C++. but is written and based on the proprietary work of its author.

The valuable work for energy derivatives of Doerr (2002). use of array template classes (that can handle multiple dimensions) and vectors (of vectors) in the Standard Template Library in C++ are more efficient because they are dynamic and only use as much memory as is needed. The work of Picone (2004) is discussed in the chapter on collateralized-debt obligations. trading. The book does not focus on design patterns or best coding practices (these issues may be discussed in subsequent editions of the book. Tien-Foo Sing. The book emphasizes how to implement and code complex models for pricing. the work and models developed and written by various leading practitioners and experts for certain topics are provided and incorporated throughout the book. a two-dimensional alternating implicit difference (ADI) finite difference scheme for pricing energy derivatives. but it also incorporates important work contributions from leading practitioners in the industry. e. is not the most efficient way to allocate memory since it is fixed in size. a single number is treated as a 1 x 1 array. professor in the Department of Real Estate Finance at the National University of Singapore.g. the book does provide some discussions and helpful tips for building efficient models. . and Excel. However. The work of Johnson (2004) is discussed in the chapters on fixed-income instruments and mortgage-backed securities. Thus. In some cases in this book.) Efficiency and modularity are important design goals in building robust object-oriented code. Matlab.ftpress. which is written and is based on the proprietary work of its author. Craig Pirrong discusses the Pirrong-Jermayakan model. a matrix manipulation language. the work of Galiani (2003) is discussed in the chapter on copulas and credit derivatives. not only does this book cover complex derivatives models and provide all of the code (which can be downloaded using a secure ID code from the companion Web site at www. Tien-Foo Sing discusses using Monte Carlo to price asset-based securities. numerous individuals named in the acknowledgments contributed useful code throughout the book. and Xu (2004) is given. For instance. and hedging using C++. On the other hand. memory allocation for data structures is always an issue when developing a model that requires use and storage of multi-dimensional data.. Although two-dimensional arrays are easy to define. provides automatic memory allocation of memory as data is used if no array sizes are predefined. A lot of memory may be unutilized and wasted if you do not know how large the structure needs to be to store the actual data. In Chapter 9. Data can be added or removed from an object and the object will dynamically expand or reduce the amount of memory space as needed. the predefined array sizes may turn out not to be large enough. Matlab. All data in Matlab are treated as matrix objects. Moreover. The emphasis throughout the book has been to provide working implementations for the reader to adapt. for instance. Use of a predefined two-dimensional In Chapter 8. For instance.xvi Preface • Chapter 9: Commercial real-estate backed securities (a type of asset-backed security). Xiang (2004). Such structures are used in the book. In order to provide different perspectives to readers and provide as much useful information as possible. the C++ code provided could perhaps be more modular as with some of the routines in building interest rate trees. although some two-dimensional arrays are used as well.

Hopefully.ftpress. inevitably in a book of this length and complexity. NOTE: The code files are Copyrighted © 2006 by Justin London and the contributors thereof.Preface xvii While every effort has been made to catch all typos and errors in the book.ftpress. you must first register online. there may still be a few. go to www. Unauthorized reproduction or distribution is prohibited. If you have any questions about online registration or downloading the code. All rights reserved. build. .com/title/0131962590 and follow the on-screen instructions. You will need a valid email address and the access code that is printed inside the envelope located at the back of the book. To register online. this book will give you the foundation to develop. please send us an inquiry via the Contact Us page at http://www. SUPPLEMENTAL F ILES ON THE W EB SITE To download the code in this book. and test your own models while saving you a great deal of development time through use of pre-tested robust us/. Any corrections will be posted on the Web site.


ACKNOWLEDGMENTS Special thanks to the following people for their code and work contributions to this book: Ahsan Amin Sean Campbell Francis Diebold Uwe Doerr Stefano Galiani Michael Gibson Stafford Johnson Jochen Meyer Dominic Picone Craig Pirrong Eduardo Schwartz Tien Foo Sing Liuren Wu Lei Xiong James Xu xix .


as well as advised several banks in their implementation of derivative trading systems.A.S. xxi . computer science.A. in applied economics. He has analyzed and managed bank corporate loan portfolios using credit derivatives in the Asset Portfolio Group of a large bank in Chicago. in economics and mathematics.A BOUT THE AUTHOR Justin London has developed fixed-income and equity models for trading companies and his own quantitative consulting firm. A graduate of the University of Michigan. London is the founder of a global online trading and financial technology company. Illinois. and an M. in financial engineering. London holds a B. and mathematics. respectively. an M.