Lecture 2: C++ fundamentals with use cases from finance
Introduction to OOP in C++
Ivan Zhdankin
06.06.2021
Cuemacro Lecture 2: C++ fundamentals with use cases from finance 1 / 35
Some Reference for Derivatives Pricing and Monte-Carlo Implementation in
C++
C++ Design Patterns and Derivatives Pricing by Mark S. Joshi
Modern Computational Finance: AAD and Parallel Simulations by Antoine Savine
Curve construction and interpolation link
You can ”fork” my code on Monte-Carlo and Derivatives pricing from gitHub here
Cuemacro Lecture 2: C++ fundamentals with use cases from finance 2 / 35
String
One of the key type in C++ is strings - the collections of characters
String can be words, sentences, user passwords and IDs
C++ has a class which implements string
To use stings we should include it:
#include <string >
We can compare stings, combine them and perform other manipulation
Can search for substring, swap and replace the substrings
The various manipulation include:
I To combine strings: +, + =
I The member functions: length , substr , find
Let us take a look at demo ”String”
Cuemacro Lecture 2: C++ fundamentals with use cases from finance 3 / 35
Vector
Often we need to work with many similar items (of the same type)
I Transactions in an account
I Students in a class
I Trades in a book
In other words we have a collection of items
We can perform different actions on the items in a collection:
I To sum the items
I To average the items
I To sort the items
The Standard Library provides different collections within it
On of the simplest is a vector:
I Holds a number of items of the same type
I Size does not need to be known in advance
I Easy to access a specific items or all of them
Some operations with a vector:
I push back () to add the item
I Type of the item added must match the type of items in a vector
I To access the items we can use [] or iterators begin () and end ()
I Some free functions work with a vector: count () or sort ()
To use a vector we need to include it
# i n c l u d e <vector >
Let us take a look at demo ”Vector”
Cuemacro Lecture 2: C++ fundamentals with use cases from finance 4 / 35
OOP - Object Oriented Programming
C++ is object oriented programming language
C++ is made up not just of functions but also of Classes and Objects
A class defines the template for objects:
I What the object contains?
I What the object can do with anything it contains
Class Student
Member Member
Constructor
Variables functions
Setting initial
values of a Student ID Study
Student
Class DoAssignment
First Name Sleep
Last Name
Current State
Cuemacro Lecture 2: C++ fundamentals with use cases from finance 5 / 35
Class and design
An object is an instance of a class
Function that are inside a class are called member functions
The functions which are not part of a class (discussed so far) are called free or non-member
functions
When we write a class we tell to the compiler what any objects of the class have or can do
I Example of data: a customer has a name, address, email, phone number
I Example of member functions: we can withdraw or debit the account, we can show the balances and
transactions
Keeping the data and what we can do with it together inside a class makes the code easier to
change and use
Let us design a class of Bank account
Account:
I Contains account’s ID number
I Contains Current balance
I Contains list of transaction objects
I Can withdraw and debit some amount of cash
I Can report the balances and the latest transactions
Transaction:
I Holds the date and time of the transaction
I Holds amount and transaction type
I Can report the amount and transaction type
Member function Deposit:
I Create a transaction object
I Add the object to the vector of a transactions
I Update the balances
Cuemacro Lecture 2: C++ fundamentals with use cases from finance 6 / 35
Design into the code
Generally, member variables are private inside the class
The private members are not accessible outside of the class
This is idea of encapsulation - the idea of bundling of data and what we can do with it within one
unit
Functions, you think are important, are normally public - the functions are services that a class can
offer
Public functions are accessible from outside of a class
There are special member functions called constructors:
I Constructors initialize variables
I Name of the contractors is the same as of a class
I Constructors do not have return type (in particular void)
I Constructors can take parameters
The use case for constructors: you should have the transaction amount at the initialization of the
transaction and should not be able to change it
Let us take a look at demo ”Classes”
Cuemacro Lecture 2: C++ fundamentals with use cases from finance 7 / 35
Files
So far we were using only one file for the source code with extension .cpp
Imagine the big organization with code that has several thousands lines
I Requires compiling it all when making small changes
I Difficult to coordinate the work of the developers
I Difficult to find anything in one single file
In practise the code organised in multiple files to resolve those issues
In case of multiple files one has to compile each of the files in to object file and then link them all
using the linker
If we use the other files in our code we need to explicitly tell the compiler about it
Cuemacro Lecture 2: C++ fundamentals with use cases from finance 8 / 35
Header Files
In previous implementation we had to declare the functions and classes before we can use them
Consider the project that has tens of functions and classes, this may become frustrating
We can put all of the declaration in a separate files and then include the file into the code we would
like to compile
The file is called Header file and has extension .h
The directive to include the file would ne: #include
Everything that starts with # will be included into the code by the preprocessor and after that the
whole file will be compiled
As a result your code would look nicer, be more maintainable and easier to understand
Cuemacro Lecture 2: C++ fundamentals with use cases from finance 9 / 35
Organising the code
Typical approach:
I Have one header file per class to explain and declare what is in the class
I Have one implementation file .cpp per class that implements all the functions of a class
Any code that uses the class should include the header file
We should also include the header file in .cpp file that implements the class
We will have a look at demo ”Classes”
Cuemacro Lecture 2: C++ fundamentals with use cases from finance 10 / 35
Inline Functions
In one file (header file .h) we declare the functions and in another one (implementation file .cpp)
we implement the functions of classes
Some functions in a class are obvious
Often the function work with private variables
For such functions it makes sense to implement them in a header file
These functions are called inline
The advantages of using the inline functions is that it can speed up your application
For example we can make current balance function in Account class to be inline
Cuemacro Lecture 2: C++ fundamentals with use cases from finance 11 / 35
Encapsulation
Encapsulation is about how changeable a class is
By default the member variables should be private
We can add public member functions that work with private variables
In some sense such public functions are gatekeepers
Add as few public functions as possible
As a rule of thumb: the more encapsulated, the better
Cuemacro Lecture 2: C++ fundamentals with use cases from finance 12 / 35
Access specifiers
Any member of a class can have it is own access specifier that defines how the member can be
accessed:
Cuemacro Lecture 2: C++ fundamentals with use cases from finance 13 / 35
Creating Instances of a class
A constructor that takes no arguments is called a default constructor
Declare objects with default constructors the same as built in types:
Account a1;
Declare objects with some parameters using ():
Transaction t1 (10 , " Deposit ");
Do not use = when declaring an object and instantiating it
Cuemacro Lecture 2: C++ fundamentals with use cases from finance 14 / 35
Constructors
The objects are initialized by a special function called constructor
The constructor takes parameters that can be used to initialize the member variables
We also can initialize the member values to a default values
The colon introduces initializers
Do not forget the empty braces in case we use lazy initialization
As a reminder from previous slides:
I Name of the contractors is the same as of a class
I Constructors do not have return type (in particular void)
Demo: ”Constructors”
Cuemacro Lecture 2: C++ fundamentals with use cases from finance 15 / 35
Scope
So far we have seen the object created locally
Each object has a lifetime:
I When the line is reached the constructor is called and memory is allocated
I Normally we say that the object is created on the stack (stack semantics)
I The object is then has a scope - it lasts until the close the brace is encountered
I When the close brace is reached, the memory for the object is freed and the another special functions is
called - a destructor
The resources are acquired when the constructors is called and are released when the destructors
are called
In case we do not specify the destructors - there are default destructors
Demo: ”Scope”
Cuemacro Lecture 2: C++ fundamentals with use cases from finance 16 / 35
Struct
One keyword to define your own type is class
There is another keyword to define types - struct
Historically the keyword was used to define plain data
However the struct can have member functions, constructors and destructors and everything else
that a class has
The only difference is that if we do not specify the access specifiers, by default it is public
However when we need some business logic and some member functions people use classes
Cuemacro Lecture 2: C++ fundamentals with use cases from finance 17 / 35
Namespaces
When you have a lot of code it is impossible to code it without namespaces
They are designed to prevent name collisions
You separate the namespaces using ::
Example std :: string
It enables me to have my own string class which is different from the standard string class
We can code full name of the class we specified however there is a simpler syntax for this
Demo: Namespaces
Cuemacro Lecture 2: C++ fundamentals with use cases from finance 18 / 35
Inheritance
Inheritance is key to OOP design
In C++ we can have Base classes and Derived from them
Derived classes can add or override member variables or functions
As an example we can consider different valuation function:
Class Valuation
Function
Class Fixed Class FX
Class Call Option
Coupon Bond Forward
Cuemacro Lecture 2: C++ fundamentals with use cases from finance 19 / 35
Inheritance
We are indicating with colon that we are inheriting from something else:
class Account : public Customer {}
Inside the brackets we declare only what we are adding or overriding from the Base class
If we override we provide a special implementation of something that is in a Base class
In general the implementation of Derived classes is of no difference as compared to Base classes
However the constructors are different: we need to pass some parameters to the base class for
initialization
Account ( string first , string last , int ID , string type )
Customer (first , last , ID), acctype (tp ){}
Demo: Inheritance
Cuemacro Lecture 2: C++ fundamentals with use cases from finance 20 / 35
Enumerations
Enumerations have keyword enum and give names to a set of constants
For example you can have a function that return a status:
I 1 if approved
I 0 if cancelled
I 2 if pending
It is easy to forget what do these numbers mean
We can give names to the numbers using enumerations
Demo: Enum
Cuemacro Lecture 2: C++ fundamentals with use cases from finance 21 / 35
PreProcessor
Include statements starts with #
This is a command for the another part of the building system, which is called preprocessor
The preprocessor control what is compiled
I Controls that a header s compiled inside the source files
I Controls part of standard library to be compiled
There a special command #pragmaonce used by the preprocessor
If we include several header files, we can redefine some of the classes causing the compiler errors
We do not want the thing to be included multiple times
One of the way to get rid of this problem just to include #pragmeonce in every header filer and
compile will cope with a problem for you
Cuemacro Lecture 2: C++ fundamentals with use cases from finance 22 / 35
Free Functions
So far we have seen different functions: free functions, constructors, member functions
The following function takes the parameter by values
double total_balance ( Account a1 , Account a2)
It creates its own copy of the variable to work with it inside the function
If something is changed inside the function the variable itself is not changed in this case
If is possible to take a parameter by reference
double total_balance ( Account & a1 , Account & a2)
If we have a line of the parameter that changes it the function also changes the variable
Demo: Free function
Cuemacro Lecture 2: C++ fundamentals with use cases from finance 23 / 35
Member Functions
We declare the member function in a class, we can also declare it in a header file
If we implement the member function in cpp we use the full name:
Account :: GetName ()
We cam implement the function in a header file to make it inline
Member functions should be mark as const unless it is going to change a member variable
const member functions mean that they do not change any variable in a class
This is useful information for both compilers and developers
Demo: Member Function
Cuemacro Lecture 2: C++ fundamentals with use cases from finance 24 / 35
Interview Questions
Describe the concept of encapsulation?
What is inline function?
What is the difference between free and member functions?
What is a class and object?
Cuemacro Lecture 2: C++ fundamentals with use cases from finance 25 / 35
Interview Questions
What are the constructors?
What is the use of Inheritance in OOP?
Can a class inherit from multiple classes in C++?
Cuemacro Lecture 2: C++ fundamentals with use cases from finance 26 / 35
Interview Questions
What is the output of the following program:
# include <iostream >
using namespace std;
class Rect{
int x, y;
public :
void set_values (int ,int );
int area (){
return (x * y);
}
};
void Rect :: set_values (int a, int b) {
x = a;
y = b;
}
int main (){
Rect recta , rectb ;
recta . set_values (5, 6);
rectb . set_values (7, 6);
cout << " recta area: " << recta .area ();
cout << " rectb area: " << rectb .area ();
return 0;
}
Cuemacro Lecture 2: C++ fundamentals with use cases from finance 27 / 35
Interview Questions
What is the output of the following program:
#include <iostream >
using namespace std;
class BaseClass1 {
public :
Base1 ()
{ cout << " BaseClass1 constructor " << endl; }
};
class BaseClass2 {
public :
Base2 ()
{ cout << " BaseClass2 constructor " << endl; }
};
class DerivedClass : public BaseClass1 , public BaseClass
public :
Derived ()
{ cout << " DerivedClass constructor " << endl; }
};
int main ()
{
Derived d;
return 0; }
Cuemacro Lecture 2: C++ fundamentals with use cases from finance 28 / 35
Closed Form Pricing
Various methods can be applied to price instruments:
I Monte-Carlo Simulation: suitable for exotic payoffs
I Closed form: suitable for simple payoffs
Closed form pricers are pricers that produce price from a function that implements a certain
formula for pricing
For scalability we can create class ”ValuationFunction” which serves as a template for all of the
pricing functions
Cuemacro Lecture 2: C++ fundamentals with use cases from finance 29 / 35
Implementing Bond Valuation Function
The bond can be defined by the following attributes that can be taken into constructor:
I Identifier
I Nominal
I Yield
I FaceValue
I Coupon Rate (Fixed)
I Coupon Frequency
I TTM
Dirty Price includes accrued interest rate:
i =9
Pdirty = ∑ e −yield ∗TimeToCoupon[i ] ∗ coupon ∗ faceValue
i =0
+e −yield ∗TimeToCoupon[10] ∗ (1 + coupon ) ∗ faceValue
accruedInterest = timeToNextCoupon ∗ coupon ∗ faceValue
Clean Price does not include accrued interest rate
Pclean = Pdirty − accruedInterest
Cuemacro Lecture 2: C++ fundamentals with use cases from finance 30 / 35
Implementing Bond Valuation Function
Bond Valuation class structure
Cuemacro Lecture 2: C++ fundamentals with use cases from finance 31 / 35
Implementing FX Forward Valuation Function
The bond can be defined by the following attributes that can be taken into constructor:
I Identifier
I Nominal
I SpotFXrate
I ratedomestic
I rateforeign
I Strike (ForwardFXrate at time zero)
I TTM
FXForward Valuation is implemented in ValueInstrument method
The relationship between SpotFXrate and ForwardFXrate at the start of FX forward is:
ForwardFXrate0 = SpotFXrate0 ∗ e (ratedomestic −rateforeign )TTMfactor
That is the price of FX forward at time t is given by [John C. Hull ”Options, Futures and Other
Derivatives” for reference]:
SpotFXrate ∗ e −ratedomestic TTMfactor − Strike ∗ e −rateforeign TTMfactor
Cuemacro Lecture 2: C++ fundamentals with use cases from finance 32 / 35
Implementing FX Forward Valuation Function
FX Forward Valuation class structure
Cuemacro Lecture 2: C++ fundamentals with use cases from finance 33 / 35
Implementing Call Option Valuation Function
The Call Option can be defined by the following attributes that can be taken into constructor:
I Identifier
I Nominal (N)
I SpotPrice (S)
I interestRate (r)
I dividendRate (d)
I impliedVol (σ)
I Strike (K )
I TTM (t)
Call Option Valuation is implemented in ValueInstrument method
The option price is derived from Black-Scholes model as follows:
Pcall −option = N (Se −dt N (d1 ) − Ke −rt N (d2 ))
Where
Rx 1 2
I N (x ) = √1
−∞ e− 2 z dz
h2π i
1 S σ2
I d1 = σ
√
t
ln K
+t r + 2
h i
1 S σ2
I d2 = σ
√
t
ln K
+t r − 2
Cuemacro Lecture 2: C++ fundamentals with use cases from finance 34 / 35
Implementing Call Option Valuation Function
Call Option Valuation class structure
Cuemacro Lecture 2: C++ fundamentals with use cases from finance 35 / 35