33 typedef typename compositor_t::function function_t;
35 const std::string option_implied_volatility_program =
36 " const var epsilon := 0.0000001; "
37 " const var max_iters := 1000; "
39 " var vola := 0.5; /* Initial volatility guess */ "
42 " while ((itr += 1) <= max_iters) "
47 " case callput_flag == 'call' : bsm_call(s, k, r, t, vola); "
48 " case callput_flag == 'put' : bsm_put (s, k, r, t, vola); "
51 " var price_diff := price - target_price; "
53 " if (abs(price_diff) <= epsilon) "
58 " var vega := bsm_vega(s, k, r, t, vola); "
60 " if (vega < epsilon) "
62 " itr := max_iters + 1; "
66 " vola -= price_diff / vega; "
69 " itr <= max_iters ? vola : null; ";
75 T target_price = T( 0.00);
77 std::string callput_flag;
79 symbol_table_t symbol_table(symbol_table_t::e_immutable);
80 symbol_table.add_variable(
"s",s);
81 symbol_table.add_variable(
"k",k);
82 symbol_table.add_variable(
"t",t);
83 symbol_table.add_variable(
"r",r);
84 symbol_table.add_stringvar(
"callput_flag",callput_flag);
85 symbol_table.add_variable (
"target_price",target_price);
86 symbol_table.add_pi();
88 compositor_t compositor(symbol_table);
91 function_t(
"bsm_call")
92 .vars(
"s",
"k",
"r",
"t",
"v")
95 " var d1 := (log(s / k) + (r + v^2 / 2) * t) / (v * sqrt(t)); "
96 " var d2 := d1 - v * sqrt(t); "
97 " s * ncdf(d1) - k * exp(-r * t) * ncdf(d2); "
101 function_t(
"bsm_put")
102 .vars(
"s",
"k",
"r",
"t",
"v")
105 " var d1 := (log(s / k) + (r + v^2 / 2) * t) / (v * sqrt(t)); "
106 " var d2 := d1 - v * sqrt(t); "
107 " k * exp(-r * t) * ncdf(-d2) - s * ncdf(-d1); "
111 function_t(
"bsm_vega")
112 .vars(
"s",
"k",
"r",
"t",
"v")
115 " var d1 := (log(s / k) + (r + v^2 / 2) * t) / (v * sqrt(t)); "
116 " s * exp(-d1^2 / 2) / sqrt(2pi) * sqrt(t); "
119 expression_t expression;
120 expression.register_symbol_table(symbol_table);
123 parser.compile(option_implied_volatility_program, expression);
126 callput_flag =
"call";
127 target_price = T(18.339502);
129 const T call_option_implied_vola = expression.value();
131 printf(
"Call Option(s: %5.3f, k: %5.3f, t: %5.3f, r: %5.3f) "
132 "@ $%8.6f Implied volatility = %10.8f\n",
133 s, k, t, r, target_price, call_option_implied_vola);
137 callput_flag =
"put";
138 target_price = T(16.782764);
140 const T put_option_implied_vola = expression.value();
142 printf(
"Put Option(s: %5.3f, k: %5.3f, t: %5.3f, r: %5.3f) "
143 "@ $%8.6f Implied volatility = %10.8f\n",
144 s, k, t, r, target_price, put_option_implied_vola);