I have this error when calculating the yield to maturity of coupon based bonds, I have all the templates that I need and tested them, no problem in there, but when I tried to run it gave me an error:
Exception in thread "main" org.apache.commons.math3.exception.NoBracketingException: function values at endpoints do not have different signs, endpoints: [0, 0.9], values: [4.5, 19.138] at org.apache.commons.math3.analysis.solvers.BrentSolver.doSolve(BrentSolver.java:132) at org.apache.commons.math3.analysis.solvers.BaseAbstractUnivariateSolver.solve(BaseAbstractUnivariateSolver.java:199) at Pack1.YTM.calculateYTM(YTM.java:54) at Pack1.YTM.calculateYTMForAllSeries(YTM.java:60) at Pack1.MainApp.main(MainApp.java:21)
Tried to change bounds and initialGuess but it still don't work, does it have any logic issue that I missed?
UnivariateFunction function = new UnivariateFunction() {
@Override
public double value(double r) {
double sum = 0.0;
for (double j = 1; j <= maturity * frequency; j++) {
sum += (CouponPayment / frequency) / Math.pow(1 + r / frequency, j);
}
sum += FaceValue / Math.pow(1 + r / frequency, maturity * frequency);
return Price - sum;
}
};
UnivariateSolver solver = new BrentSolver();
double lowerBound = 0.0; // Lower bound
double upperBound = 0.9; // Upper bound
double initialGuess = 0.01; // Initial guess
double ytm = solver.solve(1000, function, lowerBound, upperBound, initialGuess);
return ytm; // yield
}