| 25 | |
| 26 | template <typename T> |
| 27 | void compute_implied_volatility() |
| 28 | { |
| 29 | typedef exprtk::symbol_table<T> symbol_table_t; |
| 30 | typedef exprtk::expression<T> expression_t; |
| 31 | typedef exprtk::parser<T> parser_t; |
| 32 | typedef exprtk::function_compositor<T> compositor_t; |
| 33 | typedef typename compositor_t::function function_t; |
| 34 | |
| 35 | const std::string implied_volatility_program = |
| 36 | " const var epsilon := 0.0000001; " |
| 37 | " const var max_iters := 1000; " |
| 38 | " " |
| 39 | " var v := 0.5; /* Initial volatility guess */ " |
| 40 | " var itr := 0; " |
| 41 | " " |
| 42 | " while ((itr += 1) <= max_iters) " |
| 43 | " { " |
| 44 | " var price := " |
| 45 | " switch " |
| 46 | " { " |
| 47 | " case callput_flag == 'call' : bsm_call(s, k, r, t, v); " |
| 48 | " case callput_flag == 'put' : bsm_put (s, k, r, t, v); " |
| 49 | " }; " |
| 50 | " " |
| 51 | " var price_diff := price - target_price; " |
| 52 | " " |
| 53 | " if (abs(price_diff) <= epsilon) " |
| 54 | " { " |
| 55 | " break; " |
| 56 | " }; " |
| 57 | " " |
| 58 | " v -= price_diff / vega(s, k, r, t, v); " |
| 59 | " }; " |
| 60 | " " |
| 61 | " itr <= max_iters ? v : null; "; |
| 62 | |
| 63 | T s = T( 100.00); // Spot / Stock / Underlying / Base price |
| 64 | T k = T( 110.00); // Strike price |
| 65 | T t = T( 2.22); // Years to maturity |
| 66 | T r = T( 0.05); // Risk free rate |
| 67 | T target_price = T( 0.00); |
| 68 | |
| 69 | std::string callput_flag; |
| 70 | |
| 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(); |
| 79 | |
| 80 | compositor_t compositor(symbol_table); |
| 81 | |
| 82 | compositor.add( |
| 83 | function_t("bsm_call") |
| 84 | .vars("s", "k", "r", "t", "v") |