C# for Financial Markets - Daniel J. Duffy - E-Book

C# for Financial Markets E-Book

Daniel J. Duffy

0,0
65,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

A practice-oriented guide to using C# to design and program pricing and trading models

In this step-by-step guide to software development for financial analysts, traders, developers and quants, the authors show both novice and experienced practitioners how to develop robust and accurate pricing models and employ them in real environments. Traders will learn how to design and implement applications for curve and surface modeling, fixed income products, hedging strategies, plain and exotic option modeling, interest rate options, structured bonds, unfunded structured products, and more. A unique mix of modern software technology and quantitative finance, this book is both timely and practical. The approach is thorough and comprehensive and the authors use a combination of C# language features, design patterns, mathematics and finance to produce efficient and maintainable software.

Designed for quant developers, traders and MSc/MFE students, each chapter has numerous exercises and the book is accompanied by a dedicated companion website, www.datasimfinancial.com/forum/viewforum.php?f=196&sid=f30022095850dee48c7db5ff62192b34, providing all source code, alongside audio, support and discussion forums for readers to comment on the code and obtain new versions of the software.

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

Android
iOS
von Legimi
zertifizierten E-Readern

Seitenzahl: 1117

Veröffentlichungsjahr: 2013

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.



Contents

Cover

Title Page

Copyright

About the Authors

Series

List of Figures

List of Tables

Dedication

Introduction

0.1 WHAT IS THIS BOOK?

0.2 SPECIAL FEATURES IN THIS BOOK

0.3 WHO IS THIS BOOK FOR AND WHAT DO YOU LEARN?

0.4 STRUCTURE OF THIS BOOK

0.5 C# SOURCE CODE

Chapter 1: Global Overview of the Book

1.1 INTRODUCTION AND OBJECTIVES

1.2 COMPARING C# AND C++

1.3 USING THIS BOOK

Chapter 2: C# Fundamentals

2.1 INTRODUCTION AND OBJECTIVES

2.2 BACKGROUND TO C#

2.3 VALUE TYPES, REFERENCE TYPES AND MEMORY MANAGEMENT

2.4 BUILT-IN DATA TYPES IN C#

2.5 CHARACTER AND STRING TYPES

2.6 OPERATORS

2.7 CONSOLE INPUT AND OUTPUT

2.8 USER-DEFINED STRUCTS

2.9 MINI APPLICATION: OPTION PRICING

2.10 SUMMARY AND CONCLUSIONS

2.11 EXERCISES AND PROJECTS

Chapter 3: Classes in C#

3.1 INTRODUCTION AND OBJECTIVES

3.2 THE STRUCTURE OF A CLASS: METHODS AND DATA

3.3 THE KEYWORD ‘THIS’

3.4 PROPERTIES

3.5 CLASS VARIABLES AND CLASS METHODS

3.6 CREATING AND USING OBJECTS IN C#

3.7 EXAMPLE: EUROPEAN OPTION PRICE AND SENSITIVITIES

3.8 ENUMERATION TYPES

3.9 EXTENSION METHODS

3.10 AN INTRODUCTION TO INHERITANCE IN C#

3.11 EXAMPLE: TWO-FACTOR PAYOFF HIERARCHIES AND INTERFACES

3.12 EXCEPTION HANDLING

3.13 SUMMARY AND CONCLUSIONS

3.14 EXERCISES AND PROJECTS

Chapter 4: Classes and C# Advanced Features

4.1 INTRODUCTION AND OBJECTIVES

4.2 INTERFACES

4.3 USING INTERFACES: VASICEK AND COX-INGERSOLL-ROSS (CIR) BOND AND OPTION PRICING

4.4 INTERFACES IN .NET AND SOME ADVANCED FEATURES

4.5 COMBINING INTERFACES, INHERITANCE AND COMPOSITION

4.6 INTRODUCTION TO DELEGATES AND LAMBDA FUNCTIONS

4.7 LAMBDA FUNCTIONS AND ANONYMOUS METHODS

4.8 OTHER FEATURES IN C#

4.9 ADVANCED .NET DELEGATES

4.10 THE STANDARD EVENT PATTERN IN .NET AND THE OBSERVER PATTERN

4.11 SUMMARY AND CONCLUSIONS

4.12 EXERCISES AND PROJECTS

Chapter 5: Data Structures and Collections

5.1 INTRODUCTION AND OBJECTIVES

5.2 ARRAYS

5.3 DATES, TIMES AND TIME ZONES

5.4 ENUMERATION AND ITERATORS

5.5 OBJECT-BASED COLLECTIONS AND STANDARD COLLECTION INTERFACES

5.6 THE LIST<T> CLASS

5.7 THE Hashtable<T> CLASS

5.8 THE  Dictionary<Key, Value> CLASS

5.9 THE Hashset<T> CLASSES

5. 10 Bitarray: DYNAMICALLY SIZED BOOLEAN LISTS

5.11 OTHER DATA STRUCTURES

5.12 STRINGS AND STRINGBUILDER

5.13 SOME NEW FEATURES IN .NET 4.0

5.14 SUMMARY AND CONCLUSIONS

5.15 EXERCISES AND PROJECTS

Chapter 6: Creating User-defined Data Structures

6.1 INTRODUCTION AND OBJECTIVES

6.2 DESIGN RATIONALE AND GENERAL GUIDELINES

6.3 ARRAYS AND MATRICES

6.4 VECTORS AND NUMERIC MATRICES

6.5 HIGHER-DIMENSIONAL STRUCTURES

6.6 SETS

6.7 ASSOCIATIVE ARRAYS AND MATRICES

6.8 STANDARDISATION: INTERFACES AND CONSTRAINTS

6.9 USING ASSOCIATIVE ARRAYS AND MATRICES TO MODEL LOOKUP TABLES

6.10 TUPLES

6.11 SUMMARY AND CONCLUSIONS

6.12 EXERCISES AND PROJECTS

Chapter 7: An Introduction to Bonds and Bond Pricing

7.1 INTRODUCTION AND OBJECTIVES

7.2 EMBEDDED OPTIONALITY

7.3 THE TIME VALUE OF MONEY: FUNDAMENTALS

7.4 MEASURING YIELD

7.5 MACAULEY DURATION AND CONVEXITY

7.6 DATES AND DATE SCHEDULERS FOR FIXED INCOME APPLICATIONS

7.7 EXPORTING SCHEDULERS TO EXCEL

7.8 OTHER EXAMPLES

7.9 PRICING BONDS: AN EXTENDED DESIGN

7.10 SUMMARY AND CONCLUSIONS

7.11 EXERCISES AND PROJECTS

Chapter 8: Data Management and Data Lifecycle

8.1 INTRODUCTION AND OBJECTIVES

8.2 DATA LIFECYCLE IN TRADING APPLICATIONS

8.3 AN INTRODUCTION TO STREAMS AND I/O

8.4 FILE AND DIRECTORY CLASSES

8.5 SERIALISATION ENGINES IN .NET

8.6 THE BINARY SERIALISER

8.7 XML SERIALISATION

8.8 DATA LIFETIME MANAGEMENT IN FINANCIAL AND TRADING APPLICATIONS

8.9 SUMMARY AND CONCLUSIONS

8.10 EXERCISES AND PROJECTS

Chapter 9: Binomial Method, Design Patterns and Excel Output

9.1 INTRODUCTION AND OBJECTIVES

9.2 DESIGN OF BINOMIAL METHOD

9.3 DESIGN PATTERNS AND CLASSES

9.4 EARLY EXERCISE FEATURES

9.5 COMPUTING HEDGE SENSITIVITIES

9.6 MULTI-DIMENSIONAL BINOMIAL METHOD

9.7 IMPROVING PERFORMANCE USING PADé RATIONAL APPROXIMANTS

9.8 SUMMARY AND CONCLUSIONS

9.9 PROJECTS AND EXERCISES

Chapter 10: Advanced Lattices and Finite Difference Methods

10.1 INTRODUCTION AND OBJECTIVES

10.2 TRINOMIAL MODEL OF THE ASSET PRICE AND ITS C# IMPLEMENTATION

10.3 STABILITY AND CONVERGENCE OF THE TRINOMIAL METHOD

10.4 THE BLACK-SCHOLES PARTIAL DIFFERENTIAL EQUATION AND EXPLICIT SCHEMES

10.5 IMPLEMENTING EXPLICIT SCHEMES IN C#

10.6 STABILITY OF THE EXPLICIT FINITE DIFFERENCE SCHEME

10.7 AN INTRODUCTION TO THE ALTERNATING DIRECTION EXPLICIT METHOD (ADE)

10.8 IMPLEMENTING ADE FOR THE BLACK-SCHOLES PDE

10.9 TESTING THE ADE METHOD

10.10 ADVANTAGES OF THE ADE METHOD

10.11 SUMMARY AND CONCLUSIONS

10.12 APPENDIX: ADE NUMERICAL EXPERIMENTS

10.13 EXERCISES AND PROJECTS

Chapter 11: Interoperability: Namespaces, Assemblies and C++/CLI

11.1 INTRODUCTION AND OBJECTIVES

11.2 NAMESPACES

11.3 AN INTRODUCTION TO ASSEMBLIES

11.4 REFLECTION AND METADATA

11.5 C# AND NATIVE C++ INTEROPERABILITY: HOW IS THAT POSSIBLE?

11.6 USING C# FROM C++

11.7 CODE GENERATION USING THE REFLECTION API

11.8 APPLICATION DOMAINS

11.9 SUMMARY AND CONCLUSIONS

11.10 EXERCISES AND PROJECTS

Chapter 12: Bond Pricing: Design, Implementation and Excel Interfacing

12.1 INTRODUCTION AND OBJECTIVES

12.2 HIGH-LEVEL DESIGN OF BOND PRICING PROBLEM

12.3 BOND SCHEDULING

12.4 BOND FUNCTIONALITY AND CLASS HIERARCHIES

12.5 CALCULATING PRICE, YIELD AND DISCOUNT FACTORS: MATHTOOLS

12.6 DATA PRESENTATION AND EXCEL INTEROP

12.7 BOND DATA MANAGEMENT

12.8 USING THE EXCEL FILES

12.9 SUMMARY AND CONCLUSIONS

12.10 EXERCISES AND PROJECTS

Chapter 13: Interpolation Methods in Interest Rate Applications

13.1 INTRODUCTION AND OBJECTIVES

13.2 INTERPOLATION AND CURVE BUILDING: BASIC FORMULA FOR INTERPOLATOR TESTS

13.3 TYPES OF CURVE SHAPE

13.4 AN OVERVIEW OF INTERPOLATORS

13.5 BACKGROUND TO INTERPOLATION

13.6 APPROXIMATION OF FUNCTION DERIVATIVES

13.7 LINEAR AND CUBIC SPLINE INTERPOLATION

13.8 POSITIVITY-PRESERVING CUBIC INTERPOLATIONS: DOUGHERTY/HYMAN AND HUSSEIN

13.9 THE AKIMA METHOD

13.10 HAGAN-WEST APPROACH

13.11 GLOBAL INTERPOLATION

13.12 BILINEAR INTERPOLATION

13.13 SOME GENERAL GUIDELINES, HINTS AND TIPS

13.14 USING THE INTERPOLATORS AND TEST EXAMPLES

13.15 SUMMARY AND CONCLUSIONS

13.16 EXERCISES AND PROJECTS

Chapter 14: Short Term Interest Rate (STIR) Futures and Options

14.1 INTRODUCTION AND OBJECTIVES

14.2 AN OVERVIEW OF CASH MONEY MARKETS

14.3 SOURCES OF RISK IN MONEY MARKET TRANSACTIONS

14.4 REFERENCE RATE AND FIXINGS

14.5 STIR FUTURES

14.6 PRICING STIR OPTIONS

14.7 GENERATING INTERNATIONAL MONETARY MARKET (IMM) DATES

14.8 LIST STIR FUTURES AND STIR FUTURES OPTIONS

14.9 PUTTING IT ALL TOGETHER: STIR VERSUS OTC FROM A TRADER'S PERSPECTIVE

14.10 SUMMARY AND CONCLUSIONS

14.11 EXERCISES AND PROJECTS

Chapter 15: Single-curve Building

15.1 INTRODUCTION AND OBJECTIVES

15.2 STARTING DEFINITIONS AND OVERVIEW OF CURVE BUILDING PROCESS

15.3 BUILDING BLOCKS

15.4 INTRODUCTION TO INTEREST RATE SWAP

15.5 THE CURVE CONSTRUCTION MECHANISM

15.6 CODE DESIGN AND IMPLEMENTATION

15.7 CONSOLE EXAMPLES

15.8 SUMMARY AND CONCLUSIONS

15.9 EXERCISES AND PROJECTS

15.10 APPENDIX: TYPES OF SWAPS

Chapter 16: Multi-curve Building

16.1 INTRODUCTION AND OBJECTIVES

16.2 THE CONSEQUENCES OF THE CRISIS ON INTEREST RATE DERIVATIVES VALUATION

16.3 IMPACT OF USING OIS DISCOUNTING

16.4 THE BOOTSTRAPPING PROCESS USING TWO CURVES: DESCRIPTION OF THE MECHANISM

16.5 SENSITIVITIES

16.6 HOW TO ORGANISE THE CODE: A POSSIBLE SOLUTION

16.7 PUTTING IT TOGETHER, WORKING EXAMPLES

16.8 SUMMARY AND CONCLUSIONS

16.9 EXERCISES AND PROJECTS

16.10 APPENDIX: PAR ASSET SWAP SPREAD AND ZERO VOLATILITY SPREAD

Chapter 17: Swaption, Cap and Floor

17.1 INTRODUCTION AND OBJECTIVES: A CLOSED FORMULA WORLD

17.2 DESCRIPTION OF INSTRUMENTS AND FORMULAE

17.3 MULTI-CURVE FRAMEWORK ON CAP, FLOOR AND SWAPTION

17.4 BOOTSTRAPPING VOLATILITY FOR CAP AND FLOOR

17.5 HOW TO ORGANISE THE CODE IN C#: A POSSIBLE SOLUTION

17.6 CONSOLE AND EXCEL WORKING EXAMPLES

17.7 SUMMARY AND CONCLUSIONS

17.8 EXERCISE AND DISCUSSION

Chapter 18: Software Architectures and Patterns for Pricing Applications

18.1 INTRODUCTION AND OBJECTIVES

18.2 AN OVERVIEW OF THE GOF PATTERN

18.3 CREATIONAL PATTERNS

18.4 BUILDER PATTERN

18.5 STRUCTURAL PATTERNS

18.6 BEHAVIOURAL PATTERNS

18.7 BUILDER APPLICATION EXAMPLE: CALIBRATION ALGORITHMS FOR CAP AND FLOOR

18.8 A PDE/FDM PATTERNS-BASED FRAMEWORK FOR EQUITY OPTIONS

18.9 USING DELEGATES TO IMPLEMENT BEHAVIOURAL DESIGN PATTERNS

18.10 A SYSTEM DESIGN FOR MONTE CARLO APPLICATIONS

18.11 DYNAMIC PROGRAMMING IN .NET

18.12 SUMMARY AND CONCLUSIONS

18.13 EXERCISES AND PROJECTS

Chapter 19: LINQ (Language Integrated Query) and Fixed Income Applications

19.1 INTRODUCTION AND OBJECTIVES

19.2 SCOPE OF CHAPTER AND PREREQUISITES

19.3 LINQ QUERY OPERATORS

19.4 LINQ QUERIES AND INITIAL EXAMPLES

19.5 ADVANCED QUERIES

19.6 A NUMERICAL EXAMPLE

19.7 JOIN AND GROUPJOIN

19.8 EXAMPLES IN FIXED INCOME APPLICATIONS

19.9 LINQ AND EXCEL INTEROPERABILITY

19.10 SUMMARY AND CONCLUSIONS

19.11 EXERCISES AND PROJECTS

Chapter 20: Introduction to C# and Excel Integration

20.1 INTRODUCTION AND OBJECTIVES

20.2 EXCEL OBJECT MODEL

20.3 USING COM TECHNOLOGY IN .NET

20.4 PRIMARY INTEROP ASSEMBLIES (PIA)

20.5 STANDALONE APPLICATIONS

20.6 TYPES OF EXCEL ADD-INS

20.7 THE IDTExtensibility2 INTERFACE AND COM/.NET INTEROPERABILITY

20.8 DATA VISUALISATION IN EXCEL

20.9 CONCLUSION AND SUMMARY

20.10 EXERCISES AND PROJECTS

Chapter 21: Excel Automation Add-ins

21.1 INTRODUCTION AND OBJECTIVES

21.2 COM OVERVIEW

21.3 CREATING AUTOMATION ADD-INS: THE STEPS

21.4 EXAMPLE: CREATING A CALCULATOR, VERSION 1

21.5 EXAMPLE: CREATING A CALCULATOR, VERSION 2

21.6 VERSIONING

21.7 WORKING WITH RANGES

21.8 VOLATILE METHODS

21.9 OPTIONAL PARAMETERS

21.10 USING VBA WITH AUTOMATION ADD-INS

21.11 SUMMARY AND CONCLUSIONS

21.12 EXERCISES AND PROJECTS

Chapter 22: C# and Excel Integration COM Add-ins

22.1 INTRODUCTION AND OBJECTIVES

22.2 PREPARATIONS FOR COM ADD-INS

22.3 THE INTERFACE IDTExtensibility2

22.4 CREATING COM ADD-INS: THE STEPS

22.5 UTILITY CODE AND CLASSES

22.6 USING WINDOWS FORMS

22.7 EXAMPLE: CREATING A COM ADD-IN

22.8 DEBUGGING AND TROUBLESHOOTING

22.9 AN INTRODUCTION TO EXCEL-DNA

22.10 EXCEL COM INTEROPERABILITY AND RATE MULTI-CURVE

22.11 CONCLUSION AND SUMMARY

22.12 EXERCISES AND PROJECTS

Chapter 23: Real-time Data (RTD) Server

23.1 INTRODUCTION AND OBJECTIVES

23.2 REAL-TIME DATA IN EXCEL: OVERVIEW

23.3 REAL-TIME DATA FUNCTION

23.4 EXAMPLE

23.5 THE TOPIC CLASS AND DATA

23.6 CREATING AN RTD SERVER

23.7 USING THE RTD SERVER

23.8 TESTING AND TROUBLESHOOTING THE RTD SERVER

23.9 CONCLUSION AND SUMMARY

23.10 EXERCISES AND PROJECTS

Chapter 24: Introduction to Multi-threading in C#

24.1 INTRODUCTION AND OBJECTIVES

24.2 PROCESSES

24.3 USING Processstartinfo TO REDIRECT PROCESS I/O

24.4 AN INTRODUCTION TO THREADS IN C#

24.5 PASSING DATA TO A THREAD AND BETWEEN THREADS

24.6 THREAD STATES AND THREAD LIFECYCLE

24.7 THREAD PRIORITY

24.8 THREAD POOLING

24.9 ATOMIC OPERATIONS AND THE Interlocked CLASS

24.10 EXCEPTION HANDLING

24.11 MULTI-THREADED DATA STRUCTURES

24.12 A SIMPLE EXAMPLE OF TRADITIONAL MULTI-THREADING

24.13 SUMMARY AND CONCLUSIONS

24.14 EXERCISES AND PROJECTS

Chapter 25: Advanced Multi-threading in C#

25.1 INTRODUCTION AND OBJECTIVES

25.2 THREAD SAFETY

25.3 LOCKING MECHANISMS FOR OBJECTS AND CLASSES

25.4 MUTEX AND SEMAPHORE

25.5 NOTIFICATION AND SIGNALLING

25.6 ASYNCHRONOUS DELEGATES

25.7 SYNCHRONISING COLLECTIONS

25.8 TIMERS

25.9 FOREGROUND AND BACKGROUND THREADS

25.10 EXECUTING OPERATIONS ON SEPARATE THREADS: THE BackgroundWorker CLASS

25.11 PARALLEL PROGRAMMING IN .NET

25.12 TASK PARALLEL LIBRARY (TPL)

25.13 CONCURRENT DATA STRUCTURES

25.14 EXCEPTION HANDLING

25.15 SHIFTING CURVES

25.16 SUMMARY AND CONCLUSIONS

25.17 EXERCISES AND PROJECTS

Chapter 26: Creating Multi-threaded and Parallel Applications for Computational Finance

26.1 INTRODUCTION AND OBJECTIVES

26.2 MULTI-THREADED AND PARALLEL APPLICATIONS FOR COMPUTATIONAL FINANCE

26.3 FORK AND JOIN PATTERN

26.4 GEOMETRIC DECOMPOSITION

26.5 SHARED DATA AND READER/WRITER LOCKS: MULTIPLE READERS AND MULTIPLE WRITERS

26.6 MONTE CARLO OPTION PRICING AND THE PRODUCER–CONSUMER PATTERN

26.7 THE StopWatch CLASS

26.8 GARBAGE COLLECTION AND DISPOSAL

26.9 SUMMARY AND CONCLUSIONS

26.10 EXERCISES AND PROJECTS

Appendix 1: Object-oriented Fundamentals

A1.1 INTRODUCTION AND OBJECTIVES

A1.2 OBJECT-ORIENTED PARADIGM

A1.3 GENERIC PROGRAMMING

A1.4 PROCEDURAL PROGRAMMING

A1.5 STRUCTURAL RELATIONSHIPS

A1.6 AN INTRODUCTION TO CONCEPT MODELLING

A1.7 CATEGORISATION AND CONCEPT LEVELS

A1.8 WHOLE–PART PATTERN

A1.9 MESSAGE-PASSING CONCEPT VERSUS PROCEDURAL PROGRAMMING

Appendix 2: Nonlinear Least-squares Minimisation

A2.1 INTRODUCTION AND OBJECTIVES

A2.2 NONLINEAR PROGRAMMING AND MULTI-VARIABLE OPTIMISATION

A2.3 NONLINEAR LEAST SQUARES

A2.4 SOME SPECIFIC METHODS

A2.5 THE ALGLIB LIBRARY

A2.6 AN APPLICATION TO CURVE BUILDING

A2.7 RATE CALIBRATION EXAMPLE

A2.8 EXERCISES AND PROJECTS

Appendix 3: The Mathematical Background to the Alternating Direction Explicit (ADE) Method

A3.1 INTRODUCTION AND OBJECTIVES

A3.2 BACKGROUND TO ADE

A3.3 SCOPING THE PROBLEM: ONE-FACTOR PROBLEMS

A3.4 AN EXAMPLE: ONE-FACTOR BLACK-SCHOLES PDE

A3.5 BOUNDARY CONDITIONS

A3.6 EXAMPLE: BOUNDARY CONDITIONS FOR THE ONE-FACTOR BLACK-SCHOLES PDE

A3.7 MOTIVATING THE ADE METHOD

A3.8 THE ADE METHOD EXPOSED

A3.9 THE CONVECTION TERM

A3.10 OTHER KINDS OF BOUNDARY CONDITIONS

A3.11 NONLINEAR PROBLEMS

A3.12 ADE FOR PDEs IN CONSERVATIVE FORM

A3.13 NUMERICAL RESULTS AND GUIDELINES

A3.14 THE STEPS TO USE WHEN IMPLEMENTING ADE

A3.15 SUMMARY AND CONCLUSIONS

A3.16 EXERCISES AND PROJECTS

Appendix 4: Cap, Floor and Swaption Using Excel-DNA

A4.1 INTRODUCTION

A4.2 DIFFERENT WAYS OF STRIPPING CAP VOLATILITY

A4.3 COMPARING CAPLET VOLATILITY SURFACE

A4.4 CALL PUT PARITY

A4.5 CAP PRICE MATRIX

A4.6 MULTI-STRIKE AND AMORTISING

A4.7 SIMPLE SWAPTION FORMULA

A4.8 SWAPTION STRADDLE

A4.9 EXERCISES

Bibliography

Web References

Index

End User License Agreement

© 2013 Daniel J Duffy and Andrea Germani

Registered OfficeJohn 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.

The right of the author to be identified as the author of this work has been asserted in accordance with the Copyright, Designs and Patents Act 1988

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. C# for financial markets / Daniel J. Duffy and Andrea Germani. p. cm. Includes bibliographical references and index. ISBN 978-0-470-03008-0 (cloth) 1. Finance–Mathematical models. 2. Finance–Data processing. 3. C# (Computer program language) I. Germani, Andrea, 1975– II. Title. HG106.D838 2013 332.0285′5133–dc23 2012040263

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

ISBN 978-0-470-03008-0 (hbk) ISBN 978-1-118-50281-5 (ebk)

ISBN 978-1-118-50275-4 (ebk) ISBN 978-1-118-50283-9 (ebk)

Cover image reproduced by permission of Shutterstock.com

ABOUT THE AUTHORS

Daniel J. Duffy has been working with numerical methods in finance, industry and engineering since 1979. He has written four books on financial models and numerical methods and C++ for computational finance and he has also developed a number of new schemes for this field. He is the founder of Datasim Education and has a PhD in Numerical Analysis from Trinity College, Dublin.

Andrea Germani was born in Lodi, Italy in 1975, where he currently lives. After graduating from Bocconi University in Milano, he obtained the Certificate in Quantitative Finance in London under the supervision of Paul Wilmott. Since then he has been working as a trader in some of the major Italian banks, where he gained a deep knowledge of financial markets. He also worked on valuation and pricing of equity and interest-derivatives, with a focus on the practical use of models on the trading floor. His teaching experience includes finance training courses for university students and practitioners. He is the Head of Interest Rate Derivatives Trading and Treasury in a bank.

For other titles in the Wiley Finance series please see www.wiley.com/finance

List of Figures

2.1 Computational engine

3.1 Payoff hierarchy

4.1 Generic design in C#

4.2 Bond and bond option pricers

4.3 Design blueprint model for differential equations

4.4 UML component diagram

4.5 Order class

4.6 ExternalOrder class derived from Order

4.7 IPricing interface implemented in Order class

4.8 Discount behaviour overridden in ExternalOrder class

5.1 Collection interfaces

5.2 Order and its order items

6.1 Basic vector and matrix classes

6.2 Associative array class

6.3 Associative matrix class

7.1 UML class diagram for Bond Pricer

8.1 Stream classes

8.2 Stream decorator classes

8.3 Stream decorator data flow

8.4 Stream adapter classes

8.5 Stream adapter data flow

8.6 File and directory classes

8.7 Serialisation classes

8.8 Serialisation data flow

8.9 Major components in a POS

8.10 Persistence mechanism using Visitor pattern

9.1 Component diagram for Binomial method

9.2 Basic lattice, multiplicative

9.3 Basic lattice, additive

9.4 Binomial method class diagram

9.5 Two-factor binomial process

10.1 Trinomial tree model

10.2 Modules for trinomial method

10.3 Modules for Explicit Finite Difference method

10.4 Option price as a function of the underlying

10.5 Region of integration

10.6 Extending the framework: ADE scheme

11.1 Reflection classes

11.2 Dynamical assembly loading

11.3 Dialog box for input

11.4 Output from C# form

12.1 Schedules class hierarchy and special contract dates

12.2 Bond class hierarchy

12.3 Bond hierarchy methods

12.4 Special bond types in the market place

12.5 Computing bond price and bond yield

12.6 Excel connection mechanism

12.7 Basic bond class

12.8 Classes for data serialisation

12.9 Calculating bond yields in Excel (dictionary in memory)

12.10 Adding a bond to a serialised dictionary

12.11 Request yield to a serialised dictionary

12.12 Floating rate

13.1 Tree structure for interpolation

13.2 Basis setup for bilinear interpolation

13.3 (a) Linear on log df (b) Cubic spline on log df (c) Hyman monotone-preserving (d) Hagan-West approach

13.4 Continuously compounded rates

13.5 Discrete forward rates using Hyman interpolation

13.6 Output of the function Sigmoid1

13.7 Output of the function Sigmoid2

14.1 Listed contracts

14.2 Futures and futures options

15.1 Swap cash flows example

15.2 Using swap to change asset rate risk exposure

15.3 System design

15.4 Building blocks hierarchy

15.5 Factory pattern for building blocks creation

15.6InterpAdapter base class and derived classes hierarchy

15.7 Interpolator class hierarchy

15.8SingleCurveBuilder classes hierarchy

15.9 Test case: 6m forward rates

16.1 Indicative 3m Eonia-Euribor spread

16.2 Indicative Eur basis swap 1Y and 5Y 3mVs6m

16.3MultiCurveBuilder and other classes

16.4 Interface hierarchy and functionality

16.5 Multi-curve forward rate example

16.6 Multi-curve discount factors

16.7 Using different interpolators for discount curve in single-curve

16.8 Using different interpolators for discount in multi-curve

16.9 Comparing discount factors in single and multi-curve framework

16.10 Bond payments schedule

16.11 Swap payments schedule

16.12 Asset swap payments schedule

17.1 Visualisation of caplet test case

17.2 Swaption schedule

17.3 Cap structure

17.4 Quarterly caps

17.5 Finding value between quoted points

17.6 Mono-strike class hierarchy

17.7 Using bilinear interpolation

18.1 Class diagram for Builder

18.2 Sequence diagram for Builder pattern

18.3 Class diagram for Monte Carlo framework

18.4 Layers pattern: (a) three-layer case; (b) two-layer case

18.5 Builder pattern for cap and floor

18.6 Extended Builder

18.7 State machine of FDM application

18.8 Class diagram

18.9 Top-level component diagram

18.10 Context diagram for Monte Carlo applications

18.11 Interfaces for SDE

19.1 Input/output and LINQ operators

20.1 Excel Object Model (simplified)

20.2 Runtime Callable Wrapper

20.3 Adding a COM component

20.4 Adding a .NET component

20.5 Project with Excel included

20.6 Curve drawing in Excel

21.1 COM Callable Wrapper

21.2 The Automation add-in in the OLE/COM viewer

21.3 The Automation add-in in the Excel add-in manager

21.4 Selecting a function from the Automation add-in

21.5 Worksheet using Automation add-in functions

21.6 VBA dialog box

22.1 Windows Form asking for start and end values

22.2 Necessary project files for Excel-DNA Option Pricer

22.3 Example of input to curve building

22.4 UDF functions in Excel-DNA

22.5 Multi-curve input data example

22.6 Sensitivity calculations

23.1 RTD server sequence diagram

24.1 System thread and ThreadStart

24.2 State chart thread lifecycle

24.3 Extended Producer Consumer pattern

A1.1 Examples of aggregation

A1.2 My first binary association

A1.3 Derivatives and underlying

A1.4 My first unary association

A1.5 Unary association and inheritance relationship

A1.6 Modelling a spread as a composition

A1.7 Extended Whole-Parts example

A1.8 Collection-Members relationship

A2.1 Plotting the rates

A3.1 Region and boundary

A3.2 Nonuniform mesh

A3.3 Visualisation of ADE process

A4.1 Screenshot of cap volatilities from Excel

A4.2 Screenshot of different stripping approach from Excel

A4.3 Caplet volatilities comparing stripping approaches

A4.4 Caplet volatilities more stripping approaches

A4.5 (a) Best fit (b) Linear interpolation (c) Interpolation on cap volatility (d) Best fit on smoothness condition (e) Best fit standard (f) Best fit, cubic interp. on caplet vols (g) Best fit, linear interp. on caplet vols (h) Piecewise constant

A4.6 Call-put parity for swaptions

A4.7 Call-put parity for caplet and floorlet

A4.8 Screenshot of cap recalculated prices using caplet stripped volatilities

A4.9 Screenshot of pricing multi-strike, amortising cap using sample data

A4.10 Bilinear interpolation for swaption volatility

A4.11 Single swaption and straddle pricer

A4.12 Example of swaption Black volatility matrix

A4.13 At the money strike for swaptions

A4.14 Matrix of swaption straddle premium

Andrea Germani would like to thank: Eleonora for her patience and enthusiasm, Laura and the coming child, Riccardo Longoni for constructive discussion, Alda and Giuseppe for their examples.

Introduction

0.1 WHAT IS THIS BOOK?

The goal of this book is to develop applications related to pricing, hedging and data processing for fixed income and other derivative products in the .NET framework and using C# as the programming language. We pay attention to each stage in the process of defining financial models, designing algorithms and implementing these algorithms using the object-oriented and generic programming techniques in C# in combination with libraries in .NET. We address a number of issues that face quant developers and quant traders when designing new applications:

Step 1: Create and set up a financial model.Step 2: Determine which algorithms, numerical methods and data to use in order to approximate the financial model.Step 3: Implement the algorithms from Step 2 in C#.

We discuss each of the steps in detail. In particular, we introduce a number of standard fixed-income derivatives products. We pay particular attention to the curve building process and interpolation in the single-curve and multi-curve framework. Second, we show how to use the features in C# and .NET to design and implement flexible and efficient software systems for pricing and risk applications.

One of the consequences of using C# and .NET libraries to develop finance applications is that we can take advantage of the modern and effective software methods to create flexible applications and to improve programmer productivity. A special topic is how to use Excel as a front-end to our applications.

In short, the main objective in writing this book is to show all the major steps in transforming a financial model into a working C# program.

0.2 SPECIAL FEATURES IN THIS BOOK

In our opinion, this is the first book to discuss how to create fixed income applications using C#. The authors' background is in mathematics and software design in combination with quantitative development and trading experience. In summary the book features are:

A thorough introduction to the C# language and .NET libraries.Object-oriented, interface and generic programming models.Effective use of .NET data structures; creating your own data structures.Data serialisation and deserialisation.Assembly and DLL management.Bond and interest rate option pricing.The Binomial and Finite Difference Methods (FDM) in C#.Interpolation algorithms.Discount curves; multi-curve calculations.Bootstrapping volatilities from cap floor and swaptions.Excel interoperability.Multi-threading and parallel processing.

0.3 WHO IS THIS BOOK FOR AND WHAT DO YOU LEARN?

We have written this book for students, quantitative developers and traders who create and maintain trading systems. The reason for choosing C# was that it is relatively easy to learn (certainly when compared to C++), it interoperates with the .NET libraries and, furthermore, the productivity levels are much higher than those achieved with C++. Moreover, it has high levels of interoperability with Excel and we can also safely say that the corresponding code can be quickly learned by VBA developers. The book is also suitable for those readers who are interested in learning more about developing financial systems, for example those in IT, engineers and others who are contemplating the move to C#. In particular, most of the chapters should be accessible to them. The book can also be used by MSc students.

This book discusses a number of techniques and methods that we feel are helpful to readers. We believe the following skills to be of particular value:

Modern software methods.Implementing financial models in C#.C# and Excel interoperability.Single-curve and multi-curve bootstrapping (post-2007).Parallel processing and multi-threading.

Each chapter contains exercises to test what you have learned in the chapter. The goal of the examples and exercises in the book is to show the use of computer code. Market data used in the exercises and in tables are not real data but have been created to clarify the exercises and should not be viewed as actual market data. We recommend that you at least have a look at them and, ideally, work them out and implement them in C#.

0.4 STRUCTURE OF THIS BOOK

This book contains 26 chapters that can be grouped into logical categories. Each part deals with one or more specific attention areas:

Part I: C# language and .NET libraries; UML notation and software patterns; bond and interest rate pricing, lattice methods, Finite Difference Method (FDM) (Chapters 1–11).Part II: Designing and implementing bond applications and short-term interest rate futures and options; interpolation in Interest Rate Application (Chapters 12–14).Part III: single curve and multi-curve building process; the role of interest rate curve post-2007 experience; extended pricing and hedging applications for swaps; caps, floors and swaption application (Chapters 15–17).Part IV: Software architectures and patterns; LINQ; Integrating C# applications with Excel; Excel interoperability; Automation and COM Addins; RealTime Excel Server (Chapters 18–23).Part V: Multi-threading and parallel processing in C#; some ‘101’ examples and a small application to show the curve building process (Chapters 24–26).

The parts are weakly coupled in the sense that each one can be studied independently of the chapters in other parts.

0.5 C# SOURCE CODE

You can use the source code on the software distribution medium free of charge provided you do not modify the copyright information. The software is provided as is without warranty of any kind. There is a support centre for the book at www.datasimfinancial.com for purchasers of this book. Please contact Datasim Education for more information.

Andrea Germani, Milan Daniel J. Duffy, Datasim Education BV, Amsterdam

1

Global Overview of the Book

1.1 INTRODUCTION AND OBJECTIVES

The main goal of this book is to show how to design software systems for financial derivatives products using the object-oriented language C#. We have chosen C# for a number of reasons and we would like to explain the rationale behind this choice:

C# is relatively easy to learn (certainly when we compare it to C++). This means that it can be learned by traders, quants and other finance professionals who do not necessarily spend all their waking hours designing and implementing software systems. For example, people with a background in VBA will find the transition to C# much easier than the transition from VBA to C++. Furthermore, in many cases developer productivity levels in C# can be four times as high as with C++.The .NET framework and C# offer the developer a range of functionality that he or she can use in financial applications. This is realised by the features in the language itself and by the libraries in the framework. We shall discuss these libraries and we shall also see in the rest of this book how they are used to create robust and flexible applications.It is possible to create interoperable applications that consist of a mixture of C#, C++ and VBA code and that communicate with Excel and real-time data servers. In other words, it is possible to create .NET applications that can communicate with non .NET code and it is also possible to create non .NET applications that can communicate with .NET code.Usability levels are high. Furthermore, developers do not have to worry about manual memory management as this is taken care of by garbage collection mechanisms resident in the .NET framework.C# and the .NET framework contain libraries that allow developers to create multi-threaded applications that run on shared memory multi-core processors.Many .NET libraries have been designed in such a way that they can be used and adapted to suit new developer needs. In particular, it is easy to use and apply design patterns in C# applications.

In this book we discuss each of these topics in detail.

1.2 COMPARING C# AND C++

C# is a descendant of the C programming language (K&R 1988). It is worth pausing for a moment to consider whether it is better (in some sense) to develop new applications in C# and or C++. In order to help the reader determine how to choose between C# and C++, we discuss the problem from three perspectives:

P1: The skills and knowledge of those engineers developing applications.P2: The type of application and related customer wishes.P3: The technical and organisational risks involved in choosing a given language.

We discuss each perspective in turn. First, C++ is a huge multi-paradigm language and it supports the modular, object-oriented and generic programming models. It is based on the C language and it would seem that it is the language of choice for many pricing, hedging and risk applications. It is not an easy language to learn. There are many books that discuss C++ and its syntax but there are surprisingly few that discuss how to apply C++ to finance and even to other application domains. C#, on the other hand is a relatively new language and it supports the object-oriented and generic programming models, but not the modular programming model. This implies that everything must be an object or class in C#.

In general, C# is much easier to learn than C++. It shields the developer from many of the low-level details seen in C++, in particular the pointer mechanism, memory management and garbage collection. In short, the C# developer does not have to worry about these details because they are automatically taken care of. This is a mixed blessing because there are situations where we wish to have full control of an object's lifecycle. C++ is a vendor-neutral language (it is an ISO standard) while C# was originally developed by Microsoft for its Windows operating system.

Perspective P2 is concerned with the range of applications to which C++ or C# can be applied, how appropriate C++ and C# are for these applications and how customer wants and needs determine which language will be most suitable in a particular context. In general, customers wish to have applications that perform well, are easy to use and easy to extend. On the issue of performance, C++ tends to be more efficient than C# and tests have shown that in general C++ applications are 20% faster than the corresponding applications in C#. This difference may or may not be a critical factor in determining whether C++ is more suitable than C# in a particular context.

To compare the two languages from the perspective of developer productivity, we first need to define what we are measuring. C# has many libraries that the developer can use, thus enhancing productivity. C++, on the other hand does not have such libraries and they must be purchased as third-party software products. In particular, user-interface software for C# is particularly easy to use while in C++ the developer must use libraries such as MFC, QT or OWL, for example. In general, we conclude that productivity levels are much higher in C# than in C++.

Finally, perspective P3 is concerned with the consequences and risks to the organisation after a choice has been made for a particular language. C++ is a large and difficult language, it takes some time to master and C++ applications tend to be complex and difficult to maintain. However, C++ is an ISO standard.

1.3 USING THIS BOOK

This book represents the joint work of Andrea Germani (trader/quant) and Daniel J. Duffy (numerical analyst/software designer). The focus of this book reflects the backgrounds of the authors and the objectives that they had when they first had the idea in a Milan ristorante all those years ago (or so it seems) to write a practical book that would appeal to traders and to quants who work in the financial markets. The outcome is what you have in your hands. It contains 26 chapters that are logically grouped into major categories dealing with C# syntax, .NET libraries, Excel integration, multi-threading and parallel programming and applications to fixed-income products such as caps, floors, swaps and swaptions that we price and for which we calculate rate sensitivities. We also discuss the pricing of equities using lattice and PDE/finite difference methods. It is clear that this book is not just about C# syntax alone but it is a complete introduction to the design and implementation of C# applications for financial markets. We employ object-oriented, generic and functional programming models to create flexible and efficient software systems for finance professionals. The book has a dedicated forum at www.datasimfinancial.com.

We have provided source code at the above site for all examples and applications that are discussed in the book. We recommend that you review the code, run it and extend it to suit your particular circumstances.