File: hestonmodel.cpp

package info (click to toggle)
quantlib 1.39-1
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid
  • size: 41,264 kB
  • sloc: cpp: 396,561; makefile: 6,539; python: 272; sh: 154; lisp: 86
file content (3469 lines) | stat: -rw-r--r-- 137,513 bytes parent folder | download
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657
2658
2659
2660
2661
2662
2663
2664
2665
2666
2667
2668
2669
2670
2671
2672
2673
2674
2675
2676
2677
2678
2679
2680
2681
2682
2683
2684
2685
2686
2687
2688
2689
2690
2691
2692
2693
2694
2695
2696
2697
2698
2699
2700
2701
2702
2703
2704
2705
2706
2707
2708
2709
2710
2711
2712
2713
2714
2715
2716
2717
2718
2719
2720
2721
2722
2723
2724
2725
2726
2727
2728
2729
2730
2731
2732
2733
2734
2735
2736
2737
2738
2739
2740
2741
2742
2743
2744
2745
2746
2747
2748
2749
2750
2751
2752
2753
2754
2755
2756
2757
2758
2759
2760
2761
2762
2763
2764
2765
2766
2767
2768
2769
2770
2771
2772
2773
2774
2775
2776
2777
2778
2779
2780
2781
2782
2783
2784
2785
2786
2787
2788
2789
2790
2791
2792
2793
2794
2795
2796
2797
2798
2799
2800
2801
2802
2803
2804
2805
2806
2807
2808
2809
2810
2811
2812
2813
2814
2815
2816
2817
2818
2819
2820
2821
2822
2823
2824
2825
2826
2827
2828
2829
2830
2831
2832
2833
2834
2835
2836
2837
2838
2839
2840
2841
2842
2843
2844
2845
2846
2847
2848
2849
2850
2851
2852
2853
2854
2855
2856
2857
2858
2859
2860
2861
2862
2863
2864
2865
2866
2867
2868
2869
2870
2871
2872
2873
2874
2875
2876
2877
2878
2879
2880
2881
2882
2883
2884
2885
2886
2887
2888
2889
2890
2891
2892
2893
2894
2895
2896
2897
2898
2899
2900
2901
2902
2903
2904
2905
2906
2907
2908
2909
2910
2911
2912
2913
2914
2915
2916
2917
2918
2919
2920
2921
2922
2923
2924
2925
2926
2927
2928
2929
2930
2931
2932
2933
2934
2935
2936
2937
2938
2939
2940
2941
2942
2943
2944
2945
2946
2947
2948
2949
2950
2951
2952
2953
2954
2955
2956
2957
2958
2959
2960
2961
2962
2963
2964
2965
2966
2967
2968
2969
2970
2971
2972
2973
2974
2975
2976
2977
2978
2979
2980
2981
2982
2983
2984
2985
2986
2987
2988
2989
2990
2991
2992
2993
2994
2995
2996
2997
2998
2999
3000
3001
3002
3003
3004
3005
3006
3007
3008
3009
3010
3011
3012
3013
3014
3015
3016
3017
3018
3019
3020
3021
3022
3023
3024
3025
3026
3027
3028
3029
3030
3031
3032
3033
3034
3035
3036
3037
3038
3039
3040
3041
3042
3043
3044
3045
3046
3047
3048
3049
3050
3051
3052
3053
3054
3055
3056
3057
3058
3059
3060
3061
3062
3063
3064
3065
3066
3067
3068
3069
3070
3071
3072
3073
3074
3075
3076
3077
3078
3079
3080
3081
3082
3083
3084
3085
3086
3087
3088
3089
3090
3091
3092
3093
3094
3095
3096
3097
3098
3099
3100
3101
3102
3103
3104
3105
3106
3107
3108
3109
3110
3111
3112
3113
3114
3115
3116
3117
3118
3119
3120
3121
3122
3123
3124
3125
3126
3127
3128
3129
3130
3131
3132
3133
3134
3135
3136
3137
3138
3139
3140
3141
3142
3143
3144
3145
3146
3147
3148
3149
3150
3151
3152
3153
3154
3155
3156
3157
3158
3159
3160
3161
3162
3163
3164
3165
3166
3167
3168
3169
3170
3171
3172
3173
3174
3175
3176
3177
3178
3179
3180
3181
3182
3183
3184
3185
3186
3187
3188
3189
3190
3191
3192
3193
3194
3195
3196
3197
3198
3199
3200
3201
3202
3203
3204
3205
3206
3207
3208
3209
3210
3211
3212
3213
3214
3215
3216
3217
3218
3219
3220
3221
3222
3223
3224
3225
3226
3227
3228
3229
3230
3231
3232
3233
3234
3235
3236
3237
3238
3239
3240
3241
3242
3243
3244
3245
3246
3247
3248
3249
3250
3251
3252
3253
3254
3255
3256
3257
3258
3259
3260
3261
3262
3263
3264
3265
3266
3267
3268
3269
3270
3271
3272
3273
3274
3275
3276
3277
3278
3279
3280
3281
3282
3283
3284
3285
3286
3287
3288
3289
3290
3291
3292
3293
3294
3295
3296
3297
3298
3299
3300
3301
3302
3303
3304
3305
3306
3307
3308
3309
3310
3311
3312
3313
3314
3315
3316
3317
3318
3319
3320
3321
3322
3323
3324
3325
3326
3327
3328
3329
3330
3331
3332
3333
3334
3335
3336
3337
3338
3339
3340
3341
3342
3343
3344
3345
3346
3347
3348
3349
3350
3351
3352
3353
3354
3355
3356
3357
3358
3359
3360
3361
3362
3363
3364
3365
3366
3367
3368
3369
3370
3371
3372
3373
3374
3375
3376
3377
3378
3379
3380
3381
3382
3383
3384
3385
3386
3387
3388
3389
3390
3391
3392
3393
3394
3395
3396
3397
3398
3399
3400
3401
3402
3403
3404
3405
3406
3407
3408
3409
3410
3411
3412
3413
3414
3415
3416
3417
3418
3419
3420
3421
3422
3423
3424
3425
3426
3427
3428
3429
3430
3431
3432
3433
3434
3435
3436
3437
3438
3439
3440
3441
3442
3443
3444
3445
3446
3447
3448
3449
3450
3451
3452
3453
3454
3455
3456
3457
3458
3459
3460
3461
3462
3463
3464
3465
3466
3467
3468
3469
/* -*- mode: c++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */

/*
 Copyright (C) 2005, 2007, 2009, 2010, 2012, 2014, 2017 Klaus Spanderen
 Copyright (C) 2022 Ignacio Anguita

 This file is part of QuantLib, a free-software/open-source library
 for financial quantitative analysts and developers - http://quantlib.org/

 QuantLib is free software: you can redistribute it and/or modify it
 under the terms of the QuantLib license.  You should have received a
 copy of the license along with this program; if not, please email
 <quantlib-dev@lists.sf.net>. The license is also available online at
 <http://quantlib.org/license.shtml>.

 This program is distributed in the hope that it will be useful, but WITHOUT
 ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
 FOR A PARTICULAR PURPOSE.  See the license for more details.
*/

#include "preconditions.hpp"
#include "toplevelfixture.hpp"
#include "utilities.hpp"
#include <algorithm>
#include <ql/instruments/barrieroption.hpp>
#include <ql/instruments/vanillaoption.hpp>
#include <ql/math/functional.hpp>
#include <ql/math/integrals/gausslobattointegral.hpp>
#include <ql/math/optimization/differentialevolution.hpp>
#include <ql/math/optimization/levenbergmarquardt.hpp>
#include <ql/math/randomnumbers/rngtraits.hpp>
#include <ql/methods/finitedifferences/operators/numericaldifferentiation.hpp>
#include <ql/methods/montecarlo/pathgenerator.hpp>
#include <ql/models/equity/hestonmodel.hpp>
#include <ql/models/equity/hestonmodelhelper.hpp>
#include <ql/models/equity/piecewisetimedependenthestonmodel.hpp>
#include <ql/pricingengines/barrier/fdblackscholesbarrierengine.hpp>
#include <ql/pricingengines/barrier/fdhestonbarrierengine.hpp>
#include <ql/pricingengines/blackformula.hpp>
#include <ql/pricingengines/vanilla/analyticdividendeuropeanengine.hpp>
#include <ql/pricingengines/vanilla/analytichestonengine.hpp>
#include <ql/pricingengines/vanilla/analyticpdfhestonengine.hpp>
#include <ql/pricingengines/vanilla/analyticptdhestonengine.hpp>
#include <ql/pricingengines/vanilla/coshestonengine.hpp>
#include <ql/pricingengines/vanilla/exponentialfittinghestonengine.hpp>
#include <ql/pricingengines/vanilla/fdblackscholesvanillaengine.hpp>
#include <ql/pricingengines/vanilla/fdhestonvanillaengine.hpp>
#include <ql/pricingengines/vanilla/hestonexpansionengine.hpp>
#include <ql/pricingengines/vanilla/mceuropeanhestonengine.hpp>
#include <ql/processes/hestonprocess.hpp>
#include <ql/quotes/simplequote.hpp>
#include <ql/termstructures/volatility/equityfx/hestonblackvolsurface.hpp>
#include <ql/termstructures/yield/flatforward.hpp>
#include <ql/termstructures/yield/zerocurve.hpp>
#include <ql/time/calendars/nullcalendar.hpp>
#include <ql/time/calendars/target.hpp>
#include <ql/time/daycounters/actual360.hpp>
#include <ql/time/daycounters/actual365fixed.hpp>
#include <ql/time/daycounters/actualactual.hpp>
#include <ql/time/period.hpp>
#include <cmath>
#include <utility>

using namespace QuantLib;
using namespace boost::unit_test_framework;

BOOST_FIXTURE_TEST_SUITE(QuantLibTests, TopLevelFixture)

BOOST_AUTO_TEST_SUITE(HestonModelTests)

struct CalibrationMarketData {
    Handle<Quote> s0;
    Handle<YieldTermStructure> riskFreeTS, dividendYield;
    std::vector<ext::shared_ptr<CalibrationHelper> > options;
};

CalibrationMarketData getDAXCalibrationMarketData() {
    /* this example is taken from A. Sepp
       Pricing European-Style Options under Jump Diffusion Processes
       with Stochstic Volatility: Applications of Fourier Transform
       http://math.ut.ee/~spartak/papers/stochjumpvols.pdf
    */

    Date settlementDate(Settings::instance().evaluationDate());
        
    DayCounter dayCounter = Actual365Fixed();
    Calendar calendar = TARGET();
        
    Integer t[] = { 13, 41, 75, 165, 256, 345, 524, 703 };
    Rate r[] = { 0.0357,0.0349,0.0341,0.0355,0.0359,0.0368,0.0386,0.0401 };
        
    std::vector<Date> dates;
    std::vector<Rate> rates;
    dates.push_back(settlementDate);
    rates.push_back(0.0357);
    Size i;
    for (i = 0; i < 8; ++i) {
        dates.push_back(settlementDate + t[i]);
        rates.push_back(r[i]);
    }
    Handle<YieldTermStructure> riskFreeTS(
            ext::make_shared<ZeroCurve>(dates, rates, dayCounter));
        
    Handle<YieldTermStructure> dividendYield(
                                    flatRate(settlementDate, 0.0, dayCounter));
        
    Volatility v[] =
        { 0.6625,0.4875,0.4204,0.3667,0.3431,0.3267,0.3121,0.3121,
          0.6007,0.4543,0.3967,0.3511,0.3279,0.3154,0.2984,0.2921,
          0.5084,0.4221,0.3718,0.3327,0.3155,0.3027,0.2919,0.2889,
          0.4541,0.3869,0.3492,0.3149,0.2963,0.2926,0.2819,0.2800,
          0.4060,0.3607,0.3330,0.2999,0.2887,0.2811,0.2751,0.2775,
          0.3726,0.3396,0.3108,0.2781,0.2788,0.2722,0.2661,0.2686,
          0.3550,0.3277,0.3012,0.2781,0.2781,0.2661,0.2661,0.2681,
          0.3428,0.3209,0.2958,0.2740,0.2688,0.2627,0.2580,0.2620,
          0.3302,0.3062,0.2799,0.2631,0.2573,0.2533,0.2504,0.2544,
          0.3343,0.2959,0.2705,0.2540,0.2504,0.2464,0.2448,0.2462,
          0.3460,0.2845,0.2624,0.2463,0.2425,0.2385,0.2373,0.2422,
          0.3857,0.2860,0.2578,0.2399,0.2357,0.2327,0.2312,0.2351,
          0.3976,0.2860,0.2607,0.2356,0.2297,0.2268,0.2241,0.2320 };
        
    Handle<Quote> s0(ext::make_shared<SimpleQuote>(4468.17));
    Real strike[] = { 3400,3600,3800,4000,4200,4400,
                      4500,4600,4800,5000,5200,5400,5600 };
        
    std::vector<ext::shared_ptr<CalibrationHelper> > options;
        
    for (Size s = 0; s < 13; ++s) {
        for (Size m = 0; m < 8; ++m) {
            Handle<Quote> vol(ext::make_shared<SimpleQuote>(v[s*8+m]));
        
            Period maturity((int)((t[m]+3)/7.), Weeks); // round to weeks
            options.push_back(ext::make_shared<HestonModelHelper>(maturity, calendar,
                                                                  s0, strike[s], vol,
                                                                  riskFreeTS, dividendYield,
                                                                  BlackCalibrationHelper::ImpliedVolError));
        }
    }
        
    CalibrationMarketData marketData = { s0, riskFreeTS, dividendYield, options };
        
    return marketData;
}

struct HestonProcessDiscretizationDesc {
    HestonProcess::Discretization discretization;
    Size nSteps;
    std::string name;
};

struct HestonParameter {
    Real v0, kappa, theta, sigma, rho;
};

void reportOnIntegrationMethodTest(VanillaOption& option,
                                   const ext::shared_ptr<HestonModel>& model,
                                   const AnalyticHestonEngine::Integration& integration,
                                   AnalyticHestonEngine::ComplexLogFormula formula,
                                   bool isAdaptive,
                                   Real expected,
                                   Real tol,
                                   Size valuations,
                                   const std::string& method) {

    if (integration.isAdaptiveIntegration() != isAdaptive)
        BOOST_ERROR(method << " is not an adaptive integration routine");

    const ext::shared_ptr<AnalyticHestonEngine> engine =
        ext::make_shared<AnalyticHestonEngine>(
                model, formula, integration, 1e-9);

    option.setPricingEngine(engine);
    const Real calculated = option.NPV();

    const Real error = std::fabs(calculated - expected);

    if (std::isnan(error) || error > tol) {
        BOOST_ERROR("failed to reproduce simple Heston Pricing with "
                    << "\n    integration method: " << method
                    <<  std::setprecision(12)
                    << "\n    expected          : " << expected
                    << "\n    calculated        : " << calculated
                    << "\n    error             : " << error);
    }

    if (   valuations != Null<Size>()
           && valuations != engine->numberOfEvaluations()) {
        BOOST_ERROR("nubmer of function evaluations does not match "
                    << "\n    integration method      : " << method
                    << "\n    expected function calls : " << valuations
                    << "\n    number of function calls: "
                    << engine->numberOfEvaluations());
    }
}

class LogCharacteristicFunction {
  public:
    LogCharacteristicFunction(Size n, Time t, ext::shared_ptr<COSHestonEngine> engine)
    : t_(t), alpha_(0.0, 1.0), engine_(std::move(engine)) {
        for (Size i=1; i < n; ++i, alpha_*=std::complex<Real>(0,1));
    }

    Real operator()(Real u) const {
        return (std::log(engine_->chF(u, t_))/alpha_).real();
    }

  private:
    const Time t_;
    std::complex<Real> alpha_;
    const ext::shared_ptr<COSHestonEngine> engine_;
};

class HestonIntegrationMaxBoundTestFct {
  public:
    explicit HestonIntegrationMaxBoundTestFct(Real maxBound)
    : maxBound_(maxBound),
      callCounter_(ext::make_shared<Size>(Size(0))) {}

    Real operator()() {
        ++(*callCounter_);
        return maxBound_;
    }

    Size getCallCounter() const {
        return *callCounter_;
    }
  private:
    const Real maxBound_;
    const ext::shared_ptr<Size> callCounter_;
};


BOOST_AUTO_TEST_CASE(testBlackCalibration) {
    BOOST_TEST_MESSAGE(
       "Testing Heston model calibration using a flat volatility surface...");

    /* calibrate a Heston model to a constant volatility surface without
       smile. expected result is a vanishing volatility of the volatility.
       In addition theta and v0 should be equal to the constant variance */

    DayCounter dayCounter = Actual360();
    Calendar calendar = NullCalendar();

    Handle<YieldTermStructure> riskFreeTS(flatRate(0.04, dayCounter));
    Handle<YieldTermStructure> dividendTS(flatRate(0.50, dayCounter));

    std::vector<Period> optionMaturities = {1 * Months, 2 * Months, 3 * Months, 6 * Months,
                                            9 * Months, 1 * Years,  2 * Years};

    std::vector<ext::shared_ptr<CalibrationHelper> > options;
    Handle<Quote> s0(ext::make_shared<SimpleQuote>(1.0));
    Handle<Quote> vol(ext::make_shared<SimpleQuote>(0.1));
    Volatility volatility = vol->value();

    for (auto& optionMaturitie : optionMaturities) {
        for (Real moneyness = -1.0; moneyness < 2.0; moneyness += 1.0) {
            const Time tau = dayCounter.yearFraction(
                riskFreeTS->referenceDate(),
                calendar.advance(riskFreeTS->referenceDate(), optionMaturitie));
            const Real fwdPrice =
                s0->value() * dividendTS->discount(tau) / riskFreeTS->discount(tau);
            const Real strikePrice = fwdPrice * std::exp(-moneyness * volatility * std::sqrt(tau));

            options.push_back(ext::make_shared<HestonModelHelper>(
                optionMaturitie, calendar, s0, strikePrice, vol, riskFreeTS, dividendTS));
        }
    }

    for (Real sigma = 0.1; sigma < 0.7; sigma += 0.2) {
        const Real v0=0.01;
        const Real kappa=0.2;
        const Real theta=0.02;
        const Real rho=-0.75;

        ext::shared_ptr<HestonProcess> process(
            ext::make_shared<HestonProcess>(riskFreeTS, dividendTS,
                              s0, v0, kappa, theta, sigma, rho));

        ext::shared_ptr<HestonModel> model(ext::make_shared<HestonModel>(process));
        ext::shared_ptr<PricingEngine> engine(
            ext::make_shared<AnalyticHestonEngine>(model, 96));

        for (auto& option : options)
            ext::dynamic_pointer_cast<BlackCalibrationHelper>(option)->setPricingEngine(engine);

        LevenbergMarquardt om(1e-8, 1e-8, 1e-8);
        model->calibrate(options, om, EndCriteria(400, 40, 1.0e-8,
                                                  1.0e-8, 1.0e-8));

        Real tolerance = 3.0e-3;

        if (model->sigma() > tolerance) {
            BOOST_ERROR("Failed to reproduce expected sigma"
                        << "\n    calculated: " << model->sigma()
                        << "\n    expected:   " << 0.0
                        << "\n    tolerance:  " << tolerance);
        }

        if (std::fabs(model->kappa()
                  *(model->theta()-volatility*volatility)) > tolerance) {
            BOOST_ERROR("Failed to reproduce expected theta"
                        << "\n    calculated: " << model->theta()
                        << "\n    expected:   " << volatility*volatility);
        }

        if (std::fabs(model->v0()-volatility*volatility) > tolerance) {
            BOOST_ERROR("Failed to reproduce expected v0"
                        << "\n    calculated: " << model->v0()
                        << "\n    expected:   " << volatility*volatility);
        }
    }
}

BOOST_AUTO_TEST_CASE(testDAXCalibration) {

    BOOST_TEST_MESSAGE(
             "Testing Heston model calibration using DAX volatility data...");

    Date settlementDate(5, July, 2002);
    Settings::instance().evaluationDate() = settlementDate;

    CalibrationMarketData marketData = getDAXCalibrationMarketData();
    
    const Handle<YieldTermStructure> riskFreeTS = marketData.riskFreeTS;
    const Handle<YieldTermStructure> dividendTS = marketData.dividendYield;
    const Handle<Quote> s0 = marketData.s0;

    const std::vector<ext::shared_ptr<CalibrationHelper> >& options = marketData.options;

    const Real v0=0.1;
    const Real kappa=1.0;
    const Real theta=0.1;
    const Real sigma=0.5;
    const Real rho=-0.5;

    const ext::shared_ptr<HestonProcess> process(
        ext::make_shared<HestonProcess>(
            riskFreeTS, dividendTS, s0, v0, kappa, theta, sigma, rho));

    const ext::shared_ptr<HestonModel> model(
        ext::make_shared<HestonModel>(process));

    const ext::shared_ptr<PricingEngine> engines[] = {
        ext::make_shared<AnalyticHestonEngine>(model, 64),
        ext::make_shared<COSHestonEngine>(model, 12, 75),
        ext::make_shared<ExponentialFittingHestonEngine>(model)
    };

    const Array params = model->params();
    for (const auto& engine : engines) {
        model->setParams(params);
        for (const auto& option : options)
            ext::dynamic_pointer_cast<BlackCalibrationHelper>(option)->setPricingEngine(engine);

        LevenbergMarquardt om(1e-8, 1e-8, 1e-8);
        model->calibrate(options, om,
                         EndCriteria(400, 40, 1.0e-8, 1.0e-8, 1.0e-8));

        Real sse = 0;
        for (Size i = 0; i < 13*8; ++i) {
            const Real diff = options[i]->calibrationError()*100.0;
            sse += diff*diff;
        }
        Real expected = 177.2; //see article by A. Sepp.
        if (std::fabs(sse - expected) > 1.0) {
            BOOST_FAIL("Failed to reproduce calibration error"
                       << "\n    calculated: " << sse
                       << "\n    expected:   " << expected);
        }
    }
}

BOOST_AUTO_TEST_CASE(testAnalyticVsBlack) {
    BOOST_TEST_MESSAGE("Testing analytic Heston engine against Black formula...");

    Date settlementDate = Settings::instance().evaluationDate();

    DayCounter dayCounter = ActualActual(ActualActual::ISDA);
    Date exerciseDate = settlementDate + 6*Months;

    ext::shared_ptr<StrikedTypePayoff> payoff(
        ext::make_shared<PlainVanillaPayoff>(Option::Put, 30));
    ext::shared_ptr<Exercise> exercise(
        ext::make_shared<EuropeanExercise>(exerciseDate));

    Handle<YieldTermStructure> riskFreeTS(flatRate(0.1, dayCounter));
    Handle<YieldTermStructure> dividendTS(flatRate(0.04, dayCounter));

    Handle<Quote> s0(ext::make_shared<SimpleQuote>(32.0));

    const Real v0=0.05;
    const Real kappa=5.0;
    const Real theta=0.05;
    const Real sigma=1.0e-4;
    const Real rho=0.0;

    ext::shared_ptr<HestonProcess> process(ext::make_shared<HestonProcess>(
                   riskFreeTS, dividendTS, s0, v0, kappa, theta, sigma, rho));

    VanillaOption option(payoff, exercise);
    ext::shared_ptr<PricingEngine> engine(
        ext::make_shared<AnalyticHestonEngine>(
            ext::make_shared<HestonModel>(process), 144));

    option.setPricingEngine(engine);
    Real calculated = option.NPV();

    Real yearFraction = dayCounter.yearFraction(settlementDate, exerciseDate);
    Real forwardPrice = 32*std::exp((0.1-0.04)*yearFraction);
    Real expected = blackFormula(payoff->optionType(), payoff->strike(),
        forwardPrice, std::sqrt(0.05*yearFraction)) *
                                            std::exp(-0.1*yearFraction);
    Real error = std::fabs(calculated - expected);
    Real tolerance = 2.0e-7;
    if (error > tolerance) {
        BOOST_FAIL("failed to reproduce Black price with AnalyticHestonEngine"
                   << "\n    calculated: " << calculated
                   << "\n    expected:   " << expected
                   << "\n    error:      " << std::scientific << error);
    }

    engine = 
        ext::make_shared<FdHestonVanillaEngine>(
            ext::make_shared<HestonModel>(process),
              200,200,100);
    option.setPricingEngine(engine);

    calculated = option.NPV();
    error = std::fabs(calculated - expected);
    tolerance = 1.0e-3;
    if (error > tolerance) {
        BOOST_FAIL("failed to reproduce Black price with FdHestonVanillaEngine"
                   << "\n    calculated: " << calculated
                   << "\n    expected:   " << expected
                   << "\n    error:      " << std::scientific << error);
    }

}

BOOST_AUTO_TEST_CASE(testAnalyticVsCached) {
    BOOST_TEST_MESSAGE("Testing analytic Heston engine against cached values...");

    Date settlementDate(27, December, 2004);
    Settings::instance().evaluationDate() = settlementDate;
    DayCounter dayCounter = ActualActual(ActualActual::ISDA);
    Date exerciseDate(28, March, 2005);

    ext::shared_ptr<StrikedTypePayoff> payoff(
        ext::make_shared<PlainVanillaPayoff>(Option::Call, 1.05));
    ext::shared_ptr<Exercise> exercise(
        ext::make_shared<EuropeanExercise>(exerciseDate));

    Handle<YieldTermStructure> riskFreeTS(flatRate(0.0225, dayCounter));
    Handle<YieldTermStructure> dividendTS(flatRate(0.02, dayCounter));

    Handle<Quote> s0(ext::make_shared<SimpleQuote>(1.0));
    const Real v0 = 0.1;
    const Real kappa = 3.16;
    const Real theta = 0.09;
    const Real sigma = 0.4;
    const Real rho = -0.2;

    ext::shared_ptr<HestonProcess> process(ext::make_shared<HestonProcess>(
                   riskFreeTS, dividendTS, s0, v0, kappa, theta, sigma, rho));

    VanillaOption option(payoff, exercise);

    ext::shared_ptr<AnalyticHestonEngine> engine(
        ext::make_shared<AnalyticHestonEngine>(
            ext::make_shared<HestonModel>(process), 64));

    option.setPricingEngine(engine);

    Real expected1 = 0.0404774515;
    Real calculated1 = option.NPV();
    Real tolerance = 1.0e-8;

    if (std::fabs(calculated1 - expected1) > tolerance) {
        BOOST_ERROR("Failed to reproduce cached analytic price"
                    << "\n    calculated: " << calculated1
                    << "\n    expected:   " << expected1);
    }


    // reference values from www.wilmott.com, technical forum
    // search for "Heston or VG price check"

    Real K[] = {0.9,1.0,1.1};
    Real expected2[] = { 0.1330371,0.0641016, 0.0270645 };
    Real calculated2[6];

    Size i;
    for (i = 0; i < 6; ++i) {
        Date exerciseDate(8+i/3, September, 2005);

        ext::shared_ptr<StrikedTypePayoff> payoff(
            ext::make_shared<PlainVanillaPayoff>(Option::Call, K[i%3]));
        ext::shared_ptr<Exercise> exercise(
            ext::make_shared<EuropeanExercise>(exerciseDate));

        Handle<YieldTermStructure> riskFreeTS(flatRate(0.05, dayCounter));
        Handle<YieldTermStructure> dividendTS(flatRate(0.02, dayCounter));

        Real s = riskFreeTS->discount(0.7)/dividendTS->discount(0.7);
        Handle<Quote> s0(ext::make_shared<SimpleQuote>(s));

        ext::shared_ptr<HestonProcess> process(
            ext::make_shared<HestonProcess>(
                   riskFreeTS, dividendTS, s0, 0.09, 1.2, 0.08, 1.8, -0.45));

        VanillaOption option(payoff, exercise);

        ext::shared_ptr<PricingEngine> engine(
            ext::make_shared<AnalyticHestonEngine>(
                ext::make_shared<HestonModel>(process)));

        option.setPricingEngine(engine);
        calculated2[i] = option.NPV();
    }

    // we are after the value for T=0.7
    Time t1 = dayCounter.yearFraction(settlementDate, Date(8, September,2005));
    Time t2 = dayCounter.yearFraction(settlementDate, Date(9, September,2005));

    for (i = 0; i < 3; ++i) {
        const Real interpolated =
            calculated2[i]+(calculated2[i+3]-calculated2[i])/(t2-t1)*(0.7-t1);

        if (std::fabs(interpolated - expected2[i]) > 100*tolerance) {
            BOOST_ERROR("Failed to reproduce cached analytic prices:"
                        << "\n    calculated: " << interpolated
                        << "\n    expected:   " << expected2[i] );
        }
    }
}

BOOST_AUTO_TEST_CASE(testMcVsCached) {
    BOOST_TEST_MESSAGE(
                "Testing Monte Carlo Heston engine against cached values...");

    Date settlementDate(27, December, 2004);
    Settings::instance().evaluationDate() = settlementDate;

    DayCounter dayCounter = ActualActual(ActualActual::ISDA);
    Date exerciseDate(28, March, 2005);

    ext::shared_ptr<StrikedTypePayoff> payoff(
        ext::make_shared<PlainVanillaPayoff>(Option::Put, 1.05));
    ext::shared_ptr<Exercise> exercise(
        ext::make_shared<EuropeanExercise>(exerciseDate));

    Handle<YieldTermStructure> riskFreeTS(flatRate(0.7, dayCounter));
    Handle<YieldTermStructure> dividendTS(flatRate(0.4, dayCounter));

    Handle<Quote> s0(ext::make_shared<SimpleQuote>(1.05));

    ext::shared_ptr<HestonProcess> process(
        ext::make_shared<HestonProcess>(
                   riskFreeTS, dividendTS, s0, 0.3, 1.16, 0.2, 0.8, 0.8,
                   HestonProcess::QuadraticExponentialMartingale));

    VanillaOption option(payoff, exercise);

    ext::shared_ptr<PricingEngine> engine;
    engine = MakeMCEuropeanHestonEngine<PseudoRandom>(process)
        .withStepsPerYear(11)
        .withAntitheticVariate()
        .withSamples(50000)
        .withSeed(1234);

    option.setPricingEngine(engine);

    Real expected = 0.0632851308977151;
    Real calculated = option.NPV();
    Real errorEstimate = option.errorEstimate();
    Real tolerance = 7.5e-4;

    if (std::fabs(calculated - expected) > 2.34*errorEstimate) {
        BOOST_ERROR("Failed to reproduce cached price"
                    << "\n    calculated: " << calculated
                    << "\n    expected:   " << expected
                    << " +/- " << errorEstimate);
    }

    if (errorEstimate > tolerance) {
        BOOST_ERROR("failed to reproduce error estimate"
                    << "\n    calculated: " << errorEstimate
                    << "\n    expected:   " << tolerance);
    }
}

BOOST_AUTO_TEST_CASE(testFdBarrierVsCached, *precondition(if_speed(Fast))) {
    BOOST_TEST_MESSAGE("Testing FD barrier Heston engine against cached values...");

    DayCounter dc = Actual360();
    Date today = Settings::instance().evaluationDate();

    Handle<Quote> s0(ext::make_shared<SimpleQuote>(100.0));
    Handle<YieldTermStructure> rTS(flatRate(today, 0.08, dc));
    Handle<YieldTermStructure> qTS(flatRate(today, 0.04, dc));

    Date exDate = today + 180;
    ext::shared_ptr<Exercise> exercise(
        ext::make_shared<EuropeanExercise>(exDate));

    ext::shared_ptr<StrikedTypePayoff> payoff(
        ext::make_shared<PlainVanillaPayoff>(Option::Call, 90.0));

    ext::shared_ptr<HestonProcess> process(
        ext::make_shared<HestonProcess>(
            rTS, qTS, s0, 0.25*0.25, 1.0, 0.25*0.25, 0.001, 0.0));

    ext::shared_ptr<PricingEngine> engine;
    engine = ext::make_shared<FdHestonBarrierEngine>(
                ext::make_shared<HestonModel>(process),
                    200,400,100);

    BarrierOption option(Barrier::DownOut, 95.0, 3.0, payoff, exercise);
    option.setPricingEngine(engine);

    Real calculated = option.NPV();
    Real expected = 9.0246;
    Real error = std::fabs(calculated-expected);
    if (error > 1.0e-3) {
        BOOST_FAIL("failed to reproduce cached price with FD Barrier engine"
                   << "\n    calculated: " << calculated
                   << "\n    expected:   " << expected
                   << "\n    error:      " << std::scientific << error);
    }

    option = BarrierOption(Barrier::DownIn, 95.0, 3.0, payoff, exercise);
    option.setPricingEngine(engine);

    calculated = option.NPV();
    expected = 7.7627;
    error = std::fabs(calculated-expected);
    if (error > 1.0e-3) {
        BOOST_FAIL("failed to reproduce cached price with FD Barrier engine"
                   << "\n    calculated: " << calculated
                   << "\n    expected:   " << expected
                   << "\n    error:      " << std::scientific << error);
    }
}

BOOST_AUTO_TEST_CASE(testFdVanillaVsCached) {
    BOOST_TEST_MESSAGE("Testing FD vanilla Heston engine against cached values...");

    Date settlementDate(27, December, 2004);
    Settings::instance().evaluationDate() = settlementDate;

    DayCounter dayCounter = ActualActual(ActualActual::ISDA);
    Date exerciseDate(28, March, 2005);

    ext::shared_ptr<StrikedTypePayoff> payoff(
        ext::make_shared<PlainVanillaPayoff>(Option::Put, 1.05));
    ext::shared_ptr<Exercise> exercise(
        ext::make_shared<EuropeanExercise>(exerciseDate));

    Handle<YieldTermStructure> riskFreeTS(flatRate(0.7, dayCounter));
    Handle<YieldTermStructure> dividendTS(flatRate(0.4, dayCounter));

    Handle<Quote> s0(ext::make_shared<SimpleQuote>(1.05));

    VanillaOption option(payoff, exercise);

    ext::shared_ptr<HestonProcess> process(
        ext::make_shared<HestonProcess>(
                   riskFreeTS, dividendTS, s0, 0.3, 1.16, 0.2, 0.8, 0.8));

    option.setPricingEngine(
        MakeFdHestonVanillaEngine(ext::make_shared<HestonModel>(process))
            .withTGrid(100)
            .withXGrid(200)
            .withVGrid(100)
        );

    Real expected = 0.06325;
    Real calculated = option.NPV();
    Real error = std::fabs(calculated - expected);
    Real tolerance = 1.0e-4;

    if (error > tolerance) {
        BOOST_FAIL("failed to reproduce cached price with FD engine"
                   << "\n    calculated: " << calculated
                   << "\n    expected:   " << expected
                   << "\n    error:      " << std::scientific << error);
    }
}

BOOST_AUTO_TEST_CASE(testFdVanillaWithDividendsVsCached) {
    BOOST_TEST_MESSAGE("Testing FD vanilla Heston engine for discrete dividends...");

    Date settlementDate(27, December, 2004);
    Settings::instance().evaluationDate() = settlementDate;

    DayCounter dayCounter = ActualActual(ActualActual::ISDA);

    auto payoff = ext::make_shared<PlainVanillaPayoff>(Option::Call, 95.0);

    auto s0 = Handle<Quote>(ext::make_shared<SimpleQuote>(100.0));
    auto riskFreeTS = Handle<YieldTermStructure>(flatRate(0.05, dayCounter));
    auto dividendTS = Handle<YieldTermStructure>(flatRate(0.0, dayCounter));

    auto exerciseDate = Date(28, March, 2006);
    auto exercise = ext::make_shared<EuropeanExercise>(exerciseDate);

    std::vector<Date> dividendDates;
    std::vector<Real> dividends;
    for (Date d = settlementDate + 3*Months;
              d < exercise->lastDate();
              d += 6*Months) {
        dividendDates.push_back(d);
        dividends.push_back(1.0);
    }

    auto process = ext::make_shared<HestonProcess>(
                   riskFreeTS, dividendTS, s0, 0.04, 1.0, 0.04, 0.001, 0.0);

    VanillaOption option(payoff, exercise);
    option.setPricingEngine(
        MakeFdHestonVanillaEngine(ext::make_shared<HestonModel>(process))
        .withCashDividends(dividendDates, dividends)
        .withTGrid(200)
        .withXGrid(400)
        .withVGrid(100)
    );

    Real calculated = option.NPV();
    // Value calculated with an independent FD framework, validated with
    // an independent MC framework
    Real expected = 12.946;
    Real error = std::fabs(calculated - expected);
    Real tolerance = 5.0e-3;

    if (error > tolerance) {
        BOOST_FAIL("failed to reproduce discrete dividend price with FD engine"
                   << "\n    calculated: " << calculated
                   << "\n    expected:   " << expected
                   << "\n    error:      " << std::scientific << error);
    }
}

BOOST_AUTO_TEST_CASE(testFdAmerican) {
    BOOST_TEST_MESSAGE("Testing FD vanilla Heston engine for american exercise...");

    Date settlementDate(27, December, 2004);
    Settings::instance().evaluationDate() = settlementDate;

    DayCounter dayCounter = ActualActual(ActualActual::ISDA);

    auto s0 = Handle<Quote>(ext::make_shared<SimpleQuote>(100.0));
    auto riskFreeTS = Handle<YieldTermStructure>(flatRate(0.05, dayCounter));
    auto dividendTS = Handle<YieldTermStructure>(flatRate(0.03, dayCounter));
    auto process = ext::make_shared<HestonProcess>(
                   riskFreeTS, dividendTS, s0, 0.04, 1.0, 0.04, 0.001, 0.0);
    auto payoff = ext::make_shared<PlainVanillaPayoff>(Option::Put, 95.0);
    auto exerciseDate = Date(28, March, 2006);
    auto exercise = ext::make_shared<AmericanExercise>(
            settlementDate, exerciseDate);
    auto option = VanillaOption(payoff, exercise);
    option.setPricingEngine(
        MakeFdHestonVanillaEngine(ext::make_shared<HestonModel>(process))
            .withTGrid(200)
            .withXGrid(400)
            .withVGrid(100)
        );
    Real calculated = option.NPV();

    Handle<BlackVolTermStructure> volTS(flatVol(settlementDate, 0.2,
                                                  dayCounter));
    ext::shared_ptr<BlackScholesMertonProcess> ref_process(
        ext::make_shared<BlackScholesMertonProcess>(s0, dividendTS, riskFreeTS, volTS));
    ext::shared_ptr<PricingEngine> ref_engine(
        ext::make_shared<FdBlackScholesVanillaEngine>(ref_process, 200, 400));
    option.setPricingEngine(ref_engine);
    Real expected = option.NPV();

    Real error = std::fabs(calculated - expected);
    Real tolerance = 1.0e-3;

    if (error > tolerance) {
        BOOST_FAIL("failed to reproduce american option price with FD engine"
                   << "\n    calculated: " << calculated
                   << "\n    expected:   " << expected
                   << "\n    error:      " << std::scientific << error);
    }
}

BOOST_AUTO_TEST_CASE(testKahlJaeckelCase, *precondition(if_speed(Fast))) {
    BOOST_TEST_MESSAGE(
          "Testing MC and FD Heston engines for the Kahl-Jaeckel example...");

    /* Example taken from Wilmott mag (Sept. 2005).
       "Not-so-complex logarithms in the Heston model",
       Example was also discussed within the Wilmott thread
       "QuantLib code is very high quatlity"
    */

    Date settlementDate(30, March, 2007);
    Settings::instance().evaluationDate() = settlementDate;

    DayCounter dayCounter = ActualActual(ActualActual::ISDA);
    Date exerciseDate(30, March, 2017);

    const ext::shared_ptr<StrikedTypePayoff> payoff(
        ext::make_shared<PlainVanillaPayoff>(Option::Call, 200));
    const ext::shared_ptr<Exercise> exercise(
        ext::make_shared<EuropeanExercise>(exerciseDate));

    VanillaOption option(payoff, exercise);


    Handle<YieldTermStructure> riskFreeTS(flatRate(0.0, dayCounter));
    Handle<YieldTermStructure> dividendTS(flatRate(0.0, dayCounter));

    Handle<Quote> s0(ext::make_shared<SimpleQuote>(100));

    const Real v0    = 0.16;
    const Real theta = v0;
    const Real kappa = 1.0;
    const Real sigma = 2.0;
    const Real rho   =-0.8;


    const HestonProcessDiscretizationDesc descriptions[] = {
        { HestonProcess::NonCentralChiSquareVariance, 10,
          "NonCentralChiSquareVariance" },
        { HestonProcess::QuadraticExponentialMartingale, 100,
          "QuadraticExponentialMartingale" },
    };

    const Real tolerance = 0.2;
    const Real expected = 4.95212;

    for (const auto& description : descriptions) {
        const ext::shared_ptr<HestonProcess> process(ext::make_shared<HestonProcess>(
            riskFreeTS, dividendTS, s0, v0, kappa, theta, sigma, rho, description.discretization));

        const ext::shared_ptr<PricingEngine> engine =
            MakeMCEuropeanHestonEngine<PseudoRandom>(process)
                .withSteps(description.nSteps)
                .withAntitheticVariate()
                .withAbsoluteTolerance(tolerance)
                .withSeed(1234);
        option.setPricingEngine(engine);

        const Real calculated = option.NPV();
        const Real errorEstimate = option.errorEstimate();

        if (std::fabs(calculated - expected) > 2.34*errorEstimate) {
            BOOST_ERROR("Failed to reproduce cached price with MC engine"
                        << "\n    discretization: " << description.name
                        << "\n    expected:       " << expected
                        << "\n    calculated:     " << calculated << " +/- " << errorEstimate);
        }

        if (errorEstimate > tolerance) {
            BOOST_ERROR("failed to reproduce error estimate with MC engine"
                        << "\n    discretization: " << description.name << "\n    calculated    : "
                        << errorEstimate << "\n    expected      :   " << tolerance);
        }
    }

    option.setPricingEngine(
        MakeMCEuropeanHestonEngine<LowDiscrepancy>(
            ext::make_shared<HestonProcess>(
                    riskFreeTS, dividendTS, s0, v0, kappa, theta, sigma, rho,
                    HestonProcess::BroadieKayaExactSchemeLaguerre))
        .withSteps(1)
        .withSamples(1023));

    Real calculated = option.NPV();
    if (std::fabs(calculated - expected) > 0.5*tolerance) {
        BOOST_ERROR("Failed to reproduce cached price with MC engine"
                    << "\n    discretization: BroadieKayaExactSchemeLobatto"
                    << "\n    calculated:     " << calculated
                    << "\n    expected:       " << expected
                    << "\n    tolerance:      " << tolerance);
    }


    const ext::shared_ptr<HestonModel> hestonModel(
        ext::make_shared<HestonModel>(
            ext::make_shared<HestonProcess>(
                riskFreeTS, dividendTS, s0, v0,
                kappa, theta, sigma, rho)));

    option.setPricingEngine(
        ext::make_shared<FdHestonVanillaEngine>(hestonModel, 200, 401, 101));

    calculated = option.NPV();
    Real error = std::fabs(calculated - expected);
    if (error > 5.0e-2) {
        BOOST_FAIL("failed to reproduce cached price with FD engine"
                   << "\n    calculated: " << calculated
                   << "\n    expected:   " << expected
                   << "\n    error:      " << std::scientific << error);
    }

    option.setPricingEngine(
        ext::make_shared<AnalyticHestonEngine>(hestonModel, 1e-6, 1000));

    calculated = option.NPV();
    error = std::fabs(calculated - expected);

    if (error > 0.00002) {
        BOOST_FAIL("failed to reproduce cached price with "
                   "GaussLobatto engine"
                   << "\n    calculated: " << calculated
                   << "\n    expected:   " << expected
                   << "\n    error:      " << std::scientific << error);
    }

    option.setPricingEngine(
        ext::make_shared<COSHestonEngine>(hestonModel, 16, 400));
    calculated = option.NPV();
    error = std::fabs(calculated - expected);

    if (error > 0.00002) {
        BOOST_FAIL("failed to reproduce cached price with "
                   "Cosine engine"
                   << "\n    calculated: " << calculated
                   << "\n    expected:   " << expected
                   << "\n    error:      " << std::scientific << error);
    }

    option.setPricingEngine(
        ext::make_shared<ExponentialFittingHestonEngine>(hestonModel));
    calculated = option.NPV();
    error = std::fabs(calculated - expected);

    if (error > 0.00002) {
        BOOST_FAIL("failed to reproduce cached price with "
                   "exponential fitting Heston engine"
                   << "\n    calculated: " << calculated
                   << "\n    expected:   " << expected
                   << "\n    error:      " << std::scientific << error);
    }
}

BOOST_AUTO_TEST_CASE(testDifferentIntegrals, *precondition(if_speed(Fast))) {
    BOOST_TEST_MESSAGE(
       "Testing different numerical Heston integration algorithms...");

    const Date settlementDate(27, December, 2004);
    Settings::instance().evaluationDate() = settlementDate;

    const DayCounter dayCounter = ActualActual(ActualActual::ISDA);

    Handle<YieldTermStructure> riskFreeTS(flatRate(0.05, dayCounter));
    Handle<YieldTermStructure> dividendTS(flatRate(0.03, dayCounter));

    const Real strikes[] = { 0.5, 0.7, 1.0, 1.25, 1.5, 2.0 };
    const Integer maturities[] = { 1, 2, 3, 12, 60, 120, 360};
    const Option::Type types[] ={ Option::Put, Option::Call };

    const HestonParameter equityfx      = { 0.07, 2.0, 0.04, 0.55, -0.8 };
    const HestonParameter highCorr      = { 0.07, 1.0, 0.04, 0.55,  0.995 };
    const HestonParameter lowVolOfVol   = { 0.07, 1.0, 0.04, 0.025, -0.75 };
    const HestonParameter highVolOfVol  = { 0.07, 1.0, 0.04, 5.0, -0.75 };
    const HestonParameter kappaEqSigRho = { 0.07, 0.4, 0.04, 0.5, 0.8 };

    std::vector<HestonParameter> params = {
        equityfx,
        highCorr,
        lowVolOfVol,
        highVolOfVol,
        kappaEqSigRho
    };
    const Real tol[] = { 1e-3, 1e-3, 0.2, 0.01, 1e-3 };

    for (auto iter = params.begin();
         iter != params.end(); ++iter) {

        Handle<Quote> s0(ext::make_shared<SimpleQuote>(1.0));
        ext::shared_ptr<HestonProcess> process(
            ext::make_shared<HestonProcess>(
            riskFreeTS, dividendTS,
            s0, iter->v0, iter->kappa,
            iter->theta, iter->sigma, iter->rho));

        ext::shared_ptr<HestonModel> model(
            ext::make_shared<HestonModel>(process));

        ext::shared_ptr<AnalyticHestonEngine> lobattoEngine(
            ext::make_shared<AnalyticHestonEngine>(model, 1e-10,
                                                       1000000));
        ext::shared_ptr<AnalyticHestonEngine> laguerreEngine(
            ext::make_shared<AnalyticHestonEngine>(model, 128));
        ext::shared_ptr<AnalyticHestonEngine> legendreEngine(
            ext::make_shared<AnalyticHestonEngine>(
                model, AnalyticHestonEngine::Gatheral,
                AnalyticHestonEngine::Integration::gaussLegendre(512)));
        ext::shared_ptr<AnalyticHestonEngine> chebyshevEngine(
            ext::make_shared<AnalyticHestonEngine>(
                model, AnalyticHestonEngine::Gatheral,
                AnalyticHestonEngine::Integration::gaussChebyshev(512)));
        ext::shared_ptr<AnalyticHestonEngine> chebyshev2ndEngine(
            ext::make_shared<AnalyticHestonEngine>(
                model, AnalyticHestonEngine::Gatheral,
                AnalyticHestonEngine::Integration::gaussChebyshev2nd(512)));

        Real maxLegendreDiff    = 0.0;
        Real maxChebyshevDiff   = 0.0;
        Real maxChebyshev2ndDiff= 0.0;
        Real maxLaguerreDiff    = 0.0;

        for (int maturitie : maturities) {
            ext::shared_ptr<Exercise> exercise(
                ext::make_shared<EuropeanExercise>(settlementDate + Period(maturitie, Months)));

            for (Real strike : strikes) {
                for (auto type : types) {

                    ext::shared_ptr<StrikedTypePayoff> payoff(
                        ext::make_shared<PlainVanillaPayoff>(type, strike));

                    VanillaOption option(payoff, exercise);

                    option.setPricingEngine(lobattoEngine);
                    const Real lobattoNPV = option.NPV();

                    option.setPricingEngine(laguerreEngine);
                    const Real laguerre = option.NPV();

                    option.setPricingEngine(legendreEngine);
                    const Real legendre = option.NPV();

                    option.setPricingEngine(chebyshevEngine);
                    const Real chebyshev = option.NPV();

                    option.setPricingEngine(chebyshev2ndEngine);
                    const Real chebyshev2nd = option.NPV();

                    maxLaguerreDiff
                        = std::max(maxLaguerreDiff,
                                   std::fabs(lobattoNPV-laguerre));
                    maxLegendreDiff
                        = std::max(maxLegendreDiff,
                                   std::fabs(lobattoNPV-legendre));
                    maxChebyshevDiff
                        = std::max(maxChebyshevDiff,
                                   std::fabs(lobattoNPV-chebyshev));
                    maxChebyshev2ndDiff
                        = std::max(maxChebyshev2ndDiff,
                                   std::fabs(lobattoNPV-chebyshev2nd));
                }
            }
        }
        const Real maxDiff = std::max({
                maxLaguerreDiff,
                maxLegendreDiff,
                maxChebyshevDiff,
                maxChebyshev2ndDiff
            });

        const Real tr = tol[iter - params.begin()];
        if (maxDiff > tr) {
            BOOST_ERROR("Failed to reproduce Heston pricing values "
                        "within given tolerance"
                        << "\n    maxDifference: " << maxDiff
                        << "\n    tolerance:     " << tr);
        }
    }
}

BOOST_AUTO_TEST_CASE(testMultipleStrikesEngine) {
    BOOST_TEST_MESSAGE("Testing multiple-strikes FD Heston engine...");

    Date settlementDate(27, December, 2004);
    Settings::instance().evaluationDate() = settlementDate;

    DayCounter dayCounter = ActualActual(ActualActual::ISDA);
    Date exerciseDate(28, March, 2006);

    ext::shared_ptr<Exercise> exercise(
        ext::make_shared<EuropeanExercise>(exerciseDate));

    Handle<YieldTermStructure> riskFreeTS(flatRate(0.06, dayCounter));
    Handle<YieldTermStructure> dividendTS(flatRate(0.02, dayCounter));

    Handle<Quote> s0(ext::make_shared<SimpleQuote>(1.05));

    ext::shared_ptr<HestonProcess> process(
        ext::make_shared<HestonProcess>(
                     riskFreeTS, dividendTS, s0, 0.16, 2.5, 0.09, 0.8, -0.8));
    ext::shared_ptr<HestonModel> model(
		ext::make_shared<HestonModel>(process));

    std::vector<Real> strikes = {1.0, 0.5, 0.75, 1.5, 2.0};

    ext::shared_ptr<FdHestonVanillaEngine> singleStrikeEngine(
		ext::make_shared<FdHestonVanillaEngine>(model, 20, 400, 50));
    ext::shared_ptr<FdHestonVanillaEngine> multiStrikeEngine(
        ext::make_shared<FdHestonVanillaEngine>(model, 20, 400, 50));
    multiStrikeEngine->enableMultipleStrikesCaching(strikes);

    Real relTol = 5e-3;
    for (Real& strike : strikes) {
        ext::shared_ptr<StrikedTypePayoff> payoff(
            ext::make_shared<PlainVanillaPayoff>(Option::Put, strike));

        VanillaOption aOption(payoff, exercise);
        aOption.setPricingEngine(multiStrikeEngine);

        Real npvCalculated   = aOption.NPV();
        Real deltaCalculated = aOption.delta();
        Real gammaCalculated = aOption.gamma();
        Real thetaCalculated = aOption.theta();

        aOption.setPricingEngine(singleStrikeEngine);
        Real npvExpected   = aOption.NPV();
        Real deltaExpected = aOption.delta();
        Real gammaExpected = aOption.gamma();
        Real thetaExpected = aOption.theta();

        if (std::fabs(npvCalculated-npvExpected)/npvExpected > relTol) {
            BOOST_FAIL("failed to reproduce price with FD multi strike engine"
                       << "\n    calculated: " << npvCalculated
                       << "\n    expected:   " << npvExpected
                       << "\n    error:      " << std::scientific << relTol);
        }
        if (std::fabs(deltaCalculated-deltaExpected)/deltaExpected > relTol) {
            BOOST_FAIL("failed to reproduce delta with FD multi strike engine"
                       << "\n    calculated: " << deltaCalculated
                       << "\n    expected:   " << deltaExpected
                       << "\n    error:      " << std::scientific << relTol);
        }
        if (std::fabs(gammaCalculated-gammaExpected)/gammaExpected > relTol) {
            BOOST_FAIL("failed to reproduce gamma with FD multi strike engine"
                       << "\n    calculated: " << gammaCalculated
                       << "\n    expected:   " << gammaExpected
                       << "\n    error:      " << std::scientific << relTol);
        }
        if (std::fabs(thetaCalculated-thetaExpected)/thetaExpected > relTol) {
            BOOST_FAIL("failed to reproduce theta with FD multi strike engine"
                       << "\n    calculated: " << thetaCalculated
                       << "\n    expected:   " << thetaExpected
                       << "\n    error:      " << std::scientific << relTol);
        }
    }
}

BOOST_AUTO_TEST_CASE(testAnalyticPiecewiseTimeDependent) {
    BOOST_TEST_MESSAGE("Testing analytic piecewise time dependent Heston prices...");

    Date settlementDate(27, December, 2004);
    Settings::instance().evaluationDate() = settlementDate;
    DayCounter dayCounter = ActualActual(ActualActual::ISDA);
    Date exerciseDate(28, March, 2005);

    ext::shared_ptr<StrikedTypePayoff> payoff(
        ext::make_shared<PlainVanillaPayoff>(Option::Call, 1.0));
    ext::shared_ptr<Exercise> exercise(
		ext::make_shared<EuropeanExercise>(exerciseDate));

    std::vector<Date> dates = {settlementDate, {1, January, 2007}};
    std::vector<Rate> irates = {0.0, 0.2};
    Handle<YieldTermStructure> riskFreeTS(
		ext::make_shared<ZeroCurve>(dates, irates, dayCounter));

    std::vector<Rate> qrates = {0.0, 0.3};
    Handle<YieldTermStructure> dividendTS(
		ext::make_shared<ZeroCurve>(dates, qrates, dayCounter));
    
    const Real v0 = 0.1;
    Handle<Quote> s0(ext::make_shared<SimpleQuote>(1.0));

    ConstantParameter theta(0.09, PositiveConstraint());
    ConstantParameter kappa(3.16, PositiveConstraint());
    ConstantParameter sigma(4.40, PositiveConstraint());
    ConstantParameter rho  (-0.8, BoundaryConstraint(-1.0, 1.0));

    ext::shared_ptr<PiecewiseTimeDependentHestonModel> model =
        ext::make_shared<PiecewiseTimeDependentHestonModel>(
                                              riskFreeTS, dividendTS,
                                              s0, v0, theta, kappa, 
                                              sigma, rho, TimeGrid(20.0, 2));
    
    VanillaOption option(payoff, exercise);

    ext::shared_ptr<HestonProcess> hestonProcess(
        ext::make_shared<HestonProcess>(
                          riskFreeTS, dividendTS, s0, v0,
                          kappa(0.0), theta(0.0), sigma(0.0), rho(0.0)));
    ext::shared_ptr<HestonModel> hestonModel =
        ext::make_shared<HestonModel>(hestonProcess);
    option.setPricingEngine(
        ext::make_shared<AnalyticHestonEngine>(hestonModel));
    
    const Real expected = option.NPV();

    option.setPricingEngine(ext::shared_ptr<PricingEngine>(
         new AnalyticPTDHestonEngine(model, 192)));

    const Real calculatedGatheral = option.NPV();
    if (std::fabs(calculatedGatheral-expected) > 1e-7) {
        BOOST_ERROR("failed to reproduce Heston prices with Gatheral ChF"
                   << "\n    calculated: " << calculatedGatheral
                   << "\n    expected:   " << expected);
    }

    option.setPricingEngine(ext::shared_ptr<PricingEngine>(
         new AnalyticPTDHestonEngine(
             model,
             AnalyticPTDHestonEngine::AndersenPiterbarg,
             AnalyticPTDHestonEngine::Integration::gaussLobatto(1e-12,  Null<Real>(), 100000))));
    const Real calculatedAndersenPiterbarg = option.NPV();

    if (std::fabs(calculatedAndersenPiterbarg-expected) > 1e-9) {
        BOOST_ERROR("failed to reproduce Heston prices Andersen-Piterbarg"
                   << "\n    calculated: " << calculatedAndersenPiterbarg
                   << "\n    expected:   " << expected);
    }
}

BOOST_AUTO_TEST_CASE(testDAXCalibrationOfTimeDependentModel) {
    BOOST_TEST_MESSAGE(
             "Testing time-dependent Heston model calibration...");

    Date settlementDate(5, July, 2002);
    Settings::instance().evaluationDate() = settlementDate;

    CalibrationMarketData marketData = getDAXCalibrationMarketData();
    
    const Handle<YieldTermStructure> riskFreeTS = marketData.riskFreeTS;
    const Handle<YieldTermStructure> dividendTS = marketData.dividendYield;
    const Handle<Quote> s0 = marketData.s0;

    const std::vector<ext::shared_ptr<CalibrationHelper> >& options = marketData.options;

    std::vector<Time> modelTimes = {0.25, 10.0};
    const TimeGrid modelGrid(modelTimes.begin(), modelTimes.end());

    const Real v0=0.1;
    ConstantParameter sigma( 0.5, PositiveConstraint());
    ConstantParameter theta( 0.1, PositiveConstraint());
    ConstantParameter rho( -0.5, BoundaryConstraint(-1.0, 1.0));
   
    std::vector<Time> pTimes(1, 0.25);
    PiecewiseConstantParameter kappa(pTimes, PositiveConstraint());
    
    for (Size i=0; i < pTimes.size()+1; ++i) {
        kappa.setParam(i, 10.0);
    }

    ext::shared_ptr<PiecewiseTimeDependentHestonModel> model =
        ext::make_shared<PiecewiseTimeDependentHestonModel>(
                                              riskFreeTS, dividendTS,
                                              s0, v0, theta, kappa, 
                                              sigma, rho, modelGrid);

    const ext::shared_ptr<PricingEngine> engines[] = {
        ext::make_shared<AnalyticPTDHestonEngine>(model),
        ext::make_shared<AnalyticPTDHestonEngine>(
            model,
            AnalyticPTDHestonEngine::AndersenPiterbarg,
            AnalyticPTDHestonEngine::Integration::gaussLaguerre(64)),
        ext::make_shared<AnalyticPTDHestonEngine>(
            model,
            AnalyticPTDHestonEngine::AndersenPiterbarg,
            AnalyticPTDHestonEngine::Integration::discreteTrapezoid(72))
    };

    for (const auto& engine : engines) {
        for (const auto& option : options)
            ext::dynamic_pointer_cast<BlackCalibrationHelper>(option)->setPricingEngine(engine);

        LevenbergMarquardt om(1e-8, 1e-8, 1e-8);
        model->calibrate(options, om,
            EndCriteria(400, 40, 1.0e-8, 1.0e-8, 1.0e-8));
    
        Real sse = 0;
        for (Size i = 0; i < 13*8; ++i) {
            const Real diff = options[i]->calibrationError()*100.0;
            sse += diff*diff;
        }

        Real expected = 74.4;
        if (std::fabs(sse - expected) > 1.0) {
            BOOST_ERROR("Failed to reproduce calibration error"
                       << "\n    calculated: " << sse
                       << "\n    expected:   " << expected);
        }
    }
}

BOOST_AUTO_TEST_CASE(testAlanLewisReferencePrices) {
    BOOST_TEST_MESSAGE("Testing Alan Lewis reference prices...");

    /*
     * testing Alan Lewis reference prices posted in
     * http://wilmott.com/messageview.cfm?catid=34&threadid=90957
     */

    const Date settlementDate(5, July, 2002);
    Settings::instance().evaluationDate() = settlementDate;

    const Date maturityDate(5, July, 2003);
    const ext::shared_ptr<Exercise> exercise(
        ext::make_shared<EuropeanExercise>(maturityDate));

    const DayCounter dayCounter = Actual365Fixed();
    const Handle<YieldTermStructure> riskFreeTS(flatRate(0.01, dayCounter));
    const Handle<YieldTermStructure> dividendTS(flatRate(0.02, dayCounter));

    const Handle<Quote> s0(ext::make_shared<SimpleQuote>(100.0));

    const Real v0    =  0.04;
    const Real rho   = -0.5;
    const Real sigma =  1.0;
    const Real kappa =  4.0;
    const Real theta =  0.25;

    const ext::shared_ptr<HestonProcess> process(
        ext::make_shared<HestonProcess>(
            riskFreeTS, dividendTS, s0, v0, kappa, theta, sigma, rho));
    const ext::shared_ptr<HestonModel> model(
        ext::make_shared<HestonModel>(process));

    const ext::shared_ptr<PricingEngine> laguerreEngine(
        ext::make_shared<AnalyticHestonEngine>(model, 128U));

    const ext::shared_ptr<PricingEngine> gaussLobattoEngine(
        ext::make_shared<AnalyticHestonEngine>(model, QL_EPSILON, 100000U));

    const ext::shared_ptr<PricingEngine> cosEngine(
        ext::make_shared<COSHestonEngine>(model, 20, 400));

    const ext::shared_ptr<PricingEngine> exponentialFittingEngine(
        ext::make_shared<ExponentialFittingHestonEngine>(model));

    const ext::shared_ptr<PricingEngine> andersenPiterbargEngine(
        new AnalyticHestonEngine(
            model,
            AnalyticHestonEngine::AndersenPiterbarg,
            AnalyticHestonEngine::Integration::gaussLobatto(
                Null<Real>(), 1e-14, 1000000),
            QL_EPSILON)
    );

    const ext::shared_ptr<PricingEngine> angledContourEngine(
        new AnalyticHestonEngine(
            model,
            AnalyticHestonEngine::AngledContour,
            AnalyticHestonEngine::Integration::gaussLobatto(
                Null<Real>(), 1e-14, 1000000),
            QL_EPSILON)
    );

    const ext::shared_ptr<PricingEngine> optimalCvEngine(
        new AnalyticHestonEngine(
            model,
            AnalyticHestonEngine::OptimalCV,
            AnalyticHestonEngine::Integration::gaussLobatto(
                Null<Real>(), 1e-14, 1000000),
            QL_EPSILON)
    );

    const Real strikes[] = { 80, 90, 100, 110, 120 };
    const Option::Type types[] = { Option::Put, Option::Call };
    const ext::shared_ptr<PricingEngine> engines[]
        = { laguerreEngine, gaussLobattoEngine,
            cosEngine, andersenPiterbargEngine, exponentialFittingEngine,
            angledContourEngine, optimalCvEngine};

    const Real expectedResults[][2] = {
        { 7.958878113256768285213263077598987193482161301733,
          26.774758743998854221382195325726949201687074848341 },
        { 12.017966707346304987709573290236471654992071308187,
          20.933349000596710388139445766564068085476194042256 },
        { 17.055270961270109413522653999411000974895436309183,
          16.070154917028834278213466703938231827658768230714 },
        { 23.017825898442800538908781834822560777763225722188,
          12.132211516709844867860534767549426052805766831181 },
        { 29.811026202682471843340682293165857439167301370697,
          9.024913483457835636553375454092357136489051667150  }
    };

    const Real tol = 1e-12; // 3e-15 works on linux/ia32,
                            // but keep some buffer for other platforms

    for (Size i=0; i < std::size(strikes); ++i) {
        const Real strike = strikes[i];

        for (Size j=0; j < std::size(types); ++j) {
            const Option::Type type = types[j];

            for (Size k=0; k < std::size(engines); ++k) {
                const ext::shared_ptr<PricingEngine> engine = engines[k];

                const ext::shared_ptr<StrikedTypePayoff> payoff(
                    ext::make_shared<PlainVanillaPayoff>(type, strike));

                VanillaOption option(payoff, exercise);
                option.setPricingEngine(engine);

                const Real expected = expectedResults[i][j];
                const Real calculated = option.NPV();
                const Real relError = std::fabs(calculated-expected)/expected;

                if (relError > tol || std::isnan(calculated)) {
                    BOOST_ERROR(
                           "failed to reproduce Alan Lewis Reference prices "
                        << "\n    strike     : " << strike
                        << "\n    option type: " << type
                        << "\n    engine type: " << k
                        << "\n    rel. error : " << relError);
                }
            }
        }
    }
}

BOOST_AUTO_TEST_CASE(testExpansionOnAlanLewisReference) {
    BOOST_TEST_MESSAGE("Testing expansion on Alan Lewis reference prices...");

    const Date settlementDate(5, July, 2002);
    Settings::instance().evaluationDate() = settlementDate;

    const Date maturityDate(5, July, 2003);
    const ext::shared_ptr<Exercise> exercise =
        ext::make_shared<EuropeanExercise>(maturityDate);

    const DayCounter dayCounter = Actual365Fixed();
    const Handle<YieldTermStructure> riskFreeTS(flatRate(0.01, dayCounter));
    const Handle<YieldTermStructure> dividendTS(flatRate(0.02, dayCounter));

    const Handle<Quote> s0(ext::make_shared<SimpleQuote>(100.0));

    const Real v0    =  0.04;
    const Real rho   = -0.5;
    const Real sigma =  1.0;
    const Real kappa =  4.0;
    const Real theta =  0.25;

    const ext::shared_ptr<HestonProcess> process =
        ext::make_shared<HestonProcess>(riskFreeTS, dividendTS, s0, v0,
                                          kappa, theta, sigma, rho);
    const ext::shared_ptr<HestonModel> model =
        ext::make_shared<HestonModel>(process);

    const ext::shared_ptr<PricingEngine> lpp2Engine =
        ext::make_shared<HestonExpansionEngine>(model,
                                                  HestonExpansionEngine::LPP2);
    //don't test Forde as it does not behave well on this example
    const ext::shared_ptr<PricingEngine> lpp3Engine =
        ext::make_shared<HestonExpansionEngine>(model,
                                                  HestonExpansionEngine::LPP3);

    const Real strikes[] = { 80, 90, 100, 110, 120 };
    const Option::Type types[] = { Option::Put, Option::Call };
    const ext::shared_ptr<PricingEngine> engines[]
        = { lpp2Engine, lpp3Engine };

    const Real expectedResults[][2] = {
        { 7.958878113256768285213263077598987193482161301733,
          26.774758743998854221382195325726949201687074848341 },
        { 12.017966707346304987709573290236471654992071308187,
          20.933349000596710388139445766564068085476194042256 },
        { 17.055270961270109413522653999411000974895436309183,
          16.070154917028834278213466703938231827658768230714 },
        { 23.017825898442800538908781834822560777763225722188,
          12.132211516709844867860534767549426052805766831181 },
        { 29.811026202682471843340682293165857439167301370697,
          9.024913483457835636553375454092357136489051667150  }
    };

    const Real tol[2] = {1.003e-2, 3.645e-3};

    for (Size i=0; i < std::size(strikes); ++i) {
        const Real strike = strikes[i];

        for (Size j=0; j < std::size(types); ++j) {
            const Option::Type type = types[j];

            for (Size k=0; k < std::size(engines); ++k) {
                const ext::shared_ptr<PricingEngine> engine = engines[k];

                const ext::shared_ptr<StrikedTypePayoff> payoff =
                    ext::make_shared<PlainVanillaPayoff>(type, strike);

                VanillaOption option(payoff, exercise);
                option.setPricingEngine(engine);

                const Real expected = expectedResults[i][j];
                const Real calculated = option.NPV();
                const Real relError = std::fabs(calculated-expected)/expected;

                if (relError > tol[k]) {
                    BOOST_ERROR(
                           "failed to reproduce Alan Lewis Reference prices "
                        << "\n    strike     : " << strike
                        << "\n    option type: " << type
                        << "\n    engine type: " << k
                        << "\n    rel. error : " << relError);
                }
            }
        }
    }
}

BOOST_AUTO_TEST_CASE(testExpansionOnFordeReference) {
    BOOST_TEST_MESSAGE("Testing expansion on Forde reference prices...");

    const Real forward = 100.0;
    const Real v0      =  0.04;
    const Real rho     = -0.4;
    const Real sigma   =  0.2;
    const Real kappa   =  1.15;
    const Real theta   =  0.04;

    const Real terms[] = {0.1, 1.0, 5.0, 10.0};

    const Real strikes[] = { 60, 80, 90, 100, 110, 120, 140 };

    const Real referenceVols[][7] = {
       {0.27284673574924445, 0.22360758200372477, 0.21023988547031242, 0.1990674789471587, 0.19118230678920461, 0.18721342919371017, 0.1899869903378507},
       {0.25200775151345, 0.2127275920953156, 0.20286528150874591, 0.19479398358151515, 0.18872591728967686, 0.18470857955411824, 0.18204457060905446},
       {0.21637821506229973, 0.20077227130455172, 0.19721753043236154, 0.1942233023784151, 0.191693211401571, 0.18955229722896752, 0.18491727548069495},
       {0.20672925973965342, 0.198583062164427, 0.19668274423922746, 0.1950420231354201, 0.193610364344706, 0.1923502827886502, 0.18934360917857015}
    };

    const Real tol[][4] = {
        {0.06, 0.03, 0.03, 0.02},
        {0.15, 0.08, 0.04, 0.02},
        {0.06, 0.08, 1.0, 1.0} //forde breaks down for long maturities
    };
    const Real tolAtm[][4] = {
        {4e-6, 7e-4, 2e-3, 9e-4},
        {7e-6, 4e-4, 9e-4, 4e-4},
        {4e-4, 3e-2, 0.28, 1.0}
    };
    for (Size j=0; j < std::size(terms); ++j) {
        const Real term = terms[j];
        const ext::shared_ptr<HestonExpansion> lpp2 =
            ext::make_shared<LPP2HestonExpansion>(kappa, theta, sigma,
                                                    v0, rho, term);
        const ext::shared_ptr<HestonExpansion> lpp3 =
            ext::make_shared<LPP3HestonExpansion>(kappa, theta, sigma,
                                                    v0, rho, term);
        const ext::shared_ptr<HestonExpansion> forde =
            ext::make_shared<FordeHestonExpansion>(kappa, theta, sigma,
                                                     v0, rho, term);
        const ext::shared_ptr<HestonExpansion> expansions[] = { lpp2, lpp3, forde };
        for (Size i=0; i < std::size(strikes); ++i) {
            const Real strike = strikes[i];
            for (Size k=0; k < std::size(expansions); ++k) {
                const ext::shared_ptr<HestonExpansion> expansion = expansions[k];

                const Real expected = referenceVols[j][i];
                const Real calculated = expansion->impliedVolatility(strike, forward);
                const Real relError = std::fabs(calculated-expected)/expected;
                const Real refTol = strike == forward ? tolAtm[k][j] : tol[k][j];
                if (relError > refTol) {
                    BOOST_ERROR(
                           "failed to reproduce Forde reference vols "
                        << "\n    strike        : " << strike
                        << "\n    expansion type: " << k
                        << "\n    rel. error    : " << relError);
                }
            }
        }
    }
}

BOOST_AUTO_TEST_CASE(testAllIntegrationMethods) {
    BOOST_TEST_MESSAGE("Testing semi-analytic Heston pricing with all "
                       "integration methods...");

    const Date settlementDate(7, February, 2017);
    Settings::instance().evaluationDate() = settlementDate;

    const DayCounter dayCounter = Actual365Fixed();
    const Handle<YieldTermStructure> riskFreeTS(flatRate(0.05, dayCounter));
    const Handle<YieldTermStructure> dividendTS(flatRate(0.075, dayCounter));

    const Handle<Quote> s0(ext::make_shared<SimpleQuote>(100.0));

    const Real v0    =  0.1;
    const Real rho   = -0.75;
    const Real sigma =  0.4;
    const Real kappa =  4.0;
    const Real theta =  0.05;

    const ext::shared_ptr<HestonModel> model =
        ext::make_shared<HestonModel>(
            ext::make_shared<HestonProcess>(
                riskFreeTS, dividendTS,
                s0, v0, kappa, theta, sigma, rho));

    const ext::shared_ptr<StrikedTypePayoff> payoff =
        ext::make_shared<PlainVanillaPayoff>(Option::Put, s0->value());

    const Date maturityDate = settlementDate + Period(1, Years);
    const ext::shared_ptr<Exercise> exercise =
        ext::make_shared<EuropeanExercise>(maturityDate);

    VanillaOption option(payoff, exercise);

    const Real tol = 1e-8;
    const Real expected = 10.147041515497;

    // Gauss-Laguerre with Gatheral logarithm integration method
    reportOnIntegrationMethodTest(option, model,
        AnalyticHestonEngine::Integration::gaussLaguerre(),
        AnalyticHestonEngine::Gatheral,
        false, expected, tol, 256, "Gauss-Laguerre with Gatheral logarithm");

    // Gauss-Laguerre with branch correction integration method
    reportOnIntegrationMethodTest(option, model,
        AnalyticHestonEngine::Integration::gaussLaguerre(),
        AnalyticHestonEngine::BranchCorrection,
        false, expected, tol, 256, "Gauss-Laguerre with branch correction");

    // Gauss-Laguerre with Andersen-Piterbarg integration method
    reportOnIntegrationMethodTest(option, model,
        AnalyticHestonEngine::Integration::gaussLaguerre(),
        AnalyticHestonEngine::AndersenPiterbarg,
        false, expected, tol, 128,
        "Gauss-Laguerre with Andersen Piterbarg control variate");

    // Gauss-Legendre with Gatheral logarithm integration method
    reportOnIntegrationMethodTest(option, model,
        AnalyticHestonEngine::Integration::gaussLegendre(),
        AnalyticHestonEngine::Gatheral,
        false, expected, tol, 256, "Gauss-Legendre with Gatheral logarithm");

    // Gauss-Legendre with branch correction integration method
    reportOnIntegrationMethodTest(option, model,
        AnalyticHestonEngine::Integration::gaussLegendre(),
        AnalyticHestonEngine::BranchCorrection,
        false, expected, tol, 256, "Gauss-Legendre with branch correction");

    // Gauss-Legendre with Andersen-Piterbarg integration method
    reportOnIntegrationMethodTest(option, model,
        AnalyticHestonEngine::Integration::gaussLegendre(256),
        AnalyticHestonEngine::AndersenPiterbarg,
        false, expected, 1e-4, 256,
        "Gauss-Legendre with Andersen Piterbarg control variate");

    // Gauss-Chebyshev with Gatheral logarithm integration method
    reportOnIntegrationMethodTest(option, model,
        AnalyticHestonEngine::Integration::gaussChebyshev(512),
        AnalyticHestonEngine::Gatheral,
        false, expected, 1e-4, 1024, "Gauss-Chebyshev with Gatheral logarithm");

    // Gauss-Chebyshev with branch correction integration method
    reportOnIntegrationMethodTest(option, model,
        AnalyticHestonEngine::Integration::gaussChebyshev(512),
        AnalyticHestonEngine::BranchCorrection,
        false, expected, 1e-4, 1024, "Gauss-Chebyshev with branch correction");

    // Gauss-Chebyshev with Andersen-Piterbarg integration method
    reportOnIntegrationMethodTest(option, model,
        AnalyticHestonEngine::Integration::gaussChebyshev(512),
        AnalyticHestonEngine::AndersenPiterbarg,
        false, expected, 1e-4, 512,
        "Gauss-Laguerre with Andersen Piterbarg control variate");

    // Gauss-Chebyshev2nd with Gatheral logarithm integration method
    reportOnIntegrationMethodTest(option, model,
        AnalyticHestonEngine::Integration::gaussChebyshev2nd(512),
        AnalyticHestonEngine::Gatheral,
        false, expected, 2e-4, 1024,
        "Gauss-Chebyshev2nd with Gatheral logarithm");

    // Gauss-Chebyshev with branch correction integration method
    reportOnIntegrationMethodTest(option, model,
        AnalyticHestonEngine::Integration::gaussChebyshev2nd(512),
        AnalyticHestonEngine::BranchCorrection,
        false, expected, 2e-4, 1024,
        "Gauss-Chebyshev2nd with branch correction");

    // Gauss-Chebyshev with Andersen-Piterbarg integration method
    reportOnIntegrationMethodTest(option, model,
        AnalyticHestonEngine::Integration::gaussChebyshev2nd(512),
        AnalyticHestonEngine::AndersenPiterbarg,
        false, expected, 2e-4, 512,
        "Gauss-Chebyshev2nd with Andersen Piterbarg control variate");

    // Discrete Simpson rule with Gatheral logarithm
    reportOnIntegrationMethodTest(option, model,
        AnalyticHestonEngine::Integration::discreteSimpson(512),
        AnalyticHestonEngine::Gatheral,
        false, expected, tol, 1024,
        "Discrete Simpson rule with Gatheral logarithm");

    // Discrete Simpson rule with Andersen-Piterbarg integration method
    reportOnIntegrationMethodTest(option, model,
        AnalyticHestonEngine::Integration::discreteSimpson(64),
        AnalyticHestonEngine::AndersenPiterbarg,
        false, expected, tol, 64,
        "Discrete Simpson rule with Andersen Piterbarg control variate");

    // Discrete Trapezoid rule with Gatheral logarithm
    reportOnIntegrationMethodTest(option, model,
        AnalyticHestonEngine::Integration::discreteTrapezoid(512),
        AnalyticHestonEngine::Gatheral,
        false, expected, 2e-4, 1024,
        "Discrete Trapezoid rule with Gatheral logarithm");

    // Discrete Trapezoid rule with Andersen-Piterbarg integration method
    reportOnIntegrationMethodTest(option, model,
        AnalyticHestonEngine::Integration::discreteTrapezoid(64),
        AnalyticHestonEngine::AndersenPiterbarg,
        false, expected, tol, 64,
        "Discrete Trapezoid rule with Andersen Piterbarg control variate");

    // Gauss-Lobatto with Gatheral logarithm
    reportOnIntegrationMethodTest(option, model,
        AnalyticHestonEngine::Integration::gaussLobatto(tol, Null<Real>()),
        AnalyticHestonEngine::Gatheral,
        true, expected, tol, Null<Size>(),
        "Gauss-Lobatto with Gatheral logarithm");

    // Gauss-Lobatto with Andersen-Piterbarg integration method
    reportOnIntegrationMethodTest(option, model,
        AnalyticHestonEngine::Integration::gaussLobatto(tol, Null<Real>()),
        AnalyticHestonEngine::AndersenPiterbarg,
        true, expected, tol, Null<Size>(),
        "Gauss-Lobatto with Andersen Piterbarg control variate");

    // Gauss-Konrod with Gatheral logarithm
    reportOnIntegrationMethodTest(option, model,
        AnalyticHestonEngine::Integration::gaussKronrod(tol),
        AnalyticHestonEngine::Gatheral,
        true, expected, tol, Null<Size>(),
        "Gauss-Konrod with Gatheral logarithm");

    // Gauss-Konrod with Andersen-Piterbarg integration method
    reportOnIntegrationMethodTest(option, model,
        AnalyticHestonEngine::Integration::gaussKronrod(tol),
        AnalyticHestonEngine::AndersenPiterbarg,
        true, expected, tol, Null<Size>(),
        "Gauss-Konrod with Andersen Piterbarg control variate");

    // Simpson with Gatheral logarithm
    reportOnIntegrationMethodTest(option, model,
        AnalyticHestonEngine::Integration::simpson(tol),
        AnalyticHestonEngine::Gatheral,
        true, expected, 1e-6, Null<Size>(),
        "Simpson with Gatheral logarithm");

    // Simpson with Andersen-Piterbarg integration method
    reportOnIntegrationMethodTest(option, model,
        AnalyticHestonEngine::Integration::simpson(tol),
        AnalyticHestonEngine::AndersenPiterbarg,
        true, expected, 1e-6, Null<Size>(),
        "Simpson with Andersen Piterbarg control variate");

    // Trapezoid with Gatheral logarithm
    reportOnIntegrationMethodTest(option, model,
        AnalyticHestonEngine::Integration::trapezoid(tol),
        AnalyticHestonEngine::Gatheral,
        true, expected, 1e-6, Null<Size>(),
        "Trapezoid with Gatheral logarithm");

    // Trapezoid with Andersen-Piterbarg integration method
    reportOnIntegrationMethodTest(option, model,
        AnalyticHestonEngine::Integration::trapezoid(tol),
        AnalyticHestonEngine::AndersenPiterbarg,
        true, expected, 1e-6, Null<Size>(),
        "Trapezoid with Andersen Piterbarg control variate");

    // Angled contour shift integral
    reportOnIntegrationMethodTest(option, model,
        AnalyticHestonEngine::Integration::gaussLaguerre(),
        AnalyticHestonEngine::AngledContour,
        false, expected, tol, 128,
        "Angled contour shift integral");

    // Angled contour shift integral w/o control variate
    reportOnIntegrationMethodTest(option, model,
        AnalyticHestonEngine::Integration::gaussLaguerre(192),
        AnalyticHestonEngine::AngledContourNoCV,
        false, expected, tol, 192,
        "Angled contour shift integral without control variate");

#ifdef QL_BOOST_HAS_EXP_SINH
    // Angled contour shift integral with expSinh
    reportOnIntegrationMethodTest(option, model,
        AnalyticHestonEngine::Integration::expSinh(),
        AnalyticHestonEngine::AngledContour,
        true, expected, 1e-8, Null<Size>(),
        "exp-sinh integration with angled contour shift integral");
#endif

}

BOOST_AUTO_TEST_CASE(testCosHestonCumulants) {
    BOOST_TEST_MESSAGE("Testing Heston COS cumulants...");

    const Date settlementDate(7, February, 2017);
    Settings::instance().evaluationDate() = settlementDate;

    const DayCounter dayCounter = Actual365Fixed();
    const Handle<YieldTermStructure> riskFreeTS(flatRate(0.15, dayCounter));
    const Handle<YieldTermStructure> dividendTS(flatRate(0.075, dayCounter));

    const Handle<Quote> s0(ext::make_shared<SimpleQuote>(100.0));

    const Real v0    =  0.1;
    const Real rho   = -0.75;
    const Real sigma =  0.4;
    const Real kappa =  4.0;
    const Real theta =  0.25;

    const ext::shared_ptr<HestonModel> model =
        ext::make_shared<HestonModel>(
            ext::make_shared<HestonProcess>(
                riskFreeTS, dividendTS,
                s0, v0, kappa, theta, sigma, rho));

    const ext::shared_ptr<COSHestonEngine> cosEngine =
        ext::make_shared<COSHestonEngine>(model);

    const Real tol = 1e-7;
    const NumericalDifferentiation::Scheme central(
        NumericalDifferentiation::Central);

    for (Time t=0.01; t < 41.0; t+=t) {
        const Real nc1 = NumericalDifferentiation(
            std::function<Real(Real)>(
                LogCharacteristicFunction(1, t, cosEngine)),
            1, 1e-5, 5, central)(0.0);

        const Real c1 = cosEngine->c1(t);

        if (std::fabs(nc1 - c1) > tol) {
            BOOST_ERROR(" failed to reproduce first cumulant"
                    << "\n    expected:   " << nc1
                    << "\n    calculated: " << c1
                    << "\n    difference: " << std::fabs(nc1 - c1));
        }

        const Real nc2 = NumericalDifferentiation(
            std::function<Real(Real)>(
                LogCharacteristicFunction(2, t, cosEngine)),
            2, 1e-2, 5, central)(0.0);

        const Real c2 = cosEngine->c2(t);

        if (std::fabs(nc2 - c2) > tol) {
            BOOST_ERROR(" failed to reproduce second cumulant"
                    << "\n    expected:   " << nc2
                    << "\n    calculated: " << c2
                    << "\n    difference: " << std::fabs(nc2 - c2));
        }

        const Real nc3 = NumericalDifferentiation(
            std::function<Real(Real)>(
                LogCharacteristicFunction(3, t, cosEngine)),
            3, 5e-3, 7, central)(0.0);

        const Real c3 = cosEngine->c3(t);

        if (std::fabs(nc3 - c3) > tol) {
            BOOST_ERROR(" failed to reproduce third cumulant"
                    << "\n    expected:   " << nc3
                    << "\n    calculated: " << c3
                    << "\n    difference: " << std::fabs(nc3 - c3));
        }

        const Real nc4 = NumericalDifferentiation(
            std::function<Real(Real)>(
                LogCharacteristicFunction(4, t, cosEngine)),
            4, 5e-2, 9, central)(0.0);

        const Real c4 = cosEngine->c4(t);

        if (std::fabs(nc4 - c4) > 10*tol) {
            BOOST_ERROR(" failed to reproduce 4th cumulant"
                    << "\n    expected:   " << nc4
                    << "\n    calculated: " << c4
                    << "\n    difference: " << std::fabs(nc4 - c4));
        }
    }
}

BOOST_AUTO_TEST_CASE(testCosHestonEngine) {
    BOOST_TEST_MESSAGE("Testing Heston pricing via COS method...");

    const Date settlementDate(7, February, 2017);
    Settings::instance().evaluationDate() = settlementDate;

    const DayCounter dayCounter = Actual365Fixed();
    const Handle<YieldTermStructure> riskFreeTS(flatRate(0.15, dayCounter));
    const Handle<YieldTermStructure> dividendTS(flatRate(0.07, dayCounter));

    const Handle<Quote> s0(ext::make_shared<SimpleQuote>(100.0));

    const Real v0    =  0.1;
    const Real rho   = -0.75;
    const Real sigma =  1.8;
    const Real kappa =  4.0;
    const Real theta =  0.22;

    const ext::shared_ptr<HestonModel> model =
        ext::make_shared<HestonModel>(
            ext::make_shared<HestonProcess>(
                riskFreeTS, dividendTS,
                s0, v0, kappa, theta, sigma, rho));

    const Date maturityDate = settlementDate + Period(1, Years);

    const ext::shared_ptr<Exercise> exercise =
        ext::make_shared<EuropeanExercise>(maturityDate);

    const ext::shared_ptr<PricingEngine> cosEngine(
        ext::make_shared<COSHestonEngine>(model, 25, 600));

    const ext::shared_ptr<StrikedTypePayoff> payoffs[] = {
        ext::make_shared<PlainVanillaPayoff>(Option::Call, s0->value()+20),
        ext::make_shared<PlainVanillaPayoff>(Option::Call, s0->value()+150),
        ext::make_shared<PlainVanillaPayoff>(Option::Put, s0->value()-20),
        ext::make_shared<PlainVanillaPayoff>(Option::Put, s0->value()-90)
    };

    const Real expected[] = {
        9.364410588426075, 0.01036797658132471,
        5.319092971836708, 0.01032681906278383 };

    const Real tol = 1e-10;

    for (Size i=0; i < std::size(payoffs); ++i) {
        VanillaOption option(payoffs[i], exercise);

        option.setPricingEngine(cosEngine);
        const Real calculated = option.NPV();

        const Real error = std::fabs(expected[i] - calculated);

        if (error > tol) {
            BOOST_ERROR(" failed to reproduce prices with COSHestonEngine"
                    << "\n    expected:   " << expected[i]
                    << "\n    calculated: " << calculated
                    << "\n    difference: " << error);
        }
    }
}

BOOST_AUTO_TEST_CASE(testCosHestonEngineTruncation) {
    BOOST_TEST_MESSAGE("Testing Heston pricing via COS method outside truncation bounds...");
    
    const Date todaysDate(22, August, 2022);
    const Date maturity(23, August, 2022);
    Settings::instance().evaluationDate() = todaysDate;

    Option::Type type(Option::Call);
    Real underlying = 100;
    Real strike = 200;
    Rate dividendYield = 0;
    Rate riskFreeRate = 0;
    DayCounter dayCounter = Actual365Fixed();

    ext::shared_ptr<Exercise> europeanExercise(new EuropeanExercise(maturity));
    Handle<Quote> underlyingH(ext::shared_ptr<Quote>(new SimpleQuote(underlying)));
    Handle<YieldTermStructure> riskFreeTS(
        ext::shared_ptr<YieldTermStructure>(
            new FlatForward(todaysDate, riskFreeRate, dayCounter)));
    Handle<YieldTermStructure> dividendTS(
        ext::shared_ptr<YieldTermStructure>(
            new FlatForward(todaysDate, dividendYield, dayCounter)));

    ext::shared_ptr<StrikedTypePayoff> payoff(new PlainVanillaPayoff(type, strike));
    VanillaOption europeanOption(payoff, europeanExercise);

    ext::shared_ptr<HestonProcess> hestonProcess(
            new HestonProcess(riskFreeTS, dividendTS, underlyingH, .007, .8, .007, .1, -.2));
    ext::shared_ptr<HestonModel> hestonModel(
            new HestonModel(hestonProcess));
    
    europeanOption.setPricingEngine(ext::shared_ptr<PricingEngine>(
                new COSHestonEngine(hestonModel)));
                
    const Real tol = 1e-7;
    const Real error = std::fabs(europeanOption.NPV() - 0.0);

    if (error > tol) {
        BOOST_ERROR(" failed to reproduce prices with COSHestonEngine"
                << "\n    expected:   " << 0.0
                << "\n    calculated: " << europeanOption.NPV()
                << "\n    difference: " << error);
    }
    
}

BOOST_AUTO_TEST_CASE(testCharacteristicFct) {
    BOOST_TEST_MESSAGE("Testing Heston characteristic function...");

    const Date settlementDate(30, March, 2017);
    Settings::instance().evaluationDate() = settlementDate;

    const DayCounter dayCounter = Actual365Fixed();
    const Handle<YieldTermStructure> riskFreeTS(flatRate(0.35, dayCounter));
    const Handle<YieldTermStructure> dividendTS(flatRate(0.17, dayCounter));

    const Handle<Quote> s0(ext::shared_ptr<Quote>(new SimpleQuote(100.0)));

    const Real v0    =  0.1;
    const Real rho   = -0.85;
    const Real sigma =  0.8;
    const Real kappa =  2.0;
    const Real theta =  0.15;

    const ext::shared_ptr<HestonModel> model =
        ext::make_shared<HestonModel>(
            ext::make_shared<HestonProcess>(
                riskFreeTS, dividendTS,
                s0, v0, kappa, theta, sigma, rho));

    const Real u[] = { 1.0, 0.45, 3,4 };
    const Real t[] = { 0.01, 23.2, 3.2};

    const COSHestonEngine cosEngine(model);
    const AnalyticHestonEngine analyticEngine(model);

    constexpr double tol = 100*QL_EPSILON;
    for (Real i : u) {
        for (Real j : t) {
            const std::complex<Real> c = cosEngine.chF(i, j);
            const std::complex<Real> a = analyticEngine.chF(i, j);

            const Real error = std::abs(a-c);
            if (error > tol) {
                BOOST_ERROR(" failed to reproduce prices with characteristic Fct"
                        << "\n    Cos Engine:      " << c
                        << "\n    analytic engine: " << a
                        << "\n    difference:      " << error);
            }
        }
    }
}

BOOST_AUTO_TEST_CASE(testAndersenPiterbargPricing) {
    BOOST_TEST_MESSAGE("Testing Andersen-Piterbarg method to "
                       "price under the Heston model...");

    const Date settlementDate(30, March, 2017);
    Settings::instance().evaluationDate() = settlementDate;

    const DayCounter dayCounter = Actual365Fixed();
    const Handle<YieldTermStructure> riskFreeTS(flatRate(0.10, dayCounter));
    const Handle<YieldTermStructure> dividendTS(flatRate(0.06, dayCounter));

    const Handle<Quote> s0(ext::shared_ptr<Quote>(new SimpleQuote(100.0)));

    const Real v0    =  0.1;
    const Real rho   =  0.80;
    const Real sigma =  0.75;
    const Real kappa =  1.0;
    const Real theta =  0.1;

    const ext::shared_ptr<HestonModel> model =
        ext::make_shared<HestonModel>(
            ext::make_shared<HestonProcess>(
                riskFreeTS, dividendTS,
                s0, v0, kappa, theta, sigma, rho));

    const ext::shared_ptr<AnalyticHestonEngine>
        andersenPiterbargLaguerreEngine(
            ext::make_shared<AnalyticHestonEngine>(
                model,
                AnalyticHestonEngine::AndersenPiterbarg,
                AnalyticHestonEngine::Integration::gaussLaguerre()));

    const ext::shared_ptr<AnalyticHestonEngine>
        andersenPiterbargLobattoEngine(
            ext::make_shared<AnalyticHestonEngine>(
                model,
                AnalyticHestonEngine::AndersenPiterbarg,
                AnalyticHestonEngine::Integration::gaussLobatto(
                    Null<Real>(), 1e-9, 10000), 1e-9));

    const ext::shared_ptr<AnalyticHestonEngine>
        andersenPiterbargSimpsonEngine(
            ext::make_shared<AnalyticHestonEngine>(
                model,
                AnalyticHestonEngine::AndersenPiterbarg,
                AnalyticHestonEngine::Integration::discreteSimpson(256),
                1e-8));

    const ext::shared_ptr<AnalyticHestonEngine>
        andersenPiterbargTrapezoidEngine(
            ext::make_shared<AnalyticHestonEngine>(
                model,
                AnalyticHestonEngine::AndersenPiterbarg,
                AnalyticHestonEngine::Integration::discreteTrapezoid(164),
                1e-8));

    const ext::shared_ptr<AnalyticHestonEngine>
        andersenPiterbargTrapezoidEngine2(
            ext::make_shared<AnalyticHestonEngine>(
                model,
                AnalyticHestonEngine::AndersenPiterbarg,
                AnalyticHestonEngine::Integration::trapezoid(1e-8, 256),
                1e-8));

    const ext::shared_ptr<ExponentialFittingHestonEngine>
        andersenPiterbargExponentialFittingEngine(
            ext::make_shared<ExponentialFittingHestonEngine>(model));

    const ext::shared_ptr<PricingEngine> engines[] = {
        andersenPiterbargLaguerreEngine,
        andersenPiterbargLobattoEngine,
        andersenPiterbargSimpsonEngine,
        andersenPiterbargTrapezoidEngine,
        andersenPiterbargTrapezoidEngine2,
        andersenPiterbargExponentialFittingEngine
    };

    const std::string algos[] = {
          "Gauss-Laguerre", "Gauss-Lobatto",
          "Discrete Simpson", "Discrete Trapezoid", "Trapezoid",
          "Exponential Fitting"
    };

    const ext::shared_ptr<PricingEngine> analyticEngine(
        ext::make_shared<AnalyticHestonEngine>(model, 192));

    const Date maturityDates[] = {
        settlementDate + Period(1, Days),
        settlementDate + Period(1, Weeks),
        settlementDate + Period(1, Years),
        settlementDate + Period(10, Years)
    };

    const Option::Type optionTypes[] = { Option::Call, Option::Put };
    const Real strikes[] = { 50, 75, 90, 100, 110, 130, 150, 200};

    const Real tol = 1e-8;

    for (auto maturityDate : maturityDates) {
        const ext::shared_ptr<Exercise> exercise = ext::make_shared<EuropeanExercise>(maturityDate);

        for (auto optionType : optionTypes) {
            for (Real strike : strikes) {
                VanillaOption option(ext::make_shared<PlainVanillaPayoff>(optionType, strike),
                                     exercise);

                option.setPricingEngine(analyticEngine);
                const Real expected = option.NPV();

                for (Size k=0; k < std::size(engines); ++k) {
                    option.setPricingEngine(engines[k]);
                    const Real calculated = option.NPV();

                    const Real error = std::fabs(calculated-expected);

                    if (error > tol) {
                        BOOST_ERROR(" failed to reproduce prices with Andersen-"
                                    "Piterbarg control variate"
                                    << "\n    algorithm      : " << algos[k]
                                    << "\n    strike         : " << strike
                                    << "\n    control variate: " << calculated
                                    << "\n    classic engine : " << expected
                                    << "\n    difference:      " << error);
                    }
                }
            }
        }
    }
}

BOOST_AUTO_TEST_CASE(testAndersenPiterbargControlVariateIntegrand) {
    BOOST_TEST_MESSAGE("Testing Andersen-Piterbarg Integrand "
                        "with control variate...");

    const Date settlementDate(17, April, 2017);
    Settings::instance().evaluationDate() = settlementDate;
    const Date maturityDate = settlementDate + Period(2, Years);

    const DayCounter dayCounter = Actual365Fixed();
    const Rate r = 0.075;
    const Rate q = 0.05;
    const Handle<YieldTermStructure> rTS(flatRate(r, dayCounter));
    const Handle<YieldTermStructure> qTS(flatRate(q, dayCounter));

    const Time maturity = dayCounter.yearFraction(settlementDate, maturityDate);
    const DiscountFactor df = rTS->discount(maturity);

    const Handle<Quote> s0(ext::shared_ptr<Quote>(new SimpleQuote(100.0)));
    const Real fwd = s0->value()*qTS->discount(maturity)/df;

    const Real strike = 150;
    const Real sx = std::log(strike);
    const Real dd = std::log(s0->value()*qTS->discount(maturity)/df);

    const Real v0    =  0.08;
    const Real rho   =  -0.8;
    const Real sigma =  0.5;
    const Real kappa =  4.0;
    const Real theta =  0.05;

    const ext::shared_ptr<HestonModel> hestonModel(
        ext::make_shared<HestonModel>(
            ext::make_shared<HestonProcess>(
                rTS, qTS, s0, v0, kappa, theta, sigma, rho)));

    const ext::shared_ptr<COSHestonEngine> cosEngine(
        ext::make_shared<COSHestonEngine>(hestonModel));

    const ext::shared_ptr<AnalyticHestonEngine> engine(
        ext::make_shared<AnalyticHestonEngine>(
            hestonModel,
            AnalyticHestonEngine::AndersenPiterbarg,
            AnalyticHestonEngine::Integration::gaussLaguerre()));

    VanillaOption option(
        ext::make_shared<PlainVanillaPayoff>(Option::Call, strike),
        ext::make_shared<EuropeanExercise>(maturityDate));
    option.setPricingEngine(engine);

    const Real refNPV = option.NPV();

    const Volatility implStdDev = blackFormulaImpliedStdDev(
            Option::Call, strike, fwd, refNPV, df);

    const Real var = cosEngine->var(maturity);
    const Real stdDev = std::sqrt(var);

    const Real d = (std::log(s0->value()/strike)
        + (r-q)*maturity+ 0.5*var)/stdDev;

    const Real skew = cosEngine->skew(maturity);
    const Real kurt = cosEngine->kurtosis(maturity);

    const NormalDistribution n;

    const Real q3 = 1/6.*s0->value()*stdDev*(2*stdDev - d)*n(d);
    const Real q4 = 1/24.*s0->value()*stdDev*(d*d - 3*d*stdDev - 1)*n(d);
    const Real q5 = 1/72.*s0->value()*stdDev*(
        d*d*d*d - 5*d*d*d*stdDev - 6*d*d + 15*d*stdDev + 3)*n(d);

    const Real bsNPV = blackFormula(Option::Call, strike, fwd, stdDev, df);

    // different variance values for the control variate
    const Real variances[] = {
        v0*maturity,
        ((1-std::exp(-kappa*maturity))*(v0-theta)/(kappa*maturity) + theta)
            *maturity,
        // second moment as control variate
        var,
        // third and fourth moment pricing based on
        // Corrado C. and T. Su, (1996-b),
        // “Skewness and Kurtosis in S&P 500 IndexReturns Implied by Option Prices”,
        // Journal of Financial Research 19 (2), 175-192.
        squared(blackFormulaImpliedStdDev(
            Option::Call, strike, fwd, bsNPV + skew*q3, df)),
        squared(blackFormulaImpliedStdDev(
            Option::Call, strike, fwd, bsNPV + skew*q3 + kurt*q4, df)),
        // Moment matching based on
        // Rubinstein M., (1998), “Edgeworth Binomial Trees”,
        // Journal of Derivatives 5 (3), 20-27.
        squared(blackFormulaImpliedStdDev(
            Option::Call, strike, fwd,
            bsNPV + skew*q3 + kurt*q4 + skew*skew*q5, df)),
        // implied vol as control variate
        squared(implStdDev),
        // remaining function becomes zero for u -> 0
        -8.0*std::log(engine->chF(std::complex<Real>(0, -0.5), maturity).real())
    };

    for (Size i=0; i < std::size(variances); ++i) {
        const Real sigmaBS = std::sqrt(variances[i]/maturity);

        for (Real u =0.001; u < 15; u*=1.05) {
            const std::complex<Real> z(u, -0.5);

            const std::complex<Real> phiBS
                = std::exp(-0.5*sigmaBS*sigmaBS*maturity
                           *(z*z + std::complex<Real>(-z.imag(), z.real())));

            const std::complex<Real> ex
                = std::exp(std::complex<Real>(0.0, u*(dd-sx)));

            const std::complex<Real> chf = engine->chF(z, maturity);

            const Real orig = (-ex*chf / (u*u + 0.25)).real();
            const Real cv = (ex*(phiBS - chf) / (u*u + 0.25)).real();

            if (std::fabs(cv) > 0.03) {
                BOOST_ERROR(" Control variate function is greater "
                        "than original function"
                        << "\n    control variate method  : " << i
                        << "\n    z value                 : " << u
                        << "\n    control variate function: " << cv
                        << "\n    original function       : " << orig);
            }
        }
    }
}

BOOST_AUTO_TEST_CASE(testAndersenPiterbargConvergence) {
    BOOST_TEST_MESSAGE("Testing Andersen-Piterbarg pricing convergence...");

    const Date settlementDate(5, July, 2002);
    Settings::instance().evaluationDate() = settlementDate;
    const Date maturityDate(5, July, 2003);

    const DayCounter dayCounter = Actual365Fixed();
    const Handle<YieldTermStructure> rTS(flatRate(0.01, dayCounter));
    const Handle<YieldTermStructure> qTS(flatRate(0.02, dayCounter));

    const Handle<Quote> s0(ext::shared_ptr<Quote>(new SimpleQuote(100.0)));

    const Real v0    =  0.04;
    const Real rho   = -0.5;
    const Real sigma =  1.0;
    const Real kappa =  4.0;
    const Real theta =  0.25;

    const ext::shared_ptr<HestonModel> hestonModel(
        ext::make_shared<HestonModel>(
            ext::make_shared<HestonProcess>(
                rTS, qTS, s0, v0, kappa, theta, sigma, rho)));

    VanillaOption option(
        ext::make_shared<PlainVanillaPayoff>(Option::Call, s0->value()),
        ext::make_shared<EuropeanExercise>(maturityDate));


    // Alan Lewis reference prices posted in
    // http://wilmott.com/messageview.cfm?catid=34&threadid=90957
    const Real reference = 16.070154917028834278213466703938231827658768230714;

    const Real diffs[] = {
            0.0892433814611486298,   0.00013096156482816923,
            1.34107015270501506e-07, 1.22913235145460931e-10,
            1.24344978758017533e-13 };

    for (Size n=10; n <= 50; n+=10) {
        option.setPricingEngine(ext::make_shared<AnalyticHestonEngine>(
            hestonModel, AnalyticHestonEngine::AndersenPiterbarg,
            AnalyticHestonEngine::Integration::discreteTrapezoid(n), 1e-13));

        const Real calculatedDiff = std::fabs(option.NPV()-reference);
        if (calculatedDiff > 1.25*diffs[n/10-1])
            BOOST_ERROR("failed to prove convergence for trapezoid rule "
                    << "\n  calculated difference: " << calculatedDiff
                    << "\n  expected difference:   " << diffs[n/10-1]);
    }
}

BOOST_AUTO_TEST_CASE(testPiecewiseTimeDependentChFvsHestonChF) {
    BOOST_TEST_MESSAGE("Testing piecewise time dependent "
                       "ChF vs Heston ChF...");

    const Date settlementDate(5, July, 2017);
    Settings::instance().evaluationDate() = settlementDate;
    const Date maturityDate(5, July, 2018);

    const DayCounter dayCounter = Actual365Fixed();
    const Handle<YieldTermStructure> rTS(flatRate(0.01, dayCounter));
    const Handle<YieldTermStructure> qTS(flatRate(0.02, dayCounter));

    const Handle<Quote> s0(ext::shared_ptr<Quote>(new SimpleQuote(100.0)));

    const Real v0    =  0.04;
    const Real rho   = -0.5;
    const Real sigma =  1.0;
    const Real kappa =  4.0;
    const Real theta =  0.25;

    const ConstantParameter thetaP(theta, PositiveConstraint());
    const ConstantParameter kappaP(kappa, PositiveConstraint());
    const ConstantParameter sigmaP(sigma, PositiveConstraint());
    const ConstantParameter rhoP  (rho, BoundaryConstraint(-1.0, 1.0));

    const ext::shared_ptr<AnalyticHestonEngine> analyticEngine(
        ext::make_shared<AnalyticHestonEngine>(
            ext::make_shared<HestonModel>(
                ext::make_shared<HestonProcess>(
                    rTS, qTS, s0, v0, kappa, theta, sigma, rho))));

    const ext::shared_ptr<AnalyticPTDHestonEngine> ptdHestonEngine(
        ext::make_shared<AnalyticPTDHestonEngine>(
            ext::make_shared<PiecewiseTimeDependentHestonModel>(
                rTS, qTS, s0, v0, thetaP, kappaP, sigmaP, rhoP,
                TimeGrid(dayCounter.yearFraction(settlementDate, maturityDate),
                         10))));

    constexpr double tol = 100 * QL_EPSILON;
    for (Real r = 0.1; r < 4; r+=0.25) {
        for (Real phi = 0; phi < 360; phi+=60) {
            for (Time t=0.1; t <= 1.0; t+=0.3) {
                const std::complex<Real> z
                    = r*std::exp(std::complex<Real>(0, phi));

                const std::complex<Real> a = analyticEngine->chF(z, t);
                const std::complex<Real> b = ptdHestonEngine->chF(z, t);

                if (std::abs(a-b) > tol)
                    BOOST_ERROR("failed to compare characteristic function "
                            << "\n  time dependent model: " << b
                            << "\n  Heston model        : " << a
                            << "\n  Difference          : " << std::abs(a-b));
            }
        }
    }
}

BOOST_AUTO_TEST_CASE(testPiecewiseTimeDependentComparison) {
    BOOST_TEST_MESSAGE("Testing piecewise time dependent "
                       "ChF vs Heston ChF...");

    const Date settlementDate(5, July, 2017);
    Settings::instance().evaluationDate() = settlementDate;

    const DayCounter dc = Actual365Fixed();
    const Date maturityDate(5, July, 2018);
    const Time maturity = dc.yearFraction(settlementDate, maturityDate);

    const Handle<YieldTermStructure> rTS(flatRate(0.05, dc));
    const Handle<YieldTermStructure> qTS(flatRate(0.08, dc));

    const Handle<Quote> s0(ext::make_shared<SimpleQuote>(100.0));

    std::vector<Time> modelTimes = {0.25, 0.75, 10.0};
    const TimeGrid modelGrid(modelTimes.begin(), modelTimes.end());

    const Real v0 = 0.1;
    ConstantParameter theta( 0.1, PositiveConstraint());
    ConstantParameter kappa( 1.0, PositiveConstraint());
    ConstantParameter rho( -0.75, BoundaryConstraint(-1.0, 1.0));

    std::vector<Time> pTimes(2);
    pTimes[0] = 0.25;
    pTimes[1] = 0.75;
    PiecewiseConstantParameter sigma(pTimes, PositiveConstraint());

    sigma.setParam(0, 0.30);
    sigma.setParam(1, 0.15);
    sigma.setParam(2, 1.25);

    VanillaOption option(
        ext::make_shared<PlainVanillaPayoff>(Option::Call, s0->value()),
        ext::make_shared<EuropeanExercise>(maturityDate));

    const ext::shared_ptr<PiecewiseTimeDependentHestonModel> ptdModel(
        ext::make_shared<PiecewiseTimeDependentHestonModel>(
            rTS, qTS, s0, v0, theta, kappa, sigma, rho, modelGrid));

    const ext::shared_ptr<AnalyticPTDHestonEngine> ptdHestonEngine(
        ext::make_shared<AnalyticPTDHestonEngine>(ptdModel));

    option.setPricingEngine(ptdHestonEngine);
    const Real calculatedGatheral = option.NPV();

    const ext::shared_ptr<AnalyticPTDHestonEngine> ptdAPEngine(
        ext::make_shared<AnalyticPTDHestonEngine>(
            ptdModel,
            AnalyticPTDHestonEngine::AndersenPiterbarg,
            AnalyticPTDHestonEngine::Integration::discreteTrapezoid(128),
            1e-12));
    option.setPricingEngine(ptdAPEngine);
    const Real calculatedAndersenPiterbarg = option.NPV();

    if (std::fabs(calculatedGatheral - calculatedAndersenPiterbarg) > 1e-10)
        BOOST_ERROR("failed to reproduce npv for time dependent Heston model "
                << "\n  Gatheral ChF         : " << calculatedGatheral
                << "\n  AndersenPiterbarg ChF: " << calculatedAndersenPiterbarg
                << "\n  Difference          : "
                << std::fabs(calculatedGatheral - calculatedAndersenPiterbarg));

    const ext::shared_ptr<HestonProcess> firstPartProcess(
        ext::make_shared<HestonProcess>(
            rTS, qTS, s0, v0, 1.0, 0.1, 0.30, -0.75,
            HestonProcess::QuadraticExponentialMartingale));

    typedef PseudoRandom::rsg_type rsg_type;
    typedef PseudoRandom::urng_type urng_type;
    typedef MultiPathGenerator<rsg_type>::sample_type sample_type;

    const MultiPathGenerator<rsg_type> firstPathGen(
        firstPartProcess,
        TimeGrid(pTimes.front(), 6),
        PseudoRandom::make_sequence_generator(12, 1234));

    const urng_type urng(5678);

    Statistics stat;
    const DiscountFactor df = rTS->discount(maturityDate);

    const Size nSims = 10000;
    for (Size i=0; i < nSims; ++i) {
        Real priceS = 0.0;

        for (Size j=0; j < 2; ++j) {
            const sample_type& path1 =
                (j & 1) != 0U ? firstPathGen.antithetic() : firstPathGen.next();
            const Real spot1 = path1.value[0].back();
            const Real v1    = path1.value[1].back();

            const MultiPathGenerator<rsg_type> secondPathGen(
                ext::make_shared<HestonProcess>(
                    rTS, qTS,
                    Handle<Quote>(ext::make_shared<SimpleQuote>(spot1)),
                    v1, 1.0, 0.1, 0.15, -0.75,
                    HestonProcess::QuadraticExponentialMartingale),
                TimeGrid(pTimes[1]-pTimes[0], 12),
                PseudoRandom::make_sequence_generator(24, urng.nextInt32()));

            const sample_type& path2 = secondPathGen.next();
            const Real spot2 = path2.value[0].back();
            const Real v2    = path2.value[1].back();

            const MultiPathGenerator<rsg_type> thirdPathGen(
                ext::make_shared<HestonProcess>(
                    rTS, qTS,
                    Handle<Quote>(ext::make_shared<SimpleQuote>(spot2)),
                    v2, 1.0, 0.1, 1.25, -0.75,
                    HestonProcess::QuadraticExponentialMartingale),
                TimeGrid(maturity-pTimes[1], 6),
                PseudoRandom::make_sequence_generator(12, urng.nextInt32()));
            const sample_type& path3 = thirdPathGen.next();
            const Real spot3 = path3.value[0].back();

            priceS += 0.5*(*option.payoff())(spot3);
        }

        stat.add(priceS*df);
    }

    const Real calculatedMC = stat.mean();
    const Real errorEstimate = stat.errorEstimate();

    if (std::fabs(calculatedMC - calculatedGatheral) > 3.0*errorEstimate)
        BOOST_ERROR("failed to reproduce npv for time dependent Heston model"
                << "\n  Gatheral ChF     : " << calculatedGatheral
                << "\n  Monte-Carlo      : " << calculatedMC
                << "\n  Monte-Carlo error: " << errorEstimate
                << "\n  Difference       : "
                << std::fabs(calculatedGatheral - calculatedMC));
}

BOOST_AUTO_TEST_CASE(testPiecewiseTimeDependentChFAsymtotic) {
    BOOST_TEST_MESSAGE("Testing piecewise time dependent "
                       "ChF vs Heston ChF...");

    const Date settlementDate(5, July, 2017);
    Settings::instance().evaluationDate() = settlementDate;
    const Date maturityDate = settlementDate + Period(13, Months);

    const DayCounter dc = Actual365Fixed();
    const Time maturity = dc.yearFraction(settlementDate, maturityDate);
    const Handle<YieldTermStructure> rTS(flatRate(0.0, dc));

    std::vector<Time> modelTimes = {0.01, 0.5, 2.0};

    const TimeGrid modelGrid(modelTimes.begin(), modelTimes.end());

    const Real v0 = 0.1;
    const std::vector<Time> pTimes(modelTimes.begin(), modelTimes.end()-1);

    PiecewiseConstantParameter sigma(pTimes, PositiveConstraint());
    PiecewiseConstantParameter theta(pTimes, PositiveConstraint());
    PiecewiseConstantParameter kappa(pTimes, PositiveConstraint());
    PiecewiseConstantParameter rho(pTimes, BoundaryConstraint(-1.0, 1.0));

    const Real sigmas[] = { 0.01, 0.2, 0.6 };
    const Real thetas[] = { 0.16, 0.06, 0.36 };
    const Real kappas[] = { 1.0, 0.3, 4.0 };
    const Real rhos[] = { 0.5, -0.75, -0.25 };

    for (Size i=0; i < 3; ++i) {
        sigma.setParam(i, sigmas[i]);
        theta.setParam(i, thetas[i]);
        kappa.setParam(i, kappas[i]);
        rho.setParam(i, rhos[i]);
    }

    const Handle<Quote> s0(ext::make_shared<SimpleQuote>(100.0));
    const ext::shared_ptr<PiecewiseTimeDependentHestonModel> ptdModel(
        ext::make_shared<PiecewiseTimeDependentHestonModel>(
            rTS, rTS, s0, v0, theta, kappa, sigma, rho, modelGrid));

    const Real eps = 1e-8;

    const ext::shared_ptr<AnalyticPTDHestonEngine> ptdHestonEngine(
        ext::make_shared<AnalyticPTDHestonEngine>(
            ptdModel,
            AnalyticPTDHestonEngine::AndersenPiterbarg,
            AnalyticPTDHestonEngine::Integration::discreteTrapezoid(128),
            eps));

    const std::complex<Real> D_u_inf = -
        std::complex<Real>(std::sqrt(1-rhos[0]*rhos[0]),rhos[0])/sigmas[0];

    const std::complex<Real> dd = std::complex<Real>(kappas[0],
        (2*kappas[0]*rhos[0]-sigmas[0])
        /(2*std::sqrt(1-rhos[0]*rhos[0])))/(sigmas[0]*sigmas[0]);

    std::complex<Real> C_u_inf(0.0, 0.0), cc(0.0, 0.0), clog(0.0, 0.0);

    for (Size i=0; i < 3; ++i) {
        const Real kappa = kappas[i];
        const Real theta = thetas[i];
        const Real sigma = sigmas[i];
        const Real rho = rhos[i];
        const Time tau = std::min(maturity, modelGrid[i+1]) - modelGrid[i];

        C_u_inf += -kappa*theta*tau / sigma
            *std::complex<Real>(std::sqrt(1-rho*rho), rho);

        cc += kappa*std::complex<Real>(2*kappa,(2*kappa*rho-sigma)
            /sqrt(1-rho*rho))*tau*theta/(2*sigma*sigma);

        const std::complex<Real> Di =
            (i < 2) ? sigma/sigmas[i+1]
              *std::complex<Real>(std::sqrt(1-rhos[i+1]*rhos[i+1]), rhos[i+1])
                     : std::complex<Real>(0.0, 0.0);

        clog += 2*kappa*theta/(sigma*sigma)*std::log(1.0 -
            ( Di - std::complex<Real>(std::sqrt(1-rho*rho), rho)) /
            ( Di + std::complex<Real>(std::sqrt(1-rho*rho), -rho)));
    }

    const Real epsilon = eps*M_PI/s0->value();

    const Real uM =
        AnalyticHestonEngine::Integration::andersenPiterbargIntegrationLimit(
            -(C_u_inf + D_u_inf*v0).real(), epsilon, v0, maturity);

    const Real expectedUM = 18.6918883427;
    if (std::fabs(uM - expectedUM) > 1e-5) {
        BOOST_ERROR("failed to reproduce Andersen-Piterbarg "
                    "Integration bounds for piecewise constant "
                    "time dependent Heston Model"
                << "\n  calculated : " << uM
                << "\n  expected   : " << expectedUM
                << "\n  diff       : " << std::fabs(uM - expectedUM)
                << "\n  tolerance  : " << 1e-5);
    }

    const Real u = 1e8;
    const std::complex<Real> expectedlnChF = ptdHestonEngine->lnChF(u, maturity);
    const std::complex<Real> calculatedAsympotic =
        (D_u_inf*u + dd)*v0 + C_u_inf*u + cc + clog;

    if (std::abs(expectedlnChF - calculatedAsympotic) > 0.01) {
        BOOST_ERROR("failed to reproduce asymptotic of characteristic function"
                << "\n  ln(ChF)   : " << expectedlnChF
                << "\n  asymptotic: " << calculatedAsympotic
                << "\n  diff      : "
                << std::abs(expectedlnChF - calculatedAsympotic)
                << "\n  tolerance : " << 0.01);
    }

    VanillaOption option(
        ext::make_shared<PlainVanillaPayoff>(Option::Call, s0->value()),
        ext::make_shared<EuropeanExercise>(maturityDate));
    option.setPricingEngine(ptdHestonEngine);

    const Real expectedNPV = 17.43851162589377;
    const Real calculatedNPV = option.NPV();
    const Real diffNPV = std::fabs(expectedNPV - calculatedNPV);
    if (diffNPV > 1e-9) {
        BOOST_ERROR("failed to reproduce high precision prices for "
                "piecewise constant time dependent Heston model"
                << "\n  expeceted : " << expectedNPV
                << "\n  calclated : " << calculatedNPV
                << "\n  diff      : " << diffNPV
                << "\n  tolerance : " << 1e-9);
    }
}

BOOST_AUTO_TEST_CASE(testSmallSigmaExpansion) {
    BOOST_TEST_MESSAGE("Testing small sigma expansion of "
                       "the characteristic function...");

    const Date settlementDate(20, March, 2020);
    Settings::instance().evaluationDate() = settlementDate;
    const Date maturityDate = settlementDate + Period(2, Years);

    const DayCounter dc = Actual365Fixed();
    const Time t = dc.yearFraction(settlementDate, maturityDate);
    const Handle<YieldTermStructure> rTS(flatRate(0.0, dc));

    const Handle<Quote> spot(ext::make_shared<SimpleQuote>(100));

    const Real theta = 0.1 * 0.1;
    const Real v0 = theta + 0.02;
    const Real kappa = 1.25;
    const Real sigma = 1e-9;
    const Real rho = -0.9;

    const ext::shared_ptr<HestonModel> hestonModel =
        ext::make_shared<HestonModel>(
            ext::make_shared<HestonProcess>(
                rTS, rTS, spot, v0, kappa, theta, sigma, rho));

    const ext::shared_ptr<AnalyticHestonEngine> engine =
        ext::make_shared<AnalyticHestonEngine>(hestonModel);

    const std::complex<Real> expectedChF(
        0.990463578538352651,2.60693475987521132e-12);

    const std::complex<Real> calculatedChF = engine->chF(
        std::complex<Real>(0.55, -0.5), t);

    const Real diffChF = std::abs(expectedChF - calculatedChF);
    const Real tolChF = 1e-12;
    if (diffChF > tolChF) {
        BOOST_ERROR("failed to reproduce normalized characteristic function "
                "value for small sigma"
                << "\n  expeceted : " << expectedChF
                << "\n  calclated : " << calculatedChF
                << "\n  diff      : " << diffChF
                << "\n  tolerance : " << tolChF);
    }

    VanillaOption option(
        ext::make_shared<PlainVanillaPayoff>(Option::Call, 120.0),
        ext::make_shared<EuropeanExercise>(maturityDate));

    option.setPricingEngine(
        ext::make_shared<AnalyticHestonEngine>(
            hestonModel,
            AnalyticHestonEngine::AndersenPiterbarg,
            AnalyticHestonEngine::Integration::gaussLaguerre(192)));

    const Real calculatedNPV = option.NPV();

    const Real stdDev =
        std::sqrt(((1-std::exp(-kappa*t))*(v0-theta)/(kappa*t) + theta)*t);

    const Real expectedNPV =
        blackFormula(Option::Call, 120.0, 100.0, stdDev);

    const Real diffNPV =std::fabs(calculatedNPV - expectedNPV);
    const Real tolNPV = 50*sigma;

    if (diffNPV > tolNPV) {
        BOOST_ERROR("failed to reproduce Black Scholes prices "
                "for Heston model with very small sigma"
                << "\n  expeceted : " << expectedNPV
                << "\n  calclated : " << calculatedNPV
                << "\n  diff      : " << diffNPV
                << "\n  tolerance : " << tolNPV);
    }
}

BOOST_AUTO_TEST_CASE(testSmallSigmaExpansion4ExpFitting) {
    BOOST_TEST_MESSAGE("Testing small sigma expansion for the "
                       "exponential fitting Heston engine...");

    const Date todaysDate(13, March, 2020);
    Settings::instance().evaluationDate() = todaysDate;

    const DayCounter dc = Actual365Fixed();
    const Handle<YieldTermStructure> rTS(flatRate(0.05, dc));
    const Handle<YieldTermStructure> qTS(flatRate(0.075, dc));

    const Handle<Quote> spot(ext::make_shared<SimpleQuote>(100.0));

    // special case: reduce sigma
    const Date maturityDate = Date(14, March, 2021);
    const Time maturity = dc.yearFraction(todaysDate, maturityDate);
    const Real fwd =
        spot->value()*qTS->discount(maturity)/rTS->discount(maturity);

    const Real v0 = 0.04;
    const Real rho = -0.5;
    const Real kappa = 4.0;
    const Real theta = 0.04;

    const Real moneyness = 0.1;
    const Real strike = std::exp(-moneyness*std::sqrt(theta*maturity))*fwd;

    const Real expected = blackFormula(
        Option::Call, strike, fwd,
        std::sqrt(v0*maturity), rTS->discount(maturity));

    VanillaOption option(
        ext::make_shared<PlainVanillaPayoff>(Option::Call, strike),
        ext::make_shared<EuropeanExercise>(maturityDate));

    for (Real sigma = 1e-4; sigma > 1e-12; sigma*=0.1) {
        option.setPricingEngine(
            ext::make_shared<ExponentialFittingHestonEngine>(
                ext::make_shared<HestonModel>(
                    ext::make_shared<HestonProcess>(
                        rTS, qTS, spot, v0, kappa, theta, sigma, rho))));
        const Real calculated = option.NPV();

        const Real diff = std::fabs(expected - calculated);

        if (diff > 0.01*sigma) {
            BOOST_ERROR("failed to reproduce Black Scholes prices "
                    "for Heston model with very small sigma"
                    << "\n  expeceted : " << expected
                    << "\n  calclated : " << calculated
                    << "\n  sigma     : " << sigma
                    << "\n  diff      : " << diff
                    << "\n  tolerance : " << 10*sigma);
        }
    }


    // generic cases
    const Real kappas[] = { 0.5, 1.0, 4.0 };
    const Real thetas[] = { 0.04, 0.09};
    const Real v0s[]    = { 0.025, 0.20 };
    const Integer maturities[] = { 1, 31, 182, 1850 };

    for (int maturitie : maturities) {
        const Date maturityDate = todaysDate + Period(maturitie, Days);
        const DiscountFactor df = rTS->discount(maturityDate);
        const Real fwd = spot->value() * qTS->discount(maturityDate)/df;

        const ext::shared_ptr<Exercise> exercise =
            ext::make_shared<EuropeanExercise>(maturityDate);

        const Time t = dc.yearFraction(todaysDate, maturityDate);

        Option::Type optionType = Option::Call;

        for (Real kappa : kappas) {
            for (Real theta : thetas) {
                for (Real v0 : v0s) {
                    const ext::shared_ptr<PricingEngine> engine =
                        ext::make_shared<ExponentialFittingHestonEngine>(
                            ext::make_shared<HestonModel>(ext::make_shared<HestonProcess>(
                                rTS, qTS, spot, v0, kappa, theta, 1e-13, -0.8)));

                    const Real stdDev =
                        std::sqrt(((1-std::exp(-kappa*t))*(v0-theta)/(kappa*t) + theta)*t);

                    for (Real strike = spot->value()*exp(-10*stdDev);
                            strike < spot->value()*exp(10*stdDev); strike*= 1.2) {

                        VanillaOption option(
                            ext::make_shared<PlainVanillaPayoff>(
                                optionType, strike), exercise);

                        option.setPricingEngine(engine);
                        const Real calculated = option.NPV();

                        const Real expected =
                            blackFormula(optionType, strike, fwd, stdDev, df);

                        const Real diff = std::fabs(expected - calculated);
                        if (diff > 1e-10) {
                            BOOST_ERROR("failed to reproduce Black Scholes prices "
                                    "for Heston model with very small sigma"
                                    << "\n  expceted  : " << expected
                                    << "\n  calculated: " << calculated
                                    << "\n  diff      : " << diff
                                    << "\n  tolerance : " << 1e-10);
                        }

                        optionType = (optionType == Option::Call)
                            ? Option::Put : Option::Call;
                    }
                }
            }
        }
    }
}

BOOST_AUTO_TEST_CASE(testExponentialFitting4StrikesAndMaturities) {
    BOOST_TEST_MESSAGE("Testing exponential fitting Heston engine "
                       "with high precision results for large moneyness...");

    const Date todaysDate = Date(13, May, 2020);
    Settings::instance().evaluationDate() = todaysDate;

    const DayCounter dc = Actual365Fixed();

    const Handle<YieldTermStructure> rTS(flatRate(0.0507, dc));
    const Handle<YieldTermStructure> qTS(flatRate(0.0469, dc));

    const Handle<Quote> s0(ext::make_shared<SimpleQuote>(1.0));

    const Real moneyness[] = { -20, -10, -5, 2.5, 1, 0, 1, 2.5, 5, 10, 20 };
    const Period maturities[] = {
            Period(1, Days),
            Period(1, Months),
            Period(1, Years),
            Period(10, Years)
    };

    const Real v0    =  0.04;
    const Real rho   = -0.6;
    const Real sigma =  0.75;
    const Real kappa =  2.5;
    const Real theta =  0.06;

    // Reference prices are calculated using a boost multi-precision
    // implementation of the AnalyticHestonEngine,
    // https://github.com/klausspanderen/HestonExponentialFitting

    const Real referenceValues[] = {
            1.1631865252540813e-58,
            1.06426822273258466e-49,
            6.92896489110422086e-16,
            8.19515526286263236e-06,
            0.000625608178476390504,
            0.00417261379371945684,
            0.000625608178476390504,
            8.19515526286263236e-06,
            1.92308901296741414e-10,
            1.57327901822368115e-23,
            5.7830515043285098e-58,
            3.56081886910098813e-48,
            2.9489071194212509e-23,
            1.54181757781090727e-11,
            0.000367960011879847279,
            0.00493886106106039818,
            0.0227152343265593776,
            0.00493886106106039818,
            0.000367960011879847279,
            3.06653474407784574e-06,
            8.86665241279348934e-11,
            1.51206812371708868e-20,
            4.18506719865401643e-29,
            2.46637786897559908e-15,
            1.75338784910563671e-08,
            0.00284789176080218294,
            0.0199133097064688458,
            0.0776848755698912041,
            0.0199133097064688458,
            0.00284789176080218294,
            0.00012462190796343504,
            2.59755319566692257e-07,
            1.13853114743124721e-12,
            4.27612073892114211e-39,
            1.08387452075906664e-25,
            4.15179522944463802e-11,
            0.00134157732880653131,
            0.029018582813884912,
            0.176405213088554197,
            0.029018582813884912,
            0.00134157732880653131,
            5.43674074281991917e-06,
            6.51443921040230507e-11,
            9.25756999394709285e-21
    };

    const ext::shared_ptr<HestonModel> model =
        ext::make_shared<HestonModel>(
            ext::make_shared<HestonProcess>(
                rTS, qTS, s0, v0, kappa, theta, sigma, rho));

    const ext::shared_ptr<PricingEngine> engine =
        ext::make_shared<ExponentialFittingHestonEngine>(model);

    Size idx = 0;
    for (auto maturitie : maturities) {
        const Date maturityDate = todaysDate + maturitie;
        const Time t = dc.yearFraction(todaysDate, maturityDate);

        const ext::shared_ptr<Exercise> exercise =
            ext::make_shared<EuropeanExercise>(maturityDate);

        const DiscountFactor df = rTS->discount(t);
        const Real fwd = s0->value()*qTS->discount(t)/df;

        for (Size j=0; j < std::size(moneyness); ++j, ++idx) {
            const Real strike =
                std::exp(-moneyness[j]*std::sqrt(theta*t))*fwd;

            for (Size k=0; k < 2; ++k) {
                const ext::shared_ptr<PlainVanillaPayoff> payoff =
                    ext::make_shared<PlainVanillaPayoff>((k) != 0U ? Option::Put : Option::Call,
                                                         strike);

                VanillaOption option(payoff, exercise);
                option.setPricingEngine(engine);

                const Real calculated = option.NPV();

                Real expected;
                if (payoff->optionType() == Option::Call)
                    if (fwd < strike)
                        expected = referenceValues[idx];
                    else
                        expected = (fwd - strike)*df + referenceValues[idx];
                else
                    if (fwd > strike)
                        expected = referenceValues[idx];
                    else
                        expected = referenceValues[idx] - (fwd - strike)*df;

                const Real diff = std::fabs(calculated - expected);
                const Real tol = 1e-8;
                if (diff > tol) {
                    BOOST_ERROR("failed to reproduce cached extreme "
                            "Heston model prices with exponential fitted "
                            "Gauss-Laguerre quadrature rule"
                            << "\n  forward   : " << fwd
                            << "\n  strike    : " << strike
                            << "\n  expected  : " << expected
                            << "\n  calculated: " << calculated
                            << "\n  diff      : " << diff
                            << "\n  tolerance : " << tol);
                }
            }
        }
    }
}

BOOST_AUTO_TEST_CASE(testHestonEngineIntegration) {
    BOOST_TEST_MESSAGE("Testing Heston engine integration signature...");

    auto square = [](Real x) -> Real { return x * x; };

    const AnalyticHestonEngine::Integration integration =
        AnalyticHestonEngine::Integration::gaussLobatto(1e-12, 1e-12);

    const Real c1 = integration.calculate(1.0, square, Real(1.0));

    HestonIntegrationMaxBoundTestFct testFct(1.0);
    const Real c2 = integration.calculate(1.0, square, testFct);

    if (testFct.getCallCounter() == 0 ||
            std::fabs(c1 - 1/3.) > 1e-10 || std::fabs(c2 - 1/3.) > 1e-10) {
        BOOST_ERROR("failed to test Heston engine integration signature");
    }
}

BOOST_AUTO_TEST_CASE(testOptimalControlVariateChoice) {
    BOOST_TEST_MESSAGE(
        "Testing optimal control variate choice for the Heston model...");

    Real v0    =  0.0225;
    Real rho   =  0.5;
    Real sigma =  2.0;
    Real kappa =  0.1;
    Real theta =  0.01;
    Time t = 2.0;

    AnalyticHestonEngine::ComplexLogFormula calculated =
        AnalyticHestonEngine::optimalControlVariate(
            t, v0, kappa, theta, sigma, rho);

    if (calculated != AnalyticHestonEngine::AsymptoticChF) {
        BOOST_ERROR("failed to reproduce optimal control variate choice");
    }

    calculated = AnalyticHestonEngine::optimalControlVariate(
            t, v0, kappa, theta, 0.05, rho);
    if (calculated != AnalyticHestonEngine::AngledContour) {
        BOOST_ERROR("failed to reproduce optimal control variate choice");
    }

    calculated = AnalyticHestonEngine::optimalControlVariate(
            t, 0.5, kappa, theta, sigma, rho);
    if (calculated != AnalyticHestonEngine::AngledContour) {
        BOOST_ERROR("failed to reproduce optimal control variate choice");
    }
}

BOOST_AUTO_TEST_CASE(testAsymptoticControlVariate) {
    BOOST_TEST_MESSAGE("Testing Heston asymptotic control variate...");

    const Date todaysDate = Date(4, August, 2020);
    Settings::instance().evaluationDate() = todaysDate;

    const DayCounter dc = Actual365Fixed();

    const Handle<YieldTermStructure> rTS(flatRate(0.0, dc));

    const Handle<Quote> s0(ext::make_shared<SimpleQuote>(1.0));

    const Real v0    =  0.0225;
    const Real rho   =  0.5;
    const Real sigma =  2.0;
    const Real kappa =  0.1;
    const Real theta =  0.01;

    const ext::shared_ptr<HestonModel> model =
        ext::make_shared<HestonModel>(
            ext::make_shared<HestonProcess>(
                rTS, rTS, s0, v0, kappa, theta, sigma, rho));

    const Date maturityDate = todaysDate + Period(2, Years);
    const Time t = dc.yearFraction(todaysDate, maturityDate);
    const ext::shared_ptr<Exercise> exercise =
        ext::make_shared<EuropeanExercise>(maturityDate);

    const Real moneynesses[] = { -15, -10, -5, 0, 5, 10, 15 };

    const Real expected[] = {
        0.0074676425640918,
        0.008680823863233695,
        0.010479611906112223,
        0.023590088942038945,
        0.0019575784806211706,
        0.0005490310253748906,
        0.0001657118753134695
    };

    const ext::shared_ptr<PricingEngine> engines[] = {
        ext::make_shared<AnalyticHestonEngine>(
            model,
            AnalyticHestonEngine::OptimalCV,
            AnalyticHestonEngine::Integration::gaussLobatto(1e-10, 1e-10, 100000)),
        ext::make_shared<AnalyticHestonEngine>(
            model,
            AnalyticHestonEngine::OptimalCV,
            AnalyticHestonEngine::Integration::gaussLaguerre(96)),
        ext::make_shared<ExponentialFittingHestonEngine>(model)
    };

    for (Size j=0; j < std::size(engines); ++j) {
        for (Size i=0; i < std::size(moneynesses); ++i) {
            const Real moneyness = moneynesses[i];

            const Real strike = std::exp(-moneyness*std::sqrt(theta*t));

            const ext::shared_ptr<PlainVanillaPayoff> payoff =
                ext::make_shared<PlainVanillaPayoff>(
                    strike > 1.0 ? Option::Call : Option::Put, strike);

            const ext::shared_ptr<PricingEngine> engine = engines[j];

            VanillaOption option(payoff, exercise);
            option.setPricingEngine(engine);

            const Real calculated = option.NPV();

            const ext::shared_ptr<AnalyticHestonEngine> analyticHestonEngine =
                ext::dynamic_pointer_cast<AnalyticHestonEngine>(engine);

            if ((analyticHestonEngine != nullptr) &&
                analyticHestonEngine->numberOfEvaluations() > 5000) {
                BOOST_ERROR("too many function valuation needed "
                        << "\n  moneyness      : " << moneyness
                        << "\n  evaluations    : "
                        << analyticHestonEngine->numberOfEvaluations()
                        << "\n  max evaluations: " << 5000);
            }

            const Real diff = std::fabs(calculated - expected[i]);
            if (diff > 5e-8) {
                BOOST_ERROR("failed to reproduce extreme Heston model values for"
                        << "\n  moneyness : " << moneyness
                        << "\n  #engine   : " << j
                        << "\n  calculated: " << calculated
                        << "\n  expected  : " << expected[i]
                        << "\n  difference: " << diff
                        << "\n  tolerance : " << 1e-8);
            }
        }
    }
}

BOOST_AUTO_TEST_CASE(testLocalVolFromHestonModel) {
    BOOST_TEST_MESSAGE("Testing Local Volatility pricing from Heston Model...");

    const auto todaysDate = Date(28, June, 2021);
    Settings::instance().evaluationDate() = todaysDate;

    const auto dc = Actual365Fixed();

    const Handle<YieldTermStructure> rTS(
        ext::make_shared<ZeroCurve>(
            std::vector<Date>{
                todaysDate, todaysDate + Period(90, Days),
                todaysDate + Period(180, Days), todaysDate + Period(1, Years)
            },
            std::vector<Rate>{0.075, 0.05, 0.075, 0.1},
            dc
        )
    );

    const Handle<YieldTermStructure> qTS(
        ext::make_shared<ZeroCurve>(
            std::vector<Date>{
                todaysDate, todaysDate + Period(90, Days), todaysDate + Period(1, Years)
            },
            std::vector<Rate>{0.06, 0.04, 0.12},
            dc
        )
    );

    const Handle<Quote> s0(ext::make_shared<SimpleQuote>(100.0));

    const Real v0    =  0.1;
    const Real rho   = -0.75;
    const Real sigma =  0.8;
    const Real kappa =  1.0;
    const Real theta =  0.16;

    const auto hestonModel = ext::make_shared<HestonModel>(
        ext::make_shared<HestonProcess>(
            rTS, qTS, s0, v0, kappa, theta, sigma, rho)
    );

    VanillaOption option(
        ext::make_shared<PlainVanillaPayoff>(Option::Call, 120.0),
        ext::make_shared<EuropeanExercise>(todaysDate + Period(1, Years))
    );

    option.setPricingEngine(
        ext::make_shared<AnalyticHestonEngine>(
            hestonModel,
            AnalyticHestonEngine::OptimalCV,
            AnalyticHestonEngine::Integration::gaussLaguerre(192)
        )
    );

    const Real expected = option.NPV();

    option.setPricingEngine(
         ext::make_shared<FdBlackScholesVanillaEngine>(
             ext::make_shared<BlackScholesMertonProcess>(
                 s0, qTS, rTS,
                 Handle<BlackVolTermStructure>(
                      ext::make_shared<HestonBlackVolSurface>(
                          Handle<HestonModel>(hestonModel),
                          AnalyticHestonEngine::OptimalCV,
                          AnalyticHestonEngine::Integration::gaussLaguerre(24)
                      )
                 )
             ),
             25, 125, 1, FdmSchemeDesc::Douglas(), true, 0.4
         )
    );

    const Real calculated = option.NPV();

    const Real tol = 0.002;
    const Real diff = std::fabs(calculated - expected);
    if (diff > tol) {
        BOOST_ERROR("failed to reproduce Heston model values with "
                    "local volatility pricing"
                << "\n  calculated: " << calculated
                << "\n  expected  : " << expected
                << "\n  difference: " << diff
                << "\n  tolerance : " << tol);
    }
}

BOOST_AUTO_TEST_CASE(testOptimalAlphaKmin) {
    BOOST_TEST_MESSAGE("Testing optimal Alpha k_min for characteristic function...");

    SavedSettings backup;

    const Date todaysDate(1, January, 2023);
    Settings::instance().evaluationDate() = todaysDate;

    // Example taken from figure 3 in Andersen and M. Lake, 2018
    // Robust High-Precision Option Pricing by Fourier Transforms:
    const DayCounter dc = Actual365Fixed();
    const auto model =
         ext::make_shared<HestonModel>(
            ext::make_shared<HestonProcess>(
                Handle<YieldTermStructure>(flatRate(0.0, dc)),
                Handle<YieldTermStructure>(flatRate(0.0, dc)),
                Handle<Quote>(ext::make_shared<SimpleQuote>(150)),
                0.01, 0.1, 0.01, 2.0, 0.8
            )
        );

    const auto engine = ext::make_shared<AnalyticHestonEngine>(
        model,
        AnalyticHestonEngine::Gatheral,
        AnalyticHestonEngine::Integration::gaussLobatto(
                Null<Real>(), 1e-12, 100000)
    );

    const Real strike = 100;

    const Real alphaStar = AnalyticHestonEngine::OptimalAlpha(1.0, engine.get())
                               .alphaSmallerMinusOne(strike).first;

    QL_CHECK_SMALL(alphaStar+3.71, 0.0051);

    const Date maturityDate = todaysDate + Period(15, Months);

    VanillaOption option(
        ext::make_shared<PlainVanillaPayoff>(Option::Call, strike),
        ext::make_shared<EuropeanExercise>(maturityDate)
    );
    option.setPricingEngine(engine);
    const Real expected = option.NPV();

    option.setPricingEngine(
        ext::make_shared<AnalyticHestonEngine>(
            model,
            AnalyticHestonEngine::AngledContour,
            AnalyticHestonEngine::Integration::gaussLobatto(
                    Null<Real>(), 1e-12, 5000)
        )
    );

    if (std::abs(option.NPV() - expected)/expected > 1e-10)
        BOOST_ERROR("failed to reproduce reference values with Angled-Contour");

    option.setPricingEngine(
        ext::make_shared<ExponentialFittingHestonEngine>(
            model, ExponentialFittingHestonEngine::ControlVariate::OptimalCV
        )
    );

    if (std::abs(option.NPV() - expected)/expected > 1e-8)
        BOOST_ERROR("failed to reproduce reference values with Angled-Contour"
                    "and exponential fitting");
}

BOOST_AUTO_TEST_CASE(testOptimalAlphaKmax) {
    BOOST_TEST_MESSAGE("Testing optimal Alpha k_min for characteristic function...");

    SavedSettings backup;

    const Date todaysDate(1, January, 2022);
    Settings::instance().evaluationDate() = todaysDate;

    const DayCounter dc = Actual365Fixed();
    const Handle<YieldTermStructure> yTS
        = Handle<YieldTermStructure>(flatRate(0.0, dc));
    const Handle<Quote> spot
        = Handle<Quote>(ext::make_shared<SimpleQuote>(75));

    const Time T = 2;
    const Real strike = 100;

    // case 1: kappa - sigma*rho > 0
    auto model = ext::make_shared<HestonModel>(
        ext::make_shared<HestonProcess>(yTS, yTS, spot,  .1, 1.2, 0.2, 0.2, -0.8));
    auto engine = ext::make_shared<AnalyticHestonEngine>(model);
    Real alphaStar = AnalyticHestonEngine::OptimalAlpha(T, engine.get())
            .alphaGreaterZero(strike).first;
    QL_CHECK_SMALL(alphaStar - 3.22615, 1e-4);

    // case 2: kappa - sigma*rho < 0, T < t_cut
    model = ext::make_shared<HestonModel>(
        ext::make_shared<HestonProcess>(yTS, yTS, spot, 0.1, 1.2, 0.2, 1.5, 0.9));
    engine = ext::make_shared<AnalyticHestonEngine>(model);
    alphaStar = AnalyticHestonEngine::OptimalAlpha(T, engine.get())
            .alphaGreaterZero(strike).first;
    QL_CHECK_SMALL(alphaStar - 0.31137, 1e-4);

    // case 3: kappa - sigma*rho < 0, T >= t_cut
    model = ext::make_shared<HestonModel>(
        ext::make_shared<HestonProcess>(yTS, yTS, spot, 0.1, 1.2, 0.2, 2.25, 0.9));
    engine = ext::make_shared<AnalyticHestonEngine>(model);
    alphaStar = AnalyticHestonEngine::OptimalAlpha(T, engine.get())
            .alphaGreaterZero(strike).first;
    QL_CHECK_SMALL(alphaStar - 0.11940, 1e-4);

    // case 4: kappa - sigma*rho == 0
    model = ext::make_shared<HestonModel>(
        ext::make_shared<HestonProcess>(yTS, yTS, spot, 0.1, 1.0, 0.2, 2.0, 0.5));
    engine = ext::make_shared<AnalyticHestonEngine>(model);
    alphaStar = AnalyticHestonEngine::OptimalAlpha(T, engine.get())
            .alphaGreaterZero(strike).first;
    QL_CHECK_SMALL(alphaStar - 0.28006, 1e-4);
}
BOOST_AUTO_TEST_SUITE_END()

BOOST_AUTO_TEST_SUITE(HestonModelExperimentalTest)

BOOST_AUTO_TEST_CASE(testAnalyticPDFHestonEngine) {
    BOOST_TEST_MESSAGE("Testing analytic PDF Heston engine...");

    const Date settlementDate(5, January, 2014);
    Settings::instance().evaluationDate() = settlementDate;

    const DayCounter dayCounter = Actual365Fixed();
    const Handle<YieldTermStructure> riskFreeTS(flatRate(0.07, dayCounter));
    const Handle<YieldTermStructure> dividendTS(flatRate(0.185, dayCounter));

    const Handle<Quote> s0(ext::make_shared<SimpleQuote>(100.0));

    const Real v0    =  0.1;
    const Real rho   = -0.5;
    const Real sigma =  1.0;
    const Real kappa =  4.0;
    const Real theta =  0.05;

    const ext::shared_ptr<HestonModel> model(
        ext::make_shared<HestonModel>(
            ext::make_shared<HestonProcess>(riskFreeTS, dividendTS,
                                            s0, v0, kappa, theta, sigma, rho)));

    const Real tol = 1e-6;
    const ext::shared_ptr<AnalyticPDFHestonEngine> pdfEngine(
        ext::make_shared<AnalyticPDFHestonEngine>(model, tol));

    const ext::shared_ptr<PricingEngine> analyticEngine(
        ext::make_shared<AnalyticHestonEngine>(model, 178));

    const Date maturityDate(5, July, 2014);
    const Time maturity = dayCounter.yearFraction(settlementDate, maturityDate);
    const ext::shared_ptr<Exercise> exercise(
        ext::make_shared<EuropeanExercise>(maturityDate));

    // 1. check a plain vanilla call option
    for (Real strike=40; strike < 190; strike+=20) {
        const ext::shared_ptr<StrikedTypePayoff> vanillaPayoff(
            ext::make_shared<PlainVanillaPayoff>(Option::Call, strike));

        VanillaOption planVanillaOption(vanillaPayoff, exercise);

        planVanillaOption.setPricingEngine(pdfEngine);
        const Real calculated = planVanillaOption.NPV();

        planVanillaOption.setPricingEngine(analyticEngine);
        const Real expected = planVanillaOption.NPV();

        if (std::fabs(calculated-expected) > 3*tol) {
            BOOST_FAIL(
                "failed to reproduce plain vanilla european prices with"
                " the analytic probability density engine"
                << "\n    strike     : " << strike
                << "\n    expected   : " << expected
                << "\n    calculated : " << calculated
                << "\n    diff       : " << std::fabs(calculated-expected)
                << "\n    tol        ; " << tol);
        }
    }

    // 2. digital call option (approx. with a call spread)
    for (Real strike=40; strike < 190; strike+=10) {
        VanillaOption digitalOption(
            ext::make_shared<CashOrNothingPayoff>(Option::Call, strike, 1.0),
            exercise);
        digitalOption.setPricingEngine(pdfEngine);
        const Real calculated = digitalOption.NPV();

        const Real eps = 0.01;
        VanillaOption longCall(
            ext::make_shared<PlainVanillaPayoff>(Option::Call, strike-eps),
            exercise);
        longCall.setPricingEngine(analyticEngine);

        VanillaOption shortCall(
            ext::make_shared<PlainVanillaPayoff>(Option::Call, strike+eps),
            exercise);
        shortCall.setPricingEngine(analyticEngine);

        const Real expected = (longCall.NPV() - shortCall.NPV())/(2*eps);
        if (std::fabs(calculated-expected) > tol) {
            BOOST_FAIL(
                "failed to reproduce european digital prices with"
                " the analytic probability density engine"
                << "\n    strike     : " << strike
                << "\n    expected   : " << expected
                << "\n    calculated : " << calculated
                << "\n    diff       : " << std::fabs(calculated-expected)
                << "\n    tol        : " << tol);
        }

        const DiscountFactor d = riskFreeTS->discount(maturityDate);
        const Real expectedCDF = 1.0 - expected/d;
        const Real calculatedCDF = pdfEngine->cdf(strike, maturity);

        if (std::fabs(expectedCDF - calculatedCDF) > tol) {
            BOOST_FAIL(
                "failed to reproduce cumulative distribution function"
                << "\n    strike        : " << strike
                << "\n    expected CDF  : " << expectedCDF
                << "\n    calculated CDF: " << calculatedCDF
                << "\n    diff          : "
                << std::fabs(calculatedCDF-expectedCDF)
                << "\n    tol           : " << tol);

        }
    }
}

BOOST_AUTO_TEST_SUITE_END()

BOOST_AUTO_TEST_SUITE_END()