@continuumdao/quantlib 0.1.0 → 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/black.js CHANGED
@@ -102,6 +102,71 @@ export function blackScholesMerton(input) {
102
102
  return { price: black.price, delta, gamma, vega, theta, rho }
103
103
  }
104
104
 
105
+ function discountOf(rate, time) {
106
+ return Math.exp(-rate * time)
107
+ }
108
+
109
+ function solveVol(target, priceAtVol) {
110
+ let vol = 0.3
111
+ for (let i = 0; i < 60; i += 1) {
112
+ const priced = priceAtVol(vol)
113
+ const diff = priced.price - target
114
+ if (Math.abs(diff) <= Math.max(1e-8, 1e-8 * Math.abs(target))) return vol
115
+ if (!(priced.vega > 1e-10)) break
116
+ vol -= diff / priced.vega
117
+ if (vol < 1e-6) vol = 1e-6
118
+ if (vol > 5) vol = 5
119
+ }
120
+ return null
121
+ }
122
+
123
+ /**
124
+ * Black-76 implied vol of a forward premium.
125
+ * iv is null when the premium is outside no-arbitrage bounds or the solve fails.
126
+ */
127
+ export function impliedVolBlack76(input) {
128
+ const strike = finite('strike', input.strike)
129
+ const forward = finite('forward', input.forward)
130
+ const price = finite('price', input.price)
131
+ const time = finite('time', input.time)
132
+ const rate = input.rate == null ? 0 : finite('rate', input.rate)
133
+ typeSign(input.type)
134
+ if (strike < 0) throw new Error('strike must be non-negative.')
135
+ if (!(forward > 0)) throw new Error('forward must be positive.')
136
+ if (time < 0) throw new Error('time must be non-negative.')
137
+ if (price < 0) throw new Error('price must be non-negative.')
138
+ const sign = typeSign(input.type)
139
+ const discount = discountOf(rate, time)
140
+ const intrinsic = Math.max(sign * (forward - strike), 0) * discount
141
+ const upper = discount * (sign > 0 ? forward : Math.max(strike, 0))
142
+ const tol = 1e-8
143
+ if (price < intrinsic - tol) return { iv: null, reason: 'price below intrinsic' }
144
+ if (price > upper + tol) return { iv: null, reason: 'price above the maximum' }
145
+ if (!(time > 0) || Math.abs(price - intrinsic) <= tol) return { iv: 0, reason: null }
146
+ const iv = solveVol(price, (vol) => black76({ type: input.type, strike, forward, vol, time, rate }))
147
+ if (iv == null) return { iv: null, reason: 'implied vol did not converge' }
148
+ return { iv, reason: null }
149
+ }
150
+
151
+ /**
152
+ * Black-Scholes-Merton implied vol of a spot premium.
153
+ * dividend is the continuous yield q. iv is null outside no-arbitrage bounds.
154
+ */
155
+ export function impliedVolBlackScholesMerton(input) {
156
+ const strike = finite('strike', input.strike)
157
+ const spot = finite('spot', input.spot)
158
+ const price = finite('price', input.price)
159
+ const time = finite('time', input.time)
160
+ const rate = input.rate == null ? 0 : finite('rate', input.rate)
161
+ const dividend = input.dividend == null ? 0 : finite('dividend', input.dividend)
162
+ if (!(spot > 0)) throw new Error('spot must be positive.')
163
+ if (time < 0) throw new Error('time must be non-negative.')
164
+ if (price < 0) throw new Error('price must be non-negative.')
165
+ const forward = spot * Math.exp((rate - dividend) * time)
166
+ const solved = impliedVolBlack76({ type: input.type, strike, forward, price, time, rate })
167
+ return solved
168
+ }
169
+
105
170
  /** q such that spot * exp((rate - q) * time) equals forward. */
106
171
  export function dividendForForward(spot, forward, time, rate = 0) {
107
172
  if (!(time > 0) || !(spot > 0) || !(forward > 0)) return 0
package/decide.js ADDED
@@ -0,0 +1,379 @@
1
+ /*
2
+ * Decisions a plugin can make from one stored snapshot.
3
+ * The snapshot is the document written by the options store. No venue is fetched.
4
+ */
5
+
6
+ import { binomial } from './binomial.js'
7
+ import { baroneAdesiWhaley } from './baroneAdesiWhaley.js'
8
+ import {
9
+ black76,
10
+ blackScholesMerton,
11
+ dividendForForward,
12
+ impliedVolBlack76,
13
+ yearFraction,
14
+ } from './black.js'
15
+ import { fitHeston, hestonPrice } from './heston.js'
16
+ import { optionSmile } from './smile.js'
17
+ import { fitSviByExpiry, sviVolatility } from './svi.js'
18
+
19
+ function sviMap(tickers, now) {
20
+ const fits = new Map()
21
+ for (const slice of fitSviByExpiry(tickers, { now })) {
22
+ fits.set(slice.expiry == null ? 'none' : String(slice.expiry), slice)
23
+ }
24
+ return fits
25
+ }
26
+
27
+ export const OPTION_MODELS = Object.freeze([
28
+ 'black76',
29
+ 'black-scholes',
30
+ 'binomial',
31
+ 'barone-adesi-whaley',
32
+ 'heston',
33
+ 'svi',
34
+ ])
35
+
36
+ const MODELS = new Set(OPTION_MODELS)
37
+
38
+ function num(value) {
39
+ const n = Number(value)
40
+ return Number.isFinite(n) ? n : null
41
+ }
42
+
43
+ function requireModel(model) {
44
+ if (!MODELS.has(model)) {
45
+ throw new Error('model must be black76, black-scholes, binomial, barone-adesi-whaley, heston, or svi.')
46
+ }
47
+ }
48
+
49
+ /** cheap when the model is above the ask, rich when it is below the bid. */
50
+ export function quoteSide(model, bid, ask) {
51
+ if (model == null || bid == null || ask == null) return null
52
+ if (model > ask) return 'cheap'
53
+ if (model < bid) return 'rich'
54
+ return 'inside'
55
+ }
56
+
57
+ function contractOf(ticker, snapshot, rate) {
58
+ const spot = num(ticker.index) ?? num(snapshot?.spot)
59
+ const forward = num(ticker.forward) ?? spot
60
+ const strike = num(ticker.strike)
61
+ const expiry = num(ticker.expiry)
62
+ const time = num(ticker.time) ?? (expiry != null && snapshot?.ts != null ? yearFraction(snapshot.ts, expiry) : null)
63
+ const type = ticker.type === 'call' || ticker.type === 'put' ? ticker.type : null
64
+ if (!(spot > 0) || !(forward > 0) || !(strike > 0) || !(time > 0) || !type) return null
65
+ return {
66
+ type,
67
+ spot,
68
+ strike,
69
+ forward,
70
+ time,
71
+ rate,
72
+ dividend: dividendForForward(spot, forward, time, rate),
73
+ }
74
+ }
75
+
76
+ /** Venue IV when the ticker has one, otherwise IV inverted from the mark. */
77
+ export function attachImpliedVol(ticker, snapshot, rate = 0) {
78
+ const base = contractOf(ticker, snapshot, rate)
79
+ const ivVenue = num(ticker.iv)
80
+ let ivMark = null
81
+ let ivReason = null
82
+ if (!base) ivReason = 'missing contract'
83
+ else if (num(ticker.mark) == null) ivReason = 'no mark'
84
+ else {
85
+ const solved = impliedVolBlack76({
86
+ type: base.type,
87
+ strike: base.strike,
88
+ forward: base.forward,
89
+ price: Number(ticker.mark),
90
+ time: base.time,
91
+ rate,
92
+ })
93
+ ivMark = solved.iv
94
+ ivReason = solved.reason
95
+ }
96
+ const iv = ivVenue != null && ivVenue > 0 ? ivVenue : ivMark
97
+ return { ...ticker, iv, ivVenue, ivMark, ivReason }
98
+ }
99
+
100
+ function greeksOf(priced) {
101
+ if (!priced || typeof priced !== 'object') return null
102
+ return {
103
+ delta: priced.delta ?? null,
104
+ gamma: priced.gamma ?? null,
105
+ vega: priced.vega ?? null,
106
+ theta: priced.theta ?? null,
107
+ rho: priced.rho ?? null,
108
+ }
109
+ }
110
+
111
+ function priceModel(model, base, vol, fit) {
112
+ if (model === 'heston') {
113
+ if (!fit?.heston) return { price: null, greeks: null, reason: fit?.reason ?? 'heston fit refused' }
114
+ const priced = hestonPrice({ ...base, ...fit.heston })
115
+ return { price: priced.price, greeks: greeksOf(priced), reason: null }
116
+ }
117
+ if (model === 'svi') {
118
+ if (!fit?.svi) return { price: null, greeks: null, reason: fit?.reason ?? 'thin smile', modelVol: null }
119
+ const modelVol = sviVolatility({
120
+ strike: base.strike,
121
+ forward: fit.svi.forward,
122
+ time: fit.svi.time,
123
+ ...fit.svi,
124
+ })
125
+ const priced = black76({
126
+ type: base.type,
127
+ strike: base.strike,
128
+ forward: base.forward,
129
+ vol: modelVol,
130
+ time: base.time,
131
+ rate: base.rate,
132
+ })
133
+ return { price: priced.price, greeks: greeksOf(priced), reason: null, modelVol }
134
+ }
135
+ if (!(vol > 0)) return { price: null, greeks: null, reason: 'no vol' }
136
+ if (model === 'black76') {
137
+ const priced = black76({ type: base.type, strike: base.strike, forward: base.forward, vol, time: base.time, rate: base.rate })
138
+ return { price: priced.price, greeks: greeksOf(priced), reason: null }
139
+ }
140
+ if (model === 'black-scholes') {
141
+ const priced = blackScholesMerton({ ...base, vol })
142
+ return { price: priced.price, greeks: greeksOf(priced), reason: null }
143
+ }
144
+ if (model === 'binomial') {
145
+ const priced = binomial({ ...base, vol, exercise: 'european', tree: 'crr', steps: 128 })
146
+ return { price: priced.price, greeks: greeksOf(priced), reason: null }
147
+ }
148
+ const priced = baroneAdesiWhaley({ ...base, vol })
149
+ return { price: priced.price, greeks: greeksOf(priced), reason: null }
150
+ }
151
+
152
+ /**
153
+ * Price one contract. heston is a fitHeston parameter object.
154
+ * svi is the parameter object from fitSvi.
155
+ */
156
+ export function priceOption(input) {
157
+ requireModel(input.model)
158
+ const rate = input.rate ?? 0
159
+ const spot = num(input.spot ?? input.index)
160
+ const forward = num(input.forward) ?? spot
161
+ const strike = num(input.strike)
162
+ const time = num(input.time)
163
+ const type = input.type === 'call' || input.type === 'put' ? input.type : null
164
+ if (!(spot > 0) || !(forward > 0) || !(strike > 0) || !(time > 0) || !type) {
165
+ return { price: null, greeks: null, reason: 'missing contract' }
166
+ }
167
+ const base = {
168
+ type,
169
+ spot,
170
+ strike,
171
+ forward,
172
+ time,
173
+ rate,
174
+ dividend: input.dividend == null ? dividendForForward(spot, forward, time, rate) : Number(input.dividend),
175
+ }
176
+ const fit = input.model === 'svi'
177
+ ? { svi: input.svi ?? null, reason: input.svi ? null : 'thin smile' }
178
+ : { heston: input.heston ?? null, reason: input.reason ?? (input.heston ? null : 'heston fit refused') }
179
+ return priceModel(input.model, base, num(input.vol), fit)
180
+ }
181
+
182
+ function expiryKey(ticker) {
183
+ const expiry = num(ticker.expiry)
184
+ return expiry == null ? 'none' : String(expiry)
185
+ }
186
+
187
+ function selectTickers(tickers, query) {
188
+ return tickers.filter((ticker) => {
189
+ if (query.strike != null && num(ticker.strike) !== Number(query.strike)) return false
190
+ if (query.expiry != null && num(ticker.expiry) !== Number(query.expiry)) return false
191
+ if (query.type && ticker.type !== query.type) return false
192
+ if (query.strikeMin != null && !(num(ticker.strike) >= query.strikeMin)) return false
193
+ if (query.strikeMax != null && !(num(ticker.strike) <= query.strikeMax)) return false
194
+ if (query.expiryMin != null && !(num(ticker.expiry) >= query.expiryMin)) return false
195
+ if (query.expiryMax != null && !(num(ticker.expiry) <= query.expiryMax)) return false
196
+ const abs = Math.abs(num(ticker.delta) ?? NaN)
197
+ if (query.minDelta != null && !(abs >= query.minDelta)) return false
198
+ if (query.maxDelta != null && !(abs <= query.maxDelta)) return false
199
+ return true
200
+ })
201
+ }
202
+
203
+ function withVols(snapshot, rate) {
204
+ return (snapshot?.tickers ?? []).map((ticker) => attachImpliedVol(ticker, snapshot, rate))
205
+ }
206
+
207
+ function hestonQuotes(tickers) {
208
+ return tickers.filter((ticker) => num(ticker.iv) > 0 && num(ticker.strike) > 0 && num(ticker.time ?? ticker.expiry) > 0)
209
+ }
210
+
211
+ /**
212
+ * Attach implied vols and fit Heston and SVI once.
213
+ * priceSnapshot, impliedVols, snapshotSmile, assessContract, and assessRange accept this value
214
+ * and do not fit again. A liquidity floor on the smile still refits that filtered slice.
215
+ */
216
+ export function prepareSnapshot(snapshot, options = {}) {
217
+ if (snapshot?.prepared === true) {
218
+ if (options.rate != null && options.rate !== snapshot.rate) throw new Error('prepared snapshot rate does not match.')
219
+ return snapshot
220
+ }
221
+ const rate = options.rate ?? 0
222
+ const tickers = withVols(snapshot, rate)
223
+ const now = snapshot?.ts ?? null
224
+ return {
225
+ prepared: true,
226
+ snapshot,
227
+ rate,
228
+ tickers,
229
+ fit: fitHeston(hestonQuotes(tickers), { now, rate }),
230
+ sviByExpiry: sviMap(tickers, now),
231
+ }
232
+ }
233
+
234
+ function preparedOf(snapshot, options) {
235
+ if (snapshot?.prepared !== true) return null
236
+ if (options.rate != null && options.rate !== snapshot.rate) throw new Error('prepared snapshot rate does not match.')
237
+ return snapshot
238
+ }
239
+
240
+ function header(snapshot, fit, model) {
241
+ return {
242
+ venue: snapshot?.venue ?? null,
243
+ underlying: snapshot?.underlying ?? null,
244
+ ts: snapshot?.ts ?? null,
245
+ engine: fit?.engine ?? null,
246
+ singleExpiry: fit?.singleExpiry ?? null,
247
+ hestonReason: fit?.reason ?? null,
248
+ model,
249
+ }
250
+ }
251
+
252
+ function rowResult(ticker, model, fit, sviByExpiry, rate, snapshot) {
253
+ const base = contractOf(ticker, snapshot, rate)
254
+ const slice = model === 'svi' ? sviByExpiry.get(expiryKey(ticker)) : fit
255
+ if (!base) {
256
+ return {
257
+ instrumentName: ticker.instrumentName ?? null,
258
+ type: ticker.type ?? null,
259
+ strike: num(ticker.strike),
260
+ expiry: num(ticker.expiry),
261
+ modelPrice: null,
262
+ side: null,
263
+ reason: 'missing contract',
264
+ ivVenue: ticker.ivVenue ?? null,
265
+ ivMark: ticker.ivMark ?? null,
266
+ venue: { bid: num(ticker.bid), ask: num(ticker.ask), mark: num(ticker.mark) },
267
+ }
268
+ }
269
+ const priced = priceModel(model, base, num(ticker.iv), slice)
270
+ return {
271
+ instrumentName: ticker.instrumentName ?? null,
272
+ type: base.type,
273
+ strike: base.strike,
274
+ expiry: num(ticker.expiry),
275
+ modelPrice: priced.price,
276
+ greeks: priced.greeks,
277
+ side: quoteSide(priced.price, num(ticker.bid), num(ticker.ask)),
278
+ reason: priced.reason,
279
+ ivVenue: ticker.ivVenue ?? null,
280
+ ivMark: ticker.ivMark ?? null,
281
+ iv: num(ticker.iv),
282
+ ...(model === 'svi' ? { modelVol: priced.modelVol ?? null } : {}),
283
+ venue: {
284
+ bid: num(ticker.bid),
285
+ ask: num(ticker.ask),
286
+ mark: num(ticker.mark),
287
+ delta: num(ticker.delta),
288
+ },
289
+ }
290
+ }
291
+
292
+ /**
293
+ * Price every selected ticker on a snapshot.
294
+ * Filters are strike, expiry, type, strikeMin, strikeMax, expiryMin, expiryMax, minDelta, and maxDelta.
295
+ */
296
+ export function priceSnapshot(snapshot, options = {}) {
297
+ requireModel(options.model)
298
+ const prepared = preparedOf(snapshot, options)
299
+ const rate = prepared ? prepared.rate : (options.rate ?? 0)
300
+ const source = prepared ? prepared.snapshot : snapshot
301
+ const tickers = prepared ? prepared.tickers : withVols(snapshot, rate)
302
+ const fit = prepared ? prepared.fit : fitHeston(hestonQuotes(tickers), { now: source?.ts ?? null, rate })
303
+ const sviByExpiry = prepared
304
+ ? prepared.sviByExpiry
305
+ : (options.model === 'svi' ? sviMap(tickers, source?.ts ?? null) : new Map())
306
+ const rows = selectTickers(tickers, options).map((ticker) => rowResult(ticker, options.model, fit, sviByExpiry, rate, source))
307
+ return { ...header(source, fit, options.model), rows }
308
+ }
309
+
310
+ /** Venue IV and mark IV for the selected tickers. */
311
+ export function impliedVols(snapshot, options = {}) {
312
+ const prepared = preparedOf(snapshot, options)
313
+ const rate = prepared ? prepared.rate : (options.rate ?? 0)
314
+ const source = prepared ? prepared.snapshot : snapshot
315
+ const tickers = prepared ? prepared.tickers : withVols(snapshot, rate)
316
+ const rows = selectTickers(tickers, options).map((ticker) => ({
317
+ instrumentName: ticker.instrumentName ?? null,
318
+ type: ticker.type ?? null,
319
+ strike: num(ticker.strike),
320
+ expiry: num(ticker.expiry),
321
+ ivVenue: ticker.ivVenue ?? null,
322
+ ivMark: ticker.ivMark ?? null,
323
+ reason: ticker.ivVenue > 0 ? null : ticker.ivReason,
324
+ }))
325
+ return {
326
+ venue: source?.venue ?? null,
327
+ underlying: source?.underlying ?? null,
328
+ ts: source?.ts ?? null,
329
+ rows,
330
+ }
331
+ }
332
+
333
+ /** Smile, smirk, and a per-expiry SVI fit. quoteStrikes reads the curve off the listed strikes. */
334
+ export function snapshotSmile(snapshot, options = {}) {
335
+ const prepared = preparedOf(snapshot, options)
336
+ const source = prepared ? prepared.snapshot : snapshot
337
+ const rate = prepared ? prepared.rate : (options.rate ?? 0)
338
+ const tickers = prepared ? prepared.tickers : withVols(snapshot, rate)
339
+ const expiry = options.expiry == null ? null : Number(options.expiry)
340
+ const rows = tickers.filter((ticker) => expiry == null || num(ticker.expiry) === expiry)
341
+ const floor = options.minOpenInterest != null || options.minVolume != null
342
+ const smile = optionSmile(rows, {
343
+ weight: options.weight ?? 'none',
344
+ minOpenInterest: options.minOpenInterest,
345
+ minVolume: options.minVolume,
346
+ now: source?.ts ?? null,
347
+ quoteStrikes: options.quoteStrikes,
348
+ sviByExpiry: prepared && !floor ? prepared.sviByExpiry : null,
349
+ })
350
+ return {
351
+ venue: source?.venue ?? null,
352
+ underlying: source?.underlying ?? null,
353
+ ts: source?.ts ?? null,
354
+ ...smile,
355
+ }
356
+ }
357
+
358
+ /** One contract. strike, expiry, and type are required. */
359
+ export function assessContract(snapshot, options = {}) {
360
+ if (options.strike == null || options.expiry == null || !options.type) {
361
+ throw new Error('strike, expiry, and type are required.')
362
+ }
363
+ const priced = priceSnapshot(snapshot, options)
364
+ const row = priced.rows[0] ?? null
365
+ if (!row) throw new Error('no contract')
366
+ const { rows, ...rest } = priced
367
+ return { ...rest, row }
368
+ }
369
+
370
+ /** A strike span, an expiry span, or a delta band, with counts of cheap, rich, and inside. */
371
+ export function assessRange(snapshot, options = {}) {
372
+ const priced = priceSnapshot(snapshot, options)
373
+ const counts = { cheap: 0, rich: 0, inside: 0, skipped: 0 }
374
+ for (const row of priced.rows) {
375
+ if (row.side === 'cheap' || row.side === 'rich' || row.side === 'inside') counts[row.side] += 1
376
+ else counts.skipped += 1
377
+ }
378
+ return { ...priced, counts }
379
+ }
package/derive.js CHANGED
@@ -56,6 +56,12 @@ export function readDeriveTicker(row, now) {
56
56
  vega: greek(greeks, ['vega', 'v']),
57
57
  rho: greek(greeks, ['rho', 'r']),
58
58
  bidAskWidth: bid != null && num(row?.askPx ?? row?.ask) != null ? num(row?.askPx ?? row?.ask) - bid : null,
59
+ forward: num(row?.forward ?? row?.f ?? row?.greeks?.f ?? row?.option_pricing?.f),
60
+ volume: num(row?.volume ?? row?.stats?.v ?? row?.stats?.volume),
61
+ openInterest: num(row?.openInterest ?? row?.stats?.oi ?? row?.stats?.open_interest),
62
+ contractCount: num(row?.contractCount ?? row?.stats?.c ?? row?.stats?.contracts),
63
+ bidSize: num(row?.bidSize ?? row?.B ?? row?.best_bid_amount),
64
+ askSize: num(row?.askSize ?? row?.A ?? row?.best_ask_amount),
59
65
  }
60
66
  }
61
67
 
package/index.js CHANGED
@@ -3,13 +3,29 @@
3
3
  * Algorithms follow QuantLib. See LICENSE.
4
4
  */
5
5
 
6
- export { yearFraction, black76, blackScholesMerton, dividendForForward } from './black.js'
6
+ export { yearFraction, black76, blackScholesMerton, dividendForForward, impliedVolBlack76, impliedVolBlackScholesMerton, YEAR_SECONDS } from './black.js'
7
+ export { normalCdf, normalPdf } from './normal.js'
7
8
  export { binomial } from './binomial.js'
8
9
  export { baroneAdesiWhaley } from './baroneAdesiWhaley.js'
9
10
  export { hestonPrice, fitHeston, fellerHolds } from './heston.js'
10
11
  export { readDeriveTicker, deriveSurface, priceDeriveChain, deriveHedgeDecision } from './derive.js'
11
12
  export { ryskFairValue } from './rysk.js'
12
13
  export { buildSpreads } from './spreads.js'
14
+ export { optionSmile } from './smile.js'
15
+ export { fitSvi, fitSviByExpiry, sviParametersHold, sviTotalVariance, sviVolatility } from './svi.js'
16
+ export {
17
+ OPTION_MODELS,
18
+ assessContract,
19
+ assessRange,
20
+ attachImpliedVol,
21
+ impliedVols,
22
+ prepareSnapshot,
23
+ priceOption,
24
+ priceSnapshot,
25
+ quoteSide,
26
+ snapshotSmile,
27
+ } from './decide.js'
28
+ export { openOptionsDatabase, optionsDatabaseFile } from './optionsDb.js'
13
29
  export { buildSnapshot, memoryStore, selectDocuments } from './store.js'
14
30
  export { jsonlStore } from './jsonlStore.js'
15
31
  export { replaySnapshots } from './replay.js'
package/optionsDb.js ADDED
@@ -0,0 +1,69 @@
1
+ /*
2
+ * Read-only view of the options snapshots written by options-data-storage.
3
+ * The file is user_folder/data/databases/options.sqlite. This module does not create it.
4
+ */
5
+
6
+ import { existsSync } from 'node:fs'
7
+ import { DatabaseSync } from 'node:sqlite'
8
+ import { isAbsolute, join, sep } from 'node:path'
9
+
10
+ const FILE_NAME = 'options.sqlite'
11
+
12
+ /** Absolute path of the options database. The file is not created. */
13
+ export function optionsDatabaseFile(userFolder) {
14
+ const root = String(userFolder || '').trim()
15
+ if (!isAbsolute(root)) throw new Error('user folder must be an absolute path')
16
+ const file = join(root, 'data', 'databases', FILE_NAME)
17
+ const prefix = root.endsWith(sep) ? root : root + sep
18
+ if (!file.startsWith(prefix)) throw new Error('database path leaves the user folder')
19
+ return file
20
+ }
21
+
22
+ /**
23
+ * Open the options database for reading.
24
+ * latest returns one snapshot document. list returns venue, underlying, count, and latest time.
25
+ */
26
+ export function openOptionsDatabase(userFolder) {
27
+ const file = optionsDatabaseFile(userFolder)
28
+ if (!existsSync(file)) throw new Error(`options database is missing at ${file}`)
29
+ const db = new DatabaseSync(file, { readOnly: true })
30
+ const newest = db.prepare(
31
+ `SELECT document FROM option_snapshots
32
+ WHERE venue = ? AND underlying = ?
33
+ ORDER BY ts DESC, id DESC
34
+ LIMIT 1`,
35
+ )
36
+ const asOf = db.prepare(
37
+ `SELECT document FROM option_snapshots
38
+ WHERE venue = ? AND underlying = ? AND ts <= ?
39
+ ORDER BY ts DESC, id DESC
40
+ LIMIT 1`,
41
+ )
42
+ const summary = db.prepare(
43
+ `SELECT venue, underlying, COUNT(*) AS snapshots, MAX(ts) AS latest
44
+ FROM option_snapshots
45
+ GROUP BY venue, underlying
46
+ ORDER BY venue, underlying`,
47
+ )
48
+ return {
49
+ file,
50
+ list() {
51
+ return summary.all().map((row) => ({
52
+ venue: row.venue,
53
+ underlying: row.underlying,
54
+ snapshots: Number(row.snapshots),
55
+ latest: Number(row.latest),
56
+ }))
57
+ },
58
+ latest(venue, underlying, at) {
59
+ const book = String(venue ?? '').trim().toLowerCase()
60
+ const name = String(underlying ?? '').trim().toUpperCase()
61
+ const row = at == null ? newest.get(book, name) : asOf.get(book, name, Number(at))
62
+ if (!row) return null
63
+ return JSON.parse(row.document)
64
+ },
65
+ close() {
66
+ db.close()
67
+ },
68
+ }
69
+ }
package/package.json CHANGED
@@ -1,11 +1,11 @@
1
1
  {
2
2
  "name": "@continuumdao/quantlib",
3
- "version": "0.1.0",
4
- "description": "Option pricing and snapshot replay for Derive and Rysk. Black-76, binomial trees, and smile-gated Heston.",
3
+ "version": "0.2.0",
4
+ "description": "Option pricing and snapshot replay for Derive and Rysk. Black-76, binomial trees, smile-gated Heston, and raw SVI.",
5
5
  "license": "BSD-3-Clause",
6
6
  "type": "module",
7
7
  "engines": {
8
- "node": ">=18"
8
+ "node": ">=22"
9
9
  },
10
10
  "exports": {
11
11
  ".": "./index.js"
package/rysk.js CHANGED
@@ -1,10 +1,11 @@
1
1
  /*
2
2
  * Fair value of one Rysk listed strike against an RFQ premium.
3
- * Rysk inventory has no implied vol. A Derive Heston fit is used when the caller passes one.
3
+ * Rysk inventory has no implied vol. Pass a Heston fit, an SVI fit, or a vol.
4
4
  */
5
5
 
6
- import { blackScholesMerton, dividendForForward } from './black.js'
6
+ import { black76, blackScholesMerton, dividendForForward } from './black.js'
7
7
  import { hestonPrice } from './heston.js'
8
+ import { sviVolatility } from './svi.js'
8
9
 
9
10
  function contractType(input) {
10
11
  if (input.isPut === true || input.type === 'put' || input.type === 'P') return 'put'
@@ -38,6 +39,14 @@ export function ryskFairValue(input) {
38
39
  dividend,
39
40
  ...input.heston,
40
41
  }, input.points ?? 400).price
42
+ } else if (input.svi) {
43
+ const vol = sviVolatility({
44
+ strike,
45
+ forward: input.svi.forward ?? forward,
46
+ time: input.svi.time ?? time,
47
+ ...input.svi,
48
+ })
49
+ model = black76({ type, strike, forward, vol, time, rate }).price
41
50
  } else if (Number(input.vol) > 0) {
42
51
  model = blackScholesMerton({ type, spot, strike, vol: Number(input.vol), time, rate, dividend }).price
43
52
  } else {
package/smile.js ADDED
@@ -0,0 +1,169 @@
1
+ /*
2
+ * Smile and smirk from a chain of implied vols.
3
+ * A weight of open interest or volume needs those fields on the rows.
4
+ * SVI is fit on an expiry with at least six strikes. A thinner slice keeps the slope.
5
+ */
6
+
7
+ import { fitSvi, sviVolatility } from './svi.js'
8
+
9
+ function finite(value) {
10
+ const n = Number(value)
11
+ return Number.isFinite(n) ? n : null
12
+ }
13
+
14
+ function weightOf(row, weight) {
15
+ if (weight === 'openInterest') return finite(row.openInterest)
16
+ if (weight === 'volume') return finite(row.volume)
17
+ return 1
18
+ }
19
+
20
+ function liquidityPresent(rows) {
21
+ return rows.some((row) => finite(row.volume) != null || finite(row.openInterest) != null)
22
+ }
23
+
24
+ function slopeOf(points, weightName) {
25
+ let total = 0
26
+ let xBar = 0
27
+ let yBar = 0
28
+ const used = []
29
+ for (const point of points) {
30
+ const x = finite(point.logMoneyness)
31
+ const y = finite(point.iv)
32
+ const w = weightName === 'none' ? 1 : weightOf(point, weightName)
33
+ if (x == null || y == null || !(w > 0)) continue
34
+ used.push({ x, y, w })
35
+ total += w
36
+ xBar += w * x
37
+ yBar += w * y
38
+ }
39
+ if (!(total > 0) || used.length < 2) return { slope: null, totalWeight: total }
40
+ xBar /= total
41
+ yBar /= total
42
+ let num = 0
43
+ let den = 0
44
+ for (const point of used) {
45
+ const dx = point.x - xBar
46
+ num += point.w * dx * (point.y - yBar)
47
+ den += point.w * dx * dx
48
+ }
49
+ return { slope: den > 0 ? num / den : null, totalWeight: total }
50
+ }
51
+
52
+ function nearest(points, type, target) {
53
+ let best = null
54
+ for (const point of points) {
55
+ if (point.type !== type || finite(point.delta) == null || finite(point.iv) == null) continue
56
+ const distance = Math.abs(point.delta - target)
57
+ if (!best || distance < best.distance) best = { distance, iv: point.iv }
58
+ }
59
+ if (!best || best.distance > 0.1) return null
60
+ return best.iv
61
+ }
62
+
63
+ function preparedSvi(sviByExpiry, key) {
64
+ if (!sviByExpiry) return null
65
+ if (sviByExpiry.has(key)) return sviByExpiry.get(key)
66
+ const text = key == null || key === 'none' ? 'none' : String(key)
67
+ if (sviByExpiry.has(text)) return sviByExpiry.get(text)
68
+ return { svi: null, reason: 'thin smile' }
69
+ }
70
+
71
+ function pointFrom(row) {
72
+ const strike = finite(row.strike)
73
+ const ref = finite(row.forward) ?? finite(row.index) ?? finite(row.spot)
74
+ const iv = finite(row.iv)
75
+ const logMoneyness = strike > 0 && ref > 0 ? Math.log(strike / ref) : null
76
+ return {
77
+ instrumentName: row.instrumentName ?? null,
78
+ type: row.type ?? null,
79
+ strike,
80
+ expiry: finite(row.expiry),
81
+ moneyness: strike > 0 && ref > 0 ? strike / ref : null,
82
+ logMoneyness,
83
+ iv,
84
+ ivVenue: finite(row.ivVenue),
85
+ ivMark: finite(row.ivMark),
86
+ delta: finite(row.delta),
87
+ volume: finite(row.volume),
88
+ openInterest: finite(row.openInterest),
89
+ forward: finite(row.forward) ?? ref,
90
+ time: finite(row.time),
91
+ }
92
+ }
93
+
94
+ /**
95
+ * One smile per expiry. weight is none, openInterest, or volume.
96
+ * minOpenInterest and minVolume drop thin strikes when liquidity fields exist.
97
+ */
98
+ export function optionSmile(rows, options = {}) {
99
+ const weight = options.weight ?? 'none'
100
+ if (weight !== 'none' && weight !== 'openInterest' && weight !== 'volume') {
101
+ throw new Error('weight must be none, openInterest, or volume.')
102
+ }
103
+ const minOpenInterest = options.minOpenInterest == null ? null : Number(options.minOpenInterest)
104
+ const minVolume = options.minVolume == null ? null : Number(options.minVolume)
105
+ const source = rows ?? []
106
+ const hasLiquidity = liquidityPresent(source)
107
+ const floorAsked = minOpenInterest != null || minVolume != null
108
+ const weightAsked = weight !== 'none'
109
+ let reason = null
110
+ if ((weightAsked || floorAsked) && !hasLiquidity) {
111
+ reason = 'no liquidity fields'
112
+ }
113
+ let skipped = 0
114
+ const kept = []
115
+ for (const row of source) {
116
+ const thin = hasLiquidity && (
117
+ (minOpenInterest != null && !(finite(row.openInterest) >= minOpenInterest))
118
+ || (minVolume != null && !(finite(row.volume) >= minVolume))
119
+ )
120
+ if (thin) {
121
+ skipped += 1
122
+ continue
123
+ }
124
+ const point = pointFrom(row)
125
+ if (point.iv == null || point.strike == null) continue
126
+ kept.push(point)
127
+ }
128
+ const byExpiry = new Map()
129
+ for (const point of kept) {
130
+ const key = point.expiry ?? 'none'
131
+ const list = byExpiry.get(key) ?? []
132
+ list.push(point)
133
+ byExpiry.set(key, list)
134
+ }
135
+ const expiries = [...byExpiry.entries()].map(([key, points]) => {
136
+ points.sort((a, b) => a.strike - b.strike || String(a.type).localeCompare(String(b.type)))
137
+ const fit = slopeOf(points, reason ? 'none' : weight)
138
+ const callIv = nearest(points, 'call', 0.25)
139
+ const putIv = nearest(points, 'put', -0.25)
140
+ const sviFit = preparedSvi(options.sviByExpiry, key) ?? fitSvi(points, { now: options.now ?? null })
141
+ const expiry = {
142
+ expiry: key === 'none' ? null : Number(key),
143
+ points,
144
+ slope: fit.slope,
145
+ totalWeight: fit.totalWeight,
146
+ riskReversal25: callIv != null && putIv != null ? callIv - putIv : null,
147
+ svi: sviFit.svi,
148
+ sviReason: sviFit.reason,
149
+ }
150
+ if (options.quoteStrikes) {
151
+ expiry.quoted = options.quoteStrikes.map((strike) => ({
152
+ strike: Number(strike),
153
+ iv: sviFit.svi && Number(strike) > 0
154
+ ? sviVolatility({ strike, forward: sviFit.svi.forward, time: sviFit.svi.time, ...sviFit.svi })
155
+ : null,
156
+ }))
157
+ }
158
+ return expiry
159
+ })
160
+ expiries.sort((a, b) => (a.expiry ?? 0) - (b.expiry ?? 0))
161
+ return {
162
+ weight: reason ? 'none' : weight,
163
+ requestedWeight: weight,
164
+ applied: reason == null,
165
+ reason,
166
+ skipped,
167
+ expiries,
168
+ }
169
+ }
package/store.js CHANGED
@@ -51,7 +51,7 @@ function ryskTicker(quote, spot, ts, underlying) {
51
51
  iv: null,
52
52
  bidIv: null,
53
53
  askIv: null,
54
- delta: null,
54
+ delta: quote.delta == null || quote.delta === '' || !Number.isFinite(Number(quote.delta)) ? null : Number(quote.delta),
55
55
  gamma: null,
56
56
  theta: null,
57
57
  vega: null,
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
+ }