I am trying to find the yield of a bond given the bond price, coupon, and semiannual three yr bond using newtons method. The value for B in the output should about equal 101. I have checked everywhere for errors but cant find any. Any ideas?
And yes I am aware about my vectors but dont make fun, i dont know how to automate them.
// bondyield.cpp : Defines the entry point for the console application.
//
#include "stdafx.h"
#include <iostream>
#include <vector>
#include <cmath>
#include <iomanip>
using namespace std;
double b_est(double x);
double f_deriv(double y);
int _tmain(int argc, _TCHAR* argv[])
{
double B = 101.0;
double n = 6.0;
vector<double> t_cash_flow;
double arrayOne[]={0.5, 1.0, 1.5, 2.0, 2.5, 3.0};
t_cash_flow.assign(arrayOne, arrayOne+6);
vector<double> v_cash_flow;
double arrayTwo[]={2, 2, 2, 2, 2, 102};
v_cash_flow.assign(arrayTwo, arrayTwo+6);
double tol = 10E-6;
double x0 = 0.03;
double xnew = x0;
double xold = x0 - 1.0;
while(abs(xnew - xold) > tol)
{
xold = xnew;
xnew = xnew + ((b_est(xold) - B)/f_deriv(xold));
}
cout << setprecision (12) << xnew << endl;
double Bp = 0.0;
double D = 0.0;
double C = 0.0;
double disc[6];
for(int i=0; i<n; ++i)
{
disc[i] = exp(-t_cash_flow[i]*xnew);
Bp = Bp + v_cash_flow[i]*disc[i];
D = D + t_cash_flow[i]*v_cash_flow[i]*disc[i];
C = C + pow(t_cash_flow[i], 2)*v_cash_flow[i]*disc[i];
}
D = D/Bp;
C = C/Bp;
cout << setprecision (16) << "Bond Price= " << Bp << endl;
cout << setprecision (16) << "Duration= " << D << endl;
cout << setprecision (16) << "Convexity= " << C << endl << endl;
system ("pause");
return 0;
}
double b_est(double x)
{
double n = 6.0;
vector<double> t_cash_flow;
double arrayOne[]={0.5, 1.0, 1.5, 2.0, 2.5, 3.0};
t_cash_flow.assign(arrayOne, arrayOne+6);
vector<double> v_cash_flow;
double arrayTwo[]={2, 2, 2, 2, 2, 102};
v_cash_flow.assign(arrayTwo, arrayTwo+6);
double best;
for(int i=0; i<n; ++i)
{
best = v_cash_flow[i]*exp(-x*t_cash_flow[i]);
}
return best;
}
double f_deriv(double y)
{
double n = 6.0;
vector<double> t_cash_flow;
double arrayOne[]={0.5, 1.0, 1.5, 2.0, 2.5, 3.0};
t_cash_flow.assign(arrayOne, arrayOne+6);
vector<double> v_cash_flow;
double arrayTwo[]={2, 2, 2, 2, 2, 102};
v_cash_flow.assign(arrayTwo, arrayTwo+6);
double fderiv;
for(int i=0; i<n; ++i)
{
fderiv = t_cash_flow[i]*v_cash_flow[i]*exp(-y*t_cash_flow[i]);
}
return fderiv;
}