@continuumdao/quantlib 0.0.0-stage → 0.2.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 +242 -0
- package/baroneAdesiWhaley.js +136 -0
- package/binomial.js +158 -0
- package/black.js +174 -0
- package/decide.js +379 -0
- package/derive.js +243 -0
- package/heston.js +330 -0
- package/index.js +31 -0
- package/jsonlStore.js +42 -0
- package/normal.js +19 -0
- package/optionsDb.js +69 -0
- package/package.json +26 -4
- package/replay.js +91 -0
- package/rysk.js +61 -0
- package/smile.js +169 -0
- package/spreads.js +90 -0
- package/store.js +94 -0
- package/svi.js +344 -0
- package/README.md +0 -3
package/svi.js
ADDED
|
@@ -0,0 +1,344 @@
|
|
|
1
|
+
/*
|
|
2
|
+
* Raw SVI smile for one expiry.
|
|
3
|
+
* QuantLib: ql/experimental/volatility/sviinterpolation.hpp
|
|
4
|
+
* and ql/experimental/volatility/svismilesection.cpp.
|
|
5
|
+
* Total variance is a + b * (rho * (k - m) + sqrt((k - m)^2 + sigma^2)),
|
|
6
|
+
* with k = log(strike / forward). A slice with fewer than six strikes is refused.
|
|
7
|
+
*/
|
|
8
|
+
|
|
9
|
+
import { yearFraction } from './black.js'
|
|
10
|
+
import { normalPdf } from './normal.js'
|
|
11
|
+
|
|
12
|
+
const EPS1 = 1e-6
|
|
13
|
+
const EPS2 = 0.999999
|
|
14
|
+
const MIN_STRIKES = 6
|
|
15
|
+
|
|
16
|
+
function finite(value) {
|
|
17
|
+
const n = Number(value)
|
|
18
|
+
return Number.isFinite(n) ? n : null
|
|
19
|
+
}
|
|
20
|
+
|
|
21
|
+
/** QuantLib detail::checkSviParameters. The time argument is unused there. */
|
|
22
|
+
export function sviParametersHold(params) {
|
|
23
|
+
const a = finite(params?.a)
|
|
24
|
+
const b = finite(params?.b)
|
|
25
|
+
const sigma = finite(params?.sigma)
|
|
26
|
+
const rho = finite(params?.rho)
|
|
27
|
+
const m = finite(params?.m)
|
|
28
|
+
if (a == null || b == null || sigma == null || rho == null || m == null) return 'svi parameters must be finite'
|
|
29
|
+
if (b < 0) return 'b must be non-negative'
|
|
30
|
+
if (!(Math.abs(rho) < 1)) return 'rho must be in (-1, 1)'
|
|
31
|
+
if (!(sigma > 0)) return 'sigma must be positive'
|
|
32
|
+
if (a + b * sigma * Math.sqrt(1 - rho * rho) < 0) return 'variance floor is negative'
|
|
33
|
+
if (b * (1 + Math.abs(rho)) > 4) return 'b(1+|rho|) must be at most 4'
|
|
34
|
+
return null
|
|
35
|
+
}
|
|
36
|
+
|
|
37
|
+
/** QuantLib detail::sviTotalVariance. */
|
|
38
|
+
export function sviTotalVariance(params, k) {
|
|
39
|
+
const reason = sviParametersHold(params)
|
|
40
|
+
if (reason) throw new Error(reason)
|
|
41
|
+
const dk = finite(k)
|
|
42
|
+
if (dk == null) throw new Error('log-moneyness must be finite.')
|
|
43
|
+
return params.a + params.b * (params.rho * (dk - params.m) + Math.sqrt((dk - params.m) ** 2 + params.sigma ** 2))
|
|
44
|
+
}
|
|
45
|
+
|
|
46
|
+
/**
|
|
47
|
+
* Black volatility at a strike. QuantLib SviSmileSection::volatilityImpl.
|
|
48
|
+
*/
|
|
49
|
+
export function sviVolatility(input) {
|
|
50
|
+
const forward = finite(input.forward)
|
|
51
|
+
const time = finite(input.time)
|
|
52
|
+
const strike = finite(input.strike)
|
|
53
|
+
if (!(forward > 0)) throw new Error('forward must be positive.')
|
|
54
|
+
if (!(time > 0)) throw new Error('time must be positive.')
|
|
55
|
+
if (!(strike > 0)) throw new Error('strike must be positive.')
|
|
56
|
+
const k = Math.log(Math.max(strike, 1e-6) / forward)
|
|
57
|
+
const variance = sviTotalVariance(input, k)
|
|
58
|
+
return Math.sqrt(Math.max(0, variance / time))
|
|
59
|
+
}
|
|
60
|
+
|
|
61
|
+
function direct(x) {
|
|
62
|
+
const sigma = x[2] * x[2] + EPS1
|
|
63
|
+
const rho = Math.sin(x[3]) * EPS2
|
|
64
|
+
const m = x[4]
|
|
65
|
+
const b = ((Math.atan(x[1]) + Math.PI / 2) / Math.PI) * EPS2 * 4 / (1 + Math.abs(rho))
|
|
66
|
+
const a = EPS1 + x[0] * x[0] - b * sigma * Math.sqrt(1 - rho * rho)
|
|
67
|
+
return { a, b, sigma, rho, m }
|
|
68
|
+
}
|
|
69
|
+
|
|
70
|
+
function inverse(params) {
|
|
71
|
+
if (sviParametersHold(params)) return null
|
|
72
|
+
const rhoScale = params.rho / EPS2
|
|
73
|
+
if (!(Math.abs(rhoScale) < 1)) return null
|
|
74
|
+
const underSigma = params.sigma - EPS1
|
|
75
|
+
if (!(underSigma > 0)) return null
|
|
76
|
+
const wing = Math.sqrt(1 - params.rho * params.rho)
|
|
77
|
+
const underA = params.a - EPS1 + params.b * params.sigma * wing
|
|
78
|
+
if (!(underA >= 0)) return null
|
|
79
|
+
const bTerm = params.b * (1 + Math.abs(params.rho)) / (4 * EPS2)
|
|
80
|
+
if (!(bTerm > 0) || !(bTerm < 1)) return null
|
|
81
|
+
return [
|
|
82
|
+
Math.sqrt(underA),
|
|
83
|
+
Math.tan(bTerm * Math.PI - Math.PI / 2),
|
|
84
|
+
Math.sqrt(underSigma),
|
|
85
|
+
Math.asin(rhoScale),
|
|
86
|
+
params.m,
|
|
87
|
+
]
|
|
88
|
+
}
|
|
89
|
+
|
|
90
|
+
function defaultParams(time) {
|
|
91
|
+
const sigma = 0.1
|
|
92
|
+
const rho = -0.4
|
|
93
|
+
const m = 0
|
|
94
|
+
const b = 2 / (1 + Math.abs(rho))
|
|
95
|
+
const a = Math.max(
|
|
96
|
+
0.04 * time - b * (rho * (-m) + Math.sqrt(m * m + sigma * sigma)),
|
|
97
|
+
-b * sigma * Math.sqrt(1 - rho * rho) + EPS1,
|
|
98
|
+
)
|
|
99
|
+
return { a, b, sigma, rho, m }
|
|
100
|
+
}
|
|
101
|
+
|
|
102
|
+
function solve3(matrix, rhs) {
|
|
103
|
+
const a = matrix.map((row, index) => [...row, rhs[index]])
|
|
104
|
+
for (let col = 0; col < 3; col += 1) {
|
|
105
|
+
let pivot = col
|
|
106
|
+
for (let row = col + 1; row < 3; row += 1) {
|
|
107
|
+
if (Math.abs(a[row][col]) > Math.abs(a[pivot][col])) pivot = row
|
|
108
|
+
}
|
|
109
|
+
if (!(Math.abs(a[pivot][col]) > 1e-14)) return null
|
|
110
|
+
const swap = a[col]
|
|
111
|
+
a[col] = a[pivot]
|
|
112
|
+
a[pivot] = swap
|
|
113
|
+
const scale = a[col][col]
|
|
114
|
+
for (let j = col; j < 4; j += 1) a[col][j] /= scale
|
|
115
|
+
for (let row = 0; row < 3; row += 1) {
|
|
116
|
+
if (row === col) continue
|
|
117
|
+
const factor = a[row][col]
|
|
118
|
+
for (let j = col; j < 4; j += 1) a[row][j] -= factor * a[col][j]
|
|
119
|
+
}
|
|
120
|
+
}
|
|
121
|
+
return [a[0][3], a[1][3], a[2][3]]
|
|
122
|
+
}
|
|
123
|
+
|
|
124
|
+
function fromLinear(a, c, d, sigma, m) {
|
|
125
|
+
if (!(d > 1e-8) || Math.abs(c) >= d || d + Math.abs(c) > 4) return null
|
|
126
|
+
const rho = c / d
|
|
127
|
+
const floor = -d * sigma * Math.sqrt(1 - rho * rho)
|
|
128
|
+
const params = { a: Math.max(a, floor), b: d, sigma, rho, m }
|
|
129
|
+
return sviParametersHold(params) ? null : params
|
|
130
|
+
}
|
|
131
|
+
|
|
132
|
+
function linearStart(ks, variances, weights, time) {
|
|
133
|
+
const kMin = Math.min(...ks)
|
|
134
|
+
const kMax = Math.max(...ks)
|
|
135
|
+
const span = Math.max(0.05, kMax - kMin)
|
|
136
|
+
const mGrid = []
|
|
137
|
+
for (let i = 0; i <= 12; i += 1) mGrid.push(kMin - 0.25 * span + (1.5 * span * i) / 12)
|
|
138
|
+
const sigmaGrid = [0.02, 0.05, 0.1, 0.15, 0.25, 0.4, 0.7, span]
|
|
139
|
+
let best = null
|
|
140
|
+
for (const m of mGrid) {
|
|
141
|
+
for (const sigma of sigmaGrid) {
|
|
142
|
+
const ata = [[0, 0, 0], [0, 0, 0], [0, 0, 0]]
|
|
143
|
+
const atb = [0, 0, 0]
|
|
144
|
+
for (let i = 0; i < ks.length; i += 1) {
|
|
145
|
+
const dk = ks[i] - m
|
|
146
|
+
const cols = [1, dk, Math.sqrt(dk * dk + sigma * sigma)]
|
|
147
|
+
const w = weights[i]
|
|
148
|
+
for (let r = 0; r < 3; r += 1) {
|
|
149
|
+
atb[r] += w * cols[r] * variances[i]
|
|
150
|
+
for (let c = 0; c < 3; c += 1) ata[r][c] += w * cols[r] * cols[c]
|
|
151
|
+
}
|
|
152
|
+
}
|
|
153
|
+
const solved = solve3(ata, atb)
|
|
154
|
+
if (!solved) continue
|
|
155
|
+
const params = fromLinear(solved[0], solved[1], solved[2], sigma, m)
|
|
156
|
+
if (!params) continue
|
|
157
|
+
const error = weightedVolError(params, ks, variances, weights, time).error
|
|
158
|
+
if (!best || error < best.error) best = { ...params, error }
|
|
159
|
+
}
|
|
160
|
+
}
|
|
161
|
+
if (best) return best
|
|
162
|
+
const fallback = defaultParams(time)
|
|
163
|
+
fallback.m = ks.reduce((sum, k) => sum + k, 0) / ks.length
|
|
164
|
+
return sviParametersHold(fallback) ? defaultParams(time) : fallback
|
|
165
|
+
}
|
|
166
|
+
|
|
167
|
+
function vegaWeights(ks, vols, forward, time) {
|
|
168
|
+
const raw = ks.map((k, index) => {
|
|
169
|
+
const stdDev = Math.max(vols[index] * Math.sqrt(time), 1e-8)
|
|
170
|
+
const d1 = -k / stdDev + 0.5 * stdDev
|
|
171
|
+
return forward * normalPdf(d1)
|
|
172
|
+
})
|
|
173
|
+
const sum = raw.reduce((total, weight) => total + weight, 0)
|
|
174
|
+
if (!(sum > 0)) return raw.map(() => 1 / raw.length)
|
|
175
|
+
return raw.map((weight) => weight / sum)
|
|
176
|
+
}
|
|
177
|
+
|
|
178
|
+
function weightedVolError(params, ks, variances, weights, time) {
|
|
179
|
+
let squared = 0
|
|
180
|
+
let maxError = 0
|
|
181
|
+
for (let i = 0; i < ks.length; i += 1) {
|
|
182
|
+
const model = Math.sqrt(Math.max(0, sviTotalVariance(params, ks[i]) / time))
|
|
183
|
+
const market = Math.sqrt(Math.max(0, variances[i] / time))
|
|
184
|
+
const gap = model - market
|
|
185
|
+
squared += gap * gap * weights[i]
|
|
186
|
+
maxError = Math.max(maxError, Math.abs(gap))
|
|
187
|
+
}
|
|
188
|
+
const n = ks.length
|
|
189
|
+
const error = Math.sqrt((n * squared) / (n === 1 ? 1 : n - 1))
|
|
190
|
+
return { error, maxError }
|
|
191
|
+
}
|
|
192
|
+
|
|
193
|
+
function nelderMead(fn, x0, maxIter) {
|
|
194
|
+
const n = x0.length
|
|
195
|
+
let simplex = [x0.slice()]
|
|
196
|
+
for (let i = 0; i < n; i += 1) {
|
|
197
|
+
const point = x0.slice()
|
|
198
|
+
point[i] += point[i] === 0 ? 0.1 : 0.15 * Math.sign(point[i])
|
|
199
|
+
simplex.push(point)
|
|
200
|
+
}
|
|
201
|
+
let scores = simplex.map((point) => fn(point))
|
|
202
|
+
for (let iter = 0; iter < maxIter; iter += 1) {
|
|
203
|
+
const order = scores.map((score, index) => [score, index]).sort((a, b) => a[0] - b[0])
|
|
204
|
+
simplex = order.map(([, index]) => simplex[index])
|
|
205
|
+
scores = order.map(([score]) => score)
|
|
206
|
+
if (scores[n] - scores[0] < 1e-12) break
|
|
207
|
+
const centroid = Array(n).fill(0)
|
|
208
|
+
for (let i = 0; i < n; i += 1) {
|
|
209
|
+
for (let j = 0; j < n; j += 1) centroid[j] += simplex[i][j]
|
|
210
|
+
}
|
|
211
|
+
for (let j = 0; j < n; j += 1) centroid[j] /= n
|
|
212
|
+
const worst = simplex[n]
|
|
213
|
+
const reflected = centroid.map((value, j) => value + (value - worst[j]))
|
|
214
|
+
const reflectedScore = fn(reflected)
|
|
215
|
+
if (reflectedScore < scores[n - 1] && reflectedScore >= scores[0]) {
|
|
216
|
+
simplex[n] = reflected
|
|
217
|
+
scores[n] = reflectedScore
|
|
218
|
+
continue
|
|
219
|
+
}
|
|
220
|
+
if (reflectedScore < scores[0]) {
|
|
221
|
+
const expanded = centroid.map((value, j) => value + 2 * (reflected[j] - value))
|
|
222
|
+
const expandedScore = fn(expanded)
|
|
223
|
+
if (expandedScore < reflectedScore) {
|
|
224
|
+
simplex[n] = expanded
|
|
225
|
+
scores[n] = expandedScore
|
|
226
|
+
} else {
|
|
227
|
+
simplex[n] = reflected
|
|
228
|
+
scores[n] = reflectedScore
|
|
229
|
+
}
|
|
230
|
+
continue
|
|
231
|
+
}
|
|
232
|
+
const contracted = centroid.map((value, j) => value + 0.5 * (worst[j] - value))
|
|
233
|
+
const contractedScore = fn(contracted)
|
|
234
|
+
if (contractedScore < scores[n]) {
|
|
235
|
+
simplex[n] = contracted
|
|
236
|
+
scores[n] = contractedScore
|
|
237
|
+
continue
|
|
238
|
+
}
|
|
239
|
+
for (let i = 1; i <= n; i += 1) {
|
|
240
|
+
simplex[i] = simplex[0].map((value, j) => value + 0.5 * (simplex[i][j] - value))
|
|
241
|
+
scores[i] = fn(simplex[i])
|
|
242
|
+
}
|
|
243
|
+
}
|
|
244
|
+
const best = scores.indexOf(Math.min(...scores))
|
|
245
|
+
return simplex[best]
|
|
246
|
+
}
|
|
247
|
+
|
|
248
|
+
function polish(start, ks, variances, weights, time) {
|
|
249
|
+
const x0 = inverse(start)
|
|
250
|
+
if (!x0) return start
|
|
251
|
+
const fitted = nelderMead((x) => weightedVolError(direct(x), ks, variances, weights, time).error, x0, 160)
|
|
252
|
+
return direct(fitted)
|
|
253
|
+
}
|
|
254
|
+
|
|
255
|
+
function usableQuotes(rows, now) {
|
|
256
|
+
const chosen = new Map()
|
|
257
|
+
for (const row of rows ?? []) {
|
|
258
|
+
const iv = finite(row.iv)
|
|
259
|
+
const strike = finite(row.strike)
|
|
260
|
+
const forward = finite(row.forward) ?? finite(row.index) ?? finite(row.spot)
|
|
261
|
+
let time = finite(row.time)
|
|
262
|
+
if (!(time > 0) && finite(row.expiry) != null && now != null) time = yearFraction(now, row.expiry)
|
|
263
|
+
if (!(iv > 0) || !(strike > 0) || !(forward > 0) || !(time > 0)) continue
|
|
264
|
+
const typeName = String(row.type ?? row.optionType ?? '').toLowerCase()
|
|
265
|
+
const type = typeName === 'p' || typeName === 'put' ? 'put' : (typeName === 'c' || typeName === 'call' ? 'call' : null)
|
|
266
|
+
const otm = type == null
|
|
267
|
+
|| (type === 'call' && strike >= forward)
|
|
268
|
+
|| (type === 'put' && strike < forward)
|
|
269
|
+
const prev = chosen.get(strike)
|
|
270
|
+
if (!prev || (otm && !prev.otm)) chosen.set(strike, { strike, forward, time, iv, otm })
|
|
271
|
+
}
|
|
272
|
+
return [...chosen.values()]
|
|
273
|
+
}
|
|
274
|
+
|
|
275
|
+
/**
|
|
276
|
+
* Fit one expiry. Fewer than six strikes returns a reason and no parameters.
|
|
277
|
+
* error is the vega-weighted root-mean-square volatility gap.
|
|
278
|
+
*/
|
|
279
|
+
export function fitSvi(rows, options = {}) {
|
|
280
|
+
const quotes = usableQuotes(rows, options.now ?? null)
|
|
281
|
+
if (quotes.length < MIN_STRIKES) return { svi: null, reason: 'thin smile' }
|
|
282
|
+
const anchor = quotes.reduce((best, row) => (
|
|
283
|
+
Math.abs(Math.log(row.strike / row.forward)) < Math.abs(Math.log(best.strike / best.forward)) ? row : best
|
|
284
|
+
))
|
|
285
|
+
const forward = anchor.forward
|
|
286
|
+
const time = anchor.time
|
|
287
|
+
const ks = quotes.map((row) => Math.log(row.strike / forward))
|
|
288
|
+
const variances = quotes.map((row) => row.iv * row.iv * time)
|
|
289
|
+
const vols = quotes.map((row) => row.iv)
|
|
290
|
+
const weights = vegaWeights(ks, vols, forward, time)
|
|
291
|
+
const starts = [linearStart(ks, variances, weights, time), defaultParams(time)]
|
|
292
|
+
for (const rho of [-0.7, -0.3, 0.3]) {
|
|
293
|
+
const guess = defaultParams(time)
|
|
294
|
+
guess.rho = rho
|
|
295
|
+
guess.b = 2 / (1 + Math.abs(rho))
|
|
296
|
+
guess.m = ks.reduce((sum, k) => sum + k, 0) / ks.length
|
|
297
|
+
guess.a = Math.max(
|
|
298
|
+
anchor.iv * anchor.iv * time - guess.b * guess.sigma,
|
|
299
|
+
-guess.b * guess.sigma * Math.sqrt(1 - rho * rho) + EPS1,
|
|
300
|
+
)
|
|
301
|
+
if (!sviParametersHold(guess)) starts.push(guess)
|
|
302
|
+
}
|
|
303
|
+
let best = null
|
|
304
|
+
const seen = new Set()
|
|
305
|
+
for (const start of starts) {
|
|
306
|
+
const key = [start.a, start.b, start.sigma, start.rho, start.m].map((value) => value.toFixed(6)).join()
|
|
307
|
+
if (seen.has(key)) continue
|
|
308
|
+
seen.add(key)
|
|
309
|
+
const params = polish(start, ks, variances, weights, time)
|
|
310
|
+
const score = weightedVolError(params, ks, variances, weights, time)
|
|
311
|
+
if (!best || score.error < best.error) best = { params, ...score }
|
|
312
|
+
}
|
|
313
|
+
return {
|
|
314
|
+
svi: {
|
|
315
|
+
a: best.params.a,
|
|
316
|
+
b: best.params.b,
|
|
317
|
+
sigma: best.params.sigma,
|
|
318
|
+
rho: best.params.rho,
|
|
319
|
+
m: best.params.m,
|
|
320
|
+
forward,
|
|
321
|
+
time,
|
|
322
|
+
error: best.error,
|
|
323
|
+
maxError: best.maxError,
|
|
324
|
+
quotes: quotes.length,
|
|
325
|
+
},
|
|
326
|
+
reason: null,
|
|
327
|
+
}
|
|
328
|
+
}
|
|
329
|
+
|
|
330
|
+
/** One SVI fit per expiry. A thin slice is returned with a reason and no parameters. */
|
|
331
|
+
export function fitSviByExpiry(rows, options = {}) {
|
|
332
|
+
const groups = new Map()
|
|
333
|
+
for (const row of rows ?? []) {
|
|
334
|
+
const expiry = finite(row.expiry)
|
|
335
|
+
const key = expiry == null ? 'none' : String(expiry)
|
|
336
|
+
const list = groups.get(key) ?? []
|
|
337
|
+
list.push(row)
|
|
338
|
+
groups.set(key, list)
|
|
339
|
+
}
|
|
340
|
+
return [...groups.entries()].map(([key, slice]) => ({
|
|
341
|
+
expiry: key === 'none' ? null : Number(key),
|
|
342
|
+
...fitSvi(slice, options),
|
|
343
|
+
})).sort((a, b) => (a.expiry ?? 0) - (b.expiry ?? 0))
|
|
344
|
+
}
|
package/README.md
DELETED