33 typedef typename compositor_t::function function_t;
35 const std::string implied_volatility_program =
36 " const var epsilon := 0.0000001; "
37 " const var max_iters := 1000; "
39 " var v := 0.5; /* Initial volatility guess */ "
42 " while ((itr += 1) <= max_iters) "
47 " case callput_flag == 'call' : bsm_call(s, k, r, t, v); "
48 " case callput_flag == 'put' : bsm_put (s, k, r, t, v); "
51 " var price_diff := price - target_price; "
53 " if (abs(price_diff) <= epsilon) "
58 " v -= price_diff / vega(s, k, r, t, v); "
61 " itr <= max_iters ? v : null; ";
67 T target_price = T( 0.00);
69 std::string callput_flag;
71 symbol_table_t symbol_table(symbol_table_t::e_immutable);
72 symbol_table.add_variable(
"s",s);
73 symbol_table.add_variable(
"k",k);
74 symbol_table.add_variable(
"t",t);
75 symbol_table.add_variable(
"r",r);
76 symbol_table.add_stringvar(
"callput_flag",callput_flag);
77 symbol_table.add_variable (
"target_price",target_price);
78 symbol_table.add_pi();
80 compositor_t compositor(symbol_table);
83 function_t(
"bsm_call")
84 .vars(
"s",
"k",
"r",
"t",
"v")
87 " var d1 := (log(s / k) + (r + v^2 / 2) * t) / (v * sqrt(t)); "
88 " var d2 := d1 - v * sqrt(t); "
89 " s * ncdf(d1) - k * exp(-r * t) * ncdf(d2); "
94 .vars(
"s",
"k",
"r",
"t",
"v")
97 " var d1 := (log(s / k) + (r + v^2 / 2) * t) / (v * sqrt(t)); "
98 " var d2 := d1 - v * sqrt(t); "
99 " k * exp(-r * t) * ncdf(-d2) - s * ncdf(-d1); "
104 .vars(
"s",
"k",
"r",
"t",
"v")
107 " var d1 := (log(s / k) + (r + v^2 / 2) * t) / (v * sqrt(t)); "
108 " s * sqrt(t) * exp(-d1^2 / 2) / sqrt(2pi); "
111 expression_t expression;
112 expression.register_symbol_table(symbol_table);
115 parser.compile(implied_volatility_program,expression);
118 callput_flag =
"call";
119 target_price = T(18.339502);
121 const T implied_vol = expression.value();
123 printf(
"Call Option(s: %5.3f, k: %5.3f, t: %5.3f, r: %5.3f) "
124 "@ $%8.6f Implied volatility = %10.8f\n",
125 s, k, t, r, target_price, implied_vol);
129 callput_flag =
"put";
130 target_price = T(16.782764);
132 const T implied_vol = expression.value();
134 printf(
"Put Option(s: %5.3f, k: %5.3f, t: %5.3f, r: %5.3f) "
135 "@ $%8.6f Implied volatility = %10.8f\n",
136 s, k, t, r, target_price, implied_vol);