quanto-range-put 0.1.0__tar.gz

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.
@@ -0,0 +1,12 @@
1
+ Metadata-Version: 2.4
2
+ Name: quanto-range-put
3
+ Version: 0.1.0
4
+ Summary: Monte Carlo pricer for a USD quanto equity put with a quarterly SOFR range barrier (Hull-White rates).
5
+ Author: Nigel Li
6
+ Keywords: quanto,hull-white,monte-carlo,range-barrier,derivatives-pricing
7
+ Classifier: Programming Language :: Python :: 3
8
+ Classifier: Topic :: Office/Business :: Financial
9
+ Classifier: Intended Audience :: Financial and Insurance Industry
10
+ Requires-Python: >=3.10
11
+ Requires-Dist: numpy>=1.24
12
+ Requires-Dist: scipy>=1.10
@@ -0,0 +1,315 @@
1
+ """Monte Carlo pricer for a USD quanto put on the SX5E with a quarterly SOFR range barrier.
2
+
3
+ The contract has four parts, each with its own role:
4
+
5
+ * a USD notional N, which scales the payoff;
6
+ * the SX5E price return S(T)/S(0), a EUR index paid in USD without FX conversion (quanto);
7
+ * the fixing dates T_i = i * delta, i = 1..n, at which the 3M forward rate must stay inside
8
+ [L_min, L_max] for the put to survive, with the last fixing at equity maturity T;
9
+ * USD settlement at T + delta, one fixing period after maturity.
10
+
11
+ Example::
12
+
13
+ from pricing import price, load_market_data
14
+ market = load_market_data("market_data_20261120.json")
15
+ result = price(T=3, delta=0.25, k=1.00, L_min=0.02, L_max=0.05, n=12, market_data=market)
16
+ result["price_usd"], result["se_usd"]
17
+
18
+ Command line, with the brief's example terms as defaults::
19
+
20
+ python pricing.py market_data_20261120.json --T 2 --n 8 --k 1.1
21
+
22
+ Requires NumPy only. See price() for every argument, input key and output.
23
+ """
24
+ import json
25
+ from pathlib import Path
26
+
27
+ import numpy as np
28
+
29
+ __all__ = ["price", "simulate", "load_market_data", "REPORT_PATHS", "REPORT_SEED"]
30
+
31
+ # Settings behind every number in the report.
32
+ REPORT_PATHS = 400_000
33
+ REPORT_SEED = 888
34
+ GAUSS_LEGENDRE_POINTS = 24 # quadrature nodes per quarter for the Hull-White integrals
35
+
36
+
37
+ def load_market_data(source):
38
+ """Load the calibrated market inputs.
39
+
40
+ Parameters
41
+ ----------
42
+ source : dict or str or pathlib.Path
43
+ A market-data dict, returned unchanged, or the path of a JSON file holding one.
44
+
45
+ Returns
46
+ -------
47
+ dict
48
+ The market data, with the keys listed in price().
49
+ """
50
+ if isinstance(source, dict):
51
+ return source
52
+ return json.loads(Path(source).read_text())
53
+
54
+
55
+ def price(T, delta, k, L_min, L_max, n, market_data, *, notional=1_000_000,
56
+ paths=REPORT_PATHS, seed=REPORT_SEED):
57
+ """Price the range-barrier quanto put by Monte Carlo.
58
+
59
+ The payoff, paid in USD at T + delta, is
60
+
61
+ N * max(k - S(T)/S(0), 0) * 1{L_min <= L(T_i) <= L_max for every i = 1..n},
62
+
63
+ where L(T_i) is the 3M forward rate fixed at T_i for [T_i, T_i + delta].
64
+
65
+ Model: the USD short rate is r = x + phi, with dx = -a x dt + eta(t) dW_r (one-factor
66
+ Hull-White, phi fitted to today's curve). The SX5E is lognormal under the USD measure
67
+ with the quanto drift r_EUR - q - rho_SX sigma_S sigma_X, and dW_S dW_r = rho_Sr dt.
68
+ Each quarter is simulated exactly, the fixings are closed form in x, and the payment
69
+ delay is discounted with the bond P(T, T + delta).
70
+
71
+ Parameters
72
+ ----------
73
+ T : float
74
+ Equity maturity and last fixing date, in years. Must equal n * delta.
75
+ delta : float
76
+ Fixing tenor and payment delay, in years (0.25 = 3 months).
77
+ k : float
78
+ Relative strike on S(T)/S(0), e.g. 1.00 for at the money.
79
+ L_min, L_max : float
80
+ Corridor on the 3M forward fixing, as decimals (0.02 = 2%). Both bounds are inside.
81
+ n : int
82
+ Number of fixings, at T_i = i * delta.
83
+ market_data : dict or str or pathlib.Path
84
+ Calibrated inputs, or the path of a JSON file holding them, with keys
85
+
86
+ usd_discount_curve
87
+ [[t, P(0, t)], ...] from t = 0 to at least T + delta; log-linear between nodes.
88
+ mean_reversion
89
+ Hull-White a, per year. Must be nonzero.
90
+ rate_vol
91
+ Hull-White factor vol eta, rate per sqrt(year). A scalar, or a list whose
92
+ value j covers [j * rate_vol_step, (j + 1) * rate_vol_step).
93
+ rate_vol_step
94
+ Length of each rate_vol period, in years. Optional, default 0.25.
95
+ fixing_accrual_factor
96
+ Accrual of one fixing period is delta times this factor (365/360 quotes the
97
+ fixing ACT/360 on the ACT/365 model clock). Optional, default 1.
98
+ equity_vol
99
+ SX5E lognormal vol sigma_S, per sqrt(year).
100
+ eur_equity_carry
101
+ Continuously compounded EUR carry r_EUR - q of the SX5E, per year.
102
+ fx_vol
103
+ Vol sigma_X of USD per EUR, per sqrt(year).
104
+ rho_equity_fx
105
+ Correlation of the SX5E and USD per EUR.
106
+ rho_equity_rate
107
+ Correlation of the SX5E and the Hull-White rate factor.
108
+ notional : float, optional
109
+ USD notional N. Default 1,000,000.
110
+ paths : int, optional
111
+ Number of Monte Carlo paths. Default REPORT_PATHS.
112
+ seed : int, optional
113
+ Seed of NumPy's default generator. Default REPORT_SEED.
114
+
115
+ Returns
116
+ -------
117
+ dict
118
+ price_usd, se_usd
119
+ Value and Monte Carlo standard error, USD.
120
+ ungated_usd, ungated_se_usd
121
+ The same put with no range barrier, on the same paths, USD.
122
+ survival_by_quarter
123
+ Share of paths with every fixing so far inside the corridor, one per T_i.
124
+ in_band_by_quarter
125
+ Share of paths whose fixing at T_i alone is inside, one per T_i.
126
+ mean_fixing_by_quarter
127
+ Mean simulated fixing at each T_i.
128
+ mean_settlement_weight
129
+ Mean of exp(-int_0^T r dt) P(T, T + delta); equals P(0, T + delta) up to
130
+ sampling error.
131
+
132
+ Raises
133
+ ------
134
+ ValueError
135
+ If the deal terms, path count or market data are invalid, with the reason.
136
+ """
137
+ paths_out = simulate(T, delta, k, L_min, L_max, n, market_data, notional=notional, paths=paths, seed=seed)
138
+ knock_out_value, ungated_value = paths_out["knock_out_value"], paths_out["ungated_value"]
139
+ return {"price_usd": float(knock_out_value.mean()),
140
+ "se_usd": float(knock_out_value.std(ddof=1) / np.sqrt(paths)),
141
+ "ungated_usd": float(ungated_value.mean()),
142
+ "ungated_se_usd": float(ungated_value.std(ddof=1) / np.sqrt(paths)),
143
+ "survival_by_quarter": paths_out["survival_by_quarter"],
144
+ "in_band_by_quarter": paths_out["in_band_by_quarter"],
145
+ "mean_fixing_by_quarter": paths_out["mean_fixing_by_quarter"],
146
+ "mean_settlement_weight": float(paths_out["settlement_weight"].mean())}
147
+
148
+
149
+ def simulate(T, delta, k, L_min, L_max, n, market_data, *, notional=1_000_000,
150
+ paths=REPORT_PATHS, seed=REPORT_SEED, normal_draws=None):
151
+ """Simulate the paths behind price() and return per-path discounted payoffs.
152
+
153
+ Use this for variance reduction and quasi-Monte Carlo: pass normal_draws to replace
154
+ the random numbers while keeping the same model code.
155
+
156
+ Parameters
157
+ ----------
158
+ T, delta, k, L_min, L_max, n, market_data, notional, paths, seed
159
+ As in price().
160
+ normal_draws : callable, optional
161
+ normal_draws(i, paths) returns an array of shape (3, paths) of standard normals for
162
+ quarter i = 1..n. By default they come from np.random.default_rng(seed), as in price().
163
+
164
+ Returns
165
+ -------
166
+ dict
167
+ knock_out_value, ungated_value
168
+ Discounted payoff on each path with and without the range barrier, USD.
169
+ settlement_weight
170
+ exp(-int_0^T r dt) P(T, T + delta) on each path, USD today per USD at T + delta.
171
+ fixings
172
+ Array of shape (n, paths): the 3M fixing on every path at every T_i.
173
+ survival_by_quarter, in_band_by_quarter, mean_fixing_by_quarter
174
+ Per-quarter lists, as in price().
175
+
176
+ Raises
177
+ ------
178
+ ValueError
179
+ If the deal terms, path count or market data are invalid, with the reason.
180
+ """
181
+ market_data = load_market_data(market_data)
182
+
183
+ # ---- deal terms
184
+ if not isinstance(n, (int, np.integer)) or n < 1 or delta <= 0 or not np.isclose(T, n * delta):
185
+ raise ValueError("Require positive quarterly grid ending at T")
186
+ if not all(np.isfinite([T, delta, k, L_min, L_max, notional])) or k < 0 or L_min > L_max or notional < 0:
187
+ raise ValueError("Invalid contract terms")
188
+ if not isinstance(paths, (int, np.integer)) or paths < 2:
189
+ raise ValueError("Need at least two independent paths")
190
+
191
+ # ---- market data
192
+ curve_times, curve_discount_factors = np.asarray(market_data["usd_discount_curve"], dtype=float).T
193
+ if (len(curve_times) < 2 or not np.all(np.isfinite([curve_times, curve_discount_factors]))
194
+ or curve_times[0] != 0 or curve_discount_factors[0] != 1 or np.any(curve_discount_factors <= 0)
195
+ or np.any(np.diff(curve_times) <= 0) or curve_times[-1] < T + delta - 1e-12):
196
+ raise ValueError("Supply positive discount factors from t=0 through settlement")
197
+ mean_reversion, equity_vol, fx_vol, eur_carry, rho_equity_rate, rho_equity_fx = (
198
+ float(market_data[key]) for key in ("mean_reversion", "equity_vol",
199
+ "fx_vol", "eur_equity_carry", "rho_equity_rate", "rho_equity_fx"))
200
+ rate_vols = np.atleast_1d(np.asarray(market_data["rate_vol"], dtype=float))
201
+ if rate_vols.size > 1:
202
+ vol_step = float(market_data.get("rate_vol_step", 0.25))
203
+ if not np.isclose(delta, vol_step):
204
+ raise ValueError(f"rate_vol holds one value per {vol_step:g}-year period and cannot be used "
205
+ f"with delta = {delta:g}. Pass a scalar rate_vol or recalibrate on the deal grid")
206
+ if rate_vols.size < n + 1:
207
+ raise ValueError(f"rate_vol covers {rate_vols.size * vol_step:g} years, but the deal needs "
208
+ f"{(n + 1) * delta:g} (through settlement at T + delta)")
209
+ rate_vols = np.full(n + 1, rate_vols[0]) if rate_vols.size == 1 else rate_vols
210
+ fixing_accrual = delta * float(market_data.get("fixing_accrual_factor", 1.0))
211
+ if (not all(np.isfinite([mean_reversion, equity_vol, fx_vol, eur_carry, rho_equity_rate,
212
+ rho_equity_fx, fixing_accrual]))
213
+ or rate_vols.size < n + 1 or not np.all(np.isfinite(rate_vols)) or np.any(rate_vols < 0)
214
+ or mean_reversion == 0 or min(equity_vol, fx_vol) < 0 or fixing_accrual <= 0
215
+ or max(abs(rho_equity_rate), abs(rho_equity_fx)) > 1):
216
+ raise ValueError("Invalid model parameters")
217
+
218
+ # ---- Hull-White building blocks (report Appendix B.2)
219
+ def bond_loading(h):
220
+ """B(h) = (1 - exp(-a h)) / a: sensitivity of log P(t, t + h) to x(t)."""
221
+ return -np.expm1(-mean_reversion * h) / mean_reversion
222
+
223
+ unit_nodes, unit_weights = np.polynomial.legendre.leggauss(GAUSS_LEGENDRE_POINTS)
224
+ quad_times = delta * (unit_nodes + 1) / 2
225
+ quad_weights = unit_weights * delta / 2
226
+
227
+ def integrated_variance(quarters):
228
+ """V(0, t) = Var(int_0^t x ds) at t = quarters * delta, by quadrature per vol period."""
229
+ return sum(rate_vols[j]**2 * np.dot(quad_weights, bond_loading(quarters * delta - (j * delta + quad_times))**2)
230
+ for j in range(quarters))
231
+
232
+ def integrated_shift(quarters):
233
+ """Psi(t) = int_0^t phi ds = -ln P(0, t) + V(0, t) / 2 at t = quarters * delta (fits the curve)."""
234
+ log_discount = np.interp(quarters * delta, curve_times, np.log(curve_discount_factors))
235
+ return -log_discount + integrated_variance(quarters) / 2
236
+
237
+ def conditional_variance(quarter):
238
+ """V(T_i, T_i + delta) = Var(int_{T_i}^{T_i + delta} x ds | x(T_i)), for the bond P(T_i, T_i + delta)."""
239
+ return rate_vols[quarter]**2 * np.dot(quad_weights, bond_loading(quad_times)**2)
240
+
241
+ def quarter_shock_matrix(rate_vol):
242
+ """Matrix R with R R' = covariance of (x increment, its integral, equity Brownian increment) over one quarter.
243
+
244
+ Built from the eigendecomposition, with each eigenvector's largest entry made positive,
245
+ so the factor does not depend on the sign that eigh happens to return.
246
+ """
247
+ kernels = np.array([rate_vol * np.exp(-mean_reversion * quad_times), rate_vol * bond_loading(quad_times),
248
+ np.ones_like(quad_times)])
249
+ covariance = (kernels * quad_weights) @ kernels.T
250
+ covariance[:2, 2] *= rho_equity_rate
251
+ covariance[2, :2] = covariance[:2, 2]
252
+ eigenvalues, eigenvectors = np.linalg.eigh(covariance)
253
+ largest = eigenvectors[np.argmax(np.abs(eigenvectors), axis=0), np.arange(3)]
254
+ eigenvectors = eigenvectors * np.where(largest < 0, -1.0, 1.0)
255
+ return eigenvectors * np.sqrt(np.maximum(eigenvalues, 0))
256
+
257
+ # ---- simulation, one quarter at a time (report Appendix B.8)
258
+ if normal_draws is None:
259
+ rng = np.random.default_rng(seed)
260
+ normal_draws = lambda quarter, size: rng.standard_normal((3, size)) # noqa: E731
261
+ rate_factor = np.zeros(paths)
262
+ rate_factor_integral = np.zeros(paths)
263
+ log_equity_ratio = np.zeros(paths)
264
+ alive = np.ones(paths, dtype=bool)
265
+ survival_by_quarter, in_band_by_quarter, mean_fixing_by_quarter = [], [], []
266
+ fixings = np.empty((n, paths))
267
+ equity_log_drift = eur_carry - rho_equity_fx * equity_vol * fx_vol - equity_vol**2 / 2
268
+ for i in range(1, n + 1):
269
+ shock_matrix, normals = quarter_shock_matrix(rate_vols[i - 1]), normal_draws(i, paths)
270
+ factor_step, factor_integral_step, equity_shock = (
271
+ shock_matrix[r, 0] * normals[0] + shock_matrix[r, 1] * normals[1] + shock_matrix[r, 2] * normals[2]
272
+ for r in range(3))
273
+ rate_factor_integral += bond_loading(delta) * rate_factor + factor_integral_step
274
+ rate_factor = np.exp(-mean_reversion * delta) * rate_factor + factor_step
275
+ log_equity_ratio += equity_log_drift * delta + equity_vol * equity_shock
276
+ log_bond_price = (-(integrated_shift(i + 1) - integrated_shift(i)) - bond_loading(delta) * rate_factor
277
+ + conditional_variance(i) / 2)
278
+ fixing = np.expm1(-log_bond_price) / fixing_accrual
279
+ fixings[i - 1] = fixing
280
+ inside = (fixing >= L_min) & (fixing <= L_max)
281
+ alive &= inside
282
+ survival_by_quarter.append(float(alive.mean()))
283
+ in_band_by_quarter.append(float(inside.mean()))
284
+ mean_fixing_by_quarter.append(float(fixing.mean()))
285
+
286
+ # ---- payoff at T, discounted to today: exp(-int_0^T r) P(T, T + delta) (k - S_T/S_0)^+
287
+ settlement_weight = np.exp(-integrated_shift(n) - rate_factor_integral + log_bond_price)
288
+ ungated_value = settlement_weight * notional * np.maximum(k - np.exp(log_equity_ratio), 0)
289
+ knock_out_value = ungated_value * alive
290
+ return {"knock_out_value": knock_out_value, "ungated_value": ungated_value,
291
+ "settlement_weight": settlement_weight, "fixings": fixings, "survival_by_quarter": survival_by_quarter,
292
+ "in_band_by_quarter": in_band_by_quarter, "mean_fixing_by_quarter": mean_fixing_by_quarter}
293
+
294
+ if __name__ == "__main__":
295
+ import argparse
296
+ parser = argparse.ArgumentParser(description="Price the USD quanto SX5E put with a SOFR range knock-out. "
297
+ "Defaults are the example terms of the brief.")
298
+ parser.add_argument("market_json", type=Path, help="market data file, e.g. market_data_20261120.json")
299
+ parser.add_argument("--T", type=float, default=3.0, help="maturity in years (default 3)")
300
+ parser.add_argument("--delta", type=float, default=0.25, help="fixing tenor in years (default 0.25)")
301
+ parser.add_argument("--k", type=float, default=1.0, help="relative strike (default 1.00)")
302
+ parser.add_argument("--L-min", type=float, default=0.02, help="lower corridor (default 0.02)")
303
+ parser.add_argument("--L-max", type=float, default=0.05, help="upper corridor (default 0.05)")
304
+ parser.add_argument("--n", type=int, default=12, help="number of fixings (default 12)")
305
+ parser.add_argument("--notional", type=float, default=1_000_000, help="USD notional (default 1,000,000)")
306
+ parser.add_argument("--paths", type=int, default=REPORT_PATHS, help=f"Monte Carlo paths (default {REPORT_PATHS:,})")
307
+ parser.add_argument("--seed", type=int, default=REPORT_SEED, help=f"random seed (default {REPORT_SEED})")
308
+ args = parser.parse_args()
309
+ market = load_market_data(args.market_json)
310
+ result = price(args.T, args.delta, args.k, args.L_min, args.L_max, args.n, market,
311
+ notional=args.notional, paths=args.paths, seed=args.seed)
312
+ terms = dict(T=args.T, delta=args.delta, k=args.k, L_min=args.L_min, L_max=args.L_max, n=args.n,
313
+ notional=args.notional)
314
+ print(json.dumps({"input_label": market.get("label", str(args.market_json)), "terms": terms,
315
+ "paths": args.paths, "seed": args.seed, **result}, indent=2))
@@ -0,0 +1,20 @@
1
+ [build-system]
2
+ requires = ["setuptools>=68"]
3
+ build-backend = "setuptools.build_meta"
4
+
5
+ [project]
6
+ name = "quanto-range-put"
7
+ version = "0.1.0"
8
+ description = "Monte Carlo pricer for a USD quanto equity put with a quarterly SOFR range barrier (Hull-White rates)."
9
+ authors = [{ name = "Nigel Li" }]
10
+ requires-python = ">=3.10"
11
+ dependencies = ["numpy>=1.24", "scipy>=1.10"]
12
+ keywords = ["quanto", "hull-white", "monte-carlo", "range-barrier", "derivatives-pricing"]
13
+ classifiers = [
14
+ "Programming Language :: Python :: 3",
15
+ "Topic :: Office/Business :: Financial",
16
+ "Intended Audience :: Financial and Insurance Industry",
17
+ ]
18
+
19
+ [tool.setuptools]
20
+ py-modules = ["pricing", "quoting"]
@@ -0,0 +1,12 @@
1
+ Metadata-Version: 2.4
2
+ Name: quanto-range-put
3
+ Version: 0.1.0
4
+ Summary: Monte Carlo pricer for a USD quanto equity put with a quarterly SOFR range barrier (Hull-White rates).
5
+ Author: Nigel Li
6
+ Keywords: quanto,hull-white,monte-carlo,range-barrier,derivatives-pricing
7
+ Classifier: Programming Language :: Python :: 3
8
+ Classifier: Topic :: Office/Business :: Financial
9
+ Classifier: Intended Audience :: Financial and Insurance Industry
10
+ Requires-Python: >=3.10
11
+ Requires-Dist: numpy>=1.24
12
+ Requires-Dist: scipy>=1.10
@@ -0,0 +1,8 @@
1
+ pricing.py
2
+ pyproject.toml
3
+ quoting.py
4
+ quanto_range_put.egg-info/PKG-INFO
5
+ quanto_range_put.egg-info/SOURCES.txt
6
+ quanto_range_put.egg-info/dependency_links.txt
7
+ quanto_range_put.egg-info/requires.txt
8
+ quanto_range_put.egg-info/top_level.txt
@@ -0,0 +1,2 @@
1
+ numpy>=1.24
2
+ scipy>=1.10
@@ -0,0 +1,2 @@
1
+ pricing
2
+ quoting
@@ -0,0 +1,179 @@
1
+ """Quoting layer on top of pricing.py: re-offer and client prices, and solving for a deal term.
2
+
3
+ A desk does not quote the model mid. It adds the issuer margin m and the distributor fee f,
4
+ both in basis points of the USD notional N:
5
+
6
+ re-offer price = fair value + m N (what the distributor pays the issuer)
7
+ client price = re-offer price + f N (what the end client pays)
8
+
9
+ It often runs this backwards: the client has a budget, and the desk finds the strike or
10
+ barrier that fits it. solve_term() does this with Brent's method on common random numbers.
11
+
12
+ Example::
13
+
14
+ from quoting import quote, solve_term
15
+ terms = dict(T=3, delta=0.25, k=1.0, L_min=0.02, L_max=0.05, n=12)
16
+ quote(terms, market, margin_bp=50, fee_bp=25)
17
+ solve_term(25_000, "k", terms, market, margin_bp=50, fee_bp=25)
18
+
19
+ Nothing here changes pricing.py, so the reported fair value is unaffected. Requires SciPy.
20
+ """
21
+
22
+ from scipy.optimize import brentq
23
+
24
+ from pricing import REPORT_PATHS, REPORT_SEED, load_market_data, price
25
+
26
+ __all__ = ["quote", "solve_term", "implied_margin", "SOLVABLE", "DEFAULT_BRACKETS"]
27
+
28
+ # Terms solve_term() can solve for, and the search interval for each (None = 1 bp inside the other bound).
29
+ SOLVABLE = ("k", "L_min", "L_max")
30
+ DEFAULT_BRACKETS = {"k": (0.50, 1.50), "L_min": (-0.05, None), "L_max": (None, 0.15)}
31
+
32
+
33
+ def _bracket(solve_for, terms):
34
+ """Default Brent bracket for solve_for, keeping the corridor at least 1 bp wide."""
35
+ lo, hi = DEFAULT_BRACKETS[solve_for]
36
+ if solve_for == "L_min":
37
+ hi = terms["L_max"] - 1e-4
38
+ if solve_for == "L_max":
39
+ lo = terms["L_min"] + 1e-4
40
+ return lo, hi
41
+
42
+
43
+ def _check_fees(margin_bp, fee_bp):
44
+ """Raise ValueError if the margin or fee is negative."""
45
+ if not (margin_bp >= 0 and fee_bp >= 0):
46
+ raise ValueError("margin_bp and fee_bp are basis points of notional and cannot be negative")
47
+
48
+
49
+ def quote(terms, market_data, *, margin_bp, fee_bp, notional=1_000_000, paths=REPORT_PATHS, seed=REPORT_SEED):
50
+ """Fair value, re-offer price and client price for fixed deal terms.
51
+
52
+ Parameters
53
+ ----------
54
+ terms : dict
55
+ T, delta, k, L_min, L_max and n, as in pricing.price().
56
+ market_data : dict or str or pathlib.Path
57
+ Market inputs, as in pricing.price().
58
+ margin_bp : float
59
+ Issuer margin, bp of notional, added to the fair value.
60
+ fee_bp : float
61
+ Distributor fee, bp of notional, added on top of the re-offer price.
62
+ notional, paths, seed : optional
63
+ As in pricing.price().
64
+
65
+ Returns
66
+ -------
67
+ dict
68
+ fair_usd, se_usd, margin_usd, fee_usd, reoffer_usd, client_usd in USD; fair_pct,
69
+ reoffer_pct, client_pct in % of notional; survival, the share of paths alive at T;
70
+ and the terms and notional used.
71
+
72
+ Raises
73
+ ------
74
+ ValueError
75
+ If margin_bp or fee_bp is negative, or the terms are invalid.
76
+ """
77
+ _check_fees(margin_bp, fee_bp)
78
+ market_data = load_market_data(market_data)
79
+ result = price(**terms, market_data=market_data, notional=notional, paths=paths, seed=seed)
80
+ fair = result["price_usd"]
81
+ margin_usd, fee_usd = margin_bp * 1e-4 * notional, fee_bp * 1e-4 * notional
82
+ reoffer, client = fair + margin_usd, fair + margin_usd + fee_usd
83
+ return {"terms": dict(terms), "notional": notional, "fair_usd": fair, "se_usd": result["se_usd"],
84
+ "margin_usd": margin_usd, "fee_usd": fee_usd, "reoffer_usd": reoffer, "client_usd": client,
85
+ "fair_pct": 100 * fair / notional, "reoffer_pct": 100 * reoffer / notional,
86
+ "client_pct": 100 * client / notional, "survival": result["survival_by_quarter"][-1]}
87
+
88
+
89
+ def implied_margin(client_usd, terms, market_data, *, fee_bp, notional=1_000_000, paths=REPORT_PATHS, seed=REPORT_SEED):
90
+ """Issuer margin left in a client price after the fee, for fixed terms.
91
+
92
+ Parameters
93
+ ----------
94
+ client_usd : float
95
+ Price the client pays, USD.
96
+ terms, market_data, notional, paths, seed
97
+ As in quote().
98
+ fee_bp : float
99
+ Distributor fee, bp of notional.
100
+
101
+ Returns
102
+ -------
103
+ float
104
+ Margin in bp of notional: (client_usd - fee - fair value) / N * 1e4. Negative if the
105
+ client price is below fair value plus fee.
106
+ """
107
+ _check_fees(0, fee_bp)
108
+ fair = price(**terms, market_data=load_market_data(market_data), notional=notional, paths=paths, seed=seed)["price_usd"]
109
+ return (client_usd - fee_bp * 1e-4 * notional - fair) / notional * 1e4
110
+
111
+
112
+ def solve_term(client_usd, solve_for, terms, market_data, *, margin_bp, fee_bp, bracket=None, xtol=1e-6,
113
+ notional=1_000_000, paths=REPORT_PATHS, seed=REPORT_SEED):
114
+ """Solve for the strike or one corridor bound that makes the client price equal client_usd.
115
+
116
+ The target fair value is client_usd minus margin and fee. Brent's method
117
+ (scipy.optimize.brentq) finds the root of fair value minus target inside the bracket.
118
+ Every price uses the same paths and seed, so the fair value is a deterministic function
119
+ of the term. In k it is continuous and increasing; in L_min or L_max it moves in small
120
+ steps, and Brent returns the step within xtol.
121
+
122
+ Parameters
123
+ ----------
124
+ client_usd : float
125
+ Client's budget, USD.
126
+ solve_for : {"k", "L_min", "L_max"}
127
+ The term to solve for. The other terms stay as given.
128
+ terms, market_data, margin_bp, fee_bp, notional, paths, seed
129
+ As in quote().
130
+ bracket : tuple of float, optional
131
+ Search interval (lo, hi). Defaults to DEFAULT_BRACKETS, with the open end 1 bp inside
132
+ the other corridor bound. Fair value minus target must change sign across it.
133
+ xtol : float, optional
134
+ Absolute tolerance on the solved term. Default 1e-6.
135
+
136
+ Returns
137
+ -------
138
+ dict
139
+ value, the solved term; quote, the quote() at it; iterations and price_calls;
140
+ slope_usd_per_unit, the central-difference slope of the fair value in the term on the
141
+ same paths; term_se, the term's Monte Carlo uncertainty SE / |slope|; and the targets.
142
+
143
+ Raises
144
+ ------
145
+ ValueError
146
+ If solve_for is not solvable, the price does not cover margin and fee, or the
147
+ bracket holds no root.
148
+ """
149
+ if solve_for not in SOLVABLE:
150
+ raise ValueError(f"can solve for one of {SOLVABLE}, not {solve_for!r}")
151
+ _check_fees(margin_bp, fee_bp)
152
+ market_data = load_market_data(market_data)
153
+ target_fair = client_usd - (margin_bp + fee_bp) * 1e-4 * notional
154
+ if target_fair <= 0:
155
+ raise ValueError("the client price does not cover the margin and fee")
156
+ lo, hi = bracket or _bracket(solve_for, terms)
157
+ calls = []
158
+
159
+ def gap(x):
160
+ """Fair value at term value x minus the target, logging each call."""
161
+ fair = price(**{**terms, solve_for: x}, market_data=market_data, notional=notional, paths=paths, seed=seed)
162
+ calls.append((x, fair["price_usd"]))
163
+ return fair["price_usd"] - target_fair
164
+
165
+ g_lo, g_hi = gap(lo), gap(hi)
166
+ if g_lo * g_hi > 0:
167
+ raise ValueError(f"no root in [{lo}, {hi}]: the fair value runs from {g_lo + target_fair:,.0f} to "
168
+ f"{g_hi + target_fair:,.0f} USD against a target of {target_fair:,.0f}; widen the bracket")
169
+ value, info = brentq(gap, lo, hi, xtol=xtol, full_output=True)
170
+ q = quote({**terms, solve_for: value}, market_data, margin_bp=margin_bp, fee_bp=fee_bp,
171
+ notional=notional, paths=paths, seed=seed)
172
+ h = 0.01 if solve_for == "k" else 0.0010
173
+ up = price(**{**terms, solve_for: value + h}, market_data=market_data, notional=notional, paths=paths, seed=seed)
174
+ dn = price(**{**terms, solve_for: value - h}, market_data=market_data, notional=notional, paths=paths, seed=seed)
175
+ slope = (up["price_usd"] - dn["price_usd"]) / (2 * h)
176
+ return {"solve_for": solve_for, "value": value, "target_client_usd": client_usd, "target_fair_usd": target_fair,
177
+ "quote": q, "iterations": info.iterations, "price_calls": len(calls) + 3,
178
+ "slope_usd_per_unit": slope, "term_se": q["se_usd"] / abs(slope) if slope else float("inf")}
179
+
@@ -0,0 +1,4 @@
1
+ [egg_info]
2
+ tag_build =
3
+ tag_date = 0
4
+