C++ Mathematical Expression Toolkit (ExprTk) release
Loading...
Searching...
No Matches
exprtk_simple_example_15.cpp
Go to the documentation of this file.
1/*
2 **************************************************************
3 * C++ Mathematical Expression Toolkit Library *
4 * *
5 * Simple Example 15 *
6 * Author: Arash Partow (1999-2024) *
7 * URL: https://www.partow.net/programming/exprtk/index.html *
8 * *
9 * Copyright notice: *
10 * Free use of the Mathematical Expression Toolkit Library is *
11 * permitted under the guidelines and in accordance with the *
12 * most current version of the MIT License. *
13 * https://www.opensource.org/licenses/MIT *
14 * SPDX-License-Identifier: MIT *
15 * *
16 **************************************************************
17*/
18
19
20#include <cstdio>
21#include <string>
22
23#include "exprtk.hpp"
24
25
26template <typename T>
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
33 const std::string bsm_model_program =
34 " var d1 := (log(s / k) + (r + v^2 / 2) * t) / (v * sqrt(t)); "
35 " var d2 := d1 - v * sqrt(t); "
36 " "
37 " if (callput_flag == 'call') "
38 " s * ncdf(d1) - k * e^(-r * t) * ncdf(d2); "
39 " else if (callput_flag == 'put') "
40 " k * e^(-r * t) * ncdf(-d2) - s * ncdf(-d1); "
41 " ";
42
43 T s = T(60.00); // Spot / Stock / Underlying / Base price
44 T k = T(65.00); // Strike price
45 T v = T( 0.30); // Volatility
46 T t = T( 0.25); // Years to maturity
47 T r = T( 0.08); // Risk free rate
48
49 std::string callput_flag;
50
52
53 symbol_table_t symbol_table;
54 symbol_table.add_variable("s",s);
55 symbol_table.add_variable("k",k);
56 symbol_table.add_variable("t",t);
57 symbol_table.add_variable("r",r);
58 symbol_table.add_variable("v",v);
59 symbol_table.add_constant("e",e);
60 symbol_table.add_stringvar("callput_flag",callput_flag);
61
62 expression_t expression;
63 expression.register_symbol_table(symbol_table);
64
65 parser_t parser;
66 parser.compile(bsm_model_program,expression);
67
68 callput_flag = "call";
69
70 const T bsm_call_option_price = expression.value();
71
72 callput_flag = "put";
73
74 const T bsm_put_option_price = expression.value();
75
76 printf("BSM(call, %5.3f, %5.3f, %5.3f, %5.3f, %5.3f) = %10.6f\n",
77 s, k, t, r, v,
78 bsm_call_option_price);
79
80 printf("BSM(put , %5.3f, %5.3f, %5.3f, %5.3f, %5.3f) = %10.6f\n",
81 s, k, t, r, v,
82 bsm_put_option_price);
83
84 const T put_call_parity_diff =
85 (bsm_call_option_price - bsm_put_option_price) -
86 (s - k * std::exp(-r * t));
87
88 printf("Put-Call parity difference: %20.17f\n", put_call_parity_diff);
89}
90
91int main()
92{
93 black_scholes_merton_model<double>();
94 return 0;
95}
void black_scholes_merton_model()