@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 +242 -0
- package/baroneAdesiWhaley.js +136 -0
- package/binomial.js +158 -0
- package/black.js +109 -0
- package/derive.js +237 -0
- package/heston.js +330 -0
- package/index.js +15 -0
- package/jsonlStore.js +42 -0
- package/normal.js +19 -0
- package/package.json +26 -4
- package/replay.js +91 -0
- package/rysk.js +52 -0
- package/spreads.js +90 -0
- package/store.js +94 -0
- package/README.md +0 -3
package/derive.js
ADDED
|
@@ -0,0 +1,237 @@
|
|
|
1
|
+
/*
|
|
2
|
+
* Unsigned Derive helpers. Inputs match mapDeriveTickerRow in
|
|
3
|
+
* ctm-mpc-defi src/protocols/evm/derive/reads.ts.
|
|
4
|
+
* The hedge residual follows deriveBookHedgeOrder in hedgeBook.ts.
|
|
5
|
+
*/
|
|
6
|
+
|
|
7
|
+
import { blackScholesMerton, dividendForForward, yearFraction } from './black.js'
|
|
8
|
+
import { fitHeston, hestonPrice } from './heston.js'
|
|
9
|
+
|
|
10
|
+
export function num(value) {
|
|
11
|
+
if (value == null || value === '') return null
|
|
12
|
+
const n = typeof value === 'string' ? Number.parseFloat(value) : Number(value)
|
|
13
|
+
return Number.isFinite(n) ? n : null
|
|
14
|
+
}
|
|
15
|
+
|
|
16
|
+
function greek(greeks, keys) {
|
|
17
|
+
if (!greeks || typeof greeks !== 'object') return null
|
|
18
|
+
for (const key of keys) {
|
|
19
|
+
const n = num(greeks[key])
|
|
20
|
+
if (n != null) return n
|
|
21
|
+
}
|
|
22
|
+
return null
|
|
23
|
+
}
|
|
24
|
+
|
|
25
|
+
function optionType(value) {
|
|
26
|
+
const name = String(value ?? '').trim().toLowerCase()
|
|
27
|
+
if (name === 'c' || name === 'call') return 'call'
|
|
28
|
+
if (name === 'p' || name === 'put') return 'put'
|
|
29
|
+
return null
|
|
30
|
+
}
|
|
31
|
+
|
|
32
|
+
/** One Derive ticker in the shape a later model and the store both keep. */
|
|
33
|
+
export function readDeriveTicker(row, now) {
|
|
34
|
+
const greeks = row?.greeks ?? null
|
|
35
|
+
const bid = num(row?.bidPx ?? row?.bid)
|
|
36
|
+
const ask = num(row?.askPx ?? row?.ask)
|
|
37
|
+
const expiry = num(row?.expiry)
|
|
38
|
+
const time = row?.time != null ? num(row.time) : (expiry != null && now != null ? yearFraction(now, expiry) : null)
|
|
39
|
+
return {
|
|
40
|
+
instrumentName: row?.instrumentName ?? null,
|
|
41
|
+
type: optionType(row?.optionType ?? row?.type),
|
|
42
|
+
strike: num(row?.strike),
|
|
43
|
+
expiry,
|
|
44
|
+
time,
|
|
45
|
+
index: num(row?.indexPx ?? row?.index),
|
|
46
|
+
forward: num(row?.forward),
|
|
47
|
+
bid,
|
|
48
|
+
ask,
|
|
49
|
+
mark: num(row?.markPx ?? row?.mark),
|
|
50
|
+
iv: greek(greeks, ['iv', 'i', 'mark_iv']),
|
|
51
|
+
bidIv: greek(greeks, ['bid_iv', 'bi', 'bidIv']),
|
|
52
|
+
askIv: greek(greeks, ['ask_iv', 'ai', 'askIv']),
|
|
53
|
+
delta: greek(greeks, ['delta', 'd', 'option_delta']),
|
|
54
|
+
gamma: greek(greeks, ['gamma', 'g']),
|
|
55
|
+
theta: greek(greeks, ['theta', 't']),
|
|
56
|
+
vega: greek(greeks, ['vega', 'v']),
|
|
57
|
+
rho: greek(greeks, ['rho', 'r']),
|
|
58
|
+
bidAskWidth: bid != null && num(row?.askPx ?? row?.ask) != null ? num(row?.askPx ?? row?.ask) - bid : null,
|
|
59
|
+
}
|
|
60
|
+
}
|
|
61
|
+
|
|
62
|
+
export function deriveSurface(rows, now) {
|
|
63
|
+
return (rows ?? []).map((row) => readDeriveTicker(row, now)).filter((row) => row.strike != null && row.type)
|
|
64
|
+
}
|
|
65
|
+
|
|
66
|
+
function contract(row, rate) {
|
|
67
|
+
const spot = row.index
|
|
68
|
+
const forward = row.forward ?? row.index
|
|
69
|
+
if (!(spot > 0) || !(row.strike > 0) || !(row.time > 0) || !row.type) return null
|
|
70
|
+
return {
|
|
71
|
+
type: row.type,
|
|
72
|
+
spot,
|
|
73
|
+
strike: row.strike,
|
|
74
|
+
time: row.time,
|
|
75
|
+
rate,
|
|
76
|
+
dividend: dividendForForward(spot, forward, row.time, rate),
|
|
77
|
+
}
|
|
78
|
+
}
|
|
79
|
+
|
|
80
|
+
function hestonGreeks(base, params, points) {
|
|
81
|
+
const mid = hestonPrice({ ...base, ...params }, points).price
|
|
82
|
+
const bump = base.spot * 1e-4
|
|
83
|
+
const up = hestonPrice({ ...base, ...params, spot: base.spot + bump }, points).price
|
|
84
|
+
const down = hestonPrice({ ...base, ...params, spot: base.spot - bump }, points).price
|
|
85
|
+
const delta = (up - down) / (2 * bump)
|
|
86
|
+
const gamma = (up - 2 * mid + down) / (bump * bump)
|
|
87
|
+
const volBump = 1e-3
|
|
88
|
+
const sigma = Math.sqrt(params.v0)
|
|
89
|
+
const upVar = (sigma + volBump) ** 2
|
|
90
|
+
const downVar = Math.max(1e-6, (sigma - volBump) ** 2)
|
|
91
|
+
const scale = (next) => ({ v0: next, theta: params.theta * (next / params.v0) })
|
|
92
|
+
const volUp = hestonPrice({ ...base, ...params, ...scale(upVar) }, points).price
|
|
93
|
+
const volDown = hestonPrice({ ...base, ...params, ...scale(downVar) }, points).price
|
|
94
|
+
return { price: mid, delta, gamma, vega: (volUp - volDown) / (2 * volBump), theta: null, rho: null }
|
|
95
|
+
}
|
|
96
|
+
|
|
97
|
+
function modelPrice(row, fit, rate, points) {
|
|
98
|
+
const base = contract(row, rate)
|
|
99
|
+
if (!base) return null
|
|
100
|
+
if (fit.heston) return hestonGreeks(base, fit.heston, points)
|
|
101
|
+
if (!(row.iv > 0)) return null
|
|
102
|
+
return blackScholesMerton({ ...base, vol: row.iv })
|
|
103
|
+
}
|
|
104
|
+
|
|
105
|
+
function sideOf(model, bid, ask) {
|
|
106
|
+
if (model == null || bid == null || ask == null) return null
|
|
107
|
+
if (model > ask) return 'cheap'
|
|
108
|
+
if (model < bid) return 'rich'
|
|
109
|
+
return 'inside'
|
|
110
|
+
}
|
|
111
|
+
|
|
112
|
+
/**
|
|
113
|
+
* Compare a model with each ticker. Heston is used when the smile gate passes.
|
|
114
|
+
* side is cheap when the model is above the ask, rich when it is below the bid.
|
|
115
|
+
*/
|
|
116
|
+
export function priceDeriveChain(rows, options = {}) {
|
|
117
|
+
const now = options.now ?? null
|
|
118
|
+
const rate = options.rate ?? 0
|
|
119
|
+
const points = options.points ?? 200
|
|
120
|
+
const surface = deriveSurface(rows, now)
|
|
121
|
+
const fit = fitHeston(surface, { now, rate, points: options.fitPoints ?? 80, maxIter: options.maxIter ?? 20 })
|
|
122
|
+
const priced = surface.map((row) => {
|
|
123
|
+
const model = modelPrice(row, fit, rate, points)
|
|
124
|
+
return {
|
|
125
|
+
instrumentName: row.instrumentName,
|
|
126
|
+
modelPrice: model?.price ?? null,
|
|
127
|
+
model,
|
|
128
|
+
venue: {
|
|
129
|
+
bid: row.bid,
|
|
130
|
+
ask: row.ask,
|
|
131
|
+
mark: row.mark,
|
|
132
|
+
iv: row.iv,
|
|
133
|
+
delta: row.delta,
|
|
134
|
+
gamma: row.gamma,
|
|
135
|
+
theta: row.theta,
|
|
136
|
+
vega: row.vega,
|
|
137
|
+
rho: row.rho,
|
|
138
|
+
},
|
|
139
|
+
side: sideOf(model?.price ?? null, row.bid, row.ask),
|
|
140
|
+
}
|
|
141
|
+
})
|
|
142
|
+
return {
|
|
143
|
+
engine: fit.engine,
|
|
144
|
+
heston: fit.heston,
|
|
145
|
+
singleExpiry: fit.singleExpiry,
|
|
146
|
+
reason: fit.reason,
|
|
147
|
+
rows: priced,
|
|
148
|
+
}
|
|
149
|
+
}
|
|
150
|
+
|
|
151
|
+
function decimal(value) {
|
|
152
|
+
if (!Number.isFinite(value)) return '0'
|
|
153
|
+
const text = value.toFixed(8).replace(/\.?0+$/, '')
|
|
154
|
+
return text === '-0' ? '0' : text || '0'
|
|
155
|
+
}
|
|
156
|
+
|
|
157
|
+
function unitsOf(value) {
|
|
158
|
+
const raw = String(value).trim()
|
|
159
|
+
const neg = raw.startsWith('-')
|
|
160
|
+
const body = neg ? raw.slice(1) : raw
|
|
161
|
+
const [whole, frac = ''] = body.split('.')
|
|
162
|
+
const scale = 10n ** 18n
|
|
163
|
+
const w = BigInt(whole || '0')
|
|
164
|
+
const f = BigInt((frac.replace(/\D/g, '') + '000000000000000000').slice(0, 18) || '0')
|
|
165
|
+
const units = w * scale + f
|
|
166
|
+
return neg ? -units : units
|
|
167
|
+
}
|
|
168
|
+
|
|
169
|
+
function floorToStep(value, step) {
|
|
170
|
+
if (!(value > 0) || !Number.isFinite(value)) return null
|
|
171
|
+
const stepText = String(step ?? '').trim()
|
|
172
|
+
if (!stepText || !(Number(stepText) > 0)) return decimal(value)
|
|
173
|
+
const stepUnits = unitsOf(stepText)
|
|
174
|
+
if (stepUnits <= 0n) return null
|
|
175
|
+
const floored = (unitsOf(value.toFixed(12)) / stepUnits) * stepUnits
|
|
176
|
+
if (floored <= 0n) return null
|
|
177
|
+
const scale = 10n ** 18n
|
|
178
|
+
const whole = floored / scale
|
|
179
|
+
const frac = floored % scale
|
|
180
|
+
if (frac === 0n) return whole.toString()
|
|
181
|
+
return `${whole}.${frac.toString().padStart(18, '0').replace(/0+$/, '')}`
|
|
182
|
+
}
|
|
183
|
+
|
|
184
|
+
/**
|
|
185
|
+
* Residual perp that moves net delta to targetDelta.
|
|
186
|
+
* Option delta is signed amount times delta. A perp's delta is its signed size.
|
|
187
|
+
* deltaSource chooses which delta map to pass in. This function does not sign.
|
|
188
|
+
*/
|
|
189
|
+
export function deriveHedgeDecision(args) {
|
|
190
|
+
const currency = String(args.currency ?? '').trim().toUpperCase()
|
|
191
|
+
if (!currency) throw new Error('currency is required.')
|
|
192
|
+
const perpName = `${currency}-PERP`
|
|
193
|
+
let optionDelta = 0
|
|
194
|
+
let perpDelta = 0
|
|
195
|
+
for (const row of args.positions ?? []) {
|
|
196
|
+
const name = String(row.instrumentName ?? '').trim().toUpperCase()
|
|
197
|
+
const amount = num(row.amount)
|
|
198
|
+
if (amount == null || amount === 0) continue
|
|
199
|
+
if (name === perpName) {
|
|
200
|
+
perpDelta += amount
|
|
201
|
+
continue
|
|
202
|
+
}
|
|
203
|
+
if (!name.startsWith(`${currency}-`)) continue
|
|
204
|
+
const delta = num(args.deltas?.[name] ?? args.deltas?.[row.instrumentName])
|
|
205
|
+
if (delta == null) throw new Error(`Missing delta for ${name}.`)
|
|
206
|
+
optionDelta += amount * delta
|
|
207
|
+
}
|
|
208
|
+
const target = args.targetDelta == null ? 0 : Number(args.targetDelta)
|
|
209
|
+
if (!Number.isFinite(target)) throw new Error('targetDelta must be a number.')
|
|
210
|
+
const net = optionDelta + perpDelta
|
|
211
|
+
const residual = target - net
|
|
212
|
+
const min = args.minResidual != null && args.minResidual > 0 ? args.minResidual : 0
|
|
213
|
+
const floored = Math.abs(residual) <= min ? null : floorToStep(Math.abs(residual), args.perpStep)
|
|
214
|
+
const base = {
|
|
215
|
+
currency,
|
|
216
|
+
optionDelta: decimal(optionDelta),
|
|
217
|
+
perpDelta: decimal(perpDelta),
|
|
218
|
+
netDelta: decimal(net),
|
|
219
|
+
targetDelta: decimal(target),
|
|
220
|
+
instrumentName: perpName,
|
|
221
|
+
}
|
|
222
|
+
if (!floored) {
|
|
223
|
+
return {
|
|
224
|
+
...base,
|
|
225
|
+
direction: null,
|
|
226
|
+
amount: null,
|
|
227
|
+
message: `No hedge. Net delta ${decimal(net)} is within one step of target ${decimal(target)}.`,
|
|
228
|
+
}
|
|
229
|
+
}
|
|
230
|
+
const direction = residual > 0 ? 'buy' : 'sell'
|
|
231
|
+
return {
|
|
232
|
+
...base,
|
|
233
|
+
direction,
|
|
234
|
+
amount: floored,
|
|
235
|
+
message: `${direction} ${floored} ${perpName} to move net delta ${decimal(net)} to ${decimal(target)}.`,
|
|
236
|
+
}
|
|
237
|
+
}
|
package/heston.js
ADDED
|
@@ -0,0 +1,330 @@
|
|
|
1
|
+
/*
|
|
2
|
+
* Analytic Heston price (Gatheral logarithm) and a smile-gated fit.
|
|
3
|
+
* QuantLib: ql/pricingengines/vanilla/analytichestonengine.cpp
|
|
4
|
+
* and ql/models/equity/hestonmodel.hpp (Feller condition).
|
|
5
|
+
*/
|
|
6
|
+
|
|
7
|
+
import { black76 } from './black.js'
|
|
8
|
+
|
|
9
|
+
function cadd(a, b) {
|
|
10
|
+
return { re: a.re + b.re, im: a.im + b.im }
|
|
11
|
+
}
|
|
12
|
+
function csub(a, b) {
|
|
13
|
+
return { re: a.re - b.re, im: a.im - b.im }
|
|
14
|
+
}
|
|
15
|
+
function cmul(a, b) {
|
|
16
|
+
return { re: a.re * b.re - a.im * b.im, im: a.re * b.im + a.im * b.re }
|
|
17
|
+
}
|
|
18
|
+
function cdiv(a, b) {
|
|
19
|
+
const d = b.re * b.re + b.im * b.im
|
|
20
|
+
return { re: (a.re * b.re + a.im * b.im) / d, im: (a.im * b.re - a.re * b.im) / d }
|
|
21
|
+
}
|
|
22
|
+
function cscale(a, s) {
|
|
23
|
+
return { re: a.re * s, im: a.im * s }
|
|
24
|
+
}
|
|
25
|
+
function cexp(a) {
|
|
26
|
+
const e = Math.exp(a.re)
|
|
27
|
+
return { re: e * Math.cos(a.im), im: e * Math.sin(a.im) }
|
|
28
|
+
}
|
|
29
|
+
function clog(a) {
|
|
30
|
+
return { re: Math.log(Math.hypot(a.re, a.im)), im: Math.atan2(a.im, a.re) }
|
|
31
|
+
}
|
|
32
|
+
function csqrt(a) {
|
|
33
|
+
if (a.re === 0 && a.im === 0) return { re: 0, im: 0 }
|
|
34
|
+
const m = Math.hypot(a.re, a.im)
|
|
35
|
+
const re = Math.sqrt((m + a.re) / 2)
|
|
36
|
+
let im = Math.sqrt(Math.max(0, (m - a.re) / 2))
|
|
37
|
+
if (a.im < 0) im = -im
|
|
38
|
+
return { re, im }
|
|
39
|
+
}
|
|
40
|
+
|
|
41
|
+
function fj(phi, j, params) {
|
|
42
|
+
const { kappa, theta, sigma, v0, rho, time, logMoneyness } = params
|
|
43
|
+
if (phi === 0) {
|
|
44
|
+
if (j === 1) {
|
|
45
|
+
const kmr = rho * sigma - kappa
|
|
46
|
+
if (Math.abs(kmr) > 1e-7) {
|
|
47
|
+
return logMoneyness
|
|
48
|
+
+ (Math.exp(kmr * time) * kappa * theta - kappa * theta * (kmr * time + 1)) / (2 * kmr * kmr)
|
|
49
|
+
- v0 * (1 - Math.exp(kmr * time)) / (2 * kmr)
|
|
50
|
+
}
|
|
51
|
+
return logMoneyness + 0.25 * kappa * theta * time * time + 0.5 * v0 * time
|
|
52
|
+
}
|
|
53
|
+
return logMoneyness
|
|
54
|
+
- (Math.exp(-kappa * time) * kappa * theta + kappa * theta * (kappa * time - 1)) / (2 * kappa * kappa)
|
|
55
|
+
- v0 * (1 - Math.exp(-kappa * time)) / (2 * kappa)
|
|
56
|
+
}
|
|
57
|
+
const sigma2 = sigma * sigma
|
|
58
|
+
const t0 = kappa - (j === 1 ? rho * sigma : 0)
|
|
59
|
+
const t1 = { re: t0, im: -rho * sigma * phi }
|
|
60
|
+
const phiTerm = { re: -phi * phi, im: phi * (j === 1 ? 1 : -1) }
|
|
61
|
+
const d = csqrt(csub(cmul(t1, t1), cscale(phiTerm, sigma2)))
|
|
62
|
+
const ex = cexp(cscale(d, -time))
|
|
63
|
+
const one = { re: 1, im: 0 }
|
|
64
|
+
const t1d = csub(t1, d)
|
|
65
|
+
let exponent
|
|
66
|
+
// QuantLib switches at 1e-5. Doubles cancel earlier, so the stable branch starts at 1e-3.
|
|
67
|
+
if (sigma > 1e-3) {
|
|
68
|
+
const p = cdiv(t1d, cadd(t1, d))
|
|
69
|
+
const g = clog(cdiv(csub(one, cmul(p, ex)), csub(one, p)))
|
|
70
|
+
const num = cmul(t1d, csub(one, ex))
|
|
71
|
+
const den = cscale(csub(one, cmul(ex, p)), sigma2)
|
|
72
|
+
exponent = cadd(
|
|
73
|
+
cadd(cscale(cdiv(num, den), v0), cscale(csub(cscale(t1d, time), cscale(g, 2)), (kappa * theta) / sigma2)),
|
|
74
|
+
{ re: 0, im: phi * logMoneyness },
|
|
75
|
+
)
|
|
76
|
+
} else {
|
|
77
|
+
const td = cmul(cdiv({ re: phi, im: 0 }, cscale(t1, 2)), { re: -phi, im: j === 1 ? 1 : -1 })
|
|
78
|
+
const p = cdiv(cscale(td, sigma2), cadd(t1, d))
|
|
79
|
+
const g = cmul(p, csub(one, ex))
|
|
80
|
+
const first = cdiv(cmul(td, csub(one, ex)), csub(one, cmul(p, ex)))
|
|
81
|
+
const second = csub(cscale(td, time), cscale(g, 2 / sigma2))
|
|
82
|
+
exponent = cadd(
|
|
83
|
+
cadd(cscale(first, v0), cscale(second, kappa * theta)),
|
|
84
|
+
{ re: 0, im: phi * logMoneyness },
|
|
85
|
+
)
|
|
86
|
+
}
|
|
87
|
+
return cexp(exponent).im / phi
|
|
88
|
+
}
|
|
89
|
+
|
|
90
|
+
function integrate(f, cInf, points) {
|
|
91
|
+
const n = points % 2 === 0 ? points : points + 1
|
|
92
|
+
const a = 1e-12
|
|
93
|
+
const b = 1 - 1e-12
|
|
94
|
+
const h = (b - a) / n
|
|
95
|
+
const g = (x) => {
|
|
96
|
+
if (x * cInf <= 1e-14) return 0
|
|
97
|
+
const y = f(-Math.log(x) / cInf) / (x * cInf)
|
|
98
|
+
return Number.isFinite(y) ? y : 0
|
|
99
|
+
}
|
|
100
|
+
let sum = g(a) + g(b)
|
|
101
|
+
for (let i = 1; i < n; i += 1) {
|
|
102
|
+
sum += (i % 2 === 0 ? 2 : 4) * g(a + i * h)
|
|
103
|
+
}
|
|
104
|
+
return (sum * h) / 3
|
|
105
|
+
}
|
|
106
|
+
|
|
107
|
+
function cInfOf(params) {
|
|
108
|
+
const { rho, sigma, v0, kappa, theta, time } = params
|
|
109
|
+
const raw = Math.sqrt(Math.max(0, 1 - rho * rho)) / sigma
|
|
110
|
+
return Math.min(0.2, Math.max(0.0001, raw)) * (v0 + kappa * theta * time)
|
|
111
|
+
}
|
|
112
|
+
|
|
113
|
+
/**
|
|
114
|
+
* European Heston price. params are v0, kappa, theta, sigma, rho.
|
|
115
|
+
* spot, strike, time, rate, and dividend describe the contract.
|
|
116
|
+
*/
|
|
117
|
+
export function hestonPrice(input, points = 1600) {
|
|
118
|
+
const type = String(input.type ?? 'call').toLowerCase()
|
|
119
|
+
const call = type === 'call' || type === 'c'
|
|
120
|
+
if (!call && type !== 'put' && type !== 'p') throw new Error('type must be call or put.')
|
|
121
|
+
const spot = Number(input.spot)
|
|
122
|
+
const strike = Number(input.strike)
|
|
123
|
+
const time = Number(input.time)
|
|
124
|
+
const rate = input.rate == null ? 0 : Number(input.rate)
|
|
125
|
+
const dividend = input.dividend == null ? 0 : Number(input.dividend)
|
|
126
|
+
const v0 = Number(input.v0)
|
|
127
|
+
const kappa = Number(input.kappa)
|
|
128
|
+
const theta = Number(input.theta)
|
|
129
|
+
const sigma = Number(input.sigma)
|
|
130
|
+
const rho = Number(input.rho)
|
|
131
|
+
if (!(spot > 0) || !(strike > 0) || !(time > 0)) throw new Error('spot, strike, and time must be positive.')
|
|
132
|
+
if (!(v0 > 0) || !(kappa > 0) || !(theta > 0) || !(sigma > 0)) throw new Error('v0, kappa, theta, and sigma must be positive.')
|
|
133
|
+
if (!(rho > -1 && rho < 1)) throw new Error('rho must be inside (-1, 1).')
|
|
134
|
+
|
|
135
|
+
const forward = spot * Math.exp((rate - dividend) * time)
|
|
136
|
+
const params = { kappa, theta, sigma, v0, rho, time, logMoneyness: Math.log(forward / strike) }
|
|
137
|
+
const cInf = cInfOf(params)
|
|
138
|
+
const p1 = integrate((phi) => fj(phi, 1, params), cInf, points) / Math.PI
|
|
139
|
+
const p2 = integrate((phi) => fj(phi, 2, params), cInf, points) / Math.PI
|
|
140
|
+
const dfq = Math.exp(-dividend * time)
|
|
141
|
+
const dfr = Math.exp(-rate * time)
|
|
142
|
+
const price = call
|
|
143
|
+
? spot * dfq * (p1 + 0.5) - strike * dfr * (p2 + 0.5)
|
|
144
|
+
: spot * dfq * (p1 - 0.5) - strike * dfr * (p2 - 0.5)
|
|
145
|
+
return { price, forward }
|
|
146
|
+
}
|
|
147
|
+
|
|
148
|
+
export function fellerHolds(params) {
|
|
149
|
+
return params.sigma * params.sigma < 2 * params.kappa * params.theta
|
|
150
|
+
}
|
|
151
|
+
|
|
152
|
+
function uniqueStrikes(rows) {
|
|
153
|
+
return new Set(rows.map((row) => row.strike)).size
|
|
154
|
+
}
|
|
155
|
+
|
|
156
|
+
/**
|
|
157
|
+
* Fit Heston when at least one expiry has five usable strikes.
|
|
158
|
+
* A quote is dropped when its mark IV is outside the bid and ask IV.
|
|
159
|
+
* One expiry still fits and is marked singleExpiry.
|
|
160
|
+
*/
|
|
161
|
+
export function fitHeston(quotes, options = {}) {
|
|
162
|
+
const now = options.now ?? null
|
|
163
|
+
const rate = options.rate ?? 0
|
|
164
|
+
const usable = []
|
|
165
|
+
for (const quote of quotes ?? []) {
|
|
166
|
+
const iv = Number(quote.iv)
|
|
167
|
+
const strike = Number(quote.strike)
|
|
168
|
+
const forward = Number(quote.forward ?? quote.index ?? quote.spot)
|
|
169
|
+
const bidIv = quote.bidIv == null ? null : Number(quote.bidIv)
|
|
170
|
+
const askIv = quote.askIv == null ? null : Number(quote.askIv)
|
|
171
|
+
let time = quote.time == null ? null : Number(quote.time)
|
|
172
|
+
if (time == null && quote.expiry != null && now != null) {
|
|
173
|
+
time = (Number(quote.expiry) - Number(now)) / (365.25 * 24 * 60 * 60)
|
|
174
|
+
}
|
|
175
|
+
if (!Number.isFinite(iv) || iv <= 0 || !(strike > 0) || !(forward > 0) || !(time > 0)) continue
|
|
176
|
+
if (Number.isFinite(bidIv) && Number.isFinite(askIv)) {
|
|
177
|
+
const lo = Math.min(bidIv, askIv)
|
|
178
|
+
const hi = Math.max(bidIv, askIv)
|
|
179
|
+
if (iv < lo || iv > hi) continue
|
|
180
|
+
}
|
|
181
|
+
const typeName = String(quote.type ?? quote.optionType ?? 'call').toLowerCase()
|
|
182
|
+
const type = typeName === 'p' || typeName === 'put' ? 'put' : 'call'
|
|
183
|
+
usable.push({
|
|
184
|
+
strike,
|
|
185
|
+
forward,
|
|
186
|
+
time,
|
|
187
|
+
iv,
|
|
188
|
+
type,
|
|
189
|
+
expiryKey: time.toFixed(8),
|
|
190
|
+
})
|
|
191
|
+
}
|
|
192
|
+
const byExpiry = new Map()
|
|
193
|
+
for (const row of usable) {
|
|
194
|
+
const bucket = byExpiry.get(row.expiryKey) ?? []
|
|
195
|
+
bucket.push(row)
|
|
196
|
+
byExpiry.set(row.expiryKey, bucket)
|
|
197
|
+
}
|
|
198
|
+
const kept = []
|
|
199
|
+
for (const bucket of byExpiry.values()) {
|
|
200
|
+
const chosen = new Map()
|
|
201
|
+
for (const row of bucket) {
|
|
202
|
+
const otm = (row.type === 'call' && row.strike >= row.forward) || (row.type === 'put' && row.strike < row.forward)
|
|
203
|
+
const prev = chosen.get(row.strike)
|
|
204
|
+
if (!prev || (otm && !prev.otm)) chosen.set(row.strike, { ...row, otm })
|
|
205
|
+
}
|
|
206
|
+
const rows = [...chosen.values()]
|
|
207
|
+
if (uniqueStrikes(rows) >= 5) kept.push(...rows)
|
|
208
|
+
}
|
|
209
|
+
const expiries = new Set(kept.map((row) => row.expiryKey))
|
|
210
|
+
if (expiries.size === 0) {
|
|
211
|
+
return { engine: 'black76', heston: null, singleExpiry: null, reason: 'thin smile' }
|
|
212
|
+
}
|
|
213
|
+
const market = kept.map((row) => {
|
|
214
|
+
const price = black76({
|
|
215
|
+
type: row.type,
|
|
216
|
+
strike: row.strike,
|
|
217
|
+
forward: row.forward,
|
|
218
|
+
vol: row.iv,
|
|
219
|
+
time: row.time,
|
|
220
|
+
rate,
|
|
221
|
+
}).price
|
|
222
|
+
return { ...row, market: price, spot: row.forward * Math.exp(-rate * row.time) }
|
|
223
|
+
})
|
|
224
|
+
const atm = market.reduce((best, row) => (Math.abs(Math.log(row.strike / row.forward)) < Math.abs(Math.log(best.strike / best.forward)) ? row : best))
|
|
225
|
+
const v0 = Math.min(1.5, Math.max(0.01, atm.iv * atm.iv))
|
|
226
|
+
const start = [Math.log(v0), Math.log(1.2), Math.log(v0), Math.log(0.4), Math.atanh(-0.4)]
|
|
227
|
+
const points = options.points ?? 120
|
|
228
|
+
const objective = (x) => {
|
|
229
|
+
const params = {
|
|
230
|
+
v0: Math.exp(x[0]),
|
|
231
|
+
kappa: Math.exp(x[1]),
|
|
232
|
+
theta: Math.exp(x[2]),
|
|
233
|
+
sigma: Math.exp(x[3]),
|
|
234
|
+
rho: Math.tanh(x[4]),
|
|
235
|
+
}
|
|
236
|
+
let error = 0
|
|
237
|
+
for (const row of market) {
|
|
238
|
+
const model = hestonPrice({
|
|
239
|
+
type: row.type,
|
|
240
|
+
spot: row.spot,
|
|
241
|
+
strike: row.strike,
|
|
242
|
+
time: row.time,
|
|
243
|
+
rate,
|
|
244
|
+
dividend: 0,
|
|
245
|
+
...params,
|
|
246
|
+
}, points).price
|
|
247
|
+
const scale = Math.max(row.market, 1e-6)
|
|
248
|
+
const gap = (model - row.market) / scale
|
|
249
|
+
error += gap * gap
|
|
250
|
+
}
|
|
251
|
+
if (!fellerHolds(params)) {
|
|
252
|
+
const slack = params.sigma * params.sigma - 2 * params.kappa * params.theta
|
|
253
|
+
error += 25 * slack * slack
|
|
254
|
+
}
|
|
255
|
+
return error
|
|
256
|
+
}
|
|
257
|
+
const fitted = nelderMead(objective, start, { maxIter: options.maxIter ?? 60 })
|
|
258
|
+
const heston = {
|
|
259
|
+
v0: Math.exp(fitted.x[0]),
|
|
260
|
+
kappa: Math.exp(fitted.x[1]),
|
|
261
|
+
theta: Math.exp(fitted.x[2]),
|
|
262
|
+
sigma: Math.exp(fitted.x[3]),
|
|
263
|
+
rho: Math.tanh(fitted.x[4]),
|
|
264
|
+
error: fitted.fx,
|
|
265
|
+
feller: false,
|
|
266
|
+
}
|
|
267
|
+
heston.feller = fellerHolds(heston)
|
|
268
|
+
return {
|
|
269
|
+
engine: 'heston',
|
|
270
|
+
heston,
|
|
271
|
+
singleExpiry: expiries.size === 1,
|
|
272
|
+
reason: null,
|
|
273
|
+
quotes: market.length,
|
|
274
|
+
}
|
|
275
|
+
}
|
|
276
|
+
|
|
277
|
+
function nelderMead(fn, x0, { maxIter }) {
|
|
278
|
+
const n = x0.length
|
|
279
|
+
let simplex = [x0.slice()]
|
|
280
|
+
for (let i = 0; i < n; i += 1) {
|
|
281
|
+
const point = x0.slice()
|
|
282
|
+
point[i] += point[i] === 0 ? 0.1 : 0.15 * Math.sign(point[i])
|
|
283
|
+
simplex.push(point)
|
|
284
|
+
}
|
|
285
|
+
let scores = simplex.map((point) => fn(point))
|
|
286
|
+
for (let iter = 0; iter < maxIter; iter += 1) {
|
|
287
|
+
const order = scores.map((score, index) => [score, index]).sort((a, b) => a[0] - b[0])
|
|
288
|
+
simplex = order.map(([, index]) => simplex[index])
|
|
289
|
+
scores = order.map(([score]) => score)
|
|
290
|
+
if (scores[n] - scores[0] < 1e-8) break
|
|
291
|
+
const centroid = Array(n).fill(0)
|
|
292
|
+
for (let i = 0; i < n; i += 1) {
|
|
293
|
+
for (let j = 0; j < n; j += 1) centroid[j] += simplex[i][j]
|
|
294
|
+
}
|
|
295
|
+
for (let j = 0; j < n; j += 1) centroid[j] /= n
|
|
296
|
+
const worst = simplex[n]
|
|
297
|
+
const reflected = centroid.map((value, j) => value + (value - worst[j]))
|
|
298
|
+
const reflectedScore = fn(reflected)
|
|
299
|
+
if (reflectedScore < scores[n - 1] && reflectedScore >= scores[0]) {
|
|
300
|
+
simplex[n] = reflected
|
|
301
|
+
scores[n] = reflectedScore
|
|
302
|
+
continue
|
|
303
|
+
}
|
|
304
|
+
if (reflectedScore < scores[0]) {
|
|
305
|
+
const expanded = centroid.map((value, j) => value + 2 * (reflected[j] - value))
|
|
306
|
+
const expandedScore = fn(expanded)
|
|
307
|
+
if (expandedScore < reflectedScore) {
|
|
308
|
+
simplex[n] = expanded
|
|
309
|
+
scores[n] = expandedScore
|
|
310
|
+
} else {
|
|
311
|
+
simplex[n] = reflected
|
|
312
|
+
scores[n] = reflectedScore
|
|
313
|
+
}
|
|
314
|
+
continue
|
|
315
|
+
}
|
|
316
|
+
const contracted = centroid.map((value, j) => value + 0.5 * (worst[j] - value))
|
|
317
|
+
const contractedScore = fn(contracted)
|
|
318
|
+
if (contractedScore < scores[n]) {
|
|
319
|
+
simplex[n] = contracted
|
|
320
|
+
scores[n] = contractedScore
|
|
321
|
+
continue
|
|
322
|
+
}
|
|
323
|
+
for (let i = 1; i <= n; i += 1) {
|
|
324
|
+
simplex[i] = simplex[0].map((value, j) => value + 0.5 * (simplex[i][j] - value))
|
|
325
|
+
scores[i] = fn(simplex[i])
|
|
326
|
+
}
|
|
327
|
+
}
|
|
328
|
+
const best = scores.indexOf(Math.min(...scores))
|
|
329
|
+
return { x: simplex[best], fx: scores[best] }
|
|
330
|
+
}
|
package/index.js
ADDED
|
@@ -0,0 +1,15 @@
|
|
|
1
|
+
/*
|
|
2
|
+
* quantlib. Pricing, snapshot documents, and replay for a later Derive or Rysk plugin.
|
|
3
|
+
* Algorithms follow QuantLib. See LICENSE.
|
|
4
|
+
*/
|
|
5
|
+
|
|
6
|
+
export { yearFraction, black76, blackScholesMerton, dividendForForward } from './black.js'
|
|
7
|
+
export { binomial } from './binomial.js'
|
|
8
|
+
export { baroneAdesiWhaley } from './baroneAdesiWhaley.js'
|
|
9
|
+
export { hestonPrice, fitHeston, fellerHolds } from './heston.js'
|
|
10
|
+
export { readDeriveTicker, deriveSurface, priceDeriveChain, deriveHedgeDecision } from './derive.js'
|
|
11
|
+
export { ryskFairValue } from './rysk.js'
|
|
12
|
+
export { buildSpreads } from './spreads.js'
|
|
13
|
+
export { buildSnapshot, memoryStore, selectDocuments } from './store.js'
|
|
14
|
+
export { jsonlStore } from './jsonlStore.js'
|
|
15
|
+
export { replaySnapshots } from './replay.js'
|
package/jsonlStore.js
ADDED
|
@@ -0,0 +1,42 @@
|
|
|
1
|
+
/*
|
|
2
|
+
* JSONL store. The caller chooses the directory.
|
|
3
|
+
* One file per venue and underlying. Each line is one snapshot document.
|
|
4
|
+
*/
|
|
5
|
+
|
|
6
|
+
import { appendFile, mkdir, readFile } from 'node:fs/promises'
|
|
7
|
+
import { join } from 'node:path'
|
|
8
|
+
import { selectDocuments } from './store.js'
|
|
9
|
+
|
|
10
|
+
function safeName(value) {
|
|
11
|
+
return String(value ?? 'unknown').replace(/[^A-Za-z0-9._-]/g, '_')
|
|
12
|
+
}
|
|
13
|
+
|
|
14
|
+
function fileFor(dir, venue, underlying) {
|
|
15
|
+
return join(dir, safeName(venue), `${safeName(underlying)}.jsonl`)
|
|
16
|
+
}
|
|
17
|
+
|
|
18
|
+
export function jsonlStore(dir) {
|
|
19
|
+
return {
|
|
20
|
+
async append(document) {
|
|
21
|
+
const venue = document.venue ?? 'derive'
|
|
22
|
+
const file = fileFor(dir, venue, document.underlying)
|
|
23
|
+
await mkdir(join(dir, safeName(venue)), { recursive: true })
|
|
24
|
+
await appendFile(file, `${JSON.stringify(document)}\n`)
|
|
25
|
+
},
|
|
26
|
+
async load(query = {}) {
|
|
27
|
+
if (!query.venue || !query.underlying) {
|
|
28
|
+
throw new Error('load requires venue and underlying.')
|
|
29
|
+
}
|
|
30
|
+
const file = fileFor(dir, query.venue, query.underlying)
|
|
31
|
+
let text = ''
|
|
32
|
+
try {
|
|
33
|
+
text = await readFile(file, 'utf8')
|
|
34
|
+
} catch (err) {
|
|
35
|
+
if (err && err.code === 'ENOENT') return []
|
|
36
|
+
throw err
|
|
37
|
+
}
|
|
38
|
+
const docs = text.split('\n').filter((line) => line.trim()).map((line) => JSON.parse(line))
|
|
39
|
+
return selectDocuments(docs, query)
|
|
40
|
+
},
|
|
41
|
+
}
|
|
42
|
+
}
|
package/normal.js
ADDED
|
@@ -0,0 +1,19 @@
|
|
|
1
|
+
/*
|
|
2
|
+
* Standard normal helpers used by the Black formula.
|
|
3
|
+
* QuantLib: ql/math/distributions/normaldistribution.hpp
|
|
4
|
+
*/
|
|
5
|
+
|
|
6
|
+
export function normalPdf(x) {
|
|
7
|
+
return Math.exp(-0.5 * x * x) / Math.sqrt(2 * Math.PI)
|
|
8
|
+
}
|
|
9
|
+
|
|
10
|
+
/** Abramowitz and Stegun 26.2.17, absolute error below 7.5e-8. */
|
|
11
|
+
export function normalCdf(x) {
|
|
12
|
+
if (x < -8) return 0
|
|
13
|
+
if (x > 8) return 1
|
|
14
|
+
const z = Math.abs(x)
|
|
15
|
+
const t = 1 / (1 + 0.2316419 * z)
|
|
16
|
+
const d = normalPdf(z)
|
|
17
|
+
const p = d * t * (0.319381530 + t * (-0.356563782 + t * (1.781477937 + t * (-1.821255978 + t * 1.330274429))))
|
|
18
|
+
return x >= 0 ? 1 - p : p
|
|
19
|
+
}
|
package/package.json
CHANGED
|
@@ -1,6 +1,28 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@continuumdao/quantlib",
|
|
3
|
-
"version": "0.
|
|
4
|
-
"
|
|
5
|
-
"
|
|
6
|
-
|
|
3
|
+
"version": "0.1.0",
|
|
4
|
+
"description": "Option pricing and snapshot replay for Derive and Rysk. Black-76, binomial trees, and smile-gated Heston.",
|
|
5
|
+
"license": "BSD-3-Clause",
|
|
6
|
+
"type": "module",
|
|
7
|
+
"engines": {
|
|
8
|
+
"node": ">=18"
|
|
9
|
+
},
|
|
10
|
+
"exports": {
|
|
11
|
+
".": "./index.js"
|
|
12
|
+
},
|
|
13
|
+
"files": [
|
|
14
|
+
"*.js",
|
|
15
|
+
"LICENSE"
|
|
16
|
+
],
|
|
17
|
+
"repository": {
|
|
18
|
+
"type": "git",
|
|
19
|
+
"url": "git+https://github.com/Selqui/continuumdao-plugins.git",
|
|
20
|
+
"directory": "lib/quantlib"
|
|
21
|
+
},
|
|
22
|
+
"publishConfig": {
|
|
23
|
+
"access": "public"
|
|
24
|
+
},
|
|
25
|
+
"scripts": {
|
|
26
|
+
"test": "node --test test/*.test.js"
|
|
27
|
+
}
|
|
28
|
+
}
|