Problem with finance c++ code

Can someone please help me?? I keep getting a debug assertion failed message saying my vector subscript is out of range. Unfortunately i do not know where the problem lies

Here's my code for a trinomial tree to calculate a american put option:

#include <vector>
#include <cmath>
#include <iostream>
#include <fstream>

using namespace std;

struct dividend {
double time;
double amount;
};

double stockprice(double S0,double u,double d,int j,int states, double t,double r,vector<dividend> divi)
{
//calculate S*
double s;
s = S0*pow(u,j)*pow(d,states-j);
//include deterministic dividends when before dividend paydate.
for (int i=0;i<divi.size();i++)
{
if (divi[i].time >= t)
{
s = s + divi[i].amount*exp(-r*(divi[i].time-t));
}
}
return s;
}

int main()
{
//initialise variables

double r=0.10,
T=2,
sigma=0.4,
S0=12,
K=10,
delta_t, betta, u, d, p_u,p_m,p_d;
int number = 100;
vector<int> vec_steps(number,0);
int steps;

vector<double> S_M, V_M_left, V_M_right;

vector<dividend> div;

vector<double> V0(number,0);

//set number of steps vector
for (int i=0;i<number;i++)
{
vec_steps[i] = 5 + 5*i;
}



//configure dividends
//values from exercise 2
div.resize(2);
div[0].time = 2.5/12;
div[0].amount = 1.06;
div[1].time = 4.5/12;
div[1].amount = 1.0;


//calculate S0*
for (int i=0; i<div.size();i++)
{
S0 = S0 - div[i].amount * exp(-r*div[i].time);
}

//start tree calculation
for (int n=0;n<number;n++)
{
//tree factors
steps = vec_steps[n];
delta_t = T/steps;
u= exp(sigma*sqrt(3*delta_t));
d=1/u;
p_u=sqrt(delta_t/(12*sigma*sigma))*(r-0.5*sigma*sigma)+ (1.0/6.0);
p_m=(2.0/3.0);
p_d=-sqrt(delta_t/(12*sigma*sigma))*(r-0.5*sigma*sigma)+ (1.0/6.0);


//set size of the vectors at the end of the tree
S_M.resize(steps+1);
V_M_right.resize(steps+1);
V_M_left.resize(steps);

//calculate last step in the tree with final values and payoff at time of maturaty
for(int j=0;j<=steps;j++)
{
S_M[j]=stockprice(S0,u,d,j,steps,T,r,div);
V_M_right[j]=max(K-S_M[j],0.0);
}

//calculate for the last-1 step using the step after
for (int i=steps-1; i>=0; i--)
{
S_M.pop_back();
for(int j=0; j<=i; j++)
{
//stockprice at time t
S_M[j]=stockprice(S0,u,d,j,i,delta_t*i,r,div);
//value of the payoff of an american put, risk neutral based
V_M_left[j]=max(max(K-S_M[j],0.0),exp(-r*delta_t)*(p_u*V_M_right[j+1]+p_m*V_M_right[j] + p_d*V_M_right[j-1]));
}
V_M_right.pop_back();
V_M_right=V_M_left;
V_M_left.pop_back();
}
//save option value at t=0
V0[n]=V_M_right[0];
}

//save to file
ofstream outfile("EX2_trinomial.txt");
outfile << "M" << " " << "Trinomial_Tree" << " " << endl;

for(int i=0; i<=vec_steps.size()-1; i++)
{
outfile << vec_steps[i] << " " << V0[i] << " " << endl;
}


return 1;
}



Thanks in advance
Last edited on
Topic archived. No new replies allowed.