Modern Computational Finance - Antoine Savine - E-Book

Modern Computational Finance E-Book

Antoine Savine

0,0
73,99 €

-100%
Sammeln Sie Punkte in unserem Gutscheinprogramm und kaufen Sie E-Books und Hörbücher mit bis zu 100% Rabatt.

Mehr erfahren.
Beschreibung

An incisive and essential guide to building a complete system for derivative scripting In Volume 2 of Modern Computational Finance Scripting for Derivatives and xVA, quantitative finance experts and practitioners Drs. Antoine Savine and Jesper Andreasen deliver an indispensable and insightful roadmap to the interrogation, aggregation, and manipulation of cash-flows in a variety of ways. The book demonstrates how to facilitate portfolio-wide risk assessment and regulatory calculations (like xVA). Complete with a professional scripting library written in modern C++, this stand-alone volume walks readers through the construction of a comprehensive risk and valuation tool. This essential book also offers: * Effective strategies for improving scripting libraries, from basic examples--like support for dates and vectors--to advanced improvements, including American Monte Carlo techniques * Exploration of the concepts of fuzzy logic and risk sensitivities, including support for smoothing and condition domains * Discussion of the application of scripting to xVA, complete with a full treatment of branching Perfect for quantitative analysts, risk professionals, system developers, derivatives traders, and financial analysts, Modern Computational Finance Scripting for Derivatives and xVA: Volume 2 is also a must-read resource for students and teachers in master's and PhD finance programs.

Sie lesen das E-Book in den Legimi-Apps auf:

Android
iOS
von Legimi
zertifizierten E-Readern

Seitenzahl: 311

Veröffentlichungsjahr: 2021

Bewertungen
0,0
0
0
0
0
0
Mehr Informationen
Mehr Informationen
Legimi prüft nicht, ob Rezensionen von Nutzern stammen, die den betreffenden Titel tatsächlich gekauft oder gelesen/gehört haben. Wir entfernen aber gefälschte Rezensionen.



Table of Contents

Cover

Title Page

Copyright

My Life in Script by Jesper Andreasen

PART I: A Scripting Library in C++

Introduction

CHAPTER 1: Opening Remarks

INTRODUCTION

1.1 SCRIPTING IS NOT ONLY FOR EXOTICS

1.2 SCRIPTING IS FOR CASH‐FLOWS NOT PAYOFFS

1.3 SIMULATION MODELS

1.4 PRE‐PROCESSING

1.5 VISITORS

1.6 MODERN IMPLEMENTATION IN C++

1.7 SCRIPT TEMPLATES

NOTES

CHAPTER 2: Expression Trees

2.1 IN THEORY

2.2 IN CODE

NOTE

CHAPTER 3: Visitors

3.1 THE VISITOR PATTERN

3.2 THE DEBUGGER VISITOR

3.3 THE VARIABLE INDEXER

3.4 PRE‐PROCESSORS

3.5 CONST VISITORS

3.6 THE EVALUATOR

3.7 COMMUNICATING WITH MODELS

NOTES

CHAPTER 4: Putting Scripting Together with a Model

4.1 A SIMPLISTIC BLACK‐SCHOLES MONTE‐CARLO SIMULATOR

4.2 CONNECTING THE MODEL TO THE SCRIPTING FRAMEWORK

NOTES

CHAPTER 5: Core Extensions and the “Pays” Keyword

5.1 IN THEORY

5.2 IN CODE

NOTE

PART II: Basic Improvements

Introduction

CHAPTER 6: Past Evaluator

CHAPTER 7: Macros

CHAPTER 8: Schedules of Cash‐Flows

CHAPTER 9: Support for Dates

NOTE

CHAPTER 10: Predefined Schedules and Functions

CHAPTER 11: Support for Vectors

11.1 BASIC FUNCTIONALITY

11.2 ADVANCED FUNCTIONALITY

PART III: Advanced Improvements

Introduction

CHAPTER 12: Linear Products

12.1 INTEREST RATES AND SWAPS

12.2 EQUITIES, FOREIGN EXCHANGE, AND COMMODITIES

12.3 LINEAR MODEL IMPLEMENTATION

CHAPTER 13: Fixed Income Instruments

13.1 DELAYED PAYMENTS

13.2 DISCOUNT FACTORS

13.3 THE SIMULATED DATA PROCESSOR

13.4 INDEXING

13.5 UPGRADING “PAYS” TO SUPPORT DELAYED PAYMENTS

13.6 ANNUITIES

13.7 FORWARD DISCOUNT FACTORS

13.8 BACK TO EQUITIES

13.9 LIBOR AND RATE FIXINGS

13.10 SCRIPTS FOR SWAPS AND OPTIONS

CHAPTER 14: Multiple Underlying Assets

14.1 MULTIPLE ASSETS

14.2 MULTIPLE CURRENCIES

CHAPTER 15: American Monte‐Carlo

15.1 LEAST SQUARES METHOD

15.2 ONE PROXY

15.3 ADDITIONAL REGRESSION VARIABLES

15.4 FEEDBACK AND EXERCISE

15.5 MULTIPLE EXERCISE AND RECURSION

NOTES

PART IV: Fuzzy Logic and Risk Sensitivities

Introduction

CHAPTER 16: Risk Sensitivities with Monte‐Carlo

16.1 RISK INSTABILITIES

16.2 TWO APPROACHES TOWARD A SOLUTION

16.3 SMOOTHING FOR DIGITALS AND BARRIERS

16.4 SMOOTHING FOR SCRIPTED TRANSACTIONS

NOTE

CHAPTER 17: Support for Smoothing

CHAPTER 18: An Automated Smoothing Algorithm

18.1 BASIC ALGORITHM

18.2 NESTED AND COMBINED CONDITIONS

18.3 AFFECTED VARIABLES

18.4 FURTHER OPTIMIZATION

NOTE

CHAPTER 19: Fuzzy Logic

NOTE

CHAPTER 20: Condition Domains

20.1 FUZZY EVALUATION OF DISCRETE CONDITIONS

20.2 IDENTIFICATION OF CONDITION DOMAINS

20.3 CONSTANT EXPRESSIONS

NOTE

CHAPTER 21: Limitations

21.1 DEAD AND ALIVE

21.2 NON‐LINEAR USE OF FUZZY VARIABLES

CHAPTER 22: The Smoothing Factor

22.1 SCRIPTING SUPPORT

22.2 AUTOMATIC DETERMINATION

PART V: Application to xVA

CHAPTER 23: xVA

NOTE

CHAPTER 24: Branching

CHAPTER 25: Closing Remarks

25.1 SCRIPT EXAMPLES

25.2 MULTI‐THREADING AND AAD

25.3 ADVANCED LSM OPTIMIZATIONS

APPENDIX A: Parsing

A.1 PREPARING FOR PARSING

A.2 PARSING STATEMENTS

A.3 RECURSIVELY PARSING CONDITIONS

A.4 RECURSIVELY PARSING EXPRESSIONS

A.5 PERFORMANCE

NOTES

Bibliography

Index

End User License Agreement

Guide

Cover Page

Table of Contents

Title Page

Copyright

Begin Reading

Appendix A Parsing

Bibliography

Index

End User License Agreement

Pages

iii

iv

xi

xii

xiii

1

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

25

26

27

28

29

30

31

32

33

34

35

36

37

38

39

41

42

43

44

45

46

47

48

49

50

51

52

53

54

55

56

57

58

59

60

61

62

63

64

65

66

67

68

69

70

71

72

73

74

75

76

77

78

79

80

81

82

83

84

85

86

87

88

89

91

93

95

96

97

98

99

100

101

102

103

105

106

107

109

110

111

113

114

115

116

117

119

121

122

123

124

125

126

127

128

129

130

131

132

133

134

135

136

137

138

139

140

141

142

143

144

145

146

147

148

149

150

151

152

153

154

155

157

158

159

161

162

163

164

165

166

167

168

169

170

171

172

173

175

176

177

178

179

180

181

183

184

185

186

187

189

190

191

192

193

194

195

196

197

198

199

200

201

203

204

205

206

207

209

210

211

212

213

215

216

217

219

220

221

223

224

225

226

227

228

229

231

232

233

234

235

236

237

238

239

240

241

242

243

244

245

246

247

248

249

250

251

252

253

255

256

257

258

259

260

261

262

263

264

265

266

267

268

269

270

271

272

273

Modern Computational Finance

Scripting for Derivatives and xVA

 

ANTOINE SAVINE AND JESPER ANDREASEN

 

 

 

 

Copyright © 2022 by John Wiley & Sons, Inc. All rights reserved.

Published by John Wiley & Sons, Inc., Hoboken, New Jersey.

Published simultaneously in Canada.

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, scanning, or otherwise, except as permitted under Section 107 or 108 of the 1976 United States Copyright Act, without either the prior written permission of the Publisher, or authorization through payment of the appropriate per‐copy fee to the Copyright Clearance Center, Inc., 222 Rosewood Drive, Danvers, MA 01923, (978) 750‐8400, fax (978) 750‐4470, or on the web at www.copyright.com. Requests to the Publisher for permission should be addressed to the Permissions Department, John Wiley & Sons, Inc., 111 River Street, Hoboken, NJ 07030, (201) 748‐6011, fax (201) 748‐6008, or online at http://www.wiley.com/go/permission.

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 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. No warranty may be created or extended by sales representatives or written sales materials. The advice and strategies contained herein may not be suitable for your situation. You should consult with a professional where appropriate. Further, readers should be aware that websites listed in this work may have changed or disappeared between when this work was written and when it is read. Neither the publisher nor authors shall be liable for any loss of profit or any other commercial damages, including but not limited to special, incidental, consequential, or other damages.

For general information on our other products and services or for technical support, please contact our Customer Care Department within the United States at (800) 762‐2974, outside the United States at (317) 572‐3993 or fax (317) 572‐4002.

Wiley also publishes its books in a variety of electronic formats. Some content that appears in print may not be available in electronic formats. For more information about Wiley products, visit our web site at www.wiley.com.

Library of Congress Cataloging-in-Publication Data

Names: Antoine Savine, author. | Jesper Andreasen, 1970– author.

Title: Modern computational finance : scripting for derivatives and XVA / Antoine Savine and Jesper Andreasen.

Description: Hoboken, New Jersey : John Wiley & Sons, Inc., [2022] | Includes bibliographical references.

Identifiers: LCCN 2021036994 (print) | LCCN 2021036995 (ebook) | ISBN 9781119540786 (hardback) | ISBN 9781119540816 (adobe pdf) | ISBN 9781119540793 (epub)

Subjects: LCSH: Finance—Mathematical models. | Finance—Computer simulation. | Finance—Data processing.

Classification: LCC HG106 .A556 2022 (print) | LCC HG106 (ebook) | DDC 332.01/5195—dc23

LC record available at https://lccn.loc.gov/2021036994

LC ebook record available at https://lccn.loc.gov/2021036995

Cover Design: Wiley

Cover Image: © kentarcajuan/Getty Images

My Life in Script by Jesper Andreasen

Antoine came to General Re Financial Products in London in 1998 with a lot of youthful spirit and many refreshing ideas. One of them was a financial payoff language called SynTech (Syntactic interpreter Technology). I am not sure that I was immediately convinced but when he connected it to a real model and priced some structures that we made up on the fly, I was hooked. I learned SynTech in hours but it took me months to figure out how it was put together, a process that forced me to learn structured programming in general and C++ in particular.

As always, it was a general struggle to keep up with the financial innovation, and constant re‐coding of new payoffs was a painful and error prone process. We had been toying with a cocktail of Visual Basic for scripting of the payoffs and scenarios of future prices generated by C programs. However, the implementation was slow, model specific, hard to use, and generally more elephant than elegant.

SynTech, however, was easy to use with a readable simple Basic‐like syntax and thoroughly built for speed and versatility. Scripts were pre‐processed to cache and index static information for maximum pricing speed, and its API allowed a seamless hook‐up with any dynamic model in our library. In fact, it took Antoine very little time to hook up SynTech to our then newly developed Libor Market Model.

Further, it was clear that SynTech could be extended to perform various life cycle tasks such as fixings and payments to limit the manual burden on the back office in the handling of exotic trades. SynTech implemented a clear separation between instrument and model.

From then on, I have only used scripting languages as the interfaces for all the models I have developed. And when I need to price something I rarely use anything else than naked scripting. The scripting languages that I have used and developed have all had a syntax very close to the original SynTech. The developments that I have done have mainly been underneath. Remarkably, SynTech's original 50 keywords still cover the ground.

SynTech was inspired by developments Antoine had seen at previous occupations, most notably the GRFN system at Paribas. Other young quants spread out from Paribas and seeded ideas and developments of scripting languages at other institutions, for example, at UBS, Commerzbank, Nikko‐Salomon, Citi, and Reech Capital.

Paribas's GRFN developed by Guillaume Amblard and Societe Generale's OptIt by Jean‐Marc Eber were as far as we know the first scripting languages that were used on an industrial scale. Jean‐Marc Eber went on to set up the company Lexifi, which to this date supplies the industry with scripting technology.

GRFN and OptIt emerged in the mid‐1990s. There were, for sure, other earlier attempts to develop scripting languages, most notably various uses of the LEX‐YACC suite of tools for creating languages. Emmanuel Derman mentions such efforts in passing in My Life as a Quant and I have heard of similar experiments at JP Morgan. However, to my knowledge, none of these made it to large‐scale production.

In 2001, I went to Bank of America in London, where I ganged up with James Pfeffer and developed Thor. The main innovation of Thor was the use of the visitor pattern technology that later was instrumental in using scripting as the backbone for xVA and regulatory calculations. The main idea of the visitor pattern is to have visitors that visit the cash flows for different purposes: pre‐processing, valuation, dependency graph generation, compression, decoration, and so on. The diverse use of visitors shows that development of your own scripting language is necessary. Python or C# can not be visited.

In 2002–2005 I worked for Nordea in Copenhagen where we developed a scripting language called Loke. The main innovation during this period was the integration of American Monte‐Carlo techniques with Loke, including upper‐bound techniques implemented by Ove Scavenius.

In 2005–2008 I was back with Bank of America, where I found the Thor language to be heavily used by the structured interest rate and equity desks. Often they used a macro language called Sif, developed by Mohan Namasivayam, to generate Thor scripts.

At Danske Bank, which I joined in 2008 and left in 2018, the scripting language is called Jive. Jive is used for everything traded at Danske Bank: from vanilla swaps to mortgage bonds to equity exotics to regulatory capital. Jive is even used in the yield curve calibration. This is the only bank that I know of that uses a scripting language so consistently. Developments have mainly concentrated on aggregation, compression, and decoration used for xVA and regulatory calculations. Here, we have heavily leveraged on the visitor pattern technology. But we have also done significant work on Automatic Adjoint Differentiation (AAD), multi‐threading, branching simulations, and fuzzy logic to stabilize risk calculations. Antoine joined Danske in 2013, and since then he has played a key role in these developments. In 2015, we received Risk Magazine's In‐House Risk System of the Year award for our xVA system. The AAD and the speed of the calculations achieved by the xVA system have received a lot of attention in the quant community, but the scripting and visitor pattern technologies are actually the unsung heroes that have made all of this possible.

To document how we did xVA on an iPad Mini without thoroughly describing our approach to scripting would be wrong and not give the reader the full picture. I was therefore very happy when Antoine told me he was going to write a book on scripting. This would give us the opportunity to finally get our work on scripting languages documented and pave the way for fully documenting our xVA system.

There are a number of reasons why the story of scripting has not been told before. Among these:

– It's not mathematics, but software design, which is actually something that we do every day but not something that we usually write about.

– It's a complex and relatively long and winding story that cannot easily be summoned in a few punchlines. On top of this it contains subjects that most people haven't even heard about, such as visitors and pre‐processors.

– It's a hard sell to change conventional wisdom that scripting is only for exotics and has no relevance in post‐crisis finance. Actually, scripting is more relevant now than ever, because banks are under tough regulatory and cost pressures.

– It's very C++ and as such not following the current trend of lighter languages such as Matlab and Python backed by GPUs running parallel instructions in C.

– The subject is still very much alive: whenever we start documenting our efforts, we always get new ideas that we can do with scripting, which in turn tends to take away focus from documenting past glories.

My next employer is Saxo Bank and the scripting language there will be Jife.

Jesper Andreasen, June 2018

PART IA Scripting Library in C++

Introduction

This part leads readers through the development steps of the scripting library provided in our source repository.

A transaction consists of a number of events occurring on given dates in the future. This is where a payment or coupon is fixed, a discrete barrier is monitored, or an exercise takes place. This is also where a path‐dependency is updated with reference to the simulated variables on that future date.1 Future dates when such events take place are called event dates.

As an illustration, we consider a simplified version of the popular autocallable transaction. It pays a high coupon (say 10%) if some index (say S&P500) increased during the first year of its life. In this case, it pays the notional redemption together with the coupon of 10% and terminates at the end of year 1. Otherwise, it may still deliver a 20% coupon (10% per annum) at the end of year 2 provided the index overall increased over the two years. In this case, it repays the notional together with the 20% coupon and terminates at the end of year 2. If not, it is given a last chance on year 3, provided the underlying index increased over the three years. If this is the case, the investor receives the redemption + 30% at the end of year 3. If not, only 50% of the notional is repaid. It is easy to see that the investor implicitly sells a (somewhat exotic) option on what may appear as a low probability event (index decreasing over one, two, and three years) in exchange for a high coupon in a low‐yield environment, which explains the success of this structure.2This product may be scripted as follows (say today is 1 June 2020)3:

01Jun2020

vRef=spot() vAlive=1

01Jun2021

if spot() > vRef then prd=110 vAlive=0 endIf

01Jun2022

if spot() > vRef then if vAlive=1 then prd=120 endIf vAlive=0 endIf

01Jun2023

if vAlive=1 then if spot() > vRef then prd=130 else prd=50 endIf endIf

We have four events on four event dates:

Today, we set the reference to the current spot level and initialize the

alive

status to 1.

Year 1, we check whether the spot increased, in which case we pay redemption + 10% and die.

Year 2, we check that the spot overall increased over two years. In this case, provided we survived year 1, we pay redemption + 20% and die.

Year 3, provided we survived the first two, we check if the spot overall increased. In this case we pay redemption + 30%. If not, we repay 50% of the notional.

We see that our language must at the very minimum support numbers, arithmetic operations, and conditional statements. We know we also need some mathematical functions like or and some financial functions such as a multi‐argument and . Critically, we must be able to read, write, and compare variables and access the simulated market with a spot() keyword that references the fixing of the underlying asset on the corresponding event date. This is a simple language, similar to Python, that supports only the constructs necessary for the description of financial cash‐flows, for which it provides some specific keywords.

The language considers as a variable anything that starts with a letter and is not otherwise a keyword. We used the variables , , and in our example. Evidently, ancillary variable names don't have to start with the letter V; this is only for clarity.

Products are variables. The language makes no difference between products and ancillary variables; only users do. Our example actually scripts three products: obviously; , which pays the spot fixing today and is worth today's underlying asset price; and , which is worth 1 at maturity if the product survived the first two years, 0 otherwise. Its value is the (risk‐neutral) probability of surviving to year 3. All variables may be seen as products, although, in general, the values of ancillary variables are disregarded in the end. In chapter5, we will implement other means of distinguishing products from helper variables, and actual payments from assignments, with the keyword pays.

To value a script in the context of path‐wise Monte‐Carlo simulations means to evaluate it against a number of scenarios, each scenario providing different values for spot on the event dates in 1y, 2y, and 3y. For every such scenario generated by the model, we evaluate the script and record the final value of all its variables. In the end, we average those final variables' values across scenarios to estimate the values of the corresponding products. If we also require risk sensitivities, we compute the derivatives of the final variable values to changes in the model parameters. Evidently, the derivatives of prices are averages of the path‐wise derivatives, which permits an efficient path‐wise computations of sensitivities, in particular with adjoint propagation. See for instance Giles and Glasseman's “Smoking Adjoints,” which introduced adjoint techniques to finance [14], and our publication [27], which explains automatic adjoint differentiation (AAD) and provides professional differentiation code.

We remind the reader, however, that evaluation (including of sensitivities) is only one thing we can do with the script. The purpose of this library is to parse scripts into visitable data structures and implement a framework that enables all types of visitors, not only the evaluator, to traverse and manipulate scripts in many ways.

We split the implementation in five steps.

First, we describe in chapter 2 the data structure for the internal representation of the script, ready for evaluation and other forms of visits. We will use expression trees as a data structure, and we describe these in detail. The discussion and code for the actual parsing (that turns a text script into a collection of expression trees) is left to the appendix.

Then, we introduce in chapter 3 the evaluator that values expression trees during simulations, pre‐processors that optimize evaluation before simulations, and other visitors, objects that traverse expression trees and perform calculations and actions depending on the visited node, while maintaining internal state. We explain the visitor pattern, a common framework for all types of visitors, which encapsulates traversal logic and makes the development of specific visitors particularly simple.

Third, in chapter 4, we bring the pieces together and develop a (very) basic model to test the scripting library.

Fourth, we improve our framework with the addition of the keyword pays in chapter 5 and take this opportunity to illustrate how a core extension is made to the language.

NOTES

1

Continuous barriers are somehow outside of this logic and require specific support that is not discussed. Support for early exercises is discussed in

chapter 15

.

2

This is an overly simplified version of the autocallable product and one that is purposely structured to illustrate the implementation and application of scripting. It is significantly different from actual autocallable transactions, which can also be scripted with our language, but in a more complicated manner.

3

We make some arbitrary choices regarding the syntax of our scripting language. Readers can easily implement their own preferred grammar once they are comfortable with the idioms explained here.

CHAPTER 1Opening Remarks

INTRODUCTION

In the early stages of derivative markets, dedicated models were typically put together to value and risk manage new transaction types as they emerged. After Black and Scholes [5] published in 1973 a closed‐form formula for European options under a constant volatility assumption, alternative models—like the Cox‐Ross‐Rubinstein binomial tree [7] in 1979, later replaced by more efficient finite difference grids—were developed to value American options under the same assumptions.

As trading in derivatives matured, the range of complex transactions expanded and models increased in complexity so that numerical methods became necessary for all but the simplest vanilla products. Models were typically implemented in terms of finite difference grids for transactions with early exercise and Monte‐Carlo simulations for products with path‐dependency. Notably, models increased in dimension as they grew in complexity, making grids impractical in most cases, and Monte‐Carlo simulations became the norm, with early exercises typically supported by a version of the Longstaff‐Schwartz regression‐based algorithm [22]. Sophisticated models also had to be calibrated before they were used to value and risk manage exotics: their parameters were set to match the market prices of less complex, more liquid derivatives, typically European calls and puts.

Most of the steps involved—calibration, Monte‐Carlo path generation, backward induction through finite difference grids—were independent of the transactions being valued; therefore, it became best practice to implement models in terms of generic numerical algorithms, independently of products. Practitioners developed modular libraries, like the simulation library of our publication [27], where transactions were represented in separate code that interacted with models to produce values and risk sensitivities.

However, at that stage, dedicated code was still written for different families of transactions, and it was necessary in order to add a new product to the library, to hard code its payoff by hand, compile, test, debug, and release an updated software.

The modular logic could be pushed one step further with the introduction of scripting languages, where users create products dynamically at run time. The user describes the schedule of cash‐flows for a transaction with a dedicated language specifically designed for that purpose, for example:

STRIKE

100

01Jun2021

opt pays max( 0, spot() ‐ STRIKE)

for a 1y European call with strike 100, or

STRIKE

100

BARRIER

120

01Jun2020

vAlive = 1

Start: 01Jun2020

End: 01Jun2021

if spot() > BARRIER then vAlive = 0 endIf

Freq: weekly

01Jun2021

opt pays vAlive * max( 0, spot() ‐ STRIKE)

for the same call with a 120 (weekly monitored) knock‐out barrier.1

The scripts are parsed into expression trees, and visited by an evaluator, a particular breed of visitor, who traverses the trees, while maintaining the internal state, to compute payoffs over the scenarios generated by a model:

All of this is explained in deep detail with words and code in part I.

With scripting, finance professionals were able to create and modify a product on the fly, while calculating its price and risk sensitivities in real time. The obvious benefits of such technology quickly made it a best practice among key derivatives players and greatly contributed in itself to the development of structured derivatives markets.

Early implementations, however, suffered from an excessive performance overhead and a somewhat obscure syntax that made scripting inaccessible to anyone but experienced quantitative analysts and traders. Later implementations fixed those flaws. The modern implementation in this publication comes with a natural syntax, is accessible to non‐programmers,2 and its performance approaches hard‐coded payoffs.

This publication builds on the authors' experience to produce a scripting library with maximum scope, modularity, transparency, stability, scalability, and performance.

Importantly, our implementation transcends the context of valuation and sensitivities; it offers a consistent, visitable representation of cash‐flows that lends itself to a scalable production of risk, back‐testing, capital assessment, value adjustments, or even middle office processing for portfolios of heterogeneous financial transactions. We also focus on performance and introduce the key notion of pre‐processing, whereby a script is automatically analyzed, prior to its valuation or risk, to optimize the upcoming calculations. Our framework provides a representation of the cash‐flows and a way of working with them that facilitates not only valuation but also pre‐processing and any kind of query or transformation that we may want to conduct on the cash‐flows of a set of transactions.

Scripting makes a significant difference in the context of xVA, as explained in part V, and more generally, all regulatory calculations that deal with multiple derivatives transactions of various sophistication, written on many underlying assets belonging to different asset classes. Before xVA may be computed over a netting set,3 all the transactions in the netting set must be aggregated. This raises a very practical challenge and a conundrum when the different transactions are booked in different systems and represented under different forms. Scripting offers a consistent representation of all the transactions, down to their cash‐flows. Scripted transactions are therefore naturally aggregated or manipulated in any way. A key benefit of scripted cash‐flows is that scripts are not black boxes. Our software (more precisely, the visitors implemented in the software) can “see” and analyze scripts, in order to aggregate, compress, or decorate transactions as explained in part V, extract information such as path‐dependence or non‐linearity and select the model accordingly, implement automatic risk smoothing (part IV), or analyze a valuation problem to optimize its calculation. Our library is designed to facilitate all these manipulations, as well as those we haven't thought about yet.

The purpose of this publication is to provide a complete reference for the implementation of scripting and its application in derivatives systems to its full potential. The defining foundations of a well‐designed scripting library are described and illustrated with C++ code, available online on:

https://github.com/asavine/Scripting/tree/Book-V1

Readers will find significant differences between the repository code and the code printed in the book. The repository has been undergoing substantial modernization and performance improvements not covered in this edition of the text. Make sure you connect to the branch Book‐V1, not the master. Besides, the code base evolves throughout the book and the online repository contains the final version. It is advisable to type by hand the code printed in the text rather than rely on the online repository while reading the book.

This code constitutes a self‐contained, professional implementation of scripting in C++. It is written in standard, modern C++ without any external dependency. It was tested to compile on Visual Studio 2017. The library is fully portable across financial libraries and platforms and includes an API, described in section 3.7, to communicate with any model.

The code as it stands can deal with a model of any complexity as long as it is a single underlying model. It works with the Black and Scholes model of [5] and all kind of extensions, including with local and/or stochastic volatility, like Dupire's [9] and [10], or single underlying stochastic volatility models.4 The library cannot deal with multiple underlying assets, stochastic interest rates, or advanced features such as the Longstaff‐Schwartz algorithm of [22]. It doesn't cover the management of transactions throughout their life cycle or deal with past fixings. All those features, necessary in a production environment, would distract us from correctly establishing the defining bases. These extensions are discussed in detail in parts II and III, although not in code.

Our online repository also provides an implementation of Fuzzy Logic for automatic risk smoothing, an excel interface to the library, a tutorial for exporting C++ code to Excel, a prebuilt xll, and a demonstration spreadsheet.

The C++ implementation is discussed in part I, where we explore in detail the key concepts of expression trees and visitors. We show how they are implemented in modern C++ and define the foundations for an efficient, scalable scripting library. We also provide some (very) basic self‐contained models to test the library, although the library is model agnostic by design and meant to work with any model that implements an API that we specify. For clarity, the code and comments related to parsing (the transformation of a text script into an expression tree) are moved from the body of the text into an appendix.

We discuss in part II the implementation of some basic extensions, and in part III more advanced features like interest rates and multiple currencies and assets. We discuss the key notion of indexing simulated data. Indexing is a special flavor of pre‐processing, crucial for performance. We also discuss the support for LSM, the regression‐based algorithm designed by Carriere and Longstaff‐Schwartz in [6] and [22] to deal with early exercise in the context of Monte‐Carlo simulations, and later reused in the industry in the context of xVA and other regulatory calculations. These parts include extensive guidance for the development of the extensions, but not source code.

The rest of the publication describes some applications of scripting outside the strict domain of pricing and demonstrates that our framework, based on visitors, can resolve many other problems.

Part IV shows how our framework can accommodate a systematic smoothing of discontinuities to resolve the problem of unstable risk sensitivities for products like digitals or barriers with Monte‐Carlo simulations. Smoothing consists of the approximation of the discontinuous payoffs by close continuous ones, like the approximation of digitals by tight call spreads. Bergomi discusses and optimizes smoothing in [4]. Our purpose is different. We demonstrate that smoothing can be abstracted as a particular application of fuzzy logic. This realization leads to an algorithm to systematically smooth not only digitals and barriers but also any payoff, automatically. The practical implementation of the algorithm is facilitated by the design of our scripting library. For clarity, the source code is not provided in the body of the text, but it is provided in our online repository.

Part V introduces the application to xVA, which is further covered in our upcoming dedicated publication. The code for xVA calculations is not provided.

1.1 SCRIPTING IS NOT ONLY FOR EXOTICS

While scripted payoffs are now part of the standard toolkit for the structuring of derivatives, it does not appear to be widely used yet in the wider context of xVA, CCR, VAR, FRTB, capital charges, or other related calculations. This is an unfortunate oversight. Market risk, value adjustments, and capital calculations over large heterogeneous portfolios of transactions are best conducted when all cash‐flows from all transactions are represented in a consistent manner, which the software can understand, analyze, and otherwise manipulate. This is exactly what scripting offers, for a small performance cost if implemented correctly.

Further, a CVA (similarly to other xVAs and other regulatory calculations) is a real option that a bank gives away any time it trades with a defaultable counterparty. That option is a put on the netting set, contingent to default. It is therefore an exotic option with a complex payoff written on the sum of all the cash‐flows of all the transactions in a netting set. This is however still an option, and as such, it can be scripted like any other transaction. Scripting is ideally suited in this context, both for the representation of the cash‐flow of the underlying transactions and the description of the value adjustments themselves. We explore the details in part V and will extend that discussion in our upcoming publication dedicated to xVA.

As exotic transactions fell out of favor in the aftermaths of the 2008 global crisis, some practitioners believe that scripting lost relevance. That could not be more wrong. From the reasons enumerated, scripting is more relevant now than ever, not only for exotics but more importantly today as the centerpiece of correctly designed systems for the calculation of risks, value adjustments, and capital charges for large heterogeneous portfolios.

We therefore believe that scripting is not limited to an external interface for users to conveniently create transactions on the fly. Scripting does offer such convenience, but its main purpose is to represent transactions internally as collections of cash‐flows consistently accessible to all components in a system. Code (actually, visitors that are part of the code) can “see” the cash‐flows and manipulate them in a number of ways. Evaluation is just one such manipulation. The design of our scripting library in part I is driven by such considerations.

1.2 SCRIPTING IS FOR CASH‐FLOWS NOT PAYOFFS

What did lose relevance is scripting for exotics only. Scripting must be rethought today, no longer as a means of valuing complex transactions but as a way to represent cash‐flows so that these cash‐flows may be visited from various components of system and analyzed and modified in various ways, including, but not limited to, valuation. For this purpose, it is essential that it is the actual cash‐flows that are scripted and not option payoffs.

For example, a receiver swaption with physical settlement would frequently be represented as a European option on the PV of the underlying swap at the exercise date. This would produce a script resembling:

exerciseDate

     swaption pays max( 0, swapPv (startDate, endDate, fixCpn, fixFreq, fixBasis, floatRef))

Such shortcut may be relevant for valuation,5 because it is sometimes economically equivalent to receive the PV of the cash‐flows on the exercise date, or become entitled to these cash‐flows, paid later on their respective payment dates. But this shortcut only works in particular contexts and with particular models. When credit risk is considered, it is no longer equivalent to exercise into the swap or to cash settle the option. In particular, this script is not correct in the context of CVA.

The correct script for a swaption must describe the schedule of the cash‐flows of the underlying swap and use a proxy to estimate the PV of the future cash‐flows of the swap at the exercise date to make an exercise decision. A proxy is an estimate of the transaction's value on the exercise date as a function of the model's state variables on that date. Proxies are typically produced by regression, in a process designed by Carriere [6] and Longstaff‐Schwartz [22]