quantmath 0.1.0

A library of quantitative maths and a framework for quantitative valuation and risk
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
use std::sync::Arc;
use std::f64::NAN;
use instruments::Instrument;
use instruments::RcInstrument;
use instruments::Priceable;
use instruments::PricingContext;
use instruments::DependencyContext;
use instruments::assets::Currency;
use instruments::assets::RcCurrency;
use instruments::bonds::ZeroCoupon;
use instruments::SpotRequirement;
use instruments::MonteCarloPriceable;
use instruments::MonteCarloDependencies;
use instruments::MonteCarloContext;
use math::optionpricing::Black76;
use data::fixings::FixingTable;
use dates::Date;
use dates::rules::RcDateRule;
use dates::datetime::DateTime;
use dates::datetime::DateDayFraction;
use core::qm;
use core::factories::TypeId;
use core::factories::Qrc;
use core::dedup::InstanceId;
use ndarray::Axis;
use ndarray::Array2;
use erased_serde as esd;
use serde::Deserialize;

/// A call option pays (S-K).max(0).
/// A put option pays (K-S).max(0).
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
pub enum PutOrCall { Put, Call }

/// At expiry, a cash settled option fixes into a cash payment at the payment
/// date. A physically settled option fixes into a payment of the strike at
/// the payment date, and a transfer of the stock at the stock settlement date
/// (in practice always the same time, otherwise there would be credit risk)
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
pub enum OptionSettlement { Cash, Physical }

/// A VanillaOption is an internal data structure to help share code between
/// types of vanilla.
#[derive(Clone, Serialize, Deserialize, Debug)]
struct VanillaOption {
    id: String,
    credit_id: String,
    underlying: RcInstrument,
    settlement: RcDateRule,
    expiry: DateTime,
    put_or_call: PutOrCall,
    cash_or_physical: OptionSettlement,

    // fields precomputed for performance and simplicity
    expiry_time: DateDayFraction,
    pay_date: Date,
}

impl TypeId for VanillaOption {
    fn type_id(&self) -> &'static str {
        // should never get here, as VanillaOption should not need tagged serialization
        panic!("VanillaOption::type_id: not implemented");
    }
}

impl VanillaOption {
    pub fn new(id: &str, credit_id: &str, underlying: RcInstrument,
        settlement: RcDateRule, expiry: DateTime, put_or_call: PutOrCall,
        cash_or_physical: OptionSettlement)
        -> Result<VanillaOption, qm::Error> {

        let pay_date = settlement.apply(expiry.date());
        let expiry_time = underlying.time_to_day_fraction(expiry)?;
        Ok(VanillaOption {
            id: id.to_string(),
            credit_id: credit_id.to_string(),
            underlying: underlying,
            settlement: settlement,
            expiry: expiry,
            put_or_call: put_or_call,
            cash_or_physical: cash_or_physical,
            expiry_time: expiry_time,
            pay_date: pay_date })
    }

    /// Prices this option with a range of val dates, and given a closure that
    /// calculates the strike
    fn prices(&self, context: &PricingContext, dates: &[DateTime], out: &mut [f64], 
        vol_from: DateDayFraction,  
        strike_and_forward: &Fn(&Priceable) -> Result<(f64, f64), qm::Error>) 
        -> Result<(), qm::Error> {
        
        assert_eq!(dates.len(), out.len());
        if dates.is_empty() {
            return Ok(())  // nothing to do
        }

        // fetch the market data we need. Note that the forward curve is only fetched if
        // sticky delta dynamics forces it. Otherwise, there is nothing to stop the underlying
        // being calculated rather than supplied directly as a forward curve.
        let expiry_date = self.expiry.date();
        let yc = context.yield_curve(self.underlying.credit_id(), self.pay_date)?;
        let vol = context.vol_surface(&*self.underlying, expiry_date, 
            &|| context.forward_curve(&*self.underlying, expiry_date))?;

        // Calculate the parameters for the BlackScholes formula. We discount to
        // the base date of the discount curve. (Any date would do so long as we
        // are consistent.)
        let underlying = self.underlying.as_priceable().ok_or_else(|| qm::Error::new(
            "The underlying of an option must itself be priceable"))?;
        let (strike, forward) = strike_and_forward(underlying)?;
        let df_from_base = (-yc.rt(self.pay_date)?).exp();
 
        // For some div assumptions, we must displace the forward and strike.
        // (This errors for JumpDivs, which we do not currently handle.)
        let displacement = vol.displacement(self.expiry.date())?;
        let k = strike + displacement;
        let f = forward - displacement;
        if f < 0.0 {
            return Err(qm::Error::new("Negative forward"));
        }

        // price the option using the Black76 formula
        let black76 = Black76::new()?;

        // All the prices are the same, except that they are discounted to a different date,
        // and if the date is after the ex time, they are zero.
        // We assume the option goes ex just after its expiry date/time
        let ex_date = self.expiry;
        for (date, output) in dates.iter().zip(out.iter_mut()) {
            *output = if *date <= ex_date {
                let settlement_date = self.settlement().apply(date.date());
                let df = df_from_base * yc.rt(settlement_date)?.exp();

                let val_date = self.underlying.time_to_day_fraction(*date)?;
                let from_date = vol_from.max(val_date);
                let variance = vol.forward_variance(from_date, self.expiry_time, strike)?;
                if variance < 0.0 {
                    return Err(qm::Error::new("Negative variance"));
                }
                let sqrt_var = variance.sqrt();

                // What we calculate here is the expected value of an option on the 
                // val date. This means that we ignore any time value or volatility
                // between now and the val date. Whether this is the right thing to
                // do depends on how forward valuation will be used. The first real
                // use case should drive the behaviour.
                let price = match self.put_or_call {
                    PutOrCall::Put => black76.put_price(df, f, k, sqrt_var),
                    PutOrCall::Call => black76.call_price(df, f, k, sqrt_var)
                };

                // for helpful debug trace, uncomment the below
                //println!("forward-starting european: df={} F={} K={} sqrt_var={} displacement={} spot_date={} expiry={:?} price={}", 
                //     df, f, k, sqrt_var, displacement, context.spot_date(), self.expiry_time, price);

                price
            } else {
                0.0
            };
        }

        Ok(())
    }
}

/// A European option gives the buyer the option but not the obligation to
/// buy or sell the underlying for a fixed price, the 'strike'. Call options
/// give the buyer the option to buy, and put options give the buyer the option
/// to sell. At expiry therefore, the value of a call option is (S-K).max(0)
/// and the value of a put is (K-S).max(0) where K is the strike and S is the
/// value of the underlying.
///
/// Before expiry, the value is generally greater than the discounted value
/// at expiry because of the effect of 'time value'. When the underlying is
/// volatile, time value means there is a possibility of the underlying price
/// going up or down. The optionality means that the downside is limited, but
/// not the upside, so time value generally means the option is worth more.
#[derive(Clone, Serialize, Deserialize, Debug)]
pub struct SpotStartingEuropean {
    #[serde(flatten)]
    vanilla: VanillaOption,
    strike: f64,
}

impl TypeId for SpotStartingEuropean {
    fn type_id(&self) -> &'static str { "SpotStartingEuropean" }
}

/// A forward-starting European option behaves like a spot-starting one,
/// except that the strike is determined some time in the future. Before
/// that date, the strike date, the strike is known only as some fraction
/// of the forward on the strike date. After the strike fixing is known,
/// the option transforms into a spot-starting European, with the strike
/// equal to the strike fixing times the strike fraction.
///
/// Note that this flavour of forward-starting option is called a fixed-
/// shares option, because the underlying is a fixed number of shares. An
/// alternative is to have a fixed-notional option, where the underlying
/// number of shares is modified at the strike date such that the strike
/// remains constant. Fixed-shares options are far more common.
#[derive(Clone, Serialize, Deserialize, Debug)]
//#[derive(Clone, SerializeState, DeserializeState, Debug)]
//#[serde(serialize_state = "HashMap<String, RcInstrument>")]
//#[serde(deserialize_state = "HashMap<String, RcInstrument>")]
pub struct ForwardStartingEuropean {
    #[serde(flatten)]
    vanilla: VanillaOption,
    strike_fraction: f64,
    strike_date: DateTime,

    // fields precomputed for performance and simplicity
    strike_time: DateDayFraction,
}

impl TypeId for ForwardStartingEuropean {
    fn type_id(&self) -> &'static str { "ForwardStartingEuropean" }
}

impl SpotStartingEuropean {
    pub fn new(
        id: &str,
        credit_id: &str,
        underlying: RcInstrument,
        settlement: RcDateRule,
        expiry: DateTime,
        strike: f64,
        put_or_call: PutOrCall,
        cash_or_physical: OptionSettlement)
        -> Result<SpotStartingEuropean, qm::Error> {

        if strike < 0.0 {
            Err(qm::Error::new("Strike must be greater or equal to zero"))
        } else {
            let vanilla = VanillaOption::new(id, credit_id, underlying,
                settlement, expiry, put_or_call, cash_or_physical)?;
            Ok(SpotStartingEuropean { vanilla: vanilla, strike: strike })
        }
    }

    fn from_vanilla(vanilla: VanillaOption, strike: f64)
        -> SpotStartingEuropean {
        SpotStartingEuropean { vanilla: vanilla, strike: strike }
    }

    pub fn from_serial<'de>(de: &mut esd::Deserializer<'de>) -> Result<Qrc<Instrument>, esd::Error> {
        Ok(Qrc::new(Arc::new(SpotStartingEuropean::deserialize(de)?)))
    }
}

impl ForwardStartingEuropean {
    pub fn new(
        id: &str,
        credit_id: &str,
        underlying: RcInstrument,
        settlement: RcDateRule,
        expiry: DateTime,
        strike_fraction: f64,
        strike_date: DateTime,
        put_or_call: PutOrCall,
        cash_or_physical: OptionSettlement)
        -> Result<ForwardStartingEuropean, qm::Error> {

        if strike_fraction <= 0.0 {
            Err(qm::Error::new("Strike fraction must be greater than zero"))
        } else {
            let strike_time = underlying.time_to_day_fraction(strike_date)?;
            let vanilla = VanillaOption::new(id, credit_id, underlying,
                settlement, expiry, put_or_call, cash_or_physical)?;
            Ok(ForwardStartingEuropean { vanilla: vanilla,
                strike_fraction: strike_fraction, strike_date: strike_date,
                strike_time: strike_time })
        }
    }

    pub fn from_serial<'de>(de: &mut esd::Deserializer<'de>) -> Result<Qrc<Instrument>, esd::Error> {
        Ok(Qrc::new(Arc::new(ForwardStartingEuropean::deserialize(de)?)))
    }
}

impl InstanceId for VanillaOption {
    fn id(&self) -> &str {
        &self.id
    }
}

/// We do not expect VanillaOption to be used as an instrument, as it is an
/// incomplete type. However, it is useful for derived classes to use the
/// interface.
impl Instrument for VanillaOption {

    fn payoff_currency(&self) -> &Currency {
        self.underlying.payoff_currency()
    }

    fn credit_id(&self) -> &str {
        &*self.credit_id
    }

    fn settlement(&self) -> &RcDateRule {
        &self.settlement
    }

    fn dependencies(&self, context: &mut DependencyContext)
        -> SpotRequirement {

        // just one fixing, at expiry
        context.fixing(self.underlying.id(), self.expiry);

        // this is the yield curve used for discounting the option. The yield
        // curve for projecting the forward is defined indirectly via forward_curve.
        context.yield_curve(self.credit_id(), self.pay_date);

        // this forward dependency needs to be revisited. The underlying may
        // be a calculated value with no spot.
        let expiry_date = self.expiry.date();
        context.forward_curve(&self.underlying, expiry_date);
        context.vol_surface(&self.underlying, expiry_date);

        // A listed option does not need a spot, because the vols are
        // calibrated to match the market. An OTC option cannot have a spot,
        // because they are not published (for equities, anyway).
        SpotRequirement::NotRequired
    }
}

impl InstanceId for SpotStartingEuropean {
    fn id(&self) -> &str { self.vanilla.id() }
}

// TODO is there a cleaner way of doing this delegation in Rust?
impl Instrument for SpotStartingEuropean {
    fn payoff_currency(&self) -> &Currency { self.vanilla.payoff_currency() }
    fn credit_id(&self) -> &str { self.vanilla.credit_id() }
    fn settlement(&self) -> &RcDateRule { self.vanilla.settlement() }
    fn dependencies(&self, context: &mut DependencyContext)
        -> SpotRequirement { self.vanilla.dependencies(context) }
    fn as_priceable(&self) -> Option<&Priceable> { Some(self) }
    fn as_mc_priceable(&self) -> Option<&MonteCarloPriceable> { Some(self) }

    // We cannot delegate fix to the contained vanilla, because it needs
    // to know the strike
    fn fix(&self, fixing_table: &FixingTable)
        -> Result<Option<Vec<(f64, RcInstrument)>>, qm::Error> {

        // If there is an expiry fixing (error if missing and in the past),
        // the product turns into either a cash flow, or an equity flow and
        // a cash flow.
        let fixing = fixing_table.get(self.vanilla.underlying.id(),
            self.vanilla.expiry)?;
        if let Some(spot_fixing) = fixing {
            let mut decomp : Vec<(f64, RcInstrument)> = Vec::new();
            let strike = self.strike;
            let sign = match self.vanilla.put_or_call {
                        PutOrCall::Call => 1.0,
                        PutOrCall::Put => -1.0 };
            let payment_id = format!("{}:payment", self.id());
            match self.vanilla.cash_or_physical {

                // cash settlement -- pay a zero coupon if payment > 0
                OptionSettlement::Cash => {
                    let payment = sign * (spot_fixing - strike);
                    if payment > 0.0 {
                        decomp.push((payment, RcInstrument::new(Qrc::new(Arc::new(ZeroCoupon::new(
                            &payment_id, self.credit_id(), 
                            RcCurrency::new(Arc::new(self.payoff_currency().clone())),
                            self.vanilla.expiry, 
                            self.vanilla.pay_date,
                            self.vanilla.settlement.clone()))))));
                    }
                },

                OptionSettlement::Physical => {
                    if sign * (spot_fixing - strike) > 0.0 {
                        decomp.push((-strike * sign, RcInstrument::new(Qrc::new(Arc::new(ZeroCoupon::new(
                            &payment_id, self.credit_id(), 
                            RcCurrency::new(Arc::new(self.payoff_currency().clone())), 
                            self.vanilla.expiry,
                            self.vanilla.pay_date,
                            self.vanilla.settlement.clone()))))));
                        decomp.push((sign, self.vanilla.underlying.clone()));
                    }
                }
            }

            Ok(Some(decomp))
        } else {
            Ok(None)
        }
    }
}

impl InstanceId for ForwardStartingEuropean {
    fn id(&self) -> &str { self.vanilla.id() }
}

impl Instrument for ForwardStartingEuropean {
    fn payoff_currency(&self) -> &Currency { self.vanilla.payoff_currency() }
    fn credit_id(&self) -> &str { self.vanilla.credit_id() }
    fn settlement(&self) -> &RcDateRule { self.vanilla.settlement() }
    fn as_priceable(&self) -> Option<&Priceable> { Some(self) }
    fn as_mc_priceable(&self) -> Option<&MonteCarloPriceable> { Some(self) }

    fn dependencies(&self, context: &mut DependencyContext)
        -> SpotRequirement {

        // make sure we record the strike fixing before the expiry fixing
        context.fixing(self.vanilla.underlying.id(), self.strike_date);
         
        self.vanilla.dependencies(context) 
    }

    // We cannot delegate fix to the contained vanilla, because it needs
    // to know the strike_fraction and strike date
    fn fix(&self, fixing_table: &FixingTable)
        -> Result<Option<Vec<(f64, RcInstrument)>>, qm::Error> {

        // If there is a strike fixing (error if missing and in the past),
        // the product turns into a spot starting European
        let fixing = fixing_table.get(self.vanilla.underlying.id(),
            self.strike_date)?;
        if let Some(f) = fixing {
            let mut decomp: Vec<(f64, RcInstrument)> = Vec::new();
            let strike = f * self.strike_fraction;
            let spot_starting = SpotStartingEuropean::from_vanilla(
                self.vanilla.clone(), strike);

            // we may be able to further decompose this
            let further = spot_starting.fix(fixing_table)?;
            if let Some(_) = further {
                Ok(further)
            } else {
                decomp.push((1.0, RcInstrument::new(Qrc::new(Arc::new(spot_starting)))));
                Ok(Some(decomp))
            }
        } else {
            Ok(None)
        }
    }
}

impl Priceable for SpotStartingEuropean {
    fn as_instrument(&self) -> &Instrument { self }

    // Values the European Option using the analytic formula Black 76
    fn prices(&self, context: &PricingContext, dates: &[DateTime], out: &mut [f64])
        -> Result<(), qm::Error> {

        let before_time = DateDayFraction::new(Date::from_nil(), 0.0);
        self.vanilla.prices(context, dates, out, before_time, 
            &|underlying| Ok((self.strike, underlying.price(context, self.vanilla.expiry)?)))
    }
}

impl Priceable for ForwardStartingEuropean {
    fn as_instrument(&self) -> &Instrument { self }

    /// The valuation of a forward-starting option is the same as a spot-
    /// starting one, except that the strike is calculated from the forward,
    /// and we use forward vol from the strike date to expiry.
    fn prices(&self, context: &PricingContext, dates: &[DateTime], out: &mut [f64])
        -> Result<(), qm::Error> {

        // it is an error if the option has already started
        if context.spot_date() > self.strike_date.date() {
            return Err(qm::Error::new("You should fix the European before \
                pricing it, so it does not forward-start in the past"))
        }

        self.vanilla.prices(context, dates, out, self.strike_time, &|underlying| {
            let mut values = vec![NAN, NAN];
            let dates = vec![self.strike_date, self.vanilla.expiry];
            underlying.prices(context, &dates, &mut values)?;
            Ok((values[0] * self.strike_fraction, values[1]))
        })
    }
}

impl MonteCarloPriceable for SpotStartingEuropean {
    fn as_instrument(&self) -> &Instrument { self }

    fn mc_dependencies(&self, _dates: &[DateDayFraction],
        output: &mut MonteCarloDependencies) -> Result<(), qm::Error> {

        // one observation, at expiry
        output.observation(&self.vanilla.underlying, self.vanilla.expiry_time);

        // TODO this feels inefficient and ugly
        let currency = RcCurrency::new(Arc::new(self.payoff_currency().clone()));

        // For the purposes of Monte-Carlo valuation we treat all vanillas as
        // if they paid cash at the pay date. (Physically settled vanillas pay
        // stock as well, but that does not affect the price before expiry.)
        let payment : RcInstrument = RcInstrument::new(Qrc::new(Arc::new(
            ZeroCoupon::new(&format!("{}:Expiry", self.vanilla.id),
            &self.vanilla.credit_id, currency, self.vanilla.expiry, self.vanilla.pay_date,
            self.vanilla.settlement.clone()))));
        output.flow(&payment);

        Ok(())
    }

    fn start_date(&self) -> Option<DateDayFraction> {
        None
    }

    fn mc_price(&self, context: &MonteCarloContext)
        -> Result<f64, qm::Error> {

        // This is asserting what the context should know from our response
        // to the mc_dependencies call. No need for proper error handling.
        let ref paths = context.paths(&self.vanilla.underlying)?;
        let shape = paths.shape();
        assert_eq!(shape.len(), 2);
        let n_paths = shape[0];
        let n_obs = shape[1];
        assert_eq!(n_obs, 1);
        let ref path_column = paths.subview(Axis(1), 0);

        // Create an array to hold the cashflows (one per path). Note that
        // there is no need to distinguish cash and physically settled options,
        // as they value the same in the future.
        let mut quantities = Array2::zeros((n_paths, 1));

        let strike = self.strike;
        let sign = match self.vanilla.put_or_call {
            PutOrCall::Call => 1.0,
            PutOrCall::Put => -1.0 };

        // Calculate the quantity of each flow for each path
        {
            let ref mut flow_column = quantities.subview_mut(Axis(1), 0);
            for (spot, flow) in path_column.iter().zip(flow_column.iter_mut()) {
                let intrinsic = (sign * (spot - strike)).max(0.0);
                *flow = intrinsic;
            }
        }

        // sum and discount the flows
        context.evaluate_flows(quantities.view())
    }
}

impl MonteCarloPriceable for ForwardStartingEuropean {
    fn as_instrument(&self) -> &Instrument { self }

    fn mc_dependencies(&self, _dates: &[DateDayFraction],
        output: &mut MonteCarloDependencies) -> Result<(), qm::Error> {

        // two observations, at strike and expiry
        output.observation(&self.vanilla.underlying, self.strike_time);
        output.observation(&self.vanilla.underlying, self.vanilla.expiry_time);

        // TODO this feels inefficient and ugly
        let currency = RcCurrency::new(Arc::new(self.payoff_currency().clone()));

        // For the purposes of Monte-Carlo valuation we treat all vanillas as
        // if they paid cash at the pay date. (Physically settled vanillas pay
        // stock as well, but that does not affect the price before expiry.)
        let payment : RcInstrument = RcInstrument::new(Qrc::new(Arc::new(
            ZeroCoupon::new(&format!("{}:Expiry", self.vanilla.id),
            &self.vanilla.credit_id, currency, self.vanilla.expiry, self.vanilla.pay_date,
            self.vanilla.settlement.clone()))));
        output.flow(&payment);

        Ok(())
    }

    fn start_date(&self) -> Option<DateDayFraction> {
        Some(self.strike_time)
    }

    fn mc_price(&self, context: &MonteCarloContext)
        -> Result<f64, qm::Error> {

        // This is asserting what the context should know from our response
        // to the mc_dependencies call. No need for proper error handling.
        let ref paths = context.paths(&self.vanilla.underlying)?;
        let shape = paths.shape();
        assert_eq!(shape.len(), 2);
        let n_paths = shape[0];
        let n_obs = shape[1];
        assert_eq!(n_obs, 2);
  
        // Create an array to hold the cashflows (one per path). Note that
        // there is no need to distinguish cash and physically settled options,
        // as they value the same in the future.
        let mut quantities = Array2::zeros((n_paths, 1));

        let strike_fraction = self.strike_fraction;
        let sign = match self.vanilla.put_or_call {
            PutOrCall::Call => 1.0,
            PutOrCall::Put => -1.0 };

        // Calculate the quantity of each flow for each path
        {
            let ref mut flow_column = quantities.subview_mut(Axis(1), 0);
            for (path, flow) in paths.axis_iter(Axis(0)).zip(flow_column.iter_mut()) {
                let strike = strike_fraction * path[0];
                let spot = path[1];
                let intrinsic = (sign * (spot - strike)).max(0.0);
                *flow = intrinsic;
            }
        }

        // sum and discount the flows
        context.evaluate_flows(quantities.view())
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use std::collections::HashMap;
    use core::dedup::{Dedup, DedupControl};
    use math::numerics::approx_eq;
    use math::interpolation::Extrap;
    use math::interpolation::CubicSpline;
    use data::forward::Forward;
    use data::volsurface::RcVolSurface;
    use data::curves::RateCurveAct365;
    use data::curves::RcRateCurve;
    use data::forward::InterpolatedForward;
    use data::volsurface::FlatVolSurface;
    use dates::calendar::WeekdayCalendar;
    use dates::calendar::RcCalendar;
    use dates::Date;
    use dates::datetime::TimeOfDay;
    use instruments::basket::Basket;
    use instruments::assets::tests::sample_currency;
    use instruments::assets::tests::sample_equity;
    use instruments::assets::DEDUP_CURRENCY;
    use instruments::DEDUP_INSTRUMENT;
    use serde_json;
    use serde::Serialize;

    struct SamplePricingContext { 
        spot: f64
    }

    impl PricingContext for SamplePricingContext {
        fn spot_date(&self) -> Date {
            Date::from_ymd(2018, 06, 01)
        }

        fn yield_curve(&self, _credit_id: &str, _high_water_mark: Date)
                -> Result<RcRateCurve, qm::Error> {

            let d = Date::from_ymd(2018, 05, 30);
            let points = [(d, 0.05), (d + 14, 0.08), (d + 56, 0.09),
                (d + 112, 0.085), (d + 224, 0.082)];
            let c = RateCurveAct365::new(d, &points,
                Extrap::Flat, Extrap::Flat)?;
            Ok(RcRateCurve::new(Arc::new(c)))
        }

        fn spot(&self, id: &str) -> Result<f64, qm::Error> {
            print!("spot for {}", id);
            Ok(self.spot)
        }

        fn forward_curve(&self, instrument: &Instrument, 
            _high_water_mark: Date) -> Result<Arc<Forward>, qm::Error> {
 
            print!("forward for {}", instrument.id());

            let d = Date::from_ymd(2018, 06, 01);

            let points = [(d, self.spot), (d+30, 1.03 * self.spot),
                (d+60, 0.97 * self.spot), (d+90, 0.99 * self.spot),
                (d+120, 1.05 * self.spot)];
            let cs = Box::new(CubicSpline::new(&points,
                Extrap::Natural, Extrap::Natural).unwrap());
            let fwd = InterpolatedForward::new(cs);
            Ok(Arc::new(fwd))
        }

        fn vol_surface(&self, _instrument: &Instrument, _high_water_mark: Date,
            _forward_fn: &Fn() -> Result<Arc<Forward>, qm::Error>)
            -> Result<RcVolSurface, qm::Error> {

            let calendar = RcCalendar::new(Arc::new(WeekdayCalendar()));
            let base_date = Date::from_ymd(2018, 05, 30);
            let base = DateDayFraction::new(base_date, 0.2);
            let vol = FlatVolSurface::new(0.3, calendar, base);
            Ok(RcVolSurface::new(Arc::new(vol)))
        }

        fn correlation(&self, _first: &Instrument, _second: &Instrument)
            -> Result<f64, qm::Error> {
            Err(qm::Error::new("unsupported"))
        }
    }

    fn sample_pricing_context(spot: f64) -> SamplePricingContext {
        SamplePricingContext { spot: spot }
    }

    fn sample_fixings() -> FixingTable {
        let today = Date::from_ymd(2018, 06, 01);
        FixingTable::from_fixings(today, &[
            ("BP.L", &[
            (DateTime::new(today, TimeOfDay::Close), 100.0),
            (DateTime::new(today - 7, TimeOfDay::Close), 102.0)])]).unwrap()
    }

    #[test]
    fn european_call_far_in_the_money_at_expiry() {

        let spot = 123.4;
        let strike = 100.0;
        let expiry = DateTime::new(Date::from_ymd(2018, 06, 01), TimeOfDay::Open);

        check_european_value(spot, strike, expiry, PutOrCall::Call, spot - strike);
    }

    #[test]
    fn european_put_far_in_the_money_at_expiry() {
        
        let spot = 123.4;
        let strike = 150.0;
        let expiry = DateTime::new(Date::from_ymd(2018, 06, 01), TimeOfDay::Open);

        check_european_value(spot, strike, expiry, PutOrCall::Put, strike - spot);
    }

    #[test]
    fn european_call_at_the_money_before_expiry() {

        let spot = 100.0;
        let strike = 115.170375;
        let expiry = DateTime::new(
            Date::from_ymd(2018, 12, 01), TimeOfDay::Close);

        check_european_value(spot, strike, expiry, PutOrCall::Call,
            9.511722618202752);
    }

    #[test]
    fn european_put_at_the_money_before_expiry() {
        
        let spot = 100.0;
        let strike = 115.170375;
        let expiry = DateTime::new(
            Date::from_ymd(2018, 12, 01), TimeOfDay::Close);

        check_european_value(spot, strike, expiry, PutOrCall::Put,
            9.511722618202759);
    }

    #[test]
    fn forward_european_call_far_in_the_money() {

        let spot = 100.0;
        let strike_fraction = 0.7;
        let strike_date = DateTime::new(
            Date::from_ymd(2018, 06, 08), TimeOfDay::Close);
        let expiry = DateTime::new(
            Date::from_ymd(2018, 07, 01), TimeOfDay::Close);

        check_forward_european_value(spot, strike_fraction, strike_date, expiry,
            PutOrCall::Call, 31.833089791935123);
    }

    #[test]
    fn forward_european_call_at_strike() {

        let spot = 100.0;
        let strike_fraction = 1.15170375;
        let strike_date = DateTime::new(
            Date::from_ymd(2018, 06, 01), TimeOfDay::Close);
        let expiry = DateTime::new(
            Date::from_ymd(2018, 12, 01), TimeOfDay::Close);

        check_forward_european_value(spot, strike_fraction, strike_date, expiry,
            PutOrCall::Call, 9.482747427099154);
    }

    #[test]
    fn forward_european_put_at_strike() {

        let spot = 100.0;
        let strike_fraction = 1.15170375;
        let strike_date = DateTime::new(
            Date::from_ymd(2018, 06, 01), TimeOfDay::Close);
        let expiry = DateTime::new(
            Date::from_ymd(2018, 12, 01), TimeOfDay::Close);

        check_forward_european_value(spot, strike_fraction, strike_date, expiry,
            PutOrCall::Put, 9.482747427099161);
    }

    #[test]
    fn forward_european_call_fixed_today() {

        let spot = 100.0;
        let strike_fraction = 1.15170375;
        let strike_date = DateTime::new(
            Date::from_ymd(2018, 06, 01), TimeOfDay::Close);
        let expiry = DateTime::new(
            Date::from_ymd(2018, 12, 01), TimeOfDay::Close);

        check_fixed_european_value(spot, strike_fraction, strike_date, expiry,
            PutOrCall::Call, 9.511722618202752);
    }

    #[test]
    fn forward_european_put_fixed_today() {

        let spot = 100.0;
        let strike_fraction = 1.15170375;
        let strike_date = DateTime::new(
            Date::from_ymd(2018, 06, 01), TimeOfDay::Close);
        let expiry = DateTime::new(
            Date::from_ymd(2018, 12, 01), TimeOfDay::Close);

        check_fixed_european_value(spot, strike_fraction, strike_date, expiry,
            PutOrCall::Put, 9.511722618202759);
    }

    #[test]
    fn forward_european_call() {

        let spot = 100.0;
        let strike_fraction = 1.15170375;
        let strike_date = DateTime::new(
            Date::from_ymd(2018, 06, 08), TimeOfDay::Close);
        let expiry = DateTime::new(
            Date::from_ymd(2018, 12, 01), TimeOfDay::Close);

        check_forward_european_value(spot, strike_fraction, strike_date, expiry,
            PutOrCall::Call, 8.639339890285823);
    }

    #[test]
    fn forward_european_put() {

        let spot = 100.0;
        let strike_fraction = 1.15170375;
        let strike_date = DateTime::new(
            Date::from_ymd(2018, 06, 08), TimeOfDay::Close);
        let expiry = DateTime::new(
            Date::from_ymd(2018, 12, 01), TimeOfDay::Close);

        check_forward_european_value(spot, strike_fraction, strike_date, expiry,
            PutOrCall::Put, 10.121695405560876);
    }

    #[test]
    fn basket_european_put() {

        let spot = 100.0;
        let strike = 115.170375;
        let expiry = DateTime::new(
            Date::from_ymd(2018, 12, 01), TimeOfDay::Close);

        check_basket_european_value(spot, strike, expiry, PutOrCall::Call,
            9.511722618202752);
    }

    #[test]
    fn basket_forward_european_put() {

        let spot = 100.0;
        let strike_fraction = 1.15170375;
        let strike_date = DateTime::new(
            Date::from_ymd(2018, 06, 08), TimeOfDay::Close);
        let expiry = DateTime::new(
            Date::from_ymd(2018, 12, 01), TimeOfDay::Close);

        check_basket_forward_european_value(spot, strike_fraction, strike_date, expiry,
            PutOrCall::Put, 10.121695405560876);
    }

    fn check_european_value(spot: f64, strike: f64, expiry: DateTime,
        put_or_call: PutOrCall, expected: f64) {

        let currency = RcCurrency::new(Arc::new(sample_currency(2)));
        let equity = RcInstrument::new(Qrc::new(Arc::new(sample_equity(currency, "BP.L", 2))));
        let settlement = equity.settlement().clone();
        let cash_or_physical = OptionSettlement::Cash;
        let european = SpotStartingEuropean::new("SampleEuropean", "OPT",
            equity.clone(), settlement, expiry,
            strike, put_or_call, cash_or_physical).unwrap();
        let val_date = DateTime::new(Date::from_ymd(2018, 06, 01), TimeOfDay::Open);

        let context = sample_pricing_context(spot);
        let price = european.price(&context, val_date).unwrap();
        assert_approx(price, expected, 1e-8);
    }

    fn check_basket_european_value(spot: f64, strike: f64, expiry: DateTime,
        put_or_call: PutOrCall, expected: f64) {

        let currency = RcCurrency::new(Arc::new(sample_currency(2)));
        let az = RcInstrument::new(Qrc::new(Arc::new(sample_equity(currency.clone(), "AZ.L", 2))));
        let bp = RcInstrument::new(Qrc::new(Arc::new(sample_equity(currency.clone(), "BP.L", 2))));
        let basket = vec![(0.4, az.clone()), (0.6, bp.clone())];
        let ul = RcInstrument::new(Qrc::new(Arc::new(Basket::new(
            "basket", az.credit_id(), currency.clone(), az.settlement().clone(), basket).unwrap())));
        let settlement = ul.settlement().clone();
        let cash_or_physical = OptionSettlement::Cash;
        let european = SpotStartingEuropean::new("SampleBasketEuropean", "OPT",
            ul.clone(), settlement, expiry,
            strike, put_or_call, cash_or_physical).unwrap();
        let val_date = DateTime::new(Date::from_ymd(2018, 06, 01), TimeOfDay::Open);

        let context = sample_pricing_context(spot);
        let price = european.price(&context, val_date).unwrap();
        assert_approx(price, expected, 1e-8);
    }

    fn check_forward_european_value(spot: f64, strike_fraction: f64,
        strike_date: DateTime, expiry: DateTime,
        put_or_call: PutOrCall, expected: f64) {

        let currency = RcCurrency::new(Arc::new(sample_currency(2)));
        let equity = RcInstrument::new(Qrc::new(Arc::new(sample_equity(currency, "BP.L", 2))));
        let settlement = equity.settlement().clone();
        let cash_or_physical = OptionSettlement::Cash;
        let european = ForwardStartingEuropean::new("SampleEuropean", "OPT",
            equity.clone(), settlement, expiry, strike_fraction,
            strike_date, put_or_call, cash_or_physical).unwrap();
        let val_date = DateTime::new(Date::from_ymd(2018, 06, 01), TimeOfDay::Open);

        let context = sample_pricing_context(spot);
        let price = european.price(&context, val_date).unwrap();
        assert_approx(price, expected, 1e-8);
    }

    fn check_basket_forward_european_value(spot: f64, strike_fraction: f64,
        strike_date: DateTime, expiry: DateTime,
        put_or_call: PutOrCall, expected: f64) {

        let currency = RcCurrency::new(Arc::new(sample_currency(2)));
        let az = RcInstrument::new(Qrc::new(Arc::new(sample_equity(currency.clone(), "AZ.L", 2))));
        let bp = RcInstrument::new(Qrc::new(Arc::new(sample_equity(currency.clone(), "BP.L", 2))));
        let basket = vec![(0.4, az.clone()), (0.6, bp.clone())];
        let ul = RcInstrument::new(Qrc::new(Arc::new(Basket::new(
            "basket", az.credit_id(), currency.clone(), az.settlement().clone(), basket).unwrap())));
        let settlement = ul.settlement().clone();
        let cash_or_physical = OptionSettlement::Cash;
        let european = ForwardStartingEuropean::new("SampleEuropean", "OPT",
            ul.clone(), settlement, expiry, strike_fraction,
            strike_date, put_or_call, cash_or_physical).unwrap();
        let val_date = DateTime::new(Date::from_ymd(2018, 06, 01), TimeOfDay::Open);

        let context = sample_pricing_context(spot);
        let price = european.price(&context, val_date).unwrap();
        assert_approx(price, expected, 1e-8);
    }

    fn check_fixed_european_value(spot: f64, strike_fraction: f64,
        strike_date: DateTime, expiry: DateTime,
        put_or_call: PutOrCall, expected: f64) {

        let currency = RcCurrency::new(Arc::new(sample_currency(2)));
        let equity = RcInstrument::new(Qrc::new(Arc::new(sample_equity(currency, "BP.L", 2))));
        let settlement = equity.settlement().clone();
        let cash_or_physical = OptionSettlement::Cash;
        let european = ForwardStartingEuropean::new("SampleEuropean", "OPT",
            equity.clone(), settlement, expiry, strike_fraction,
            strike_date, put_or_call, cash_or_physical).unwrap();
        let val_date = DateTime::new(Date::from_ymd(2018, 06, 01), TimeOfDay::Open);

        let fixing_table = sample_fixings();
        let fix_result = european.fix(&fixing_table).unwrap();
        if let Some(fixed) = fix_result {
            assert_eq!(fixed.len(), 1);
            let (amount, ref instrument) = fixed[0];
            assert_approx(amount, 1.0, 1e-14);
            if let Some(fixed_european) = instrument.as_priceable() {

                let context = sample_pricing_context(spot);
                let price = fixed_european.price(&context, val_date).unwrap();
                assert_approx(price, expected, 1e-8);
            } else {
                assert!(false, "failed to fix into a priceable");
            }
        } else {
            assert!(false, "failed to fix");
        }
    }

    fn sample_forward_starting_european(strike_fraction: f64, id: &str) -> ForwardStartingEuropean {
        let strike_date = DateTime::new(
            Date::from_ymd(2018, 06, 08), TimeOfDay::Close);
        let expiry = DateTime::new(
            Date::from_ymd(2018, 12, 01), TimeOfDay::Close);
        let currency = RcCurrency::new(Arc::new(sample_currency(2)));
        let az = RcInstrument::new(Qrc::new(Arc::new(sample_equity(currency.clone(), "AZ.L", 2))));
        let bp = RcInstrument::new(Qrc::new(Arc::new(sample_equity(currency.clone(), "BP.L", 2))));
        let basket = vec![(0.4, az.clone()), (0.6, bp.clone())];
        let ul = RcInstrument::new(Qrc::new(Arc::new(Basket::new(
            "basket", az.credit_id(), currency.clone(), az.settlement().clone(), basket).unwrap())));
        let settlement = ul.settlement().clone();
        let cash_or_physical = OptionSettlement::Cash;
        ForwardStartingEuropean::new(id, "OPT",
            ul.clone(), settlement, expiry, strike_fraction,
            strike_date, PutOrCall::Call, cash_or_physical).unwrap()
    }

    #[test]
    fn european_serde() {

        // tests serialization and deserialization of a strongly typed european option

        let spot = 100.0;
        let european = sample_forward_starting_european(1.15170375, "SampleEuropean");
  
        // value it
        let val_date = DateTime::new(Date::from_ymd(2018, 06, 01), TimeOfDay::Open);
        let context = sample_pricing_context(spot);
        let price = european.price(&context, val_date).unwrap();

        // Serialize to a JSON string.
        let serialized = serde_json::to_string_pretty(&european).unwrap();

        // Convert the JSON string back to an interpolator.
        let deserialized: ForwardStartingEuropean = serde_json::from_str(&serialized).unwrap();

        // check the price still matches
        let priceable = deserialized.as_priceable().unwrap();
        let serde_price = priceable.price(&context, val_date).unwrap();
    
        assert_approx(serde_price, price, 1e-12);
    }

    #[test]
    fn european_tagged_serde_dedup_inline() {
        european_tagged_serde_dedup(DedupControl::Inline, HashMap::new(), r###"{
  "ForwardStartingEuropean": {
    "id": "SampleEuropean",
    "credit_id": "OPT",
    "underlying": {
      "Basket": {
        "id": "basket",
        "credit_id": "LSE",
        "currency": {
          "id": "GBP",
          "settlement": {
            "BusinessDays": {
              "calendar": {
                "WeekdayCalendar": []
              },
              "step": 2,
              "slip_forward": true
            }
          }
        },
        "settlement": {
          "BusinessDays": {
            "calendar": {
              "WeekdayCalendar": []
            },
            "step": 2,
            "slip_forward": true
          }
        },
        "basket": [
          [
            0.4,
            {
              "Equity": {
                "id": "AZ.L",
                "credit_id": "LSE",
                "currency": {
                  "id": "GBP",
                  "settlement": {
                    "BusinessDays": {
                      "calendar": {
                        "WeekdayCalendar": []
                      },
                      "step": 2,
                      "slip_forward": true
                    }
                  }
                },
                "settlement": {
                  "BusinessDays": {
                    "calendar": {
                      "WeekdayCalendar": []
                    },
                    "step": 2,
                    "slip_forward": true
                  }
                }
              }
            }
          ],
          [
            0.6,
            {
              "Equity": {
                "id": "BP.L",
                "credit_id": "LSE",
                "currency": {
                  "id": "GBP",
                  "settlement": {
                    "BusinessDays": {
                      "calendar": {
                        "WeekdayCalendar": []
                      },
                      "step": 2,
                      "slip_forward": true
                    }
                  }
                },
                "settlement": {
                  "BusinessDays": {
                    "calendar": {
                      "WeekdayCalendar": []
                    },
                    "step": 2,
                    "slip_forward": true
                  }
                }
              }
            }
          ]
        ]
      }
    },
    "settlement": {
      "BusinessDays": {
        "calendar": {
          "WeekdayCalendar": []
        },
        "step": 2,
        "slip_forward": true
      }
    },
    "expiry": {
      "date": "2018-12-01",
      "time_of_day": "Close"
    },
    "put_or_call": "Call",
    "cash_or_physical": "Cash",
    "expiry_time": {
      "date": "2018-12-01",
      "day_fraction": 0.8
    },
    "pay_date": "2018-12-05",
    "strike_fraction": 1.15170375,
    "strike_date": {
      "date": "2018-06-08",
      "time_of_day": "Close"
    },
    "strike_time": {
      "date": "2018-06-08",
      "day_fraction": 0.8
    }
  }
}"###);
    }

    #[test]
    fn european_tagged_serde_dedup_write_once() {
        european_tagged_serde_dedup(DedupControl::WriteOnce, HashMap::new(), r###"{
  "ForwardStartingEuropean": {
    "id": "SampleEuropean",
    "credit_id": "OPT",
    "underlying": {
      "Basket": {
        "id": "basket",
        "credit_id": "LSE",
        "currency": {
          "id": "GBP",
          "settlement": {
            "BusinessDays": {
              "calendar": {
                "WeekdayCalendar": []
              },
              "step": 2,
              "slip_forward": true
            }
          }
        },
        "settlement": {
          "BusinessDays": {
            "calendar": {
              "WeekdayCalendar": []
            },
            "step": 2,
            "slip_forward": true
          }
        },
        "basket": [
          [
            0.4,
            {
              "Equity": {
                "id": "AZ.L",
                "credit_id": "LSE",
                "currency": "GBP",
                "settlement": {
                  "BusinessDays": {
                    "calendar": {
                      "WeekdayCalendar": []
                    },
                    "step": 2,
                    "slip_forward": true
                  }
                }
              }
            }
          ],
          [
            0.6,
            {
              "Equity": {
                "id": "BP.L",
                "credit_id": "LSE",
                "currency": "GBP",
                "settlement": {
                  "BusinessDays": {
                    "calendar": {
                      "WeekdayCalendar": []
                    },
                    "step": 2,
                    "slip_forward": true
                  }
                }
              }
            }
          ]
        ]
      }
    },
    "settlement": {
      "BusinessDays": {
        "calendar": {
          "WeekdayCalendar": []
        },
        "step": 2,
        "slip_forward": true
      }
    },
    "expiry": {
      "date": "2018-12-01",
      "time_of_day": "Close"
    },
    "put_or_call": "Call",
    "cash_or_physical": "Cash",
    "expiry_time": {
      "date": "2018-12-01",
      "day_fraction": 0.8
    },
    "pay_date": "2018-12-05",
    "strike_fraction": 1.15170375,
    "strike_date": {
      "date": "2018-06-08",
      "time_of_day": "Close"
    },
    "strike_time": {
      "date": "2018-06-08",
      "day_fraction": 0.8
    }
  }
}"###);
    }

    #[test]
    fn european_tagged_serde_dedup_error_if_missing() {
        let currency = RcCurrency::new(Arc::new(sample_currency(2)));
        let mut map = HashMap::new();
        map.insert("GBP".to_string(), currency);

        european_tagged_serde_dedup(DedupControl::ErrorIfMissing, map, r###"{
  "ForwardStartingEuropean": {
    "id": "SampleEuropean",
    "credit_id": "OPT",
    "underlying": {
      "Basket": {
        "id": "basket",
        "credit_id": "LSE",
        "currency": "GBP",
        "settlement": {
          "BusinessDays": {
            "calendar": {
              "WeekdayCalendar": []
            },
            "step": 2,
            "slip_forward": true
          }
        },
        "basket": [
          [
            0.4,
            {
              "Equity": {
                "id": "AZ.L",
                "credit_id": "LSE",
                "currency": "GBP",
                "settlement": {
                  "BusinessDays": {
                    "calendar": {
                      "WeekdayCalendar": []
                    },
                    "step": 2,
                    "slip_forward": true
                  }
                }
              }
            }
          ],
          [
            0.6,
            {
              "Equity": {
                "id": "BP.L",
                "credit_id": "LSE",
                "currency": "GBP",
                "settlement": {
                  "BusinessDays": {
                    "calendar": {
                      "WeekdayCalendar": []
                    },
                    "step": 2,
                    "slip_forward": true
                  }
                }
              }
            }
          ]
        ]
      }
    },
    "settlement": {
      "BusinessDays": {
        "calendar": {
          "WeekdayCalendar": []
        },
        "step": 2,
        "slip_forward": true
      }
    },
    "expiry": {
      "date": "2018-12-01",
      "time_of_day": "Close"
    },
    "put_or_call": "Call",
    "cash_or_physical": "Cash",
    "expiry_time": {
      "date": "2018-12-01",
      "day_fraction": 0.8
    },
    "pay_date": "2018-12-05",
    "strike_fraction": 1.15170375,
    "strike_date": {
      "date": "2018-06-08",
      "time_of_day": "Close"
    },
    "strike_time": {
      "date": "2018-06-08",
      "day_fraction": 0.8
    }
  }
}"###);
    }

    fn european_tagged_serde_dedup(control: DedupControl, map: HashMap<String, RcCurrency>, expected: &str) {

        // tests serialization and deserialization of a european option contained within a
        // Rc<Instrument>. It therefore tests the tagged serialization of the option

        let spot = 100.0;
        let european = sample_forward_starting_european(1.15170375, "SampleEuropean");
  
        // value it
        let val_date = DateTime::new(Date::from_ymd(2018, 06, 01), TimeOfDay::Open);
        let context = sample_pricing_context(spot);
        let price = european.price(&context, val_date).unwrap();

        // Serialize to a JSON string.
        let instrument = RcInstrument::new(Qrc::new(Arc::new(european)));

        // write it out and read it back in
        let mut buffer = Vec::new();
        {
            let mut serializer = serde_json::Serializer::pretty(&mut buffer);
            let mut seed = Dedup::<Currency, Arc<Currency>>::new(control.clone(), map.clone());
            seed.with(&DEDUP_CURRENCY, || instrument.serialize(&mut serializer)).unwrap();
        }

        let serialized = String::from_utf8(buffer.clone()).unwrap();
        print!("{}", serialized);
        assert_eq!(serialized, expected);

        let deserialized = {
            let mut deserializer = serde_json::Deserializer::from_slice(&buffer);
            let mut seed = Dedup::<Currency, Arc<Currency>>::new(control.clone(), map.clone());
            seed.with(&DEDUP_CURRENCY, || RcInstrument::deserialize(&mut deserializer)).unwrap()
        };

        // check the price still matches
        let priceable = deserialized.as_priceable().unwrap();
        let serde_price = priceable.price(&context, val_date).unwrap();
    
        assert_approx(serde_price, price, 1e-12);
    }

    #[test]
    fn basket_tagged_serde_dedup_inline() {
        basket_tagged_serde_dedup(DedupControl::Inline, HashMap::new(), HashMap::new(), r###"{
  "id": "OptionBasket",
  "credit_id": "OPT",
  "currency": {
    "id": "GBP",
    "settlement": {
      "BusinessDays": {
        "calendar": {
          "WeekdayCalendar": []
        },
        "step": 2,
        "slip_forward": true
      }
    }
  },
  "settlement": {
    "BusinessDays": {
      "calendar": {
        "WeekdayCalendar": []
      },
      "step": 2,
      "slip_forward": true
    }
  },
  "basket": [
    [
      0.4,
      {
        "ForwardStartingEuropean": {
          "id": "Option1",
          "credit_id": "OPT",
          "underlying": {
            "Basket": {
              "id": "basket",
              "credit_id": "LSE",
              "currency": {
                "id": "GBP",
                "settlement": {
                  "BusinessDays": {
                    "calendar": {
                      "WeekdayCalendar": []
                    },
                    "step": 2,
                    "slip_forward": true
                  }
                }
              },
              "settlement": {
                "BusinessDays": {
                  "calendar": {
                    "WeekdayCalendar": []
                  },
                  "step": 2,
                  "slip_forward": true
                }
              },
              "basket": [
                [
                  0.4,
                  {
                    "Equity": {
                      "id": "AZ.L",
                      "credit_id": "LSE",
                      "currency": {
                        "id": "GBP",
                        "settlement": {
                          "BusinessDays": {
                            "calendar": {
                              "WeekdayCalendar": []
                            },
                            "step": 2,
                            "slip_forward": true
                          }
                        }
                      },
                      "settlement": {
                        "BusinessDays": {
                          "calendar": {
                            "WeekdayCalendar": []
                          },
                          "step": 2,
                          "slip_forward": true
                        }
                      }
                    }
                  }
                ],
                [
                  0.6,
                  {
                    "Equity": {
                      "id": "BP.L",
                      "credit_id": "LSE",
                      "currency": {
                        "id": "GBP",
                        "settlement": {
                          "BusinessDays": {
                            "calendar": {
                              "WeekdayCalendar": []
                            },
                            "step": 2,
                            "slip_forward": true
                          }
                        }
                      },
                      "settlement": {
                        "BusinessDays": {
                          "calendar": {
                            "WeekdayCalendar": []
                          },
                          "step": 2,
                          "slip_forward": true
                        }
                      }
                    }
                  }
                ]
              ]
            }
          },
          "settlement": {
            "BusinessDays": {
              "calendar": {
                "WeekdayCalendar": []
              },
              "step": 2,
              "slip_forward": true
            }
          },
          "expiry": {
            "date": "2018-12-01",
            "time_of_day": "Close"
          },
          "put_or_call": "Call",
          "cash_or_physical": "Cash",
          "expiry_time": {
            "date": "2018-12-01",
            "day_fraction": 0.8
          },
          "pay_date": "2018-12-05",
          "strike_fraction": 1.15,
          "strike_date": {
            "date": "2018-06-08",
            "time_of_day": "Close"
          },
          "strike_time": {
            "date": "2018-06-08",
            "day_fraction": 0.8
          }
        }
      }
    ],
    [
      0.6,
      {
        "ForwardStartingEuropean": {
          "id": "Option2",
          "credit_id": "OPT",
          "underlying": {
            "Basket": {
              "id": "basket",
              "credit_id": "LSE",
              "currency": {
                "id": "GBP",
                "settlement": {
                  "BusinessDays": {
                    "calendar": {
                      "WeekdayCalendar": []
                    },
                    "step": 2,
                    "slip_forward": true
                  }
                }
              },
              "settlement": {
                "BusinessDays": {
                  "calendar": {
                    "WeekdayCalendar": []
                  },
                  "step": 2,
                  "slip_forward": true
                }
              },
              "basket": [
                [
                  0.4,
                  {
                    "Equity": {
                      "id": "AZ.L",
                      "credit_id": "LSE",
                      "currency": {
                        "id": "GBP",
                        "settlement": {
                          "BusinessDays": {
                            "calendar": {
                              "WeekdayCalendar": []
                            },
                            "step": 2,
                            "slip_forward": true
                          }
                        }
                      },
                      "settlement": {
                        "BusinessDays": {
                          "calendar": {
                            "WeekdayCalendar": []
                          },
                          "step": 2,
                          "slip_forward": true
                        }
                      }
                    }
                  }
                ],
                [
                  0.6,
                  {
                    "Equity": {
                      "id": "BP.L",
                      "credit_id": "LSE",
                      "currency": {
                        "id": "GBP",
                        "settlement": {
                          "BusinessDays": {
                            "calendar": {
                              "WeekdayCalendar": []
                            },
                            "step": 2,
                            "slip_forward": true
                          }
                        }
                      },
                      "settlement": {
                        "BusinessDays": {
                          "calendar": {
                            "WeekdayCalendar": []
                          },
                          "step": 2,
                          "slip_forward": true
                        }
                      }
                    }
                  }
                ]
              ]
            }
          },
          "settlement": {
            "BusinessDays": {
              "calendar": {
                "WeekdayCalendar": []
              },
              "step": 2,
              "slip_forward": true
            }
          },
          "expiry": {
            "date": "2018-12-01",
            "time_of_day": "Close"
          },
          "put_or_call": "Call",
          "cash_or_physical": "Cash",
          "expiry_time": {
            "date": "2018-12-01",
            "day_fraction": 0.8
          },
          "pay_date": "2018-12-05",
          "strike_fraction": 0.85,
          "strike_date": {
            "date": "2018-06-08",
            "time_of_day": "Close"
          },
          "strike_time": {
            "date": "2018-06-08",
            "day_fraction": 0.8
          }
        }
      }
    ]
  ]
}"###);
    }

    #[test]
    fn basket_tagged_serde_dedup_write_once() {
        basket_tagged_serde_dedup(DedupControl::WriteOnce, HashMap::new(), HashMap::new(), r###"{
  "id": "OptionBasket",
  "credit_id": "OPT",
  "currency": {
    "id": "GBP",
    "settlement": {
      "BusinessDays": {
        "calendar": {
          "WeekdayCalendar": []
        },
        "step": 2,
        "slip_forward": true
      }
    }
  },
  "settlement": {
    "BusinessDays": {
      "calendar": {
        "WeekdayCalendar": []
      },
      "step": 2,
      "slip_forward": true
    }
  },
  "basket": [
    [
      0.4,
      {
        "ForwardStartingEuropean": {
          "id": "Option1",
          "credit_id": "OPT",
          "underlying": {
            "Basket": {
              "id": "basket",
              "credit_id": "LSE",
              "currency": "GBP",
              "settlement": {
                "BusinessDays": {
                  "calendar": {
                    "WeekdayCalendar": []
                  },
                  "step": 2,
                  "slip_forward": true
                }
              },
              "basket": [
                [
                  0.4,
                  {
                    "Equity": {
                      "id": "AZ.L",
                      "credit_id": "LSE",
                      "currency": "GBP",
                      "settlement": {
                        "BusinessDays": {
                          "calendar": {
                            "WeekdayCalendar": []
                          },
                          "step": 2,
                          "slip_forward": true
                        }
                      }
                    }
                  }
                ],
                [
                  0.6,
                  {
                    "Equity": {
                      "id": "BP.L",
                      "credit_id": "LSE",
                      "currency": "GBP",
                      "settlement": {
                        "BusinessDays": {
                          "calendar": {
                            "WeekdayCalendar": []
                          },
                          "step": 2,
                          "slip_forward": true
                        }
                      }
                    }
                  }
                ]
              ]
            }
          },
          "settlement": {
            "BusinessDays": {
              "calendar": {
                "WeekdayCalendar": []
              },
              "step": 2,
              "slip_forward": true
            }
          },
          "expiry": {
            "date": "2018-12-01",
            "time_of_day": "Close"
          },
          "put_or_call": "Call",
          "cash_or_physical": "Cash",
          "expiry_time": {
            "date": "2018-12-01",
            "day_fraction": 0.8
          },
          "pay_date": "2018-12-05",
          "strike_fraction": 1.15,
          "strike_date": {
            "date": "2018-06-08",
            "time_of_day": "Close"
          },
          "strike_time": {
            "date": "2018-06-08",
            "day_fraction": 0.8
          }
        }
      }
    ],
    [
      0.6,
      {
        "ForwardStartingEuropean": {
          "id": "Option2",
          "credit_id": "OPT",
          "underlying": "basket",
          "settlement": {
            "BusinessDays": {
              "calendar": {
                "WeekdayCalendar": []
              },
              "step": 2,
              "slip_forward": true
            }
          },
          "expiry": {
            "date": "2018-12-01",
            "time_of_day": "Close"
          },
          "put_or_call": "Call",
          "cash_or_physical": "Cash",
          "expiry_time": {
            "date": "2018-12-01",
            "day_fraction": 0.8
          },
          "pay_date": "2018-12-05",
          "strike_fraction": 0.85,
          "strike_date": {
            "date": "2018-06-08",
            "time_of_day": "Close"
          },
          "strike_time": {
            "date": "2018-06-08",
            "day_fraction": 0.8
          }
        }
      }
    ]
  ]
}"###);
    }

    #[test]
    fn basket_tagged_serde_dedup_error_if_missing() {
        let currency = RcCurrency::new(Arc::new(sample_currency(2)));
        let mut currencies = HashMap::new();
        currencies.insert("GBP".to_string(), currency);

        let european1 = RcInstrument::new(Qrc::new(Arc::new(
            sample_forward_starting_european(1.15, "Option1"))));
        let european2 = RcInstrument::new(Qrc::new(Arc::new(
            sample_forward_starting_european(0.85, "Option2"))));
        let mut instruments = HashMap::new();
        instruments.insert("Option1".to_string(), european1);
        instruments.insert("Option2".to_string(), european2);

        basket_tagged_serde_dedup(DedupControl::ErrorIfMissing, currencies, instruments, r###"{
  "id": "OptionBasket",
  "credit_id": "OPT",
  "currency": "GBP",
  "settlement": {
    "BusinessDays": {
      "calendar": {
        "WeekdayCalendar": []
      },
      "step": 2,
      "slip_forward": true
    }
  },
  "basket": [
    [
      0.4,
      "Option1"
    ],
    [
      0.6,
      "Option2"
    ]
  ]
}"###);
    }

    fn basket_tagged_serde_dedup(control: DedupControl, 
        currencies: HashMap<String, RcCurrency>, 
        instruments: HashMap<String, RcInstrument>,
        expected: &str) {

        // tests serialization and deserialization of a basket containing two european options
        // on a basket of equity underliers. It therefore tests the tagged serialization of the option
        // and the deduplication of the shared components.

        let spot = 100.0;
        let european1 = RcInstrument::new(Qrc::new(Arc::new(
            sample_forward_starting_european(1.15, "Option1"))));
        let european2 = RcInstrument::new(Qrc::new(Arc::new(
            sample_forward_starting_european(0.85, "Option2"))));
        let basket = vec![(0.4f64, european1.clone()), (0.6f64, european2.clone())];
        let currency = RcCurrency::new(Arc::new(sample_currency(2)));

        let option_basket = Basket::new(
            "OptionBasket", european1.credit_id(), currency, 
            european1.settlement().clone(), basket).unwrap();

        // value it
        let val_date = DateTime::new(Date::from_ymd(2018, 06, 01), TimeOfDay::Open);
        let context = sample_pricing_context(spot);
        let price = option_basket.price(&context, val_date).unwrap();

        // write it out and read it back in
        let mut buffer = Vec::new();
        {
            let mut serializer = serde_json::Serializer::pretty(&mut buffer);
            let mut ccy_seed = Dedup::<Currency, Arc<Currency>>::new(control.clone(), currencies.clone());
            let mut opt_seed = Dedup::<Instrument, Qrc<Instrument>>::new(control.clone(), instruments.clone());
            ccy_seed.with(&DEDUP_CURRENCY, 
                || opt_seed.with(&DEDUP_INSTRUMENT,
                || option_basket.serialize(&mut serializer))).unwrap();
        }

        let serialized = String::from_utf8(buffer.clone()).unwrap();
        print!("{}", serialized);
        assert_eq!(serialized, expected);

        let deserialized = {
            let mut deserializer = serde_json::Deserializer::from_slice(&buffer);
            let mut ccy_seed = Dedup::<Currency, Arc<Currency>>::new(control.clone(), currencies.clone());
            let mut opt_seed = Dedup::<Instrument, Qrc<Instrument>>::new(control.clone(), instruments.clone());
            ccy_seed.with(&DEDUP_CURRENCY, 
                || opt_seed.with(&DEDUP_INSTRUMENT,
                || Basket::deserialize(&mut deserializer))).unwrap()
        };

        // check the price still matches
        let serde_price = deserialized.price(&context, val_date).unwrap();
    
        assert_approx(serde_price, price, 1e-12);
    }

    fn assert_approx(value: f64, expected: f64, tolerance: f64) {
        assert!(approx_eq(value, expected, tolerance),
            "value={} expected={}", value, expected);
    }
}