Calculating BS European Call & Put prices
A simple C++ script to calculate Black-Scholes European Call and Put prices.
The inputs are Option price, Risk-free rate (Percentages must be provided as decimal), Volatility of the underlying (Percentages must be provided as decimal), Time of maturity (Must be in years), Start time.
Output is the calculated Call or Put price
#include "stdafx.h"
namespace BS{
double getCDF(double x){
double b0 = 0.2316419;
double b1 = 0.319381530;
double b2 = -0.356563782;
double b3 = 1.781477937;
double b4 = -1.821255978;
double b5 = 1.330274429;
double t = 1 / (1 + b0*x);
double prod = b1*t + b2*pow(t, 2) + b3*pow(t, 3) + b4*pow(t, 4) + b5*pow(t, 5);
if (x >= 0.0) {
return (1 - stdnorm(x)*prod);
}
else {
return 1.0 - getCDF(-x);
}
}
double stdnorm(double x) {
return (1.0 / (pow(2 * M_PI, 0.5)))*exp(-0.5*x*x);
}
BSEur::BSEur() :
r(0.1), v(0.25), K(100), T(1.0), S(100), isCall(true){}
BSEur::BSEur(double r, double v, double K, double T, double S, bool isCall){
this->r = r;
this->v = v;
this->K = K;
this->T = T;
this->S = S;
this->isCall = isCall;
}
BSEur::~BSEur(){}
double BSEur::getd(){
return (log(S / K) + (r + pow(v, 2)*0.5)*(T)) / (v*sqrt(T));
}
double BSEur::getCallPrice(){
double d1 = getd();
double d2 = d1 - v*sqrt(T);
/*printf("d1: %lf\n", d1);
printf("d2: %lf\n", d2);*/
return (S*getCDF(d1)) - (K*exp(-r*(T))*getCDF(d2));
}
double BSEur::getPutPrice(){
double d1 = getd();
double d2 = d1 - v*sqrt(T);
return (K*exp(-r*(T))*getCDF(-d2)) - (S*getCDF(d1));
}
void BSEur::printPrice(){
if (isCall)
{
cout << "Price of option: " << getCallPrice()<<endl;
}
else
{
cout << "Price of option: " << getPutPrice()<<endl;
}
}
}