lecture 14 - purdue university - department of statistics ... · pdf fileoutline 1 some other...
TRANSCRIPT
Lecture 14
Xiaoguang Wang
STAT 598W
March 11th, 2014
(STAT 598W) Lecture 14 1 / 36
Outline
1 Some other terms: Namespace and Input/Output
2 Armadillo C++
3 Application
(STAT 598W) Lecture 14 2 / 36
Outline
1 Some other terms: Namespace and Input/Output
2 Armadillo C++
3 Application
(STAT 598W) Lecture 14 3 / 36
Namespace
Namespaces allow to group entities like classes, objects and functionsunder a name.
Format:
namespace identifier
{
entities
}
identifier: any valid identifier;entities: the set of classes, objects and functions that are includedwithin the namespace.
(STAT 598W) Lecture 14 4 / 36
Namespaces
Example:
namespace myNamespace
{
int a, b;
}
To access the previous variables from outside myNamespace we canwrite:
myNamespace::a
myNamespace::b
(STAT 598W) Lecture 14 5 / 36
Namespaces: Example
The functionality of namespaces is especially useful in the case that thereis a possibility that a global object or function uses the same identifier asanother one, causing redefinition errors.
Example:
// namespaces
#include <iostream>
using namespace std;
namespace first
{
int var = 5;
}
(STAT 598W) Lecture 14 6 / 36
Namespaces: Example (Continued)
namespace second
{
double var = 3.1416;
}
int main () {
cout << first::var << endl;
cout << second::var << endl;
return 0;
}
(STAT 598W) Lecture 14 7 / 36
Key Word Using: Example 1
The keyword using is used to introduce a name from a namespace into thecurrent declarative region.
Example:
// using
#include <iostream>
using namespace std;
namespace first
{
int x = 5;
int y = 10;
}
(STAT 598W) Lecture 14 8 / 36
Key Word Using: Example 1 (Continued)
namespace second
{
double x = 3.1416;
double y = 2.7183;
}
int main () {
using first::x;
using second::y;
cout << x << endl;
cout << y << endl;
cout << first::y << endl;
cout << second::x << endl;
return 0;
}
(STAT 598W) Lecture 14 9 / 36
Key Word Using: Example 2
The keyword using can also be used as a directive to introduce an entirenamespace.
Example:
// using
#include <iostream>
using namespace std;
namespace first
{
int x = 5;
int y = 10;
}
(STAT 598W) Lecture 14 10 / 36
Key Word Using: Example 2 (Continued)
namespace second
{
double x = 3.1416;
double y = 2.7183;
}
int main () {
using namespace first;
cout << x << endl;
cout << y << endl;
cout << second::x << endl;
cout << second::y << endl;
return 0;
}
(STAT 598W) Lecture 14 11 / 36
Key Word Using: Example 3
using and using namespace have validity only in the same block in whichthey are stated or in the entire code if they are used directly in the globalscope.
Example:
// using namespace example
#include <iostream>
using namespace std;
namespace first
{
int x = 5;
}
(STAT 598W) Lecture 14 12 / 36
Key Word Using: Example 3 (Continued)
namespace second
{
double x = 3.1416;
}
int main () {
{ using namespace first;
cout << x << endl;}
{ using namespace second;
cout << x << endl;}
return 0;
}
(STAT 598W) Lecture 14 13 / 36
Namespaces
Namespace alias: We can declare alternate names for existingnamespaces according to the following format:
namespace new_name = current_name;
Namespace std: All the files in the C++ standard library declare all ofits entities within the std namespace. That is why we have generallyincluded the using namespace std.
(STAT 598W) Lecture 14 14 / 36
File Input and Output
The fstream header includes the following classes:
ofstream : Stream class to write on files
ifstream : Stream class to read from files
fstream : Stream class to both read from and write on files
Once an object of one of the above classes types is declared andassociated with a file, it can be used with the insertion operator � or theextraction operator � in much the same way as cout or cin.
(STAT 598W) Lecture 14 15 / 36
Example: Basic file operations
#include<fstream>
using namespace std;
int main(){
ofstream myfile;
myfile.open ("example.txt");
myfile << "Writing this to a file.\n";
myfile.close();
return 0;
}
(STAT 598W) Lecture 14 16 / 36
Opening the file
The line:
myfile.open ("example.txt");
opens a file called example.txt and assigns to it the output streamobject myfile.
The ”open” function can take a second argument, the mode, whichhelps determine its behaviour. Each stream class has the mode set bydefault if no second argument is given.
Warning: When I ran it, the ofstream overwrote the file each time. Ifwe had just wanted to append text to the end of the file, we wouldneed to specify the mode when we open the file as
myfile.open ("example.txt", ios::app);
If the program fails to open the file, it may not explicitly give anerror. We can check whether it was successful by using
myfile.is_open()
which will return true if and only if myfile currently corresponds to anopen file.
(STAT 598W) Lecture 14 17 / 36
Data input and output
Additionally, fstream objects also come with several boolean functionsto help control data flow and detect errors.
bad() : Returns true if read/write operation fails.fail() : Returns true if read/write operation fails, or if a formattingerror occurs.eof() : Returns true if read operation has reached the end of the file.good() : Returns false if any of the above is true.
Once finished, you should always close the file with the close()function. In the case of an output stream, text isnt written to the fileimmediately when you write to the stream, but rather is stored in abuffer. The call to close() signals the program to finish writing to thefile.
(STAT 598W) Lecture 14 18 / 36
Another Example for reading data
#include <iostream>
#include <fstream>
#include <string>
using namespace std;
int main () {
string line;
ifstream myfile ("example.txt");
if (myfile.is_open())
{ while ( getline (myfile,line) )
{
cout << line << ’\n’;
}
myfile.close();
}
else cout << "Unable to open file";
return 0;
} (STAT 598W) Lecture 14 19 / 36
Outline
1 Some other terms: Namespace and Input/Output
2 Armadillo C++
3 Application
(STAT 598W) Lecture 14 20 / 36
Introduction
Developed by the National Information and CommmunicationsTechnology of Australia (NICTA) and from contributions around theworld. (Conrad Sanderson)
GNU Software.
C++ linear algebra library that outperforms NEWMAT and IT++ inspeed and ease of use.
Armadillo aims to replicate most of the MATLAB’s operations withinC++.
(STAT 598W) Lecture 14 21 / 36
C-make installation
We need to install cmake first:http://www.cmake.org/cmake/resources/software.html.
Download cmake-2.8.10.2.tar.gz in your home directory.
Extract the installation files:
tar xzf cmake-2.8.10.2.tar.gz
Create a new folder in your home directory (say ~/opt) in order tocontain library and header files.
Go to the installation folder and type:
./bootstrap --prefix=~/opt
make
make install
(STAT 598W) Lecture 14 22 / 36
Installation
Download the most current version of Armadillo(http://arma.sourceforge.net/download.html) in your homedirectory.
Follow the installation procedures in the same webpage (depending onyour operating system). In class we will perform the most basicinstallation of Linux (without using LAPACK and BLAS libraries).
Untar the installation file:
tar xzf armadillo-3.800.0.tar.gz
Go to the installation folder and type:
~/opt/bin/cmake .
make
make install DESTDIR=~/opt
(STAT 598W) Lecture 14 23 / 36
Example 1
#include <iostream>
#include "armadillo"
using namespace std;
using namespace arma;
int main()
{
mat A = randu<mat>(4,5);
mat B = randu<mat>(4,5);
cout << A*trans(B) << endl;
return 0;
}
Run it as (assume the code file named as ”name.cpp” and the outputnamed as ”name”):
g++ -Wall -g -I ~/opt/usr/include name.cpp -o name -O2
(STAT 598W) Lecture 14 24 / 36
Matrix class
See http://arma.sourceforge.net/docs.html for more details.
mat type: matrix containing double or integer numbers.
It admits several constructors: mat(), mat(n_rows,n_cols), etc.
Matrix attributes: .n_rows(), .n_cols(), .n_elem().
The elements are accessed and assigned with (i,j) operator. Notethat the index starts at 0.
Element injection: A << 1 << 2 << 3 << endr;
(STAT 598W) Lecture 14 25 / 36
Some operators
Overloaded operators: +,-,*,%,==,¿=,!=.
.trans():transpose, eye(): set an identity matrix.
Cholesky decomposition: chol(mat M).
You can save memory declaring upper and lower triangular matrices:trimatu and trimatl.
Extract columns or rows from a matrix: A.col(k), A.row(k).
(STAT 598W) Lecture 14 26 / 36
Exercise
Armadillo has the function .randn() to generate standard normalrandom variables.
Generate samples of a multivariate normal random vector with meanµ and covariance matrix Σ, where Σ is positive definite.
If you don’t have LAPACK installed (e.g. “expert” server), let’sassume we have L such that Σ = LLT .
(STAT 598W) Lecture 14 27 / 36
A good tutorial document
To learn more about Armadillo, another good material apart from itsofficial website is the document from the following link:
http://www.ngssc.se/courses/specialized-courses
/advanced-programming/cpp_part3_v2.pdf
(STAT 598W) Lecture 14 28 / 36
Outline
1 Some other terms: Namespace and Input/Output
2 Armadillo C++
3 Application
(STAT 598W) Lecture 14 29 / 36
MonteCarlo simulation
In the Black-Scholes model we assume that the underlying assetfollows a geometric Brownian motion:
dSt = µStdt + σStdWt
where µ and σ > 0 are constants, Wt is a standard Brownian Motionand S0 = s.
Using Ito formula, the previous SDE admits the solution:
St = se
(µ−σ2
2
)t+σWt
(STAT 598W) Lecture 14 30 / 36
MonteCarlo simulation
Under the risk-neutral measure (Q) we can simulate an entire path ofSt with the following scheme:
Si+1 = Si exp (r − σ2
2)δt + σ
√δtεi+1
where S0 = s and ε. ∼ N(0, 1) (iid)
Then given a payoff function Φ(·), the price of a derivative with suchpayoff at time 0 is:
Π = EQ [e−rTΦ(ST )]
(STAT 598W) Lecture 14 31 / 36
MonteCarlo Simulation
Then we can use the estimate:
Π̂ =1
M
M∑i=1
e−rTΦ(ST (i))
where ST (i) is the i-th sample path in our simulation.
We can reduce the variance in our simulation by using antitheticvariates.
(STAT 598W) Lecture 14 32 / 36
Variance improvements
Improve your rate of convergence by using antithetic variables: usexi ∼ N(0, 1) and −xi to simulate the GBM and compute (for eachone) the simulated price. Then take the average price of bothsimulations.
You can improve the rate of convergence using control variates aswell.
(STAT 598W) Lecture 14 33 / 36
Exercise
Construct a namespace called “BS” (Black Scholes). It will includethe following classes:
A base class (Black-Scholes European)(BSEur) with the followingmembers:
Constructors.Destructor.Parameters: S ,K , r , σ,T and type of option.Black Scholes price.Function that displays the price on the screen.
A derived class from BSEur (say MCarlo) with the followingmembers:
Constructors.Destructor.Parameters: number of iterations.MonteCarlo price.Function that displays the price on the screen.
(STAT 598W) Lecture 14 34 / 36
Exercise
A derived class from Mcarlo (say MCAnti) with the followingmembers:
Constructors.Destructor.MonteCarlo price (using Antithetic variables).Function that displays the price on the screen.
Test your code in C++.
Implement your class in R using Rcpp, and compare the samplingdistribution of your two estimates.
(STAT 598W) Lecture 14 35 / 36
Some recomendations
Use Armadillo for your random number generation.
Don’t forget to define your derived-class constructors as inlinefunctions.
(STAT 598W) Lecture 14 36 / 36