sipQuant 1.0.0__py3-none-any.whl

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.
sipQuant/__init__.py ADDED
@@ -0,0 +1,58 @@
1
+ """
2
+ sipQuant — Quantitative library for physically-settled commodity markets.
3
+ SIP Global (Systematic Index Partners)
4
+
5
+ Pure NumPy. No pandas, scipy, or external dependencies.
6
+
7
+ Modules
8
+ -------
9
+ schema : Data contract layer — validated input containers.
10
+ options : Option pricing: Black-Scholes, binomial, trinomial, barrier, spread, Monte Carlo.
11
+ econometrics: OLS, robust regression, stationarity tests, structural break tests.
12
+ sim : Price process simulation: GBM, OU, Lévy-OU, GARCH, Heston, ARMA.
13
+ fit : Model calibration: OU, Lévy-OU, GARCH, Heston, copula, distribution fitting.
14
+ bootstrap : Curve and surface construction: forward curves, discount curves, vol surfaces.
15
+ portfolio : Portfolio optimisation: mean-variance, HRP, risk parity, Black-Litterman.
16
+ risk : Risk metrics: VaR, CVaR, drawdown, Sortino, Calmar, Hill estimator.
17
+ distributions: Distribution fitting: normal, lognormal, t, gamma, copulas.
18
+ dimension : Dimensionality reduction: PCA, kernel PCA, t-SNE, ICA.
19
+ factor : Factor models: CAPM, rolling beta, PCA factors.
20
+ ml : Machine learning: regression trees, random forest, gradient boosting, k-means.
21
+ commodity : Physical commodity pricing: seasonality, convenience yield, basis, grade adjustment.
22
+ otc : OTC instrument pricing: swaps, Asian swaps, collars, physical forwards, swaptions.
23
+ book : Dealer book: net Greeks, hedge ratios, P&L attribution, scenario shocks.
24
+ index : Index construction, calculation, audit trail, IOSCO-aligned methodology.
25
+ liquidity : Thin-market risk: liquidity-adjusted VaR, market impact, optimal execution.
26
+
27
+ Usage
28
+ -----
29
+ import sipQuant as sq
30
+
31
+ # Namespaced access
32
+ result = sq.options.blackScholes(S=100, K=100, T=1, r=0.05, sigma=0.2)
33
+ swap = sq.otc.commoditySwap(fixedPrice=142.0, indexCurve=curve, notional=500, schedule=sched, r=0.045)
34
+ ps = sq.schema.PriceSeries(dates, values, source='broker_a', market='alberta_hay')
35
+ """
36
+
37
+ from . import schema
38
+ from . import options
39
+ from . import econometrics
40
+ from . import sim
41
+ from . import bootstrap
42
+ from . import portfolio
43
+ from . import risk
44
+ from . import distributions
45
+ from . import dimension
46
+ from . import factor
47
+ from . import commodity
48
+ from . import otc
49
+ from . import book
50
+ from . import index
51
+ from . import liquidity
52
+
53
+ from . import ml
54
+ from . import fit
55
+
56
+ __version__ = '1.0.0'
57
+ __author__ = 'SIP Global — Systematic Index Partners'
58
+ __license__ = 'MIT'
sipQuant/book.py ADDED
@@ -0,0 +1,350 @@
1
+ import numpy as np
2
+
3
+ # ---------------------------------------------------------------------------
4
+ # sipQuant — book.py
5
+ # OTC dealer book aggregation: net Greeks, hedge ratios, P&L attribution,
6
+ # scenario analysis, book summary, and margin estimation.
7
+ # Pure NumPy. No external dependencies.
8
+ # ---------------------------------------------------------------------------
9
+
10
+ _LONG_DIRECTIONS = frozenset({'buy', 'long', 'receive_fixed'})
11
+ _SHORT_DIRECTIONS = frozenset({'sell', 'short', 'pay_fixed'})
12
+
13
+
14
+ def _directionSign(direction):
15
+ """Return +1 for long/buy/receive_fixed, -1 for short/sell/pay_fixed."""
16
+ d = str(direction).lower()
17
+ if d in _LONG_DIRECTIONS:
18
+ return 1.0
19
+ if d in _SHORT_DIRECTIONS:
20
+ return -1.0
21
+ raise ValueError(f"Unrecognised direction '{direction}'.")
22
+
23
+
24
+ def netGreeks(positions):
25
+ """Aggregate Greeks across all OTC positions in the book.
26
+
27
+ Parameters
28
+ ----------
29
+ positions : list of dict
30
+ List of OTCPosition dicts (from schema.py). Each must have a 'greeks'
31
+ dict with keys 'delta', 'gamma', 'vega', 'theta', 'rho', a 'notional'
32
+ float, and a 'direction' string.
33
+
34
+ Returns
35
+ -------
36
+ dict
37
+ Keys: 'delta', 'gamma', 'vega', 'theta', 'rho' — net signed Greeks
38
+ aggregated across all positions, scaled by notional and direction.
39
+
40
+ Notes
41
+ -----
42
+ Direction sign convention: buy/long/receive_fixed = +1,
43
+ sell/short/pay_fixed = -1.
44
+ Each Greek contribution = greek * notional * direction_sign.
45
+ """
46
+ delta = 0.0
47
+ gamma = 0.0
48
+ vega = 0.0
49
+ theta = 0.0
50
+ rho = 0.0
51
+
52
+ for pos in positions:
53
+ sign = _directionSign(pos['direction'])
54
+ notional = float(pos['notional'])
55
+ g = pos['greeks']
56
+ delta += g['delta'] * notional * sign
57
+ gamma += g['gamma'] * notional * sign
58
+ vega += g['vega'] * notional * sign
59
+ theta += g['theta'] * notional * sign
60
+ rho += g['rho'] * notional * sign
61
+
62
+ return {
63
+ 'delta': delta,
64
+ 'gamma': gamma,
65
+ 'vega': vega,
66
+ 'theta': theta,
67
+ 'rho': rho,
68
+ }
69
+
70
+
71
+ def hedgeRatios(positions, hedgeInstrumentDelta):
72
+ """Compute number of hedge instruments needed to delta-hedge the book.
73
+
74
+ Parameters
75
+ ----------
76
+ positions : list of dict
77
+ List of OTCPosition dicts (from schema.py).
78
+ hedgeInstrumentDelta : float
79
+ Delta of one unit of the hedge instrument (e.g. 1.0 for a futures
80
+ contract, 0.5 for an at-the-money option).
81
+
82
+ Returns
83
+ -------
84
+ dict
85
+ Keys:
86
+
87
+ - 'hedgeUnits' : float — number of hedge instruments to transact
88
+ (negative = sell hedge, positive = buy hedge).
89
+ - 'netDelta' : float — book net delta before hedging.
90
+ - 'residualDelta' : float — delta remaining after rounding hedgeUnits
91
+ to nearest integer.
92
+
93
+ Notes
94
+ -----
95
+ hedgeUnits = -netDelta / hedgeInstrumentDelta.
96
+ residualDelta is computed using the rounded integer hedge units.
97
+ """
98
+ ng = netGreeks(positions)
99
+ netDelta = ng['delta']
100
+ hedgeInstrumentDelta = float(hedgeInstrumentDelta)
101
+
102
+ if hedgeInstrumentDelta == 0.0:
103
+ raise ValueError("hedgeInstrumentDelta cannot be zero.")
104
+
105
+ hedgeUnits = -netDelta / hedgeInstrumentDelta
106
+ roundedUnits = float(np.round(hedgeUnits))
107
+ residualDelta = netDelta + roundedUnits * hedgeInstrumentDelta
108
+
109
+ return {
110
+ 'hedgeUnits': hedgeUnits,
111
+ 'netDelta': netDelta,
112
+ 'residualDelta': residualDelta,
113
+ }
114
+
115
+
116
+ def pnlAttribution(positions, priceMoves, volMoves=None, timeDecay=None):
117
+ """P&L attribution using a first-order Taylor expansion per Greek component.
118
+
119
+ dPnL = delta*dS + 0.5*gamma*dS^2 + vega*dVol + theta*dT
120
+
121
+ Parameters
122
+ ----------
123
+ positions : list of dict
124
+ List of OTCPosition dicts (from schema.py). Each position must carry
125
+ a 'marketId' key or will default to 'default'.
126
+ priceMoves : dict
127
+ Mapping of {marketId: dS} price changes. Positions without a matching
128
+ marketId key fall back to key 'default' if present, else dS=0.
129
+ volMoves : dict, optional
130
+ Mapping of {marketId: dVol} implied-vol changes. Same fallback logic.
131
+ If None, vega contribution is zero.
132
+ timeDecay : float, optional
133
+ Number of calendar days elapsed. If None, theta contribution is zero.
134
+
135
+ Returns
136
+ -------
137
+ dict
138
+ Keys:
139
+
140
+ - 'totalPnL' : float
141
+ - 'deltaComponent' : float
142
+ - 'gammaComponent' : float
143
+ - 'vegaComponent' : float
144
+ - 'thetaComponent' : float
145
+ - 'totalByPosition' : np.ndarray — per-position total P&L.
146
+ """
147
+ if volMoves is None:
148
+ volMoves = {}
149
+ if timeDecay is None:
150
+ timeDecay = 0.0
151
+
152
+ timeDecay = float(timeDecay)
153
+
154
+ deltaComp = 0.0
155
+ gammaComp = 0.0
156
+ vegaComp = 0.0
157
+ thetaComp = 0.0
158
+ byPosition = np.zeros(len(positions))
159
+
160
+ for i, pos in enumerate(positions):
161
+ sign = _directionSign(pos['direction'])
162
+ notional = float(pos['notional'])
163
+ g = pos['greeks']
164
+ marketId = pos.get('marketId', 'default')
165
+
166
+ dS = priceMoves.get(marketId, priceMoves.get('default', 0.0))
167
+ dVol = volMoves.get(marketId, volMoves.get('default', 0.0))
168
+
169
+ d = sign * notional * g['delta'] * dS
170
+ gm = sign * notional * 0.5 * g['gamma'] * dS ** 2
171
+ v = sign * notional * g['vega'] * dVol
172
+ th = sign * notional * g['theta'] * timeDecay
173
+
174
+ deltaComp += d
175
+ gammaComp += gm
176
+ vegaComp += v
177
+ thetaComp += th
178
+ byPosition[i] = d + gm + v + th
179
+
180
+ totalPnL = deltaComp + gammaComp + vegaComp + thetaComp
181
+
182
+ return {
183
+ 'totalPnL': totalPnL,
184
+ 'deltaComponent': deltaComp,
185
+ 'gammaComponent': gammaComp,
186
+ 'vegaComponent': vegaComp,
187
+ 'thetaComponent': thetaComp,
188
+ 'totalByPosition': byPosition,
189
+ }
190
+
191
+
192
+ def scenarioShock(positions, scenarios):
193
+ """Apply scenario shocks to the book and estimate P&L impact.
194
+
195
+ Parameters
196
+ ----------
197
+ positions : list of dict
198
+ List of OTCPosition dicts (from schema.py).
199
+ scenarios : list of dict
200
+ Each scenario dict must contain:
201
+
202
+ - 'name' : str — scenario label.
203
+ - 'priceShock' : float — uniform price change dS applied to all markets.
204
+ - 'volShock' : float — uniform implied-vol change dVol applied to all
205
+ markets.
206
+
207
+ Returns
208
+ -------
209
+ dict
210
+ Keys:
211
+
212
+ - 'scenarioResults' : list of dicts, one per scenario, each with keys
213
+ 'name', 'pnl', 'deltaContrib', 'vegaContrib'.
214
+
215
+ Notes
216
+ -----
217
+ Gamma contribution is included in the per-scenario 'pnl' via the Taylor
218
+ expansion but is not separately reported. Delta and vega contributions are
219
+ isolated for transparency.
220
+ """
221
+ results = []
222
+
223
+ for scenario in scenarios:
224
+ name = scenario['name']
225
+ dS = float(scenario.get('priceShock', 0.0))
226
+ dVol = float(scenario.get('volShock', 0.0))
227
+
228
+ deltaCont = 0.0
229
+ vegaCont = 0.0
230
+ totalPnL = 0.0
231
+
232
+ for pos in positions:
233
+ sign = _directionSign(pos['direction'])
234
+ notional = float(pos['notional'])
235
+ g = pos['greeks']
236
+
237
+ d = sign * notional * g['delta'] * dS
238
+ gm = sign * notional * 0.5 * g['gamma'] * dS ** 2
239
+ v = sign * notional * g['vega'] * dVol
240
+
241
+ deltaCont += d
242
+ vegaCont += v
243
+ totalPnL += d + gm + v
244
+
245
+ results.append({
246
+ 'name': name,
247
+ 'pnl': totalPnL,
248
+ 'deltaContrib': deltaCont,
249
+ 'vegaContrib': vegaCont,
250
+ })
251
+
252
+ return {'scenarioResults': results}
253
+
254
+
255
+ def bookSummary(positions):
256
+ """Summarize book composition by instrument type and direction.
257
+
258
+ Parameters
259
+ ----------
260
+ positions : list of dict
261
+ List of OTCPosition dicts (from schema.py).
262
+
263
+ Returns
264
+ -------
265
+ dict
266
+ Keys:
267
+
268
+ - 'totalNotional' : float — sum of all position notionals.
269
+ - 'nPositions' : int — number of positions in the book.
270
+ - 'byInstrument' : dict — mapping of instrumentType to total notional.
271
+ - 'netGreeks' : dict — aggregated Greeks (see netGreeks).
272
+ - 'concentrationRisk' : float — maximum single-position fraction of
273
+ total notional (0 if book is empty).
274
+ """
275
+ if len(positions) == 0:
276
+ return {
277
+ 'totalNotional': 0.0,
278
+ 'nPositions': 0,
279
+ 'byInstrument': {},
280
+ 'netGreeks': {'delta': 0.0, 'gamma': 0.0, 'vega': 0.0,
281
+ 'theta': 0.0, 'rho': 0.0},
282
+ 'concentrationRisk': 0.0,
283
+ }
284
+
285
+ notionals = np.array([float(p['notional']) for p in positions])
286
+ totalNotional = float(np.sum(notionals))
287
+
288
+ byInstrument = {}
289
+ for pos in positions:
290
+ iType = str(pos.get('instrumentType', 'unknown'))
291
+ byInstrument[iType] = byInstrument.get(iType, 0.0) + float(pos['notional'])
292
+
293
+ concentrationRisk = float(np.max(notionals) / totalNotional) if totalNotional > 0 else 0.0
294
+
295
+ return {
296
+ 'totalNotional': totalNotional,
297
+ 'nPositions': len(positions),
298
+ 'byInstrument': byInstrument,
299
+ 'netGreeks': netGreeks(positions),
300
+ 'concentrationRisk': concentrationRisk,
301
+ }
302
+
303
+
304
+ def marginEstimate(positions, initialMarginRate=0.1, variationMarginBuffer=0.05):
305
+ """Estimate initial and variation margin requirements for the book.
306
+
307
+ Parameters
308
+ ----------
309
+ positions : list of dict
310
+ List of OTCPosition dicts (from schema.py).
311
+ initialMarginRate : float, optional
312
+ Fraction of notional applied to initial margin per unit of delta.
313
+ Default 0.10 (10%).
314
+ variationMarginBuffer : float, optional
315
+ Buffer multiplier applied to daily theta decay for variation margin.
316
+ Default 0.05 (5%).
317
+
318
+ Returns
319
+ -------
320
+ dict
321
+ Keys:
322
+
323
+ - 'initialMargin' : float — sum(notional * initialMarginRate * |delta|).
324
+ - 'variationMargin' : float — sum(|theta/252| * notional) *
325
+ variationMarginBuffer.
326
+ - 'totalMargin' : float — initialMargin + variationMargin.
327
+
328
+ Notes
329
+ -----
330
+ The daily theta decay uses a 252-trading-day convention.
331
+ Greeks are taken directly from each position's 'greeks' dict without
332
+ direction scaling — margin is always a positive quantity.
333
+ """
334
+ initialMargin = 0.0
335
+ variationMargin = 0.0
336
+
337
+ for pos in positions:
338
+ notional = float(pos['notional'])
339
+ g = pos['greeks']
340
+ initialMargin += notional * initialMarginRate * abs(g['delta'])
341
+ variationMargin += abs(g['theta'] / 252.0) * notional
342
+
343
+ variationMargin *= variationMarginBuffer
344
+ totalMargin = initialMargin + variationMargin
345
+
346
+ return {
347
+ 'initialMargin': initialMargin,
348
+ 'variationMargin': variationMargin,
349
+ 'totalMargin': totalMargin,
350
+ }