top of page
Writer's pictureRichie Sawant

Code to Calculate The Value of a Call Price of a Stock Using C++



This code is a simple implementation of a Monte Carlo Simulation-based option pricer.

We can add more complicated algorithms and build a really fast program to calculate so!


The Main Implementation File

// Monte Carlo Simulation Code.cpp : This file contains the 'main' function. Program execution begins and ends there.
//

#include "Random1.h"
#include <iostream>
#include <cmath>

using namespace std;

double MonteCarloSimulation(double Expiry,	double Strike, double Spot, double Vol, double r, unsigned long NumberOfPaths)

{
	double variance = Vol * Vol * Expiry;
	double rootVariance = sqrt(variance);
	double itoCorrection = -0.5 * variance;
	double movedSpot = Spot * exp(r * Expiry + itoCorrection);
	double thisSpot;
	double runningSum = 0;
	
	for (unsigned long i = 0; i < NumberOfPaths; i++)
	
	{
		double thisGaussian = GetOneGaussianByBoxMuller();
		
		thisSpot = movedSpot * exp(rootVariance * thisGaussian);
		
		double thisPayoff = thisSpot - Strike;
		
		thisPayoff = thisPayoff > 0 ? thisPayoff : 0;
		
		runningSum += thisPayoff;
	}
	
	double mean = runningSum / NumberOfPaths;
	
	mean *= exp(-r * Expiry);
	
	return mean;
}


int main()
{
	double Expiry;
	double Strike;
	double Spot;
	double Vol;
	double r;
	unsigned long NumberOfPaths;
	
	cout << "\nPlease Enter the Expiry Time Left: ";
	
	cin >> Expiry;
	
	cout << "\nPlease Enter the Strike Price: ";
	
	cin >> Strike;
	
	cout << "\nPlease Enter the Strike Price: ";
	
	cin >> Spot;
	
	cout << "\nPlease Enter the Volatility: ";
	
	cin >> Vol;
	
	cout << "\nPlease Enter the Interest Rate\n";
	
	cin >> r;
	
	cout << "\nNumber of Monte Carlo Simulations\n";
	
	cin >> NumberOfPaths;
	
	double result = MonteCarloSimulation(Expiry, Strike, Spot,Vol, r, NumberOfPaths);
	
	cout << "The Price of " << result << "\n";
	
	double tmp;
	
	cin >> tmp;
	
	return 0;
	}

The Random1.h file

#ifndef RANDOM1_H
#define RANDOM1_H
double GetOneGaussianBySummation();
double GetOneGaussianByBoxMuller();
#endif

The Random1.cpp file

#include "Random1.h"
#include <cstdlib>
#include <cmath>
// the basic math functions should be in namespace
// std but aren’t in VCPP6
#if !defined(_MSC_VER)
using namespace std;
#endif
double GetOneGaussianBySummation()
{
	double result = 0;
	for (unsigned long j = 0; j < 12; j++)
		result += rand() / static_cast<double>(RAND_MAX);
	result -= 6.0;
	return result;
}

double GetOneGaussianByBoxMuller()
{
	double result;
	double x;
	double y;
	double sizeSquared;
	do
	{
		x = 2.0 * rand() / static_cast<double>(RAND_MAX) - 1;
		y = 2.0 * rand() / static_cast<double>(RAND_MAX) - 1;
		sizeSquared = x * x + y * y;
	} while
		(sizeSquared >= 1.0);
	result = x * sqrt(-2 * log(sizeSquared) / sizeSquared);
	return result;
}

This code has been inspired by Mark Joshi's book!

32 views0 comments

Comments


Post: Blog2_Post
bottom of page