Learning Modern C++ for Finance Foundations for Quantitative Programming Daniel Hanson
ISBN: 978-1-098-10080-3 US $65.99 CAN $82.99 PROGR AMMING Daniel Hanson worked in financial modeling and software development for over two decades, primarily in C++ implementation of option pricing and portfolio risk models. This was followed by an appointment as a lecturer in the Computational Finance and Risk Management program at the University of Washington, where he taught classes in quantitative programming in both C++ and R, as well as courses in financial modeling and trading strategies. This practical book demonstrates why C++ is still one of the dominant production-quality languages for financial applications and systems. Many programmers believe that C++ is too difficult to learn. Author Daniel Hanson demonstrates that this is no longer the case, thanks to modern features added to the C++ Standard beginning in 2011. Financial programmers will discover how to leverage C++ abstractions that enable safe implementation of financial models. You’ll also explore how popular open source libraries provide additional weapons for attacking mathematical problems. C++ programmers unfamiliar with financial applications also benefit from this handy guide. • Learn C++ basics from a modern perspective: syntax, inheritance, polymorphism, composition, STL containers, and algorithms • Dive into newer features and abstractions including functional programming using lambdas, task-based concurrency, and smart pointers • Implement basic numerical routines in modern C++ • Understand best practices for writing clean and efficient code Learning Modern C++ for Finance
Daniel Hanson Learning Modern C++ for Finance Foundations for Quantitative Programming
978-1-098-10080-3 LSI Learning Modern C++ for Finance by Daniel Hanson Copyright © 2025 Daniel Hanson. All rights reserved. Printed in the United States of America. Published by O’Reilly Media, Inc., 1005 Gravenstein Highway North, Sebastopol, CA 95472. O’Reilly books may be purchased for educational, business, or sales promotional use. Online editions are also available for most titles (http://oreilly.com). For more information, contact our corporate/institutional sales department: 800-998-9938 or corporate@oreilly.com. Acquisitions Editor: Amanda Quinn Development Editor: Jeff Bleiel Production Editor: Ashley Stussy Copyeditor: Sharon Wilkey Proofreader: Kim Cofer Indexer: WordCo Indexing Services, Inc. Interior Designer: David Futato Cover Designer: Karen Montgomery Illustrator: Kate Dullea November 2024: First Edition Revision History for the First Edition 2024-11-04: First Release See http://oreilly.com/catalog/errata.csp?isbn=9781098100803 for release details. The O’Reilly logo is a registered trademark of O’Reilly Media, Inc. Learning Modern C++ for Finance, the cover image, and related trade dress are trademarks of O’Reilly Media, Inc. The views expressed in this work are those of the author, and do not represent the publisher’s views. While the publisher and the author have used good faith efforts to ensure that the information and instructions contained in this work are accurate, the publisher and the author disclaim all responsibility for errors or omissions, including without limitation responsibility for damages resulting from the use of or reliance on this work. Use of the information and instructions contained in this work is at your own risk. If any code samples or other technology this work contains or describes is subject to open source licenses or the intellectual property rights of others, it is your responsibility to ensure that your use thereof complies with such licenses and/or rights.
In loving memory of my parents.
(This page has no text content)
Table of Contents Preface. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . xi 1. An Overview of C++. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1 C++ and Quantitative Finance 1 C++11: The Modern Era Is Born 2 Open Source Mathematical Libraries 4 Some Myths about C++ 4 Compiled Versus Interpreted Code 4 The Components of C++ 5 C++ Language Features 5 The C++ Standard Library 6 Some New Language Features Since C++11 9 The auto Keyword 10 Range-Based for Loops 11 The using Keyword 12 Uniform Initialization 13 Formatting Output 14 Class Template Argument Deduction 15 Enumerated Constants and Scoped Enumerations 16 Lambda Expressions 20 Mathematical Operators, Functions, and Constants in C++ 23 Standard Arithmetic Operators 23 Mathematical Functions in the Standard Library 24 Mathematical Special Functions 27 Standard Library Mathematical Constants 27 Naming Conventions 29 Summary 31 Further Resources 32 v
2. Writing User-Defined Classes with Modern C++ Features. . . . . . . . . . . . . . . . . . . . . . . . 33 A Black-Scholes Class 34 Representing the Payoff 35 Writing the Class Declaration 35 Writing the Class Implementation 36 Using a Functor for Root Finding: Implied Volatility 39 Move Semantics and Special Member Functions 43 Data Members and Performance Considerations 43 An Introduction to Move Semantics 45 Initialization of Constructor Arguments with std::move(.) 48 Anonymous Temporary Objects and Move Semantics 50 Return Value Optimization 51 Default Constructor 52 Three-Way Comparison Operator (Spaceship Operator) 54 Lambda Expressions and User-Defined Class Members 58 Summary 59 Additional References 60 3. Inheritance, Polymorphism, and Smart Pointers. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 63 Polymorphism 65 Resource Ownership with Raw Pointers 70 Using Clone Methods 74 Creating an Instance of OptionInfo 75 Preventing Shallow Copy 76 Implementing the OptionInfo Destructor 79 Pricing an Option 79 Implementing Copy Operations 81 The (Old) Rule of Three 85 Introducing Smart Pointers 85 Unique Pointers 86 Shared Pointers 88 Managing Resources with Unique Pointers 91 Just Move It 91 Using the Result in a Pricing Model 94 If Copy Operations Are Required 95 Summary 100 Further Resources 101 4. The Standard Template Library Part I: Containers and Iterators. . . . . . . . . . . . . . . . . . 103 Templates 104 Using Function Templates 105 Using Class Templates 107 vi | Table of Contents
Compiling Template Code 109 STL Containers 110 Sequential Containers 111 Associative Containers 128 STL Iterators 134 Using auto to Reduce Verbosity 137 Using Constant Iterators 137 Iterators or Indices? 137 Iterators on Associative Containers 138 Summary 139 Further Resources 142 5. The Standard Template Library Part II: Algorithms and Ranges. . . . . . . . . . . . . . . . . . . 143 STL Algorithms 143 A First STL Algorithm Example 144 A First Example with Ranges 148 Some Commonly Used Algorithms 149 Function Objects as Auxiliary Functions 153 Class Member Functions as Auxiliary Functions 153 Locating, Sorting, Searching, Copying, and Moving Elements 154 Numeric Algorithms 161 Range Views, Range Adaptors, and Functional Programming 169 Range Views 170 Chaining for Functional Composition 173 Views, Containers, and Range-Based for Loops 173 Summary 174 Additional References 175 6. Random Number Generation and Concurrency. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 177 Distributional Random Number Generation 178 Introducing Engines and Distributions 178 Generating Random Normal Draws 181 Using Other Distributions 182 Shuffling 184 Monte Carlo Option Pricing 194 A Review of Monte Carlo Option Pricing 194 Generating Random Equity Price Scenarios 196 Calculating the Option Price 198 Pricing Path-Dependent Options 202 Concurrency and Parallelism 208 Parallel Algorithms from the Standard Library 209 Task-Based Concurrency 214 Table of Contents | vii
Concluding Remarks on async and future 222 Summary 222 Further Resources 223 7. Dates and Fixed Income Securities. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 225 Representation of a Date 226 Serial Representation 229 Accessor Functions for Year, Month, and Day 230 Checking the Validity of a Date 230 Checking Leap Years and Last Day of the Month 231 Identifying Weekdays and Weekends 232 Adding Years, Months, and Days 233 A Date Class Wrapper 236 Class Declaration 236 Class Implementation 239 Day Count Basis 246 Yield Curves 249 Deriving a Yield Curve from Market Data 249 Discount Factors 252 Calculating Forward Discount Factors 252 Implementing a Yield-Curve Class 253 Implementing a Linearly Interpolated Yield Curve Class 257 A Bond Class 258 Bond Payments and Valuation 259 Designing a Bond Class 264 Implementing the Bond Class 266 A Bond Valuation Example 271 Summary 275 Additional Reference 276 8. Linear Algebra. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 277 Lazy Evaluation and Expression Templates 278 Lazy Evaluation 279 Expression Templates 282 The Eigen Linear Algebra Library 286 Eigen Matrices and Vectors 287 Matrix and Vector Math Operations 291 STL Compatibility 297 Matrix Decompositions and Applications 303 Fund Tracking with Multiple Regression 303 Correlated Random Equity Paths and the Cholesky Decomposition 306 Yield-Curve Dynamics and Principal Component Analysis 310 viii | Table of Contents
Future Directions: Linear Algebra in the Standard Library 313 mdspan 314 BLAS Interface 319 Summary 321 Further Resources 321 9. The Boost Libraries. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 323 Mathematical Constants 324 Statistical Distributions 325 Probability Functions 326 Drawdown Example, Revisited 328 Random Number Generation with Boost Distributions 329 MultiArray 331 A Simple Two-Dimensional MultiArray 331 Binomial Lattice Option Pricing 333 Accumulators 346 Max and Min Example 346 Mean and Variance 348 Rolling Mean and Variance 349 Trading Indicator Examples 350 Summary 355 Further Reading 355 10. Modules and Concepts. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 357 Modules 358 Standard Library Header Units 360 Templates in Modules 361 import Versus #include 362 Declarations in Module Interfaces 364 Separating Declarations from Implementation 365 Namespaces 369 Partitions 370 Concepts 370 Defining Concepts 372 Defining Concepts with Multiple Conditions 373 Standard Library Concepts 374 Summary 376 Table of Contents | ix
A. Virtual Default Destructor. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 377 B. Object Slicing. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 381 C. Implementation of Move Special Member Functions. . . . . . . . . . . . . . . . . . . . . . . . . . . . 385 D. Resolving Conflicts in the Initialization of a vector. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 389 E. valarray and Matrix Operations. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 391 Index. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 397 x | Table of Contents
Preface The modern features that have been added to the C++ Standard beginning with C++11 in 2011 have been truly remarkable and transformative. Consider the follow‐ ing additions through 2017, which can be of immediate benefit to financial C++ developers, and in most cases are very easy to incorporate into code: • Move semantics, allowing transfer of object ownership without the performance overhead of copying (C++11) • Smart pointers, which dramatically reduce problems associated with raw pointers (C++11 and C++14) • Parallel standard algorithms that require only an additional parameter yet can speed up code by magnitudes (C++17) • Random number generation from common distributions (C++11) • Task-based concurrency, which can run tasks in parallel by simply replacing a couple of lines of code (C++11) Updated versions of the C++ Standard have been released every three years since C++11, leading to the subsequent standard C++20 and the most recent C++23. In particular, these more recent features are also now available: • A new date class, critical for fixed income applications (C++20) • Concepts, making template-based generic programs simpler to debug and more expressive (C++20) • Range adaptors, enabling the composition of algorithms in a modern functional form, while cutting out “the middleman” of inefficient object copying (C++20 and C++23) • Modules—say goodbye to #include and hello to safer code (C++20) xi
All the modern features mentioned here, plus coverage of popular open source C++ libraries such as Eigen (linear algebra) and the Boost libraries, are provided within this book, with a focus on relevant financial applications. In computer science and financial engineering curricula (at least throughout the Uni‐ ted States), however, as well as in popular online credential programs in quantitative finance, C++ education largely appears to be living in the past. Many courses still seem to be based on the 2003 Standard, referred to as C++03. This is a common complaint I have heard from many students in the CppCon (annual C++ conference) Student Program, and from a few of my own master’s students who took undergradu‐ ate C++ courses before entering the computational finance program in which I taught at the University of Washington through 2022. Some students said that professors refused to update their syllabi, while others said that professors wanted to teach modern C++, but their departments wouldn’t allow it. So I tried to write the book with this audience in mind: those who have had some introductory-level experience with C++ but who wish to learn more about modern methods relevant to the implementation of financial models. It is also feasible for those with experience in other programming languages to work through this book, in tandem with an introductory book such as C++ Primer, 5th edition, by Stanley B. Lippman et al. (Addison-Wesley, 2012), or Teach Yourself C++ in One Hour a Day, 9th edition, by Siddhartha Rao (Sams, 2022). I also highly recommend The C++ Standard Library: A Tutorial and Reference, 2nd edition, by Nicolai M. Josuttis (Addison-Wesley, 2012), as a reference book for both beginners and advanced read‐ ers. You may note that the links provided here are to the electronic editions available on the O’Reilly Learning Platform. Other references cited throughout the book will be linked to this platform where available. One more excellent resource is the Back to Basics series of talks from the annual CppCon C++ conference, which is freely available on the conference YouTube chan‐ nel. If you wish to learn more about a particular topic, chances are a Back to Basics talk is available. This book assumes readers have knowledge of the following topics. If you are new to C++ or if it has been a while, you might want to specifically review these or keep a reference book handy such as those noted previously: • Basic exception handling • static_cast<.> • Basic class design in general—and in particular public, protected, and private member functions and data members • Static data members and member functions • cout and console output xii | Preface
• Header and implementation files • The difference between #include<blah> and #include "blah.h" • The standard vector container • Code debugging with an integrated development environment (IDE) • Compiling and linking an executable program Also, because financial modeling involves math, a basic-level knowledge of the fol‐ lowing topics is also assumed, in certain chapters: • Probability theory and statistics • Basic numerical root–finding methods • Linear algebra and matrix decompositions • Black-Scholes option pricing and the associated Brownian motion stochastic process Navigating This Book This book is organized roughly as follows: • Chapter 1, “An Overview of C++” provides an overview of C++, beginning with a brief history of C++ in finance, and the shift toward modern C++, beginning with C++11. It also covers the separation of the core language and the C++ Standard Library, followed by key modern updates to the language that will be used throughout the remainder of the book, such as automatic type deduction, range-based for loops, scoped enumerations, and lambda expressions. It also includes coverage of basic mathematical features within the core language and the Standard Library. It concludes with a discussion about coding style and standards, and those that will be followed in this book. • Chapter 2, “Writing User-Defined Classes with Modern C++ Features” and Chapter 3, “Inheritance, Polymorphism, and Smart Pointers” are focused on object-oriented features in C++, and modern additions that have changed (and have helped improve) the methods once commonly employed in C++ for imple‐ menting composition and inheritance. Chapter 2 is primarily concerned with composition, namely the storage of a private data member that is itself an object, and how move semantics introduced in C++11 can make this more efficient by avoiding object copy at construction of the enclosing object. It also covers the new C++20 three-way operator (also called the spaceship operator), which greatly streamlines implementation of equality and inequality operators. Chapter 3 begins with modern features that better facilitate inheritance and Preface | xiii
dynamic polymorphism. It then shifts back to composition, where the subobject member is now a pointer resource, and how smart pointers help eliminate the problems associated with raw pointers. Composition and inheritance are then tied together in a modern context where the resource is a smart pointer to a polymorphic object. Financial examples in both chapters are related to option pricing. • Chapter 4, “The Standard Template Library Part I: Containers and Iterators” and Chapter 5, “The Standard Template Library Part II: Algorithms and Ranges” cover what has traditionally been called the Standard Template Library (STL). This is a set of standard containers—including the vector container and oth‐ ers—plus iterators that allow you to traverse these containers, and algorithms that perform operations on elements in a container. STL containers and iterators are covered in Chapter 4, while the algorithms are covered in Chapter 5. Chap‐ ter 5 also contains a discussion of C++20 and C++23 extensions of algorithms in the more expressive form of ranges, and furthermore how ranges relate to range views and range adaptors. As you will see, these can be used in a functional programming context for composing a sequence of algorithms such that the performance overhead from copying data and generating temporary container objects can be avoided. • Chapter 6, “Random Number Generation and Concurrency” begins with a dis‐ cussion of random number generation from known probability distributions, another new Standard Library feature released in C++11. Standard normal ran‐ dom variates in particular are key to continuous-time financial models, while the random values from a Poisson distribution are often used in modeling tick data for testing live trading strategies. Two examples are presented. The first is the shuffle algorithm combined with a C++11 random engine to generated Monte Carlo scenarios of equity lines to measure the risk associated with the volatility of maximum drawdown in a trading strategy. The second is a Monte Carlo model for valuing European options with barriers, where random variates from a standard normal distribution are used in a discretized Brownian motion process. The chapter then changes focus to concurrency and parallelism, first with examples of parallel STL algorithms, introduced with C++17. These are mostly overloads of existing algorithms, but with an additional execution policy parameter, which means significant performance increases can be had by simply including an extra argument. The chapter concludes with a return to the Monte Carlo option pricing example, but using the Standard Library async(.) function and future class, which help facilitate generating each Monte Carlo scenario as a parallel task, again resulting in significant increases in the magnitude of speed for larger numbers of scenarios and time steps. xiv | Preface
• Chapter 7, “Dates and Fixed Income Securities” introduces the new C++20 date functionality in the Standard Library, and how date functions and validations typically required for fixed income trading can be incorporated into code. Dis‐ cussion then proceeds to wrapping this functionality in a user-defined date class that can be used in the design of a yield curve class and a bond class, and how these can all be used together to price a coupon-paying bond. This includes coverage of potentially tedious but important details that are crucial for fixed income trading but are often left out of related textbooks and course syllabi. • Chapter 8, “Linear Algebra” is devoted to linear algebra in C++. A common technique used in C++ linear algebra library development is expression template programming, so a gentle introduction to this topic is provided before moving on to the open source, third-party C++ linear algebra library called Eigen. This will include applications to fund tracking (regression), valuing basket options (Cholesky decomposition), and yield curve dynamics (principle component decomposition). The chapter concludes with a look ahead to linear algebra capa‐ bilities in the C++ Standard Library, particularly the mdspan multidimensional array reference from C++23, and the standard interface based on the Basic Linear Algebra Subprograms (BLAS) slated for C++26. • Chapter 9, “The Boost Libraries” covers some of the peer-reviewed, open source Boost libraries. A fair amount of content from Boost has found its way into the C++ Standard over the years (in similar but not necessarily identical form), while other Boost libraries remain orthogonal to the Standard but can be applied to problems that arise in finance. In particular, the set of statistical distributions from the Boost Math Toolkit library provides the probability density function (PDF), cumulative distribution function (CDF), and percentile function for each of 34 “textbook” distributions. The Boost MultiArray library provides a generic multidimensional array that can be adapted for binomial (and trinomial) lattice option pricing models, and the Boost Accumulators library contains efficient incremental descriptive statistical computations on dynamic sets of data that are well suited for keeping track of performance metrics in trading backtests. Each of these is covered in the chapter. Preface | xv
• Chapter 10, “Modules and Concepts” covers two more recent features included in C++20: modules and concepts. Modules unfortunately have gotten off to a slow start, with some compilers only recently nearing completion of their imple‐ mentation. On the other hand, they bring a more modern touch to C++ software design and implementation, with cleaner and safer code, increased productivity, and in some cases reduced compile times. Furthermore, it is my opinion that once modules become more mainstream, they will provide a huge benefit to those learning C++, as they will be able to get up and running more quickly. In contrast, concepts have been quickly adopted by developers and were a long awaited enhancement. Concepts give programmers more control over template programming, particularly pinpointing compile-time errors that in preceding years might be buried among an avalanche of cryptic errors. They also lend clarity to code, in a sense helping it to be better self-documenting. Concepts can be user-defined, while a robust set of predefined concepts, based on C++11 type traits, is provided by the Standard Library as of C++20. • Five appendices are provided at the end of the book for readers who might be interested in a deeper dive into more advanced and historical topics. Conventions Used in This Book The following typographical conventions are used in this book: Italic Indicates new terms, URLs, email addresses, filenames, and file extensions. Constant width Used for program listings, as well as within paragraphs to refer to program elements such as variable or function names, databases, data types, environment variables, statements, and keywords. Constant width italic Shows text that should be replaced with user-supplied values or by values deter‐ mined by context. This element signifies a general note. This element indicates a warning or caution. xvi | Preface
Using Code Examples As you will see, there are numerous code examples throughout the book. These are available for download from GitHub, such that you can compile and run them on your local machine. You are free to use this code as you wish, per the reasonable con‐ ditions of the Mozilla Public License, v. 2.0. Supplemental information to accompany the repository may also be posted from time to time. It is important to note that these code examples are intended to introduce you to modern C++ features and open source libraries, and to show you ways in which you could use them. They are not meant to be simply part of a cookbook or production- ready code. The priority is to help you learn, so that from there you can use the material creatively in your own applications. There is always the chance, especially with the initial release of the software, that it contains errors or inconsistencies, so for this, apologies in advance. If you do run across a problem, please feel free to log an issue on the companion GitHub site. If you have a technical question or a problem using the code examples, please send email to support@oreilly.com. This book is here to help you get your job done. In general, if example code is offered with this book, you may use it in your programs and documentation. You do not need to contact us for permission unless you’re reproducing a significant portion of the code. For example, writing a program that uses several chunks of code from this book does not require permission. Selling or distributing examples from O’Reilly books does require permission. Answering a question by citing this book and quoting example code does not require permission. Incorporating a significant amount of example code from this book into your product’s documentation does require permission. We appreciate, but generally do not require, attribution. An attribution usually includes the title, author, publisher, and ISBN. For example: “Learning Modern C++ for Finance by Daniel Hanson (O’Reilly). Copyright 2025 Daniel Hanson, 978-1-098-10080-3.” If you feel your use of code examples falls outside fair use or the permission given above, feel free to contact us at permissions@oreilly.com. Preface | xvii
O’Reilly Online Learning For more than 40 years, O’Reilly Media has provided technol‐ ogy and business training, knowledge, and insight to help companies succeed. Our unique network of experts and innovators share their knowledge and expertise through books, articles, and our online learning platform. O’Reilly’s online learning platform gives you on-demand access to live training courses, in-depth learning paths, interactive coding environments, and a vast collection of text and video from O’Reilly and 200+ other publishers. For more information, visit https://oreilly.com. How to Contact Us Please address comments and questions concerning this book to the publisher: O’Reilly Media, Inc. 1005 Gravenstein Highway North Sebastopol, CA 95472 800-889-8969 (in the United States or Canada) 707-827-7019 (international or local) 707-829-0104 (fax) support@oreilly.com https://oreilly.com/about/contact.html We have a web page for this book, where we list errata, examples, and any additional information. You can access this page at https://oreil.ly/learningModCPlus Plus_finance. For news and information about our books and courses, visit https://oreilly.com. Find us on LinkedIn: https://linkedin.com/company/oreilly-media. Watch us on YouTube: https://youtube.com/oreillymedia. Acknowledgments I would like to sincerely thank a number of people for their help in completing this book. Patrice Roy was one of the original technical reviewers, but he agreed to stay on to patiently answer a lot of my questions about deeper technical details and matters con‐ cerning proposals that have gone before the ISO C++ committee. He also contributed specific material to Chapters 4, 5, and 6. Ken Adams provided considerable help in xviii | Preface
Comments 0
Loading comments...
Reply to Comment
Edit Comment