public class BlackScholesBinary {
// Black-Scholes formula (calculates the BS option value, using the class Gaussian. This method will be used in the binary search below to find the volatility)
public static double callPrice(double s, double x, double r, double sigma, double t) {
double a = (Math.log(s/x) + (r + sigma * sigma/2) * t) / (sigma * Math.sqrt(t));
double b = a - sigma * Math.sqrt(t);
return s * Gaussian.Phi(a) - x * Math.exp(-r * t) * Gaussian.Phi(b);
}
public static double getSigma(double s, double x, double r, double t, double price, double lo, double hi, double delta) {
lo = 0.0;
hi = 100000.0;
delta = 0.01;
double mid = lo + (hi - lo) / 2;
if (price < callPrice(s, x, r, mid, t)) return getSigma(s, x, r, t, price, lo, mid, delta); // should look for a lower volatility
else if (price > callPrice(s, x, r, mid, t)) return getSigma(s, x, r, t, price, mid, hi, delta); // should look for a higher volatility
else if (price == callPrice(s, x, r, mid, t) && (hi - lo < delta)) return mid; //should return the found volatility as a return of the function
}
public static void main(String[] args) {
double s = Double.parseDouble(args[0]);
double x = Double.parseDouble(args[1]);
double r = Double.parseDouble(args[2]);
double t = Double.parseDouble(args[3]);
double price = Double.parseDouble(args[4]);
double vol = getSigma(s, x, r, t, price);
System.out.println("The volatility is" + vol + " %");
}
}