Lecture 13 (25 Dec)

Pointers, Call by value, Call by reference, Polymorphism (same name, different functions by arguments)
#include <iostream>
using namespace std;

void fun(int *pa) {
	*pa = 3;
}

void fun(int a) {
	a = 9;
}

int main() {
	int a = 5;
	int *p;

	p = &a;
	cout << a << endl;
	// Output: 5
	*p = 2;
	cout << a << endl;
	// Output: 2
	fun(&a);  // Call by reference
	cout << a << endl;
	// Output: 3
	fun(a);   // Call by value
	cout << a << endl;
	// Output: 3  (not 9)
}

Files, Reading and writing formatted text.
#include <iostream>
#include  <fstream>
using namespace std;
// Reads real numbers from an ascii file, omits characters and writes numbers*3 to a new ascii file, one number per line
int main () {
	double d; char c;

	filebuf fb;
	fb.open ("C:\\usr\\cemgil\\tex\\bogazici\\courses\\fe\\myworkspace\\dosyaoku\\test3.txt",ios::in);
	istream is(&fb);

	ofstream outfile;
	outfile.open("C:\\usr\\cemgil\\tex\\bogazici\\courses\\fe\\myworkspace\\dosyaoku\\test4.txt");

  while (!is.eof()) {
    is >> d; // Read a double 
    if (is.fail()) { is.clear(); is >> c; cout << c; } // Discard invalid characters
    else {
    if (!is.eof()) {
    	cout << d << endl;
    	outfile << d*3;
    	outfile.put ('\n');
    }
    }
  };

  outfile.close();

  return 0;
}

Reference variables, Call by reference.
#include <iostream>
using namespace std;

void fun(int& ar)
{
	ar = 2;
}

int main() {
	int a = 3;
	int b = 7;
	int& r = a; // r is an alias of, must be initialised during declaration

	r = a;
	r = 12;
	cout << a << endl;

	r = b;
	cout << a << endl;
	r = 4;
	cout << a << endl;
	cout << b << endl;

	fun(b);
	cout << b << endl;


	return 0;
}

Lecture 12 (18 Dec)

Lecture 11 (11 Dec)

Lecture 10 (4 Dec)

Lecture 9 (27 Nov)

Lecture 8 (20 Nov)

Lecture 7 (13 Nov)

Lecture 6 (6 Nov)

Option Pricer object
#include <iostream>
#include <cmath>
#include <cstdlib>
#include <algorithm>
#include "nr3_psplot.h"

using namespace std;

// Uniform [0,1] , Warning: cstdlib::rand() is not very reliable
inline double Rand() {return double(rand())/(RAND_MAX+1);};
const double pi = 3.14159265358979323846;
// Box-Muller Transform method, Warning: this implementation is not very efficient
inline double Randn(){return (-2*log(1-Rand())) * cos(2*pi*Rand());};

class OptionPricer {
	double r;
	double sigma;

	double Pricer(double S0, // Current price
                  double K,  // Strike Price
                  double T,  // Expiry time
                  bool isCall = true
			)
	{
		int MAX_ITER = 1000000;
		double ST, CT, W;
		double EC = 0;

		for (int i=1; i<=MAX_ITER; i++) {
			W = sqrt(T)*Randn();
			ST = S0*exp((r - sigma*sigma/2)*T + sigma*W);

			CT = isCall ? ST-K : K-ST;
			if ( CT<0) CT = 0.;
			EC = 1./i * CT + double(i-1)/i*EC;
		};

		return exp(-r*T)*EC;
	}

public:
	OptionPricer(double InterestRate, double stdVol) {
		r = InterestRate;
		sigma = stdVol;
	};

	void Print() {
		cout << "InterestRate: " << r << endl;
		cout << "Volatility: " << sigma << endl;
		return;
	}

	double CallPrice(double CurrentPrice,
			         double StrikePrice,
			         double ExpiryDate)
	{
		return Pricer(CurrentPrice,
					  StrikePrice,
					  ExpiryDate,
					  true
				);
	};

	double PutPrice(double CurrentPrice,
			         double StrikePrice,
			         double ExpiryDate)
	{
		return Pricer(CurrentPrice,
					  StrikePrice,
					  ExpiryDate,
					  false
				);

	}

};

int main() {
	double S0 = 100;
	double K = 100;
	double rate = 0.01;
	double stdVol = 0.01;

	int I = 100;
	double dt = 0.1;
	OptionPricer o1(0.03, 0.1);
	vector <double> t(I);
	vector <double> CallPrice(I);
	vector <double> PutPrice(I);


	o1.Print();
	cout << endl;
	for (int i=0;i < I; i++) {
		t[i] = i*dt;
	 	CallPrice[i] = o1.CallPrice(S0, K, t[i]);
	 	PutPrice[i] = o1.PutPrice(S0, K, t[i]);
	 	cout << i << endl;
	};

	double maxCall = *max_element(CallPrice.begin(), CallPrice.end());

	PSpage pg("plot.ps");
	PSplot plot1(pg,100.,500.,100.,300.);
	plot1.setlimits(0, *max_element(t.begin(), t.end()), 0, maxCall );
	plot1.frame();
	plot1.scales(1, dt, maxCall, maxCall/10, 2, 2, 0, 0);
	plot1.xlabel("Expiry");
	plot1.ylabel("Price");
	plot1.lineplot(t, CallPrice);

	for (int i=0; i< I; i++) plot1.dot(t[i], CallPrice[i], 5.);
	for (int i=0; i< I; i++) plot1.pointsymbol(t[i], PutPrice[i], 109, 5.);


	pg.close();
	return 0;
}

Option Pricer function
#include  <iostream>
#include  <cmath>
#include  <cstdlib>

using namespace std;

double sigma = 0.1;
double r = 0.1;
double T = 1;
double S0 = 100;

// Uniform [0,1] , Warning: cstdlib::rand() is not very reliable
inline double Rand() {return double(rand())/(RAND_MAX+1);};
const double pi = 3.14159265358979323846;
// Box-Muller Transform method, Warning: this implementation is not very efficient
inline double Randn(){return (-2*log(1-Rand())) * cos(2*pi*Rand());};


double OptionPricer(double S0, // Current price
		            double K,  // Strike Price
		            double T,  // Expiry time
		            double r,  // Interest Rate
		            double sigma // Volatility
		            )
{
	int MAX_ITER = 10000;
	double ST, CT, W;
	double EC = 0;

	for (int i=1; i<=MAX_ITER; i++) {
		W = sqrt(T)*Randn();
		ST = S0*exp((r - sigma*sigma/2)*T + sigma*W);
		CT = (ST - K);
		if ( CT<0) CT = 0.;

		EC = 1./i * CT + double(i-1)/i*EC;
	};

	return exp(-r*T)*EC;
}

int main() {
	double sigma = 0.1;
	double r = 0.1;
	double T = 1;
	double S0 = 100;
	double K = 100;
	double Price;

	cout << "S_0 = " << S0 << endl;
	cout << "K = " << K  << endl;



	for (T=1;T<10.;T=T+0.1 ) {
		Price = OptionPricer(S0, K, T, r, sigma);
		cout << "T = " << T ;
	 	cout << ", Price = " << Price << endl;
	};

	return 0;
}

Lecture 5 (30 Oct)

Assignment : Vanilla European Option Pricing via Monte Carlo Description .
Generate a plot displaying the price for different strike prices and expiry dates.
A complex number Object
#include <iostream>
#include <cmath>

using namespace std;

class Complex {
	public:
	double real;
	double imag;
	Complex(double re = 0., double im = 0.) {
		real = re;
		imag = im;
	};

	void Print() {
		if (imag>0) {
			if (imag==1.)
			cout << real << "+" << "j" << endl;
			else
			cout << real << "+" << imag << "j" << endl;
		}
		else
			if (imag==-1.)
				cout << real << "-" << "j" << endl;
			else cout << real << "-" << -imag << "j" << endl;
	}
	double Magnitude() {
		return sqrt(real*real + imag*imag);
	}

	Complex operator+ (Complex c2) {
		Complex result(real+c2.real, imag+c2.imag);
		return result;
	}

	Complex operator* (Complex c2) {
		Complex result(real*c2.real-imag*c2.imag, imag*c2.real+real*c2.imag);
		return result;
	}

};

int main() {
	Complex c1(1, 1);
	Complex c2(3, 7);

	Complex c3 = c1 + c2;
	Complex c4 = c1*c1;
	Complex c5 = c1 + Complex(0, 8.0);

	c1.Print();
	c2.Print();
	c3.Print();
	c4.Print();
	c5.Print();

	cout << c1.Magnitude() << endl;
}


Estimation of pi via Monte Carlo
#include "nr3_psplot.h"

const long int N = 5000; // Number of samples

// Uniform [0,1] , Warning: cstdlib::rand() is not very reliable
inline double Rand() {return double(rand())/RAND_MAX;};

const double pi = 3.14159265358979323846;
// Box-Muller Transform method, Warning: this implementation is not very efficient
inline double Randn(){return (-2*log(Rand())) * cos(2*pi*Rand());};

int main(void) {

	PSpage pg("plot.ps");
	PSplot plot1(pg,100.,300.,100.,300.);
	plot1.setlimits(-1., 1, -1, 1 );
	plot1.frame();
	plot1.autoscales();
	plot1.xlabel("x1");
	plot1.ylabel("x2");

	int count = 0;

	for (int i=1; i<=N; i++) {
		double x1 = 2*Rand()-1;
		double x2 = 2*Rand()-1;


		if (x1*x1 + x2*x2 < 1) {
			count ++;
			plot1.setcolor(255, 0, 0);
		}
		else {
			plot1.setcolor(0, 0, 255);
		}

		plot1.dot(x1,x2);
	}

	cout << "pi = " <<  double(count)/N*4 << endl;

	pg.close();

}


Lecture 4 (23 Oct)


Lecture 3 (16 Oct)


Assignment 1: Generate random walks and plot the moving average. Input the window length from the keyboard.


// Generates a log-return process from a stochastic volatility model
// v[t+1] = a v[t] + epsilon[t]
// epsilon[t] ~ Gaussian(0, sqrt(var dt) )
//
// z[t]|v[t] ~ Gaussian(0, sqrt(v[t+1]))
//
// The output, plot.ps file can be viewed with GSview and ghostscript
// (To download Visit http://pages.cs.wisc.edu/~ghost/ and follow links to GSview)

#include "nr3_psplot.h"

const int N = 200; // Number of steps
const int E = 1;  // Number of paths
double T = 5.;   // Final time

const double var = 2; // Variance of the random walk
const double a = 1;  // AR(1) coefficient
const double dt = T/N;  // time increment

// Uniform [0,1] , Warning: cstdlib::rand() is not very reliable
inline double Rand() {return double(rand())/RAND_MAX;};
const double pi = 3.14159265358979323846;
// Box-Muller Transform method, Warning: this implementation is not very efficient
inline double Randn(){return (-2*log(Rand())) * cos(2*pi*Rand());};

int main(void) {
	double ep; // Noise, (shock)
    vector<double> t(N),v(N); // time index and volatility
    vector<double> exp_v(N); // variance
    vector<double> z(N); // log returns
    vector<double> price(N); // price

	PSpage pg("plot.ps");
	PSplot plot1(pg,100.,800.,100.,300.);
	plot1.setlimits(0., T, -5, 5 );
	plot1.frame();
	plot1.autoscales();
	plot1.xlabel("t");
	plot1.ylabel("v");

	for (int e=0; e<E; e++) {
	  v[0] = log(1);
	  exp_v[0] = exp(v[0]);
	  z[0] = sqrt(exp_v[0])*Randn();
	  price[0] = 1;
	  for (int i=0;i<N;i++) {
	    t[i] = i*dt;
	    ep = sqrt(var)*Randn()*dt;
	    if (i<N-1) {
	    	v[i+1] = a*v[i] + ep;
	    	exp_v[i+1] = exp(v[i+1]);
	    	z[i+1] = sqrt(exp_v[i+1])*Randn();
	    	price[i+1] = exp(z[i+1])*price[i];
	    }
	  }
	  plot1.setcolor(255, 0, 0);
	  plot1.lineplot(t,exp_v);
	  plot1.setcolor(0, 0, 0);
	  plot1.lineplot(t,z);
	}
	pg.close();
}

#include <iostream>
using namespace std;

int main() {
	int N = 9;
	int f;
	cout << "Carpim Tablosu" << endl;


	for (int i=1;i<=N;i++) {
		for (int j=1;j<=N;j++) {
			f = i*j;
			cout << f << " ";
		}
		cout << endl;
	}

	return 0;
}

Lecture 2 (9 Oct)

Eclipse: Download the 32 bit version of CDT -- the 64 bit version has some display problems with latest version of MinGW.
Download the header file nr3_psplot.h. This is a slight modification from numerical recipes in C++, V3.
Original documentation of PSPage and PsPlot objects is here.
The output: plot.ps
// Generates discrete time random walks and plots the realisations
// y[t+1] = a y[t] + epsilon[t]
// epsilon[t] ~ Gaussian(0, sqrt(var dt) )
//
// The output, plot.ps file can be viewed with GSview and ghostscript
// (To download Visit http://pages.cs.wisc.edu/~ghost/ and follow links to GSview)

#include "nr3_psplot.h"

const int N = 500; // Number of steps
const int E = 10;  // Number of paths
double T = 5.;   // Final time

const double var = 25; // Variance of the random walk
const double a = 1;  // AR(1) coefficient
const double dt = T/N;  // time increment

// Uniform [0,1] , Warning: cstdlib::rand() is not very reliable
inline double Rand() {return double(rand())/RAND_MAX;};

const double pi = 3.14159265358979323846;
// Box-Muller Transform method, Warning: this implementation is not very efficient
inline double Randn(){return (-2*log(Rand())) * cos(2*pi*Rand());};

int main(void) {
	double ep; // Noise, (shock)
    vector<double> t(N),y(N); // time index and state of the random walk

	PSpage pg("plot.ps");
	PSplot plot1(pg,100.,800.,100.,300.);
	plot1.setlimits(0., T, -5, 5 );
	plot1.frame();
	plot1.autoscales();
	plot1.xlabel("t");
	plot1.ylabel("y");

	for (int e=0; e<E; e++) {
	  y[0] = 0;
	  for (int i=0;i<N;i++) {
	    t[i] = i*dt;
	    ep = sqrt(var*dt)*Randn();
	    if (i<N-1) y[i+1] = a*y[i] + ep;
	  }
	  plot1.lineplot(t,y);
	  int col = int(e/double(E)*255);
	  plot1.setcolor(0, 0, col);
	}

	pg.close();
}

Lecture 1 (2 Oct)

Compile the program, produce a.exe
> g++ myprog.cpp

Compile the program, produce myprog.exe
> g++ myprog.cpp -o myprog.exe

Example 3

#include <iostream>
using namespace std;

// Calculate f_{n} = sum_i=1^n i and prints for i=1..n
int main ()
{
	int n = 20;
	int f;

	f = 0;
	for (int i=1; i<=n; i++) {
		f = f + i;
		cout << i << "," << f << endl;
	};
};

Example 2

// Prints a table of squares and cubes, waits for input to terminate
#include <iostream>
using namespace std;

int main ()
{
	char c;
	for (int i=1; i<=10; i++) {
		cout << i << " " << i*i << " " << i*i*i << endl;
	};
	cin >> c;
	return 0;
};

Example 1

#include <iostream>

using namespace std;


int square(int x0_input) {
	return x0_input*x0_input;
};

int cube(int x0_input) {
	return x0_input*x0_input*x0_input;
};

int main ()
{
	int i = 0;
	double d = 3.14;
	char ch = 'a';

	cout << "Goodby Moon" << " " << square(5) << " " << cube(5) << endl;
	cout << i << endl;
	cout << d << endl;
	cout << ch << endl;

	return 0;
};