@fullstackcraftllc/floe 0.0.13 → 0.0.15
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/README.md +8 -8
- package/dist/client/FloeClient.d.ts +5 -1
- package/dist/client/FloeClient.js +54 -0
- package/dist/client/brokers/IBKRClient.d.ts +324 -0
- package/dist/client/brokers/IBKRClient.js +797 -0
- package/dist/client/brokers/TradierClient.js +7 -6
- package/dist/hedgeflow/charm.d.ts +23 -0
- package/dist/hedgeflow/charm.js +113 -0
- package/dist/hedgeflow/curve.d.ts +27 -0
- package/dist/hedgeflow/curve.js +315 -0
- package/dist/hedgeflow/index.d.ts +33 -0
- package/dist/hedgeflow/index.js +52 -0
- package/dist/hedgeflow/regime.d.ts +7 -0
- package/dist/hedgeflow/regime.js +99 -0
- package/dist/hedgeflow/types.d.ts +185 -0
- package/dist/hedgeflow/types.js +2 -0
- package/dist/impliedpdf/adjusted.d.ts +173 -0
- package/dist/impliedpdf/adjusted.js +500 -0
- package/dist/impliedpdf/index.d.ts +1 -0
- package/dist/impliedpdf/index.js +10 -0
- package/dist/index.d.ts +8 -2
- package/dist/index.js +27 -1
- package/dist/iv/index.d.ts +52 -0
- package/dist/iv/index.js +287 -0
- package/dist/iv/types.d.ts +40 -0
- package/dist/iv/types.js +2 -0
- package/dist/pressure/grid.d.ts +14 -0
- package/dist/pressure/grid.js +220 -0
- package/dist/pressure/index.d.ts +5 -0
- package/dist/pressure/index.js +22 -0
- package/dist/pressure/ivpath.d.ts +31 -0
- package/dist/pressure/ivpath.js +304 -0
- package/dist/pressure/normalize.d.ts +6 -0
- package/dist/pressure/normalize.js +76 -0
- package/dist/pressure/regime.d.ts +7 -0
- package/dist/pressure/regime.js +99 -0
- package/dist/pressure/types.d.ts +182 -0
- package/dist/pressure/types.js +2 -0
- package/dist/rv/index.d.ts +26 -0
- package/dist/rv/index.js +81 -0
- package/dist/rv/types.d.ts +32 -0
- package/dist/rv/types.js +2 -0
- package/dist/utils/indexOptions.js +2 -1
- package/package.json +1 -1
package/dist/iv/index.js
ADDED
|
@@ -0,0 +1,287 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
Object.defineProperty(exports, "__esModule", { value: true });
|
|
3
|
+
exports.computeVarianceSwapIV = computeVarianceSwapIV;
|
|
4
|
+
exports.computeImpliedVolatility = computeImpliedVolatility;
|
|
5
|
+
const types_1 = require("../types");
|
|
6
|
+
const blackscholes_1 = require("../blackscholes");
|
|
7
|
+
// ============================================================================
|
|
8
|
+
// Internal helpers
|
|
9
|
+
// ============================================================================
|
|
10
|
+
/**
|
|
11
|
+
* Compute ΔK for each strike: half the distance between adjacent strikes.
|
|
12
|
+
* For endpoints, use the distance to the single neighbor.
|
|
13
|
+
*/
|
|
14
|
+
function computeDeltaK(strikes) {
|
|
15
|
+
const deltaK = new Map();
|
|
16
|
+
if (strikes.length === 0)
|
|
17
|
+
return deltaK;
|
|
18
|
+
if (strikes.length === 1) {
|
|
19
|
+
deltaK.set(strikes[0], 1); // fallback
|
|
20
|
+
return deltaK;
|
|
21
|
+
}
|
|
22
|
+
for (let i = 0; i < strikes.length; i++) {
|
|
23
|
+
if (i === 0) {
|
|
24
|
+
deltaK.set(strikes[i], strikes[i + 1] - strikes[i]);
|
|
25
|
+
}
|
|
26
|
+
else if (i === strikes.length - 1) {
|
|
27
|
+
deltaK.set(strikes[i], strikes[i] - strikes[i - 1]);
|
|
28
|
+
}
|
|
29
|
+
else {
|
|
30
|
+
deltaK.set(strikes[i], (strikes[i + 1] - strikes[i - 1]) / 2);
|
|
31
|
+
}
|
|
32
|
+
}
|
|
33
|
+
return deltaK;
|
|
34
|
+
}
|
|
35
|
+
/**
|
|
36
|
+
* Group options by strike, pairing calls and puts.
|
|
37
|
+
*/
|
|
38
|
+
function pairOptionsByStrike(options) {
|
|
39
|
+
const pairs = new Map();
|
|
40
|
+
for (const opt of options) {
|
|
41
|
+
const existing = pairs.get(opt.strike) || {};
|
|
42
|
+
if (opt.optionType === 'call') {
|
|
43
|
+
existing.call = opt;
|
|
44
|
+
}
|
|
45
|
+
else {
|
|
46
|
+
existing.put = opt;
|
|
47
|
+
}
|
|
48
|
+
pairs.set(opt.strike, existing);
|
|
49
|
+
}
|
|
50
|
+
return pairs;
|
|
51
|
+
}
|
|
52
|
+
/**
|
|
53
|
+
* Get mid price for an option. Returns 0 if no valid quote.
|
|
54
|
+
*/
|
|
55
|
+
function midPrice(opt) {
|
|
56
|
+
if (!opt)
|
|
57
|
+
return 0;
|
|
58
|
+
if (opt.bid > 0 && opt.ask > 0)
|
|
59
|
+
return (opt.bid + opt.ask) / 2;
|
|
60
|
+
if (opt.mark > 0)
|
|
61
|
+
return opt.mark;
|
|
62
|
+
return 0;
|
|
63
|
+
}
|
|
64
|
+
/**
|
|
65
|
+
* Compute the model-free implied variance for a single expiration
|
|
66
|
+
* using the CBOE variance swap methodology.
|
|
67
|
+
*
|
|
68
|
+
* This implements the formula:
|
|
69
|
+
*
|
|
70
|
+
* σ² = (2/T) × Σᵢ (ΔKᵢ/Kᵢ²) × e^(rT) × Q(Kᵢ) - (1/T) × (F/K₀ - 1)²
|
|
71
|
+
*
|
|
72
|
+
* Where:
|
|
73
|
+
* - K₀ is the strike where |call_mid - put_mid| is minimized
|
|
74
|
+
* - F = K₀ + e^(rT) × (call(K₀) - put(K₀)) is the forward price
|
|
75
|
+
* - Q(Kᵢ) = put mid for Kᵢ < K₀, call mid for Kᵢ > K₀,
|
|
76
|
+
* average of call and put mids at K₀
|
|
77
|
+
* - ΔKᵢ = (Kᵢ₊₁ - Kᵢ₋₁) / 2 (actual strike spacing, not hardcoded)
|
|
78
|
+
*
|
|
79
|
+
* Two consecutive zero-bid options terminate the summation in each
|
|
80
|
+
* direction (puts walking down, calls walking up), per CBOE rules.
|
|
81
|
+
*
|
|
82
|
+
* @param options - All options for one expiration (calls and puts)
|
|
83
|
+
* @param spot - Current underlying price
|
|
84
|
+
* @param riskFreeRate - Annual risk-free rate as decimal (e.g. 0.05)
|
|
85
|
+
* @returns Variance swap result with annualized IV
|
|
86
|
+
*/
|
|
87
|
+
function computeVarianceSwapIV(options, spot, riskFreeRate) {
|
|
88
|
+
// Pair calls and puts by strike
|
|
89
|
+
const pairs = pairOptionsByStrike(options);
|
|
90
|
+
const strikes = Array.from(pairs.keys()).sort((a, b) => a - b);
|
|
91
|
+
if (strikes.length === 0) {
|
|
92
|
+
return emptyResult(spot);
|
|
93
|
+
}
|
|
94
|
+
// Use first option's expiration (all should be same expiry)
|
|
95
|
+
const expiration = options[0].expirationTimestamp;
|
|
96
|
+
const T = (0, blackscholes_1.getTimeToExpirationInYears)(expiration);
|
|
97
|
+
if (T <= 0) {
|
|
98
|
+
return emptyResult(spot);
|
|
99
|
+
}
|
|
100
|
+
const r = riskFreeRate;
|
|
101
|
+
const eRT = Math.exp(r * T);
|
|
102
|
+
// Step 1: Find K₀ — strike where |call_mid - put_mid| is minimized
|
|
103
|
+
// Only consider strikes within reasonable range of spot
|
|
104
|
+
let k0 = strikes[0];
|
|
105
|
+
let minDiff = Infinity;
|
|
106
|
+
let callAtK0 = 0;
|
|
107
|
+
let putAtK0 = 0;
|
|
108
|
+
for (const strike of strikes) {
|
|
109
|
+
const pair = pairs.get(strike);
|
|
110
|
+
const callMid = midPrice(pair.call);
|
|
111
|
+
const putMid = midPrice(pair.put);
|
|
112
|
+
if (callMid > 0 && putMid > 0) {
|
|
113
|
+
const diff = Math.abs(callMid - putMid);
|
|
114
|
+
if (diff < minDiff) {
|
|
115
|
+
minDiff = diff;
|
|
116
|
+
k0 = strike;
|
|
117
|
+
callAtK0 = callMid;
|
|
118
|
+
putAtK0 = putMid;
|
|
119
|
+
}
|
|
120
|
+
}
|
|
121
|
+
}
|
|
122
|
+
// Step 2: Forward price via put-call parity
|
|
123
|
+
const F = k0 + eRT * (callAtK0 - putAtK0);
|
|
124
|
+
// Step 3: Compute ΔK for each strike
|
|
125
|
+
const deltaKMap = computeDeltaK(strikes);
|
|
126
|
+
// Step 4: Sum OTM contributions
|
|
127
|
+
// Puts below K₀ (walk down, stop after two consecutive zero bids)
|
|
128
|
+
let putContribution = 0;
|
|
129
|
+
let callContribution = 0;
|
|
130
|
+
let numStrikes = 0;
|
|
131
|
+
// Put side: strikes ≤ K₀, walking downward from K₀
|
|
132
|
+
const putStrikes = strikes.filter(k => k <= k0).reverse(); // descending
|
|
133
|
+
let consecutiveZeroBids = 0;
|
|
134
|
+
for (const strike of putStrikes) {
|
|
135
|
+
const pair = pairs.get(strike);
|
|
136
|
+
const dk = deltaKMap.get(strike) || 1;
|
|
137
|
+
let Q = 0;
|
|
138
|
+
if (strike === k0) {
|
|
139
|
+
// At K₀: average of call and put
|
|
140
|
+
Q = (midPrice(pair.call) + midPrice(pair.put)) / 2;
|
|
141
|
+
}
|
|
142
|
+
else {
|
|
143
|
+
// Below K₀: use put
|
|
144
|
+
if (!pair.put || pair.put.bid === 0) {
|
|
145
|
+
consecutiveZeroBids++;
|
|
146
|
+
if (consecutiveZeroBids >= 2)
|
|
147
|
+
break;
|
|
148
|
+
continue;
|
|
149
|
+
}
|
|
150
|
+
consecutiveZeroBids = 0;
|
|
151
|
+
Q = midPrice(pair.put);
|
|
152
|
+
}
|
|
153
|
+
if (Q > 0) {
|
|
154
|
+
putContribution += (dk / (strike * strike)) * eRT * Q;
|
|
155
|
+
numStrikes++;
|
|
156
|
+
}
|
|
157
|
+
}
|
|
158
|
+
// Call side: strikes ≥ K₀, walking upward from K₀
|
|
159
|
+
const callStrikes = strikes.filter(k => k >= k0); // ascending
|
|
160
|
+
consecutiveZeroBids = 0;
|
|
161
|
+
for (const strike of callStrikes) {
|
|
162
|
+
const pair = pairs.get(strike);
|
|
163
|
+
const dk = deltaKMap.get(strike) || 1;
|
|
164
|
+
let Q = 0;
|
|
165
|
+
if (strike === k0) {
|
|
166
|
+
// Already counted in put side, skip to avoid double-counting
|
|
167
|
+
continue;
|
|
168
|
+
}
|
|
169
|
+
else {
|
|
170
|
+
// Above K₀: use call
|
|
171
|
+
if (!pair.call || pair.call.bid === 0) {
|
|
172
|
+
consecutiveZeroBids++;
|
|
173
|
+
if (consecutiveZeroBids >= 2)
|
|
174
|
+
break;
|
|
175
|
+
continue;
|
|
176
|
+
}
|
|
177
|
+
consecutiveZeroBids = 0;
|
|
178
|
+
Q = midPrice(pair.call);
|
|
179
|
+
}
|
|
180
|
+
if (Q > 0) {
|
|
181
|
+
callContribution += (dk / (strike * strike)) * eRT * Q;
|
|
182
|
+
numStrikes++;
|
|
183
|
+
}
|
|
184
|
+
}
|
|
185
|
+
// Step 5: Compute σ²
|
|
186
|
+
const totalContribution = putContribution + callContribution;
|
|
187
|
+
const variance = (2 / T) * totalContribution - (1 / T) * Math.pow(F / k0 - 1, 2);
|
|
188
|
+
// Guard against negative variance (can happen with bad data)
|
|
189
|
+
const clampedVariance = Math.max(0, variance);
|
|
190
|
+
const iv = Math.sqrt(clampedVariance);
|
|
191
|
+
return {
|
|
192
|
+
impliedVolatility: iv,
|
|
193
|
+
annualizedVariance: clampedVariance,
|
|
194
|
+
forward: F,
|
|
195
|
+
k0,
|
|
196
|
+
timeToExpiry: T,
|
|
197
|
+
expiration,
|
|
198
|
+
numStrikes,
|
|
199
|
+
putContribution,
|
|
200
|
+
callContribution,
|
|
201
|
+
};
|
|
202
|
+
}
|
|
203
|
+
/**
|
|
204
|
+
* Compute implied volatility from option prices using the CBOE
|
|
205
|
+
* variance swap methodology.
|
|
206
|
+
*
|
|
207
|
+
* If only nearTermOptions are provided, computes the single-expiration
|
|
208
|
+
* model-free implied volatility directly.
|
|
209
|
+
*
|
|
210
|
+
* If farTermOptions are also provided, performs CBOE VIX-style
|
|
211
|
+
* interpolation between the two terms to produce a constant-maturity
|
|
212
|
+
* measure at `targetDays` (defaults to the far term's DTE).
|
|
213
|
+
*
|
|
214
|
+
* The interpolation formula (in variance space):
|
|
215
|
+
*
|
|
216
|
+
* VIX = 100 × √{ [T₁σ₁² × (N₂ - N_target)/(N₂ - N₁)
|
|
217
|
+
* + T₂σ₂² × (N_target - N₁)/(N₂ - N₁)]
|
|
218
|
+
* × N_365 / N_target }
|
|
219
|
+
*
|
|
220
|
+
* @param nearTermOptions - Options for the near-term expiration
|
|
221
|
+
* @param spot - Current underlying price
|
|
222
|
+
* @param riskFreeRate - Annual risk-free rate as decimal
|
|
223
|
+
* @param farTermOptions - Options for the far-term expiration (optional)
|
|
224
|
+
* @param targetDays - Target constant maturity in days for interpolation
|
|
225
|
+
* (defaults to far term DTE if far term provided)
|
|
226
|
+
*/
|
|
227
|
+
function computeImpliedVolatility(nearTermOptions, spot, riskFreeRate, farTermOptions, targetDays) {
|
|
228
|
+
const nearResult = computeVarianceSwapIV(nearTermOptions, spot, riskFreeRate);
|
|
229
|
+
// Single-term mode
|
|
230
|
+
if (!farTermOptions || farTermOptions.length === 0) {
|
|
231
|
+
return {
|
|
232
|
+
impliedVolatility: nearResult.impliedVolatility,
|
|
233
|
+
nearTerm: nearResult,
|
|
234
|
+
farTerm: null,
|
|
235
|
+
targetDays: null,
|
|
236
|
+
isInterpolated: false,
|
|
237
|
+
};
|
|
238
|
+
}
|
|
239
|
+
// Two-term interpolation mode
|
|
240
|
+
const farResult = computeVarianceSwapIV(farTermOptions, spot, riskFreeRate);
|
|
241
|
+
const N1 = nearResult.timeToExpiry * types_1.MILLISECONDS_PER_YEAR; // near term ms
|
|
242
|
+
const N2 = farResult.timeToExpiry * types_1.MILLISECONDS_PER_YEAR; // far term ms
|
|
243
|
+
const T1 = nearResult.timeToExpiry;
|
|
244
|
+
const T2 = farResult.timeToExpiry;
|
|
245
|
+
const sigma1sq = nearResult.annualizedVariance;
|
|
246
|
+
const sigma2sq = farResult.annualizedVariance;
|
|
247
|
+
// Target in milliseconds
|
|
248
|
+
const N365 = types_1.MILLISECONDS_PER_YEAR;
|
|
249
|
+
const effectiveTargetDays = targetDays ?? Math.round(farResult.timeToExpiry * 365);
|
|
250
|
+
const Ntarget = effectiveTargetDays * (types_1.MILLISECONDS_PER_YEAR / 365);
|
|
251
|
+
// Guard: if near and far are the same expiration, just return near
|
|
252
|
+
if (Math.abs(N2 - N1) < 1) {
|
|
253
|
+
return {
|
|
254
|
+
impliedVolatility: nearResult.impliedVolatility,
|
|
255
|
+
nearTerm: nearResult,
|
|
256
|
+
farTerm: farResult,
|
|
257
|
+
targetDays: effectiveTargetDays,
|
|
258
|
+
isInterpolated: false,
|
|
259
|
+
};
|
|
260
|
+
}
|
|
261
|
+
// CBOE interpolation in variance space
|
|
262
|
+
const weight1 = (N2 - Ntarget) / (N2 - N1);
|
|
263
|
+
const weight2 = (Ntarget - N1) / (N2 - N1);
|
|
264
|
+
const interpolatedVariance = (T1 * sigma1sq * weight1 + T2 * sigma2sq * weight2) * (N365 / Ntarget);
|
|
265
|
+
const clampedVariance = Math.max(0, interpolatedVariance);
|
|
266
|
+
const iv = Math.sqrt(clampedVariance);
|
|
267
|
+
return {
|
|
268
|
+
impliedVolatility: iv,
|
|
269
|
+
nearTerm: nearResult,
|
|
270
|
+
farTerm: farResult,
|
|
271
|
+
targetDays: effectiveTargetDays,
|
|
272
|
+
isInterpolated: true,
|
|
273
|
+
};
|
|
274
|
+
}
|
|
275
|
+
function emptyResult(spot) {
|
|
276
|
+
return {
|
|
277
|
+
impliedVolatility: 0,
|
|
278
|
+
annualizedVariance: 0,
|
|
279
|
+
forward: spot,
|
|
280
|
+
k0: spot,
|
|
281
|
+
timeToExpiry: 0,
|
|
282
|
+
expiration: 0,
|
|
283
|
+
numStrikes: 0,
|
|
284
|
+
putContribution: 0,
|
|
285
|
+
callContribution: 0,
|
|
286
|
+
};
|
|
287
|
+
}
|
|
@@ -0,0 +1,40 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Result of computing model-free implied variance for a single expiration
|
|
3
|
+
* using the CBOE variance swap methodology.
|
|
4
|
+
*/
|
|
5
|
+
export interface VarianceSwapResult {
|
|
6
|
+
/** Annualized implied volatility as decimal (e.g. 0.20 = 20%) */
|
|
7
|
+
impliedVolatility: number;
|
|
8
|
+
/** Annualized variance σ² */
|
|
9
|
+
annualizedVariance: number;
|
|
10
|
+
/** Forward price F derived from put-call parity at K₀ */
|
|
11
|
+
forward: number;
|
|
12
|
+
/** At-the-money strike K₀ (strike where |call - put| is minimized) */
|
|
13
|
+
k0: number;
|
|
14
|
+
/** Time to expiry in years */
|
|
15
|
+
timeToExpiry: number;
|
|
16
|
+
/** Expiration timestamp (ms) */
|
|
17
|
+
expiration: number;
|
|
18
|
+
/** Number of strikes that contributed to the variance sum */
|
|
19
|
+
numStrikes: number;
|
|
20
|
+
/** Total put-side contribution to variance */
|
|
21
|
+
putContribution: number;
|
|
22
|
+
/** Total call-side contribution to variance */
|
|
23
|
+
callContribution: number;
|
|
24
|
+
}
|
|
25
|
+
/**
|
|
26
|
+
* Result of computing implied volatility, either single-term or
|
|
27
|
+
* interpolated between two terms (CBOE VIX-style).
|
|
28
|
+
*/
|
|
29
|
+
export interface ImpliedVolatilityResult {
|
|
30
|
+
/** Final annualized implied volatility as decimal */
|
|
31
|
+
impliedVolatility: number;
|
|
32
|
+
/** Near-term (or only-term) variance swap result */
|
|
33
|
+
nearTerm: VarianceSwapResult;
|
|
34
|
+
/** Far-term variance swap result, if two terms provided */
|
|
35
|
+
farTerm: VarianceSwapResult | null;
|
|
36
|
+
/** Target days for interpolation (null if single-term) */
|
|
37
|
+
targetDays: number | null;
|
|
38
|
+
/** Whether the result is interpolated between two terms */
|
|
39
|
+
isInterpolated: boolean;
|
|
40
|
+
}
|
package/dist/iv/types.js
ADDED
|
@@ -0,0 +1,14 @@
|
|
|
1
|
+
import { OptionChain, IVSurface, ExposurePerExpiry } from '../types';
|
|
2
|
+
import { RegimeParams, HedgingPressure, PressureGrid } from './types';
|
|
3
|
+
/**
|
|
4
|
+
* Calculate hedging pressure at a specific (spot, time) point
|
|
5
|
+
*/
|
|
6
|
+
export declare function calculatePressureAt(spot: number, timeToExpiry: number, exposures: ExposurePerExpiry, regimeParams: RegimeParams): HedgingPressure;
|
|
7
|
+
/**
|
|
8
|
+
* Build a complete pressure grid for visualization
|
|
9
|
+
*/
|
|
10
|
+
export declare function buildPressureGrid(symbol: string, chain: OptionChain, exposures: ExposurePerExpiry, ivSurface: IVSurface, options?: {
|
|
11
|
+
spotRangePercent?: number;
|
|
12
|
+
spotStepPercent?: number;
|
|
13
|
+
timeStepMinutes?: number;
|
|
14
|
+
}): PressureGrid;
|
|
@@ -0,0 +1,220 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
Object.defineProperty(exports, "__esModule", { value: true });
|
|
3
|
+
exports.calculatePressureAt = calculatePressureAt;
|
|
4
|
+
exports.buildPressureGrid = buildPressureGrid;
|
|
5
|
+
const types_1 = require("../types");
|
|
6
|
+
const regime_1 = require("./regime");
|
|
7
|
+
/**
|
|
8
|
+
* Calculate hedging pressure at a specific (spot, time) point
|
|
9
|
+
*/
|
|
10
|
+
function calculatePressureAt(spot, timeToExpiry, exposures, regimeParams) {
|
|
11
|
+
const { expectedDailySpotMove, expectedDailyVolMove, impliedSpotVolCorr, regime } = regimeParams;
|
|
12
|
+
let gammaFlow = 0;
|
|
13
|
+
let vannaFlow = 0;
|
|
14
|
+
let charmFlow = 0;
|
|
15
|
+
for (const strike of exposures.strikeExposures) {
|
|
16
|
+
const gammaContrib = strike.gammaExposure * Math.pow(expectedDailySpotMove, 2);
|
|
17
|
+
gammaFlow += gammaContrib;
|
|
18
|
+
const corrAmplifier = 1 + Math.abs(impliedSpotVolCorr);
|
|
19
|
+
const vannaContrib = strike.vannaExposure * expectedDailySpotMove * expectedDailyVolMove * corrAmplifier;
|
|
20
|
+
vannaFlow += vannaContrib;
|
|
21
|
+
const daysToExpiry = timeToExpiry * 252;
|
|
22
|
+
const charmContrib = strike.charmExposure * Math.min(daysToExpiry, 1);
|
|
23
|
+
charmFlow += charmContrib;
|
|
24
|
+
}
|
|
25
|
+
const netPressure = gammaFlow + vannaFlow + charmFlow;
|
|
26
|
+
const regimeWeights = {
|
|
27
|
+
calm: { gamma: 0.3, vanna: 0.1, charm: 0.6 },
|
|
28
|
+
normal: { gamma: 0.4, vanna: 0.2, charm: 0.4 },
|
|
29
|
+
stressed: { gamma: 0.35, vanna: 0.4, charm: 0.25 },
|
|
30
|
+
crisis: { gamma: 0.25, vanna: 0.6, charm: 0.15 },
|
|
31
|
+
};
|
|
32
|
+
const w = regimeWeights[regime];
|
|
33
|
+
const effectivePressure = gammaFlow * w.gamma + vannaFlow * w.vanna + charmFlow * w.charm;
|
|
34
|
+
let direction = 'neutral';
|
|
35
|
+
const threshold = Math.abs(effectivePressure) * 0.1;
|
|
36
|
+
if (effectivePressure > threshold) {
|
|
37
|
+
direction = 'supportive';
|
|
38
|
+
}
|
|
39
|
+
else if (effectivePressure < -threshold) {
|
|
40
|
+
direction = 'resistive';
|
|
41
|
+
}
|
|
42
|
+
const hoursRemaining = timeToExpiry * 252 * 6.5;
|
|
43
|
+
return {
|
|
44
|
+
spot,
|
|
45
|
+
timeToExpiry,
|
|
46
|
+
hoursRemaining,
|
|
47
|
+
gammaFlow,
|
|
48
|
+
vannaFlow,
|
|
49
|
+
charmFlow,
|
|
50
|
+
netPressure,
|
|
51
|
+
effectivePressure,
|
|
52
|
+
direction,
|
|
53
|
+
};
|
|
54
|
+
}
|
|
55
|
+
/**
|
|
56
|
+
* Build a complete pressure grid for visualization
|
|
57
|
+
*/
|
|
58
|
+
function buildPressureGrid(symbol, chain, exposures, ivSurface, options = {}) {
|
|
59
|
+
const { spotRangePercent = 2, spotStepPercent = 0.1, timeStepMinutes = 15, } = options;
|
|
60
|
+
const spot = chain.spot;
|
|
61
|
+
const expiration = exposures.expiration;
|
|
62
|
+
const timeToExpiry = (expiration - Date.now()) / types_1.MILLISECONDS_PER_YEAR;
|
|
63
|
+
const regimeParams = (0, regime_1.deriveRegimeParams)(ivSurface, spot);
|
|
64
|
+
const spotMin = spot * (1 - spotRangePercent / 100);
|
|
65
|
+
const spotMax = spot * (1 + spotRangePercent / 100);
|
|
66
|
+
const spotStep = spot * (spotStepPercent / 100);
|
|
67
|
+
const hoursRemaining = timeToExpiry * 252 * 6.5;
|
|
68
|
+
const timeMin = 0;
|
|
69
|
+
const timeMax = Math.max(hoursRemaining, 0.25);
|
|
70
|
+
const timeStep = timeStepMinutes / 60;
|
|
71
|
+
const cells = [];
|
|
72
|
+
const spotLevels = [];
|
|
73
|
+
const timeLevels = [];
|
|
74
|
+
for (let s = spotMin; s <= spotMax; s += spotStep) {
|
|
75
|
+
spotLevels.push(s);
|
|
76
|
+
}
|
|
77
|
+
for (let t = timeMax; t >= timeMin; t -= timeStep) {
|
|
78
|
+
timeLevels.push(t);
|
|
79
|
+
}
|
|
80
|
+
for (let i = 0; i < spotLevels.length; i++) {
|
|
81
|
+
cells[i] = [];
|
|
82
|
+
const s = spotLevels[i];
|
|
83
|
+
for (let j = 0; j < timeLevels.length; j++) {
|
|
84
|
+
const hoursLeft = timeLevels[j];
|
|
85
|
+
const t = hoursLeft / (252 * 6.5);
|
|
86
|
+
const pressure = calculatePressureAt(s, t, exposures, regimeParams);
|
|
87
|
+
cells[i][j] = {
|
|
88
|
+
spot: s,
|
|
89
|
+
hoursRemaining: hoursLeft,
|
|
90
|
+
pressure,
|
|
91
|
+
spotGradient: 0,
|
|
92
|
+
timeGradient: 0,
|
|
93
|
+
};
|
|
94
|
+
}
|
|
95
|
+
}
|
|
96
|
+
computeGradients(cells, spotStep, timeStep);
|
|
97
|
+
const keyLevels = findKeyLevels(cells, spotLevels, exposures);
|
|
98
|
+
const pathOfLeastResistance = computePathOfLeastResistance(cells, spotLevels, spot);
|
|
99
|
+
return {
|
|
100
|
+
symbol,
|
|
101
|
+
expiration,
|
|
102
|
+
currentSpot: spot,
|
|
103
|
+
timestamp: Date.now(),
|
|
104
|
+
regime: regimeParams.regime,
|
|
105
|
+
spotRange: { min: spotMin, max: spotMax, step: spotStep },
|
|
106
|
+
timeRange: { min: timeMin, max: timeMax, step: timeStep },
|
|
107
|
+
cells,
|
|
108
|
+
keyLevels,
|
|
109
|
+
pathOfLeastResistance,
|
|
110
|
+
};
|
|
111
|
+
}
|
|
112
|
+
function computeGradients(cells, spotStep, timeStep) {
|
|
113
|
+
const numSpot = cells.length;
|
|
114
|
+
const numTime = cells[0]?.length ?? 0;
|
|
115
|
+
for (let i = 0; i < numSpot; i++) {
|
|
116
|
+
for (let j = 0; j < numTime; j++) {
|
|
117
|
+
if (i > 0 && i < numSpot - 1) {
|
|
118
|
+
cells[i][j].spotGradient =
|
|
119
|
+
(cells[i + 1][j].pressure.effectivePressure - cells[i - 1][j].pressure.effectivePressure) /
|
|
120
|
+
(2 * spotStep);
|
|
121
|
+
}
|
|
122
|
+
if (j > 0 && j < numTime - 1) {
|
|
123
|
+
cells[i][j].timeGradient =
|
|
124
|
+
(cells[i][j + 1].pressure.effectivePressure - cells[i][j - 1].pressure.effectivePressure) /
|
|
125
|
+
(2 * timeStep);
|
|
126
|
+
}
|
|
127
|
+
}
|
|
128
|
+
}
|
|
129
|
+
}
|
|
130
|
+
function findKeyLevels(cells, spotLevels, exposures) {
|
|
131
|
+
const support = [];
|
|
132
|
+
const resistance = [];
|
|
133
|
+
const pinning = [];
|
|
134
|
+
let gammaFlip = null;
|
|
135
|
+
const currentSlice = cells.map(row => row[0]);
|
|
136
|
+
for (let i = 1; i < currentSlice.length; i++) {
|
|
137
|
+
const prev = currentSlice[i - 1].pressure.effectivePressure;
|
|
138
|
+
const curr = currentSlice[i].pressure.effectivePressure;
|
|
139
|
+
if (prev < 0 && curr >= 0) {
|
|
140
|
+
support.push((spotLevels[i - 1] + spotLevels[i]) / 2);
|
|
141
|
+
}
|
|
142
|
+
else if (prev >= 0 && curr < 0) {
|
|
143
|
+
resistance.push((spotLevels[i - 1] + spotLevels[i]) / 2);
|
|
144
|
+
}
|
|
145
|
+
}
|
|
146
|
+
for (const strike of exposures.strikeExposures) {
|
|
147
|
+
if (strike.gammaExposure > 0 && strike.gammaExposure > exposures.totalGammaExposure * 0.1) {
|
|
148
|
+
pinning.push(strike.strikePrice);
|
|
149
|
+
}
|
|
150
|
+
}
|
|
151
|
+
return { support, resistance, pinning, gammaFlip };
|
|
152
|
+
}
|
|
153
|
+
function computePathOfLeastResistance(cells, spotLevels, currentSpot) {
|
|
154
|
+
let currentSpotIdx = 0;
|
|
155
|
+
let minDist = Infinity;
|
|
156
|
+
for (let i = 0; i < spotLevels.length; i++) {
|
|
157
|
+
const dist = Math.abs(spotLevels[i] - currentSpot);
|
|
158
|
+
if (dist < minDist) {
|
|
159
|
+
minDist = dist;
|
|
160
|
+
currentSpotIdx = i;
|
|
161
|
+
}
|
|
162
|
+
}
|
|
163
|
+
const pressureAbove = [];
|
|
164
|
+
const pressureBelow = [];
|
|
165
|
+
for (let i = currentSpotIdx + 1; i < spotLevels.length; i++) {
|
|
166
|
+
pressureAbove.push(cells[i][0].pressure.effectivePressure);
|
|
167
|
+
}
|
|
168
|
+
for (let i = currentSpotIdx - 1; i >= 0; i--) {
|
|
169
|
+
pressureBelow.push(cells[i][0].pressure.effectivePressure);
|
|
170
|
+
}
|
|
171
|
+
const avgPressureAbove = pressureAbove.length > 0
|
|
172
|
+
? pressureAbove.reduce((a, b) => a + b, 0) / pressureAbove.length
|
|
173
|
+
: 0;
|
|
174
|
+
const avgPressureBelow = pressureBelow.length > 0
|
|
175
|
+
? pressureBelow.reduce((a, b) => a + b, 0) / pressureBelow.length
|
|
176
|
+
: 0;
|
|
177
|
+
const currentPressure = cells[currentSpotIdx][0].pressure.effectivePressure;
|
|
178
|
+
let direction = 'pin';
|
|
179
|
+
let targetSpot = currentSpot;
|
|
180
|
+
let confidence = 0;
|
|
181
|
+
let rationale = '';
|
|
182
|
+
if (currentPressure > 0 && Math.abs(currentPressure) > Math.abs(avgPressureAbove) &&
|
|
183
|
+
Math.abs(currentPressure) > Math.abs(avgPressureBelow)) {
|
|
184
|
+
direction = 'pin';
|
|
185
|
+
targetSpot = currentSpot;
|
|
186
|
+
confidence = Math.min(1, Math.abs(currentPressure) / (Math.abs(avgPressureAbove) + Math.abs(avgPressureBelow) + 1));
|
|
187
|
+
rationale = `Strong positive gamma at current level suggests pinning`;
|
|
188
|
+
}
|
|
189
|
+
else if (avgPressureAbove > 0 && avgPressureBelow < 0) {
|
|
190
|
+
direction = 'up';
|
|
191
|
+
for (let i = currentSpotIdx + 1; i < spotLevels.length; i++) {
|
|
192
|
+
if (cells[i][0].pressure.effectivePressure < 0) {
|
|
193
|
+
targetSpot = spotLevels[i];
|
|
194
|
+
break;
|
|
195
|
+
}
|
|
196
|
+
targetSpot = spotLevels[i];
|
|
197
|
+
}
|
|
198
|
+
confidence = Math.min(1, (avgPressureAbove - avgPressureBelow) / (Math.abs(avgPressureAbove) + Math.abs(avgPressureBelow) + 1));
|
|
199
|
+
rationale = `Supportive pressure above vs resistive below`;
|
|
200
|
+
}
|
|
201
|
+
else if (avgPressureAbove < 0 && avgPressureBelow > 0) {
|
|
202
|
+
direction = 'down';
|
|
203
|
+
for (let i = currentSpotIdx - 1; i >= 0; i--) {
|
|
204
|
+
if (cells[i][0].pressure.effectivePressure > 0) {
|
|
205
|
+
targetSpot = spotLevels[i];
|
|
206
|
+
break;
|
|
207
|
+
}
|
|
208
|
+
targetSpot = spotLevels[i];
|
|
209
|
+
}
|
|
210
|
+
confidence = Math.min(1, (avgPressureBelow - avgPressureAbove) / (Math.abs(avgPressureAbove) + Math.abs(avgPressureBelow) + 1));
|
|
211
|
+
rationale = `Resistive pressure above vs supportive below`;
|
|
212
|
+
}
|
|
213
|
+
else {
|
|
214
|
+
direction = 'pin';
|
|
215
|
+
targetSpot = currentSpot;
|
|
216
|
+
confidence = 0.3;
|
|
217
|
+
rationale = `Mixed pressure signals; defaulting to pin hypothesis`;
|
|
218
|
+
}
|
|
219
|
+
return { direction, targetSpot, confidence, rationale };
|
|
220
|
+
}
|
|
@@ -0,0 +1,5 @@
|
|
|
1
|
+
export type { MarketRegime, RegimeParams, NormalizedExposure, NormalizedExposureSummary, HedgingPressure, PressureGridCell, KeyLevels, PathOfLeastResistance, PressureGrid, StrikeIVPressure, IVSurfaceEvolution, CascadeStep, CascadeSimulation, IVPathConfig, } from './types';
|
|
2
|
+
export { deriveRegimeParams, interpolateIVAtStrike } from './regime';
|
|
3
|
+
export { normalizeExposures } from './normalize';
|
|
4
|
+
export { calculatePressureAt, buildPressureGrid } from './grid';
|
|
5
|
+
export { calculateIVPressures, predictIVSurfaceEvolution, runCascadeSimulation, analyzeIVPath, getIVPathOfLeastResistance, DEFAULT_IV_PATH_CONFIG, } from './ivpath';
|
|
@@ -0,0 +1,22 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
Object.defineProperty(exports, "__esModule", { value: true });
|
|
3
|
+
exports.DEFAULT_IV_PATH_CONFIG = exports.getIVPathOfLeastResistance = exports.analyzeIVPath = exports.runCascadeSimulation = exports.predictIVSurfaceEvolution = exports.calculateIVPressures = exports.buildPressureGrid = exports.calculatePressureAt = exports.normalizeExposures = exports.interpolateIVAtStrike = exports.deriveRegimeParams = void 0;
|
|
4
|
+
// Regime derivation
|
|
5
|
+
var regime_1 = require("./regime");
|
|
6
|
+
Object.defineProperty(exports, "deriveRegimeParams", { enumerable: true, get: function () { return regime_1.deriveRegimeParams; } });
|
|
7
|
+
Object.defineProperty(exports, "interpolateIVAtStrike", { enumerable: true, get: function () { return regime_1.interpolateIVAtStrike; } });
|
|
8
|
+
// Exposure normalization
|
|
9
|
+
var normalize_1 = require("./normalize");
|
|
10
|
+
Object.defineProperty(exports, "normalizeExposures", { enumerable: true, get: function () { return normalize_1.normalizeExposures; } });
|
|
11
|
+
// Pressure field
|
|
12
|
+
var grid_1 = require("./grid");
|
|
13
|
+
Object.defineProperty(exports, "calculatePressureAt", { enumerable: true, get: function () { return grid_1.calculatePressureAt; } });
|
|
14
|
+
Object.defineProperty(exports, "buildPressureGrid", { enumerable: true, get: function () { return grid_1.buildPressureGrid; } });
|
|
15
|
+
// IV path prediction
|
|
16
|
+
var ivpath_1 = require("./ivpath");
|
|
17
|
+
Object.defineProperty(exports, "calculateIVPressures", { enumerable: true, get: function () { return ivpath_1.calculateIVPressures; } });
|
|
18
|
+
Object.defineProperty(exports, "predictIVSurfaceEvolution", { enumerable: true, get: function () { return ivpath_1.predictIVSurfaceEvolution; } });
|
|
19
|
+
Object.defineProperty(exports, "runCascadeSimulation", { enumerable: true, get: function () { return ivpath_1.runCascadeSimulation; } });
|
|
20
|
+
Object.defineProperty(exports, "analyzeIVPath", { enumerable: true, get: function () { return ivpath_1.analyzeIVPath; } });
|
|
21
|
+
Object.defineProperty(exports, "getIVPathOfLeastResistance", { enumerable: true, get: function () { return ivpath_1.getIVPathOfLeastResistance; } });
|
|
22
|
+
Object.defineProperty(exports, "DEFAULT_IV_PATH_CONFIG", { enumerable: true, get: function () { return ivpath_1.DEFAULT_IV_PATH_CONFIG; } });
|
|
@@ -0,0 +1,31 @@
|
|
|
1
|
+
import { IVSurface, ExposurePerExpiry } from '../types';
|
|
2
|
+
import { RegimeParams, StrikeIVPressure, IVSurfaceEvolution, CascadeSimulation, IVPathConfig } from './types';
|
|
3
|
+
export declare const DEFAULT_IV_PATH_CONFIG: IVPathConfig;
|
|
4
|
+
/**
|
|
5
|
+
* Calculate IV pressure at each strike based on dealer positioning
|
|
6
|
+
*/
|
|
7
|
+
export declare function calculateIVPressures(ivSurface: IVSurface, exposures: ExposurePerExpiry, regimeParams: RegimeParams, spotMove: number, config?: Partial<IVPathConfig>): StrikeIVPressure[];
|
|
8
|
+
/**
|
|
9
|
+
* Predict how the IV surface will evolve given dealer positioning
|
|
10
|
+
*/
|
|
11
|
+
export declare function predictIVSurfaceEvolution(ivSurface: IVSurface, exposures: ExposurePerExpiry, spot: number, spotMoveScenario?: number, config?: Partial<IVPathConfig>): IVSurfaceEvolution;
|
|
12
|
+
/**
|
|
13
|
+
* Run a cascade simulation showing feedback loops
|
|
14
|
+
*/
|
|
15
|
+
export declare function runCascadeSimulation(ivSurface: IVSurface, exposures: ExposurePerExpiry, spot: number, spotShock?: number, config?: Partial<IVPathConfig>): CascadeSimulation;
|
|
16
|
+
/**
|
|
17
|
+
* Analyze IV path for multiple spot scenarios
|
|
18
|
+
*/
|
|
19
|
+
export declare function analyzeIVPath(ivSurface: IVSurface, exposures: ExposurePerExpiry, spot: number, options?: {
|
|
20
|
+
spotScenarios?: number[];
|
|
21
|
+
config?: Partial<IVPathConfig>;
|
|
22
|
+
}): Map<number, IVSurfaceEvolution>;
|
|
23
|
+
/**
|
|
24
|
+
* Get the IV path of least resistance
|
|
25
|
+
*/
|
|
26
|
+
export declare function getIVPathOfLeastResistance(ivSurface: IVSurface, exposures: ExposurePerExpiry, spot: number): {
|
|
27
|
+
direction: 'up' | 'down' | 'stable';
|
|
28
|
+
magnitude: number;
|
|
29
|
+
confidence: number;
|
|
30
|
+
rationale: string;
|
|
31
|
+
};
|