37
An Introduction to C++ Dave Klein Research Analyst Credit Derivatives Research LLC

An Introduction to C++ Dave Klein Research Analyst Credit Derivatives Research LLC

Embed Size (px)

Citation preview

Page 1: An Introduction to C++ Dave Klein Research Analyst Credit Derivatives Research LLC

An Introduction to C++

Dave KleinResearch Analyst

Credit Derivatives Research LLC

Page 2: An Introduction to C++ Dave Klein Research Analyst Credit Derivatives Research LLC

2

Two Grooks

Problems worthy of attack,prove their worth by hitting back.

------

Shun advice at any price, that's what I call good advice.

Piet Hein

Page 3: An Introduction to C++ Dave Klein Research Analyst Credit Derivatives Research LLC

3

This Session

Overview of C++ Program syntax Classes Pointers Arrays Strings

Using Numerical Recipes Integrating with your project Sample program – Geometric Brownian Motion (if time)

Next Session – using C++ to model a derivative

Page 4: An Introduction to C++ Dave Klein Research Analyst Credit Derivatives Research LLC

4

Things we won’t cover

Object-oriented Design / Programming The “right” way to do anything

Software developers are fond of having “religious” discussions

In the MFE, there is no time Professional-level programming practice

Page 5: An Introduction to C++ Dave Klein Research Analyst Credit Derivatives Research LLC

5

C++ Overview

C++ is about 25 years old Originally created as a successor to C

C was created about 35 years ago as a more generic assembly language

C++ is a very “big” language It has many, many features Recommendation: during MFE program, only use

fundamental language features Unless you are an expert, avoid constructs like templates,

polymorphism, operator overloading, multiple inheritance

Page 6: An Introduction to C++ Dave Klein Research Analyst Credit Derivatives Research LLC

6

C++ Overview con’t

C++ is a “dangerous” language It is easy to introduce bugs It is often difficult to track them downTip: build and test your programs

incrementally

Page 7: An Introduction to C++ Dave Klein Research Analyst Credit Derivatives Research LLC

7

Language Features – Program Syntax Program Syntax

Functions / methodsLoopsConditional statements

Hopefully, syntax is not completely new to you. If it is, think about using a more familiar computer language.

Page 8: An Introduction to C++ Dave Klein Research Analyst Credit Derivatives Research LLC

8

...// this is a comment

int myFirstFunction(int a, int b, double c){ int rc = a + b + c;

return rc;}...

Program Syntax (con’t)

Functions

Function nameFunction return type

The function’s code

Return the value

Page 9: An Introduction to C++ Dave Klein Research Analyst Credit Derivatives Research LLC

9

Program Syntax (con’t)

For loop

Do loop

...for (int i = 0; i < 100; i++){ ... do something ...}...

...i = 0;do{ ... do something ... i++;} while (i < 100);…

Page 10: An Introduction to C++ Dave Klein Research Analyst Credit Derivatives Research LLC

10

Program Syntax (con’t)

If statement...if (i == 10){ .. do something ..} else { .. do something else}...

IMPORTANT: Note the double equal signs (==) to test for equality

Page 11: An Introduction to C++ Dave Klein Research Analyst Credit Derivatives Research LLC

11

Classes

Classes provide the basic data/code organization construct within C++

Classes are (roughly) comprised of two parts: Data members (properties) Code members (methods)

Class support inheritance – we don’t have time to cover this Recommendation – if you are not familiar with

inheritance, do not try to learn how to use it during the MFE

Page 12: An Introduction to C++ Dave Klein Research Analyst Credit Derivatives Research LLC

12

Classes (con’t)class myFirstClass{public:// Some properties int integerProperty; double floatingPointProperty; char characterArray[254];

// some methods // a constructor myFirstClass() { integerProperty = 12; floatingPointProperty = 25.2; strcpy(characterArray, "yo yo yo"); }

// a destructor virtual ~myFirstClass() { }

void doSomething() { ... some code would go here ... }};

Page 13: An Introduction to C++ Dave Klein Research Analyst Credit Derivatives Research LLC

13

Classes con’t

There are other features to classes including: Information hiding (public, protected, private)Virtual functions

They are extremely powerful and useful, but now is not the time to play with these.

Page 14: An Introduction to C++ Dave Klein Research Analyst Credit Derivatives Research LLC

14

Classes con’t

Classic interview question: What is the difference between a class and an object?

Better interview question: Can an object ever be a class?

Page 15: An Introduction to C++ Dave Klein Research Analyst Credit Derivatives Research LLC

15

Pointers

Pointers are a special type of variable Pointers hold the address of data, not the

data Pointers must be assigned values before

they can be used.

Page 16: An Introduction to C++ Dave Klein Research Analyst Credit Derivatives Research LLC

16

Pointers (con’t)

Pointers are a special type of variable Pointers hold the address of data, not the data

...

int a1; // a1 is not a pointer

int *a2; // a2 is a pointer

a1 = 10;a2 = &a1; // a2 now points to a1

*a2 = 5; // we ‘dereference’ a2 to assign a value

printf("%d %d\n", a1, *a2); // what will this print?

...

Page 17: An Introduction to C++ Dave Klein Research Analyst Credit Derivatives Research LLC

17

Pointers (con’t)

Be very careful with pointers Someone once estimated that 90% of all C++

bugs can be traced back to bad pointers

Page 18: An Introduction to C++ Dave Klein Research Analyst Credit Derivatives Research LLC

18

Memory Allocation / Arrays

C++ supports both statically and dynamically allocated arrays

If you dynamically allocate an array, make sure to deallocate it when you are done using it.Make sure you are really done using it before

you deallocate!

Page 19: An Introduction to C++ Dave Klein Research Analyst Credit Derivatives Research LLC

19

Memory Allocation / Arrays (con’t)

...

int myArray[10]; // this is statically allocated array

for (int i = 0; i < 10; i++){ // Assign a value to each member of the array // Notice that the array is 'referenced' from 0 to 9 // Arrays in C++ 'start' at 0 myArray[i] = i * i + 1;}

...

Page 20: An Introduction to C++ Dave Klein Research Analyst Credit Derivatives Research LLC

20

Memory Allocation / Arrays (con’t)

...

// this is dynamically allocated array// it looks suspiciously like a pointer!int *myArray;

// first we allocate itmyArray = new int[10];

// this is what a for loop looks likefor (int i = 0; i < 10; i++){ // Assign a value to each member of the array // Notice that the array is 'reference' from 0 to 9 // Arrays in C++ 'start' at 0 myArray[i] = i * i + 1;}

// now we deallocate itdelete[] myArray;

...

Page 21: An Introduction to C++ Dave Klein Research Analyst Credit Derivatives Research LLC

21

Memory Allocation / Arrays con’t

Question: when should you dynamically allocate an array?

When should static allocation be used?

Page 22: An Introduction to C++ Dave Klein Research Analyst Credit Derivatives Research LLC

22

Strings (or lack thereof)

C++ does not have a standard string class There is a string class within the Standard Template

Library (STL) Unless you know how to use the STL, ignore it for this

term Recommendation: for output, debugging purposes –

learn how to use printf, sprintf, fprintf The ‘classic’ way of handling strings is to treat them

as arrays of char’s. Then use strcpy, strcmp, etc.

Page 23: An Introduction to C++ Dave Klein Research Analyst Credit Derivatives Research LLC

23

Strings (or lack thereof) – printf()

printf() enables the formatting of character data

printf(format_string, data1, data2, …)Example:

printf(“This is a %s %d %lf test\n”, “printing”, 2, 5.005)

Produces: This is a printing 2 5.005 test<lf>

Page 24: An Introduction to C++ Dave Klein Research Analyst Credit Derivatives Research LLC

24

Using Numerical Recipes

There are many numerical libraries available Numerical Recipes for C++ is easy to use DO NOT RE-INVENT THE WHEEL

If you do not have NR, search on-line for numerical class libraries

Do not write your own random-number generator Do not write your own matrix classes Do not implement complex numerical algorithms if there are

“canned” routines already available Exception: if the goal of a homework assignment is to implement

an algorithm.

Page 25: An Introduction to C++ Dave Klein Research Analyst Credit Derivatives Research LLC

25

Using Numerical Recipes con’t

Warning: there are “Numerical Recipes” books for FORTRAN, C, C++, etc.

Each one is slightly different NR originally implemented in FORTRAN C & C++ versions different enough from

each other to cause problemsFor example, arrays in C version are handled

differently than in C++ version

Page 26: An Introduction to C++ Dave Klein Research Analyst Credit Derivatives Research LLC

26

Using Numerical Recipes con’t

Three different ways to add NR to your project1. Recommended : copy the files you need (including

nr.h) to your project directory and add the cpp files to your project

2. Build a static library or DLL with all the NR routines in them

3. Copy the code directly from the NR files into your code files

Page 27: An Introduction to C++ Dave Klein Research Analyst Credit Derivatives Research LLC

27

Using Numerical Recipes con’t

Example: Using an NR random number generator

Problem: Want standard normal pseudorandom variable

Solution: use gasdev() from NR

Page 28: An Introduction to C++ Dave Klein Research Analyst Credit Derivatives Research LLC

28

Using Numerical Recipes con’t

#include <time.h>#include "nr.h"

...

// let's generate 100 standard normal variablesdouble normals[100];

// seed the random number generatorint idum = -time(NULL);

for (int i = 0; i < 100; i++){ normals[i] = NR::gasdev(idum); }

...

Page 29: An Introduction to C++ Dave Klein Research Analyst Credit Derivatives Research LLC

29

Putting it All Together – A Geometric Brownian Motion Class We want to:

Model drift, diffusionReuse the same object over and over to

generate different paths

Page 30: An Introduction to C++ Dave Klein Research Analyst Credit Derivatives Research LLC

30

GBM con’t

Our class properties m_nSInitial – the initial security value (constant) m_nDrift – the drift term (constant) m_nSigma – our volatility term (constant) m_nCurrentTime – the current ‘time’ in our simulation m_nSCurrent – the current security value

Our class methods CGBMotion - our constructor void step – moves time forward double getCurrentValue – returns m_nSCurrent void reset - resets current time & security value

Page 31: An Introduction to C++ Dave Klein Research Analyst Credit Derivatives Research LLC

31

Code #include <math.h>#include "nr.h"

class CGBMotion{public: // our properties

int m_nIdum; // used by NR::gasdevdouble m_nSInitial; // initial security value (constant)double m_nDrift; // our drift (constant)double m_nSigma; // our volatility (constant)double m_nCurrentTime; // the current elapsed timedouble m_nCurrentDiffusion; // how much the process has diffused

Page 32: An Introduction to C++ Dave Klein Research Analyst Credit Derivatives Research LLC

32

Code con’t . . . public:// our constructorCGBMotion(double nSInitial, double nDrift, double nSigma, int seed){

m_nSInitial = nSInitial;m_nDrift = nDrift;m_nSigma = nSigma;m_nCurrentTime = 0;m_nCurrentDiffusion = 0;m_nIdum = seed;

}

Page 33: An Introduction to C++ Dave Klein Research Analyst Credit Derivatives Research LLC

33

Code con’t . . .

void step(double nTime){ double nDeltaT = nTime - m_nCurrentTime; // how much time has elapsed? if (nDeltaT > 0) {

// some time has elapsed// add to our diffusion relative to sqrt of elapsed timem_nCurrentDiffusion += sqrt(nDeltaT) * NR::gasdev(m_nIdum);

// update our current timem_nCurrentTime = nTime;

}}

Page 34: An Introduction to C++ Dave Klein Research Analyst Credit Derivatives Research LLC

34

Code con’t . . .

double getCurrentValue(){

return m_nSInitial * exp(m_nDrift*m_nCurrentTime - .5* m_nSigma * m_nSigma*m_nCurrentTime + m_nSigma*m_nCurrentDiffusion)

);}

double reset(){

m_nCurrentTime = 0;m_nCurrentDiffusion = 0;

}

};

Page 35: An Introduction to C++ Dave Klein Research Analyst Credit Derivatives Research LLC

35

GBM Sample Programint main(int argc, char* argv[]){ CGBMotion oGBM(100.0, .05, .2, -10); // our brownian motion object

// run 10000 simulations for (int i = 0; i < 10000; i++) { double t = 0; oGBM.reset();

// run 100 time steps for (int j = 0; j < 100; j++) { t = t + .01; oGBM.step(t); }

// print the results printf("%02d: Simulated value %lf\n", i, oGBM.getCurrentValue()); }

return 0;}

Page 36: An Introduction to C++ Dave Klein Research Analyst Credit Derivatives Research LLC

36

3 Great Resources

Wikipedia: http://www.wikipedia.org Wilmott: http://www.wilmott.com Google (of course) :

http://www.google.com

Page 37: An Introduction to C++ Dave Klein Research Analyst Credit Derivatives Research LLC

37

Questions / Discussion