@continuumdao/quantlib 0.0.0-stage → 0.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/LICENSE ADDED
@@ -0,0 +1,242 @@
1
+
2
+ Copyright (C) 2000, 2001, 2002, 2003 RiskMap srl
3
+
4
+ Copyright (C) 2001, 2002, 2003 Nicolas Di Césaré
5
+ Copyright (C) 2001, 2002, 2003 Sadruddin Rejeb
6
+
7
+ Copyright (C) 2002, 2003, 2004 Decillion Pty(Ltd)
8
+ Copyright (C) 2002, 2003, 2004, 2005, 2006, 2007, 2008, 2009, 2010, 2011, 2012, 2014, 2015 Ferdinando Ametrano
9
+
10
+ Copyright (C) 2003 Kawanishi Tomoya
11
+ Copyright (C) 2003 Niels Elken Sønderby
12
+ Copyright (C) 2003, 2004 Roman Gitlin
13
+ Copyright (C) 2003, 2004, 2005, 2006, 2007, 2008, 2009, 2010, 2011, 2012, 2014, 2015, 2016, 2017, 2018, 2019, 2020, 2021 StatPro Italia srl
14
+ Copyright (C) 2003, 2004, 2007 Neil Firth
15
+
16
+ Copyright (C) 2004 FIMAT Group
17
+ Copyright (C) 2004 Gianni Piolanti
18
+ Copyright (C) 2004 Jeff Yu
19
+ Copyright (C) 2004 M-Dimension Consulting Inc.
20
+ Copyright (C) 2004 Mike Parker
21
+ Copyright (C) 2004 Walter Penschke
22
+ Copyright (C) 2004, 2005, 2006, 2007, 2008, 2009, 2010, 2011, 2012, 2013, 2014, 2015, 2016, 2017, 2018, 2019, 2020, 2021, 2022, 2023, 2024, 2025, 2026 Klaus Spanderen
23
+
24
+ Copyright (C) 2005 Charles Whitmore
25
+ Copyright (C) 2005 Sercan Atalik
26
+ Copyright (C) 2005, 2006 Theo Boafo
27
+ Copyright (C) 2005, 2006, 2007 Joseph Wang
28
+ Copyright (C) 2005, 2006, 2007, 2009 Piter Dias
29
+ Copyright (C) 2005, 2006, 2008 Toyin Akin
30
+ Copyright (C) 2005, 2013 Gary Kennedy
31
+
32
+ Copyright (C) 2006 Richard Gould
33
+ Copyright (C) 2006 Silvia Frasson
34
+ Copyright (C) 2006 Warren Chou
35
+ Copyright (C) 2006 Yiping Chen
36
+ Copyright (C) 2006, 2007 Banca Profilo S.p.A.
37
+ Copyright (C) 2006, 2007 Chiara Fornarola
38
+ Copyright (C) 2006, 2007 Cristina Duminuco
39
+ Copyright (C) 2006, 2007 François du Vignaud
40
+ Copyright (C) 2006, 2007 Giorgio Facchinetti
41
+ Copyright (C) 2006, 2007 Katiuscia Manzoni
42
+ Copyright (C) 2006, 2007 Marco Bianchetti
43
+ Copyright (C) 2006, 2007 Mario Pucci
44
+ Copyright (C) 2006, 2007, 2008 Allen Kuo
45
+ Copyright (C) 2006, 2007, 2008, 2009, 2010 Mark Joshi
46
+ Copyright (C) 2006, 2007, 2008, 2009, 2012 Roland Lichters
47
+
48
+ Copyright (C) 2007 Affine Group Limited
49
+ Copyright (C) 2007 Gang Liang
50
+ Copyright (C) 2007 Richard Gomes
51
+ Copyright (C) 2007, 2008 Laurent Hoffmann
52
+ Copyright (C) 2007, 2008, 2009, 2010, 2011 Chris Kenyon
53
+
54
+ Copyright (C) 2008 Florent Grenier
55
+ Copyright (C) 2008 Francesca Mariani
56
+ Copyright (C) 2008 Francesco Zirilli
57
+ Copyright (C) 2008 Frank Hövermann
58
+ Copyright (C) 2008 J. Erik Radmall
59
+ Copyright (C) 2008 John Maiden
60
+ Copyright (C) 2008 Lorella Fatone
61
+ Copyright (C) 2008 Marek Glowacki
62
+ Copyright (C) 2008 Maria Cristina Recchioni
63
+ Copyright (C) 2008 Paul Farrington
64
+ Copyright (C) 2008 Piero Del Boca
65
+ Copyright (C) 2008 Roland Stamm
66
+ Copyright (C) 2008 Simon Ibbotson
67
+ Copyright (C) 2008 Yee Man Chan
68
+ Copyright (C) 2008, 2009 Andrea Odetti
69
+ Copyright (C) 2008, 2009 Andreas Gaida
70
+ Copyright (C) 2008, 2009, 2010, 2011, 2012, 2014 Master IMAFA - Polytech'Nice Sophia - Université de Nice Sophia Antipolis
71
+ Copyright (C) 2008, 2009, 2012, 2014 Ralph Schreyer
72
+ Copyright (C) 2008, 2009, 2014, 2015, 2016 Jose Aparicio
73
+ Copyright (C) 2008, 2011 Charles Chongseok Hyun
74
+
75
+ Copyright (C) 2009 Bernd Engelmann
76
+ Copyright (C) 2009 Bojan Nikolic
77
+ Copyright (C) 2009 Frédéric Degraeve
78
+ Copyright (C) 2009 Nathan Abbott
79
+ Copyright (C) 2009 Sun Xiuxin
80
+ Copyright (C) 2009 Sylvain Bertrand
81
+ Copyright (C) 2009, 2010 Dimitri Reiswich
82
+ Copyright (C) 2009, 2010, 2012 Liquidnet Holdings, Inc.
83
+ Copyright (C) 2009, 2024 Dirk Eddelbuettel
84
+
85
+ Copyright (C) 2010 Adrian O' Neill
86
+ Copyright (C) 2010 Alessandro Roveda
87
+ Copyright (C) 2010 DeriveXperts SAS
88
+ Copyright (C) 2010 Hachemi Benyahia
89
+ Copyright (C) 2010 Kakhkhor Abdijalilov
90
+ Copyright (C) 2010 Manas Bhatt
91
+ Copyright (C) 2010 Michael Heckl
92
+ Copyright (C) 2010 Robert Philipp
93
+ Copyright (C) 2010 Slava Mazur
94
+ Copyright (C) 2010 SunTrust Bank
95
+ Copyright (C) 2010, 2011, 2012, 2013, 2023 Andre Miemiec
96
+ Copyright (C) 2010, 2014 Cavit Hafizoglu
97
+
98
+ Copyright (C) 2011, 2013, 2014 Fabien Le Floc'h
99
+
100
+ Copyright (C) 2012 Mateusz Kapturski
101
+ Copyright (C) 2012 Samuel Tebege
102
+ Copyright (C) 2012 Simon Shakeshaft
103
+ Copyright (C) 2012 Édouard Tallent
104
+ Copyright (C) 2012, 2013 Grzegorz Andruszkiewicz
105
+ Copyright (C) 2012, 2013, 2014, 2015, 2016, 2017, 2018, 2023, 2024, 2025 Peter Caspers
106
+
107
+ Copyright (C) 2013 BGC Partners L.P.
108
+ Copyright (C) 2013 Chris Higgs
109
+ Copyright (C) 2013 Yue Tian
110
+ Copyright (C) 2013, 2014, 2015 Cheng Li
111
+
112
+ Copyright (C) 2014 Michal Kaut
113
+ Copyright (C) 2014, 2015 Bernd Lewerenz
114
+ Copyright (C) 2014, 2015 Johannes Göttker-Schnetmann
115
+ Copyright (C) 2014, 2015 Thema Consulting SA
116
+ Copyright (C) 2014, 2015, 2016 Michael von den Driesch
117
+ Copyright (C) 2014, 2015, 2016 Paolo Mazzocchi
118
+ Copyright (C) 2014, 2017, 2024 Francois Botha
119
+
120
+ Copyright (C) 2015 CompatibL
121
+ Copyright (C) 2015 Dmitri Nesteruk
122
+ Copyright (C) 2015 Maddalena Zanzi
123
+ Copyright (C) 2015 Riccardo Barone
124
+ Copyright (C) 2015, 2016 Andres Hernandez
125
+
126
+ Copyright (C) 2016 Nicholas Bertocchi
127
+ Copyright (C) 2016 Stefano Fondi
128
+ Copyright (C) 2016, 2017 Fabrice Lecuyer
129
+ Copyright (C) 2016, 2018, 2019, 2020, 2022 Quaternion Risk Management Ltd
130
+ Copyright (C) 2016, 2019, 2020 Eisuke Tani
131
+
132
+ Copyright (C) 2017 BN Algorithms Ltd
133
+ Copyright (C) 2017 Joseph Jeisman
134
+ Copyright (C) 2017 Paul Giltinan
135
+ Copyright (C) 2017 Werner Kuerzinger
136
+ Copyright (C) 2017, 2022 Oleg Kulkov
137
+
138
+ Copyright (C) 2018 Alexey Indiryakov
139
+ Copyright (C) 2018 Jose Garcia
140
+ Copyright (C) 2018 Matthias Groncki
141
+ Copyright (C) 2018 Matthias Lungwitz
142
+ Copyright (C) 2018 Roy Zywina
143
+ Copyright (C) 2018 Sebastian Schlenkrich
144
+ Copyright (C) 2018 Tom Anderson
145
+
146
+ Copyright (C) 2019 Aprexo Limited
147
+ Copyright (C) 2019 SoftSolutions! S.r.l.
148
+ Copyright (C) 2019 Wojciech Ślusarski
149
+
150
+ Copyright (C) 2020 Kline s.r.l.
151
+ Copyright (C) 2020 Leonardo Arcari
152
+ Copyright (C) 2020 Piotr Siejda
153
+ Copyright (C) 2020, 2021 Jack Gillett
154
+ Copyright (C) 2020, 2021 Lew Wei Hao
155
+ Copyright (C) 2020, 2021, 2022, 2023, 2024 Skandinaviska Enskilda Banken AB (publ)
156
+ Copyright (C) 2020, 2021, 2022, 2023, 2025 Marcin Rybacki
157
+
158
+ Copyright (C) 2021 Anubhav Pandey
159
+ Copyright (C) 2021 Magnus Mencke
160
+ Copyright (C) 2021, 2022, 2023, 2024 Ralf Konrad Eckel
161
+
162
+ Copyright (C) 2022, 2023 Ignacio Anguita
163
+ Copyright (C) 2022, 2023 Jonghee Lee
164
+
165
+ Copyright (C) 2023 Aditya Narayan Das
166
+ Copyright (C) 2023 Andrea Pellegatta
167
+ Copyright (C) 2023 Jonathan Sweemer
168
+ Copyright (C) 2023 Nathaniel Brough
169
+ Copyright (C) 2023 Paul Xi Cao
170
+
171
+ Copyright (C) 2024 Jacques du Toit
172
+ Copyright (C) 2024 Jongbong An
173
+
174
+ Copyright (C) 2025 AcadiaSoft Inc.
175
+ Copyright (C) 2025 Hiroto Ogawa
176
+ Copyright (C) 2025 Kareem Fareed
177
+ Copyright (C) 2025 Shubham Gaur
178
+ Copyright (C) 2025 Sotirios Papathanasopoulos
179
+ Copyright (C) 2025 Uzair Beg
180
+ Copyright (C) 2025 William Day
181
+ Copyright (C) 2025, 2026 Eugene Toder
182
+ Copyright (C) 2025, 2026 Paolo D'Elia
183
+
184
+ Copyright (C) 2026 Aaditya Panikath
185
+ Copyright (C) 2026 Abhay Chaudhary
186
+ Copyright (C) 2026 Ada Logics Ltd
187
+ Copyright (C) 2026 Chirag Desai
188
+ Copyright (C) 2026 Colin Alberts
189
+ Copyright (C) 2026 David Korczynski
190
+ Copyright (C) 2026 Jogi Sidhu
191
+ Copyright (C) 2026 Junjie Guo
192
+ Copyright (C) 2026 Kyrylo Protsenko
193
+ Copyright (C) 2026 LW Osterbrink
194
+ Copyright (C) 2026 Lawrenz Law
195
+ Copyright (C) 2026 Mahimn Patel
196
+ Copyright (C) 2026 Pratyush Patel
197
+ Copyright (C) 2026 Richard Amaya
198
+ Copyright (C) 2026 Sergio Araujo
199
+ Copyright (C) 2026 SoftSolution srl
200
+ Copyright (C) 2026 Stephen Dacek
201
+ Copyright (C) 2026 Thiago Rodrigues
202
+ Copyright (C) 2026 Yang Ye
203
+ Copyright (C) 2026 Yassine Idyiahia
204
+ Copyright (C) 2026 Zain Mughal
205
+
206
+ QuantLib includes code taken from Peter Jäckel's book "Monte Carlo
207
+ Methods in Finance".
208
+
209
+ QuantLib includes software developed by the University of Chicago,
210
+ as Operator of Argonne National Laboratory.
211
+
212
+ QuantLib includes a set of numbers provided by Stephen Joe and Frances
213
+ Kuo under a BSD-style license.
214
+
215
+
216
+ Redistribution and use in source and binary forms, with or without
217
+ modification, are permitted provided that the following conditions are met:
218
+
219
+ Redistributions of source code must retain the above copyright notice,
220
+ this list of conditions and the following disclaimer.
221
+
222
+ Redistributions in binary form must reproduce the above copyright notice,
223
+ this list of conditions and the following disclaimer in the documentation
224
+ and/or other materials provided with the distribution.
225
+
226
+ Neither the names of the copyright holders nor the names of the QuantLib
227
+ Group and its contributors may be used to endorse or promote products
228
+ derived from this software without specific prior written permission.
229
+
230
+ THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND
231
+ CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES,
232
+ INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
233
+ MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
234
+ DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDERS OR
235
+ CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
236
+ SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
237
+ LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF
238
+ USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED
239
+ AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
240
+ LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
241
+ ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
242
+ POSSIBILITY OF SUCH DAMAGE.
@@ -0,0 +1,136 @@
1
+ /*
2
+ * Barone-Adesi and Whaley American approximation (1987).
3
+ * QuantLib: ql/pricingengines/vanilla/baroneadesiwhaleyengine.cpp
4
+ */
5
+
6
+ import { normalCdf, normalPdf } from './normal.js'
7
+ import { black76 } from './black.js'
8
+
9
+ function typeSign(type) {
10
+ const name = String(type ?? '').toLowerCase()
11
+ if (name === 'call' || name === 'c') return 1
12
+ if (name === 'put' || name === 'p') return -1
13
+ throw new Error('type must be call or put.')
14
+ }
15
+
16
+ function blackUndiscounted(sign, strike, forward, stdDev) {
17
+ return black76({
18
+ type: sign > 0 ? 'call' : 'put',
19
+ strike,
20
+ forward,
21
+ vol: stdDev,
22
+ time: 1,
23
+ rate: 0,
24
+ }).price
25
+ }
26
+
27
+ function criticalPrice(sign, strike, riskFreeDiscount, dividendDiscount, variance) {
28
+ const n = 2 * Math.log(dividendDiscount / riskFreeDiscount) / variance
29
+ const m = -2 * Math.log(riskFreeDiscount) / variance
30
+ const bT = Math.log(dividendDiscount / riskFreeDiscount)
31
+ const root = Math.sqrt((n - 1) * (n - 1) + 4 * m)
32
+ let qu
33
+ let su
34
+ let si
35
+ if (sign > 0) {
36
+ qu = (-(n - 1) + root) / 2
37
+ su = strike / (1 - 1 / qu)
38
+ const h = -(bT + 2 * Math.sqrt(variance)) * strike / (su - strike)
39
+ si = strike + (su - strike) * (1 - Math.exp(h))
40
+ if (!(si > strike) || !Number.isFinite(si)) si = su
41
+ } else {
42
+ qu = (-(n - 1) - root) / 2
43
+ su = strike / (1 - 1 / qu)
44
+ const h = (bT - 2 * Math.sqrt(variance)) * strike / (strike - su)
45
+ si = su + (strike - su) * Math.exp(h)
46
+ if (!(si > 0 && si < strike) || !Number.isFinite(si)) si = su
47
+ }
48
+
49
+ const kFactor = Math.abs(riskFreeDiscount - 1) > 1e-12
50
+ ? -2 * Math.log(riskFreeDiscount) / (variance * (1 - riskFreeDiscount))
51
+ : 2 / variance
52
+ const qRoot = Math.sqrt((n - 1) * (n - 1) + 4 * kFactor)
53
+ const q = sign > 0 ? (-(n - 1) + qRoot) / 2 : (-(n - 1) - qRoot) / 2
54
+ const tolerance = 1e-6
55
+ for (let iter = 0; iter < 80; iter += 1) {
56
+ const forwardSi = si * dividendDiscount / riskFreeDiscount
57
+ const d1 = (Math.log(forwardSi / strike) + 0.5 * variance) / Math.sqrt(variance)
58
+ const temp = blackUndiscounted(sign, strike, forwardSi, Math.sqrt(variance)) * riskFreeDiscount
59
+ const nd = sign > 0 ? normalCdf(d1) : normalCdf(-d1)
60
+ const np = sign > 0 ? normalPdf(d1) : normalPdf(-d1)
61
+ let lhs
62
+ let rhs
63
+ let bi
64
+ if (sign > 0) {
65
+ lhs = si - strike
66
+ rhs = temp + (1 - dividendDiscount * nd) * si / q
67
+ bi = dividendDiscount * nd * (1 - 1 / q) + (1 - dividendDiscount * np / Math.sqrt(variance)) / q
68
+ } else {
69
+ lhs = strike - si
70
+ rhs = temp - (1 - dividendDiscount * nd) * si / q
71
+ bi = -dividendDiscount * nd * (1 - 1 / q) - (1 + dividendDiscount * np / Math.sqrt(variance)) / q
72
+ }
73
+ if (Math.abs(lhs - rhs) / strike <= tolerance) break
74
+ if (sign > 0) si = (strike + rhs - bi * si) / (1 - bi)
75
+ else si = (strike - rhs + bi * si) / (1 + bi)
76
+ if (!Number.isFinite(si) || si <= 0) {
77
+ si = su
78
+ break
79
+ }
80
+ }
81
+ return si
82
+ }
83
+
84
+ /** American price. When early exercise is never optimal this is the European price. */
85
+ export function baroneAdesiWhaley(input) {
86
+ const sign = typeSign(input.type)
87
+ const strike = Number(input.strike)
88
+ const spot = Number(input.spot)
89
+ const vol = Number(input.vol)
90
+ const time = Number(input.time)
91
+ const rate = input.rate == null ? 0 : Number(input.rate)
92
+ const dividend = input.dividend == null ? 0 : Number(input.dividend)
93
+ if (!(strike > 0)) throw new Error('strike must be positive.')
94
+ if (!(spot > 0)) throw new Error('spot must be positive.')
95
+ if (!(vol >= 0)) throw new Error('vol must be non-negative.')
96
+ if (!(time >= 0)) throw new Error('time must be non-negative.')
97
+
98
+ const variance = vol * vol * time
99
+ const dividendDiscount = Math.exp(-dividend * time)
100
+ const riskFreeDiscount = Math.exp(-rate * time)
101
+ const forward = spot * dividendDiscount / riskFreeDiscount
102
+ const european = black76({
103
+ type: input.type,
104
+ strike,
105
+ forward,
106
+ vol,
107
+ time,
108
+ rate,
109
+ }).price
110
+
111
+ const callNever = dividendDiscount >= 1 && dividendDiscount >= riskFreeDiscount && sign > 0
112
+ const putNever = riskFreeDiscount >= 1 && riskFreeDiscount >= dividendDiscount && sign < 0
113
+ if (callNever || putNever || !(variance > 1e-14)) {
114
+ const intrinsic = Math.max(sign * (spot - strike), 0)
115
+ return { price: Math.max(european, variance > 1e-14 ? european : intrinsic) }
116
+ }
117
+
118
+ const sk = criticalPrice(sign, strike, riskFreeDiscount, dividendDiscount, variance)
119
+ const forwardSk = sk * dividendDiscount / riskFreeDiscount
120
+ const d1 = (Math.log(forwardSk / strike) + 0.5 * variance) / Math.sqrt(variance)
121
+ const n = 2 * Math.log(dividendDiscount / riskFreeDiscount) / variance
122
+ const kFactor = Math.abs(riskFreeDiscount - 1) > 1e-12
123
+ ? -2 * Math.log(riskFreeDiscount) / (variance * (1 - riskFreeDiscount))
124
+ : 2 / variance
125
+ const qRoot = Math.sqrt((n - 1) * (n - 1) + 4 * kFactor)
126
+ if (sign > 0) {
127
+ const q = (-(n - 1) + qRoot) / 2
128
+ const a = (sk / q) * (1 - dividendDiscount * normalCdf(d1))
129
+ const price = spot < sk ? european + a * (spot / sk) ** q : spot - strike
130
+ return { price }
131
+ }
132
+ const q = (-(n - 1) - qRoot) / 2
133
+ const a = -(sk / q) * (1 - dividendDiscount * normalCdf(-d1))
134
+ const price = spot > sk ? european + a * (spot / sk) ** q : strike - spot
135
+ return { price }
136
+ }
package/binomial.js ADDED
@@ -0,0 +1,158 @@
1
+ /*
2
+ * European and American binomial trees.
3
+ * QuantLib: ql/methods/lattices/binomialtree.hpp, binomialtree.cpp,
4
+ * ql/pricingengines/vanilla/binomialengine.hpp,
5
+ * ql/math/distributions/binomialdistribution.hpp (Peizer-Pratt).
6
+ */
7
+
8
+ function typeSign(type) {
9
+ const name = String(type ?? '').toLowerCase()
10
+ if (name === 'call' || name === 'c') return 1
11
+ if (name === 'put' || name === 'p') return -1
12
+ throw new Error('type must be call or put.')
13
+ }
14
+
15
+ function payoff(sign, spot, strike) {
16
+ return Math.max(sign * (spot - strike), 0)
17
+ }
18
+
19
+ function peizerPratt(z, n) {
20
+ if (n % 2 !== 1) throw new Error('Leisen-Reimer steps must be odd.')
21
+ const denom = n + 1 / 3 + 0.1 / (n + 1)
22
+ const result = Math.exp(-(z / denom) * (z / denom) * (n + 1 / 6))
23
+ const root = Math.sqrt(Math.max(0, 1 - result))
24
+ if (z > 0) return 0.5 * (1 + root)
25
+ return 0.5 * result / (1 + root)
26
+ }
27
+
28
+ function treeParams(kind, { spot, strike, vol, time, rate, dividend, steps }) {
29
+ const n0 = Math.max(2, Math.trunc(steps))
30
+ const n = kind === 'lr' ? (n0 % 2 === 1 ? n0 : n0 + 1) : n0
31
+ const dt = time / n
32
+ const drift = (rate - dividend - 0.5 * vol * vol) * dt
33
+ const dx = vol * Math.sqrt(dt)
34
+ if (kind === 'crr') {
35
+ if (!(dx > 0)) throw new Error('Cox-Ross-Rubinstein needs a positive volatility.')
36
+ const pu = 0.5 + 0.5 * drift / dx
37
+ if (pu < 0 || pu > 1) throw new Error('Cox-Ross-Rubinstein probability left [0, 1]. Use more steps.')
38
+ return {
39
+ n,
40
+ dt,
41
+ pu,
42
+ pd: 1 - pu,
43
+ spotAt(i, j) {
44
+ return spot * Math.exp((2 * j - i) * dx)
45
+ },
46
+ }
47
+ }
48
+ if (kind === 'jr') {
49
+ return {
50
+ n,
51
+ dt,
52
+ pu: 0.5,
53
+ pd: 0.5,
54
+ spotAt(i, j) {
55
+ return spot * Math.exp(i * drift + (2 * j - i) * dx)
56
+ },
57
+ }
58
+ }
59
+ if (kind === 'lr') {
60
+ const variance = vol * vol * time
61
+ const width = Math.sqrt(variance)
62
+ const ermqdt = Math.exp(drift + 0.5 * variance / n)
63
+ const d2 = (Math.log(spot / strike) + drift * n) / width
64
+ const pu = peizerPratt(d2, n)
65
+ const pdash = peizerPratt(d2 + width, n)
66
+ if (!(pu > 0 && pu < 1)) throw new Error('Leisen-Reimer probability left (0, 1).')
67
+ const up = ermqdt * pdash / pu
68
+ const down = (ermqdt - pu * up) / (1 - pu)
69
+ if (!(up > 0) || !(down > 0)) throw new Error('Leisen-Reimer factors must be positive.')
70
+ return {
71
+ n,
72
+ dt,
73
+ pu,
74
+ pd: 1 - pu,
75
+ spotAt(i, j) {
76
+ return spot * down ** (i - j) * up ** j
77
+ },
78
+ }
79
+ }
80
+ throw new Error('tree must be crr, jr, or lr.')
81
+ }
82
+
83
+ function greeksFromNodes(layers, value, deltaSpot, gammaSpot, rate, dividend, vol, time) {
84
+ const theta = time > 0
85
+ ? -(
86
+ (-rate * time) * value
87
+ + (rate - dividend) * time * deltaSpot * layers.spot
88
+ + 0.5 * vol * vol * time * layers.spot * layers.spot * gammaSpot
89
+ ) / time
90
+ : 0
91
+ return { price: value, delta: deltaSpot, gamma: gammaSpot, theta }
92
+ }
93
+
94
+ /**
95
+ * Binomial price. exercise is european or american.
96
+ * tree is crr, jr, or lr. steps is at least 2. Leisen-Reimer uses the next odd count.
97
+ */
98
+ export function binomial(input) {
99
+ const sign = typeSign(input.type)
100
+ const strike = Number(input.strike)
101
+ const spot = Number(input.spot)
102
+ const vol = Number(input.vol)
103
+ const time = Number(input.time)
104
+ const rate = input.rate == null ? 0 : Number(input.rate)
105
+ const dividend = input.dividend == null ? 0 : Number(input.dividend)
106
+ const exercise = String(input.exercise ?? 'european').toLowerCase()
107
+ const tree = String(input.tree ?? 'crr').toLowerCase()
108
+ const steps = input.steps == null ? 128 : Number(input.steps)
109
+ if (!(strike > 0)) throw new Error('strike must be positive.')
110
+ if (!(spot > 0)) throw new Error('spot must be positive.')
111
+ if (!(vol >= 0)) throw new Error('vol must be non-negative.')
112
+ if (!(time > 0)) throw new Error('time must be positive.')
113
+ if (!Number.isInteger(steps) || steps < 2) throw new Error('steps must be an integer of at least 2.')
114
+ if (exercise !== 'european' && exercise !== 'american') throw new Error('exercise must be european or american.')
115
+
116
+ const params = treeParams(tree, { spot, strike, vol, time, rate, dividend, steps })
117
+ const df = Math.exp(-rate * params.dt)
118
+ const american = exercise === 'american'
119
+ let values = new Array(params.n + 1)
120
+ for (let j = 0; j <= params.n; j += 1) {
121
+ values[j] = payoff(sign, params.spotAt(params.n, j), strike)
122
+ }
123
+ let step1 = null
124
+ let step2 = null
125
+ for (let i = params.n - 1; i >= 0; i -= 1) {
126
+ const next = values
127
+ values = new Array(i + 1)
128
+ for (let j = 0; j <= i; j += 1) {
129
+ let held = df * (params.pd * next[j] + params.pu * next[j + 1])
130
+ if (american) {
131
+ const exerciseValue = payoff(sign, params.spotAt(i, j), strike)
132
+ if (exerciseValue > held) held = exerciseValue
133
+ }
134
+ values[j] = held
135
+ }
136
+ if (i === 2) step2 = values.slice()
137
+ if (i === 1) step1 = values.slice()
138
+ }
139
+ const price = values[0]
140
+ const s1u = params.spotAt(1, 1)
141
+ const s1d = params.spotAt(1, 0)
142
+ const delta = s1u > s1d ? (step1[1] - step1[0]) / (s1u - s1d) : null
143
+ let gamma = null
144
+ if (step2) {
145
+ const s2u = params.spotAt(2, 2)
146
+ const s2m = params.spotAt(2, 1)
147
+ const s2d = params.spotAt(2, 0)
148
+ if (s2u > s2m && s2m > s2d) {
149
+ const deltaUp = (step2[2] - step2[1]) / (s2u - s2m)
150
+ const deltaDown = (step2[1] - step2[0]) / (s2m - s2d)
151
+ gamma = (deltaUp - deltaDown) / ((s2u - s2d) / 2)
152
+ }
153
+ }
154
+ const theta = delta == null || gamma == null
155
+ ? null
156
+ : greeksFromNodes({ spot }, price, delta, gamma, rate, dividend, vol, time).theta
157
+ return { price, delta, gamma, theta, steps: params.n, tree, exercise }
158
+ }
package/black.js ADDED
@@ -0,0 +1,109 @@
1
+ /*
2
+ * Black-76 and Black-Scholes-Merton prices and Greeks.
3
+ * QuantLib: ql/pricingengines/blackformula.cpp and ql/pricingengines/blackcalculator.cpp
4
+ */
5
+
6
+ import { normalCdf, normalPdf } from './normal.js'
7
+
8
+ export const YEAR_SECONDS = 365.25 * 24 * 60 * 60
9
+
10
+ export function yearFraction(fromSec, toSec) {
11
+ return (Number(toSec) - Number(fromSec)) / YEAR_SECONDS
12
+ }
13
+
14
+ function typeSign(type) {
15
+ const name = String(type ?? '').toLowerCase()
16
+ if (name === 'call' || name === 'c') return 1
17
+ if (name === 'put' || name === 'p') return -1
18
+ throw new Error('type must be call or put.')
19
+ }
20
+
21
+ function finite(name, value) {
22
+ const n = Number(value)
23
+ if (!Number.isFinite(n)) throw new Error(`${name} must be a finite number.`)
24
+ return n
25
+ }
26
+
27
+ /**
28
+ * Black-76 on a forward. Greeks are with respect to the forward.
29
+ * delta is dPrice/dForward. vega is dPrice/dVol. theta and rho are per year.
30
+ */
31
+ export function black76(input) {
32
+ const sign = typeSign(input.type)
33
+ const strike = finite('strike', input.strike)
34
+ const forward = finite('forward', input.forward)
35
+ const vol = finite('vol', input.vol)
36
+ const time = finite('time', input.time)
37
+ const rate = input.rate == null ? 0 : finite('rate', input.rate)
38
+ if (strike < 0) throw new Error('strike must be non-negative.')
39
+ if (!(forward > 0)) throw new Error('forward must be positive.')
40
+ if (vol < 0) throw new Error('vol must be non-negative.')
41
+ if (time < 0) throw new Error('time must be non-negative.')
42
+
43
+ const discount = Math.exp(-rate * time)
44
+ if (!(time > 0) || vol === 0) {
45
+ const intrinsic = Math.max(sign * (forward - strike), 0) * discount
46
+ const itm = sign * (forward - strike) > 0
47
+ const atm = forward === strike
48
+ let delta = 0
49
+ if (atm) delta = sign * 0.5 * discount
50
+ else if (itm) delta = sign * discount
51
+ return { price: intrinsic, delta, gamma: 0, vega: 0, theta: 0, rho: rate === 0 ? 0 : -time * intrinsic }
52
+ }
53
+
54
+ const stdDev = vol * Math.sqrt(time)
55
+ const d1 = Math.log(forward / strike) / stdDev + 0.5 * stdDev
56
+ const d2 = d1 - stdDev
57
+ const nd1 = normalCdf(sign * d1)
58
+ const nd2 = normalCdf(sign * d2)
59
+ const price = discount * sign * (forward * nd1 - strike * nd2)
60
+ const pdf = normalPdf(d1)
61
+ const delta = discount * sign * normalCdf(sign * d1)
62
+ const gamma = discount * pdf / (forward * stdDev)
63
+ const vega = discount * forward * pdf * Math.sqrt(time)
64
+ const theta = -(Math.log(discount) * price + 0.5 * vol * vol * time * forward * forward * gamma) / time
65
+ const rho = -time * price
66
+ return { price, delta, gamma, vega, theta, rho }
67
+ }
68
+
69
+ /**
70
+ * Spot Black-Scholes-Merton. dividend is the continuous yield q.
71
+ * delta and gamma are with respect to spot.
72
+ */
73
+ export function blackScholesMerton(input) {
74
+ const sign = typeSign(input.type)
75
+ const strike = finite('strike', input.strike)
76
+ const spot = finite('spot', input.spot)
77
+ const vol = finite('vol', input.vol)
78
+ const time = finite('time', input.time)
79
+ const rate = input.rate == null ? 0 : finite('rate', input.rate)
80
+ const dividend = input.dividend == null ? 0 : finite('dividend', input.dividend)
81
+ if (!(spot > 0)) throw new Error('spot must be positive.')
82
+ const forward = spot * Math.exp((rate - dividend) * time)
83
+ const black = black76({ type: input.type, strike, forward, vol, time, rate })
84
+ if (!(time > 0) || vol === 0) {
85
+ const delta = black.delta * (forward / spot)
86
+ return { ...black, delta, gamma: 0, vega: 0 }
87
+ }
88
+ const stdDev = vol * Math.sqrt(time)
89
+ const d1 = Math.log(forward / strike) / stdDev + 0.5 * stdDev
90
+ const d2 = d1 - stdDev
91
+ const dfq = Math.exp(-dividend * time)
92
+ const delta = dfq * sign * normalCdf(sign * d1)
93
+ const gamma = dfq * normalPdf(d1) / (spot * stdDev)
94
+ const vega = spot * dfq * normalPdf(d1) * Math.sqrt(time)
95
+ const discount = Math.exp(-rate * time)
96
+ const theta = -(
97
+ Math.log(discount) * black.price
98
+ + Math.log(forward / spot) * spot * delta
99
+ + 0.5 * vol * vol * time * spot * spot * gamma
100
+ ) / time
101
+ const rho = sign * strike * time * discount * normalCdf(sign * d2)
102
+ return { price: black.price, delta, gamma, vega, theta, rho }
103
+ }
104
+
105
+ /** q such that spot * exp((rate - q) * time) equals forward. */
106
+ export function dividendForForward(spot, forward, time, rate = 0) {
107
+ if (!(time > 0) || !(spot > 0) || !(forward > 0)) return 0
108
+ return rate - Math.log(forward / spot) / time
109
+ }