radonlab 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.
Files changed (36) hide show
  1. radonlab-0.1.0/.github/workflows/ci.yml +53 -0
  2. radonlab-0.1.0/.gitignore +28 -0
  3. radonlab-0.1.0/LICENSE +201 -0
  4. radonlab-0.1.0/PKG-INFO +198 -0
  5. radonlab-0.1.0/README.md +159 -0
  6. radonlab-0.1.0/examples/barrier_greeks.py +64 -0
  7. radonlab-0.1.0/examples/benchmark_digital_delta.py +147 -0
  8. radonlab-0.1.0/examples/quickstart.py +34 -0
  9. radonlab-0.1.0/pyproject.toml +66 -0
  10. radonlab-0.1.0/src/radonlab/__init__.py +72 -0
  11. radonlab-0.1.0/src/radonlab/_special.py +37 -0
  12. radonlab-0.1.0/src/radonlab/_version.py +3 -0
  13. radonlab-0.1.0/src/radonlab/analytics.py +190 -0
  14. radonlab-0.1.0/src/radonlab/asian.py +155 -0
  15. radonlab-0.1.0/src/radonlab/benchmark.py +88 -0
  16. radonlab-0.1.0/src/radonlab/estimators/__init__.py +16 -0
  17. radonlab-0.1.0/src/radonlab/estimators/base.py +57 -0
  18. radonlab-0.1.0/src/radonlab/estimators/conditional_mc.py +111 -0
  19. radonlab-0.1.0/src/radonlab/estimators/finite_difference.py +84 -0
  20. radonlab-0.1.0/src/radonlab/estimators/likelihood_ratio.py +97 -0
  21. radonlab-0.1.0/src/radonlab/estimators/pathwise.py +57 -0
  22. radonlab-0.1.0/src/radonlab/estimators/smoothing.py +78 -0
  23. radonlab-0.1.0/src/radonlab/merton.py +175 -0
  24. radonlab-0.1.0/src/radonlab/models.py +102 -0
  25. radonlab-0.1.0/src/radonlab/payoffs.py +160 -0
  26. radonlab-0.1.0/src/radonlab/py.typed +0 -0
  27. radonlab-0.1.0/src/radonlab/rng.py +83 -0
  28. radonlab-0.1.0/src/radonlab/types.py +107 -0
  29. radonlab-0.1.0/tests/__init__.py +0 -0
  30. radonlab-0.1.0/tests/helpers.py +14 -0
  31. radonlab-0.1.0/tests/test_analytics.py +114 -0
  32. radonlab-0.1.0/tests/test_asian.py +63 -0
  33. radonlab-0.1.0/tests/test_conditional_mc.py +60 -0
  34. radonlab-0.1.0/tests/test_estimators.py +109 -0
  35. radonlab-0.1.0/tests/test_merton.py +65 -0
  36. radonlab-0.1.0/tests/test_rng_types_benchmark.py +101 -0
@@ -0,0 +1,53 @@
1
+ name: ci
2
+
3
+ on: [push, pull_request]
4
+
5
+ permissions:
6
+ contents: read
7
+
8
+ concurrency:
9
+ group: ci-${{ github.ref }}
10
+ cancel-in-progress: true
11
+
12
+ jobs:
13
+ test:
14
+ name: py${{ matrix.python-version }}
15
+ runs-on: ubuntu-latest
16
+ strategy:
17
+ fail-fast: false
18
+ matrix:
19
+ python-version: ["3.9", "3.10", "3.11", "3.12"]
20
+ steps:
21
+ - uses: actions/checkout@v4
22
+ - name: Set up Python ${{ matrix.python-version }}
23
+ uses: actions/setup-python@v5
24
+ with:
25
+ python-version: ${{ matrix.python-version }}
26
+ cache: pip
27
+ - name: Install (with dev extras)
28
+ run: |
29
+ python -m pip install --upgrade pip
30
+ pip install -e ".[dev]"
31
+ - name: Lint (ruff)
32
+ run: ruff check src tests
33
+ - name: Test (pytest)
34
+ run: pytest -q
35
+
36
+ build:
37
+ name: build sdist and wheel
38
+ runs-on: ubuntu-latest
39
+ needs: test
40
+ steps:
41
+ - uses: actions/checkout@v4
42
+ - uses: actions/setup-python@v5
43
+ with:
44
+ python-version: "3.12"
45
+ - name: Build
46
+ run: |
47
+ python -m pip install --upgrade pip build
48
+ python -m build
49
+ - name: Upload artifacts
50
+ uses: actions/upload-artifact@v4
51
+ with:
52
+ name: radonlab-dist
53
+ path: dist/*
@@ -0,0 +1,28 @@
1
+ # Byte-compiled / caches
2
+ __pycache__/
3
+ *.py[cod]
4
+ *.egg-info/
5
+ .eggs/
6
+ .pytest_cache/
7
+ .ruff_cache/
8
+ .mypy_cache/
9
+
10
+ # Build artifacts
11
+ build/
12
+ dist/
13
+ *.whl
14
+ *.tar.gz
15
+
16
+ # Example outputs
17
+ examples/*.csv
18
+ examples/*.png
19
+
20
+ # Environments
21
+ .venv/
22
+ venv/
23
+ env/
24
+
25
+ # OS / editor
26
+ .DS_Store
27
+ .idea/
28
+ .vscode/
radonlab-0.1.0/LICENSE ADDED
@@ -0,0 +1,201 @@
1
+ Apache License
2
+ Version 2.0, January 2004
3
+ http://www.apache.org/licenses/
4
+
5
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
6
+
7
+ 1. Definitions.
8
+
9
+ "License" shall mean the terms and conditions for use, reproduction,
10
+ and distribution as defined by Sections 1 through 9 of this document.
11
+
12
+ "Licensor" shall mean the copyright owner or entity authorized by
13
+ the copyright owner that is granting the License.
14
+
15
+ "Legal Entity" shall mean the union of the acting entity and all
16
+ other entities that control, are controlled by, or are under common
17
+ control with that entity. For the purposes of this definition,
18
+ "control" means (i) the power, direct or indirect, to cause the
19
+ direction or management of such entity, whether by contract or
20
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
21
+ outstanding shares, or (iii) beneficial ownership of such entity.
22
+
23
+ "You" (or "Your") shall mean an individual or Legal Entity
24
+ exercising permissions granted by this License.
25
+
26
+ "Source" form shall mean the preferred form for making modifications,
27
+ including but not limited to software source code, documentation
28
+ source, and configuration files.
29
+
30
+ "Object" form shall mean any form resulting from mechanical
31
+ transformation or translation of a Source form, including but
32
+ not limited to compiled object code, generated documentation,
33
+ and conversions to other media types.
34
+
35
+ "Work" shall mean the work of authorship, whether in Source or
36
+ Object form, made available under the License, as indicated by a
37
+ copyright notice that is included in or attached to the work
38
+ (an example is provided in the Appendix below).
39
+
40
+ "Derivative Works" shall mean any work, whether in Source or Object
41
+ form, that is based on (or derived from) the Work and for which the
42
+ editorial revisions, annotations, elaborations, or other modifications
43
+ represent, as a whole, an original work of authorship. For the purposes
44
+ of this License, Derivative Works shall not include works that remain
45
+ separable from, or merely link (or bind by name) to the interfaces of,
46
+ the Work and Derivative Works thereof.
47
+
48
+ "Contribution" shall mean any work of authorship, including
49
+ the original version of the Work and any modifications or additions
50
+ to that Work or Derivative Works thereof, that is intentionally
51
+ submitted to Licensor for inclusion in the Work by the copyright owner
52
+ or by an individual or Legal Entity authorized to submit on behalf of
53
+ the copyright owner. For the purposes of this definition, "submitted"
54
+ means any form of electronic, verbal, or written communication sent
55
+ to the Licensor or its representatives, including but not limited to
56
+ communication on electronic mailing lists, source code control systems,
57
+ and issue tracking systems that are managed by, or on behalf of, the
58
+ Licensor for the purpose of discussing and improving the Work, but
59
+ excluding communication that is conspicuously marked or otherwise
60
+ designated in writing by the copyright owner as "Not a Contribution."
61
+
62
+ "Contributor" shall mean Licensor and any individual or Legal Entity
63
+ on behalf of whom a Contribution has been received by Licensor and
64
+ subsequently incorporated within the Work.
65
+
66
+ 2. Grant of Copyright License. Subject to the terms and conditions of
67
+ this License, each Contributor hereby grants to You a perpetual,
68
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
69
+ copyright license to reproduce, prepare Derivative Works of,
70
+ publicly display, publicly perform, sublicense, and distribute the
71
+ Work and such Derivative Works in Source or Object form.
72
+
73
+ 3. Grant of Patent License. Subject to the terms and conditions of
74
+ this License, each Contributor hereby grants to You a perpetual,
75
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
76
+ (except as stated in this section) patent license to make, have made,
77
+ use, offer to sell, sell, import, and otherwise transfer the Work,
78
+ where such license applies only to those patent claims licensable
79
+ by such Contributor that are necessarily infringed by their
80
+ Contribution(s) alone or by combination of their Contribution(s)
81
+ with the Work to which such Contribution(s) was submitted. If You
82
+ institute patent litigation against any entity (including a
83
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
84
+ or a Contribution incorporated within the Work constitutes direct
85
+ or contributory patent infringement, then any patent licenses
86
+ granted to You under this License for that Work shall terminate
87
+ as of the date such litigation is filed.
88
+
89
+ 4. Redistribution. You may reproduce and distribute copies of the
90
+ Work or Derivative Works thereof in any medium, with or without
91
+ modifications, and in Source or Object form, provided that You
92
+ meet the following conditions:
93
+
94
+ (a) You must give any other recipients of the Work or
95
+ Derivative Works a copy of this License; and
96
+
97
+ (b) You must cause any modified files to carry prominent notices
98
+ stating that You changed the files; and
99
+
100
+ (c) You must retain, in the Source form of any Derivative Works
101
+ that You distribute, all copyright, patent, trademark, and
102
+ attribution notices from the Source form of the Work,
103
+ excluding those notices that do not pertain to any part of
104
+ the Derivative Works; and
105
+
106
+ (d) If the Work includes a "NOTICE" text file as part of its
107
+ distribution, then any Derivative Works that You distribute must
108
+ include a readable copy of the attribution notices contained
109
+ within such NOTICE file, excluding those notices that do not
110
+ pertain to any part of the Derivative Works, in at least one
111
+ of the following places: within a NOTICE text file distributed
112
+ as part of the Derivative Works; within the Source form or
113
+ documentation, if provided along with the Derivative Works; or,
114
+ within a display generated by the Derivative Works, if and
115
+ wherever such third-party notices normally appear. The contents
116
+ of the NOTICE file are for informational purposes only and
117
+ do not modify the License. You may add Your own attribution
118
+ notices within Derivative Works that You distribute, alongside
119
+ or as an addendum to the NOTICE text from the Work, provided
120
+ that such additional attribution notices cannot be construed
121
+ as modifying the License.
122
+
123
+ You may add Your own copyright statement to Your modifications and
124
+ may provide additional or different license terms and conditions
125
+ for use, reproduction, or distribution of Your modifications, or
126
+ for any such Derivative Works as a whole, provided Your use,
127
+ reproduction, and distribution of the Work otherwise complies with
128
+ the conditions stated in this License.
129
+
130
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
131
+ any Contribution intentionally submitted for inclusion in the Work
132
+ by You to the Licensor shall be under the terms and conditions of
133
+ this License, without any additional terms or conditions.
134
+ Notwithstanding the above, nothing herein shall supersede or modify
135
+ the terms of any separate license agreement you may have executed
136
+ with Licensor regarding such Contributions.
137
+
138
+ 6. Trademarks. This License does not grant permission to use the trade
139
+ names, trademarks, service marks, or product names of the Licensor,
140
+ except as required for reasonable and customary use in describing the
141
+ origin of the Work and reproducing the content of the NOTICE file.
142
+
143
+ 7. Disclaimer of Warranty. Unless required by applicable law or
144
+ agreed to in writing, Licensor provides the Work (and each
145
+ Contributor provides its Contributions) on an "AS IS" BASIS,
146
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
147
+ implied, including, without limitation, any warranties or conditions
148
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
149
+ PARTICULAR PURPOSE. You are solely responsible for determining the
150
+ appropriateness of using or redistributing the Work and assume any
151
+ risks associated with Your exercise of permissions under this License.
152
+
153
+ 8. Limitation of Liability. In no event and under no legal theory,
154
+ whether in tort (including negligence), contract, or otherwise,
155
+ unless required by applicable law (such as deliberate and grossly
156
+ negligent acts) or agreed to in writing, shall any Contributor be
157
+ liable to You for damages, including any direct, indirect, special,
158
+ incidental, or consequential damages of any character arising as a
159
+ result of this License or out of the use or inability to use the
160
+ Work (including but not limited to damages for loss of goodwill,
161
+ work stoppage, computer failure or malfunction, or any and all
162
+ other commercial damages or losses), even if such Contributor
163
+ has been advised of the possibility of such damages.
164
+
165
+ 9. Accepting Warranty or Additional Liability. While redistributing
166
+ the Work or Derivative Works thereof, You may choose to offer,
167
+ and charge a fee for, acceptance of support, warranty, indemnity,
168
+ or other liability obligations and/or rights consistent with this
169
+ License. However, in accepting such obligations, You may act only
170
+ on Your own behalf and on Your sole responsibility, not on behalf
171
+ of any other Contributor, and only if You agree to indemnify,
172
+ defend, and hold each Contributor harmless for any liability
173
+ incurred by, or claims asserted against, such Contributor by reason
174
+ of your accepting any such warranty or additional liability.
175
+
176
+ END OF TERMS AND CONDITIONS
177
+
178
+ APPENDIX: How to apply the Apache License to your work.
179
+
180
+ To apply the Apache License to your work, attach the following
181
+ boilerplate notice, with the fields enclosed by brackets "[]"
182
+ replaced with your own identifying information. (Don't include
183
+ the brackets!) The text should be enclosed in the appropriate
184
+ comment syntax for the file format. We also recommend that a
185
+ file or class name and description of purpose be included on the
186
+ same "printed page" as the copyright notice for easier
187
+ identification within third-party archives.
188
+
189
+ Copyright [yyyy] [name of copyright owner]
190
+
191
+ Licensed under the Apache License, Version 2.0 (the "License");
192
+ you may not use this file except in compliance with the License.
193
+ You may obtain a copy of the License at
194
+
195
+ http://www.apache.org/licenses/LICENSE-2.0
196
+
197
+ Unless required by applicable law or agreed to in writing, software
198
+ distributed under the License is distributed on an "AS IS" BASIS,
199
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
200
+ See the License for the specific language governing permissions and
201
+ limitations under the License.
@@ -0,0 +1,198 @@
1
+ Metadata-Version: 2.4
2
+ Name: radonlab
3
+ Version: 0.1.0
4
+ Summary: Monte Carlo Greeks for discontinuous payoffs: likelihood-ratio, smoothing and conditional Monte Carlo, benchmarked against closed-form references.
5
+ Project-URL: Homepage, https://github.com/quantsingularity/radonlab
6
+ Project-URL: Source, https://github.com/quantsingularity/radonlab
7
+ Project-URL: Issues, https://github.com/quantsingularity/radonlab/issues
8
+ Author: Abrar Ahmed
9
+ License-Expression: Apache-2.0
10
+ License-File: LICENSE
11
+ Keywords: greeks,likelihood-ratio,malliavin,monte-carlo,option-pricing,quantitative-finance,sensitivities
12
+ Classifier: Development Status :: 4 - Beta
13
+ Classifier: Intended Audience :: Financial and Insurance Industry
14
+ Classifier: Intended Audience :: Science/Research
15
+ Classifier: License :: OSI Approved :: Apache Software License
16
+ Classifier: Programming Language :: Python :: 3
17
+ Classifier: Programming Language :: Python :: 3.9
18
+ Classifier: Programming Language :: Python :: 3.10
19
+ Classifier: Programming Language :: Python :: 3.11
20
+ Classifier: Programming Language :: Python :: 3.12
21
+ Classifier: Topic :: Office/Business :: Financial :: Investment
22
+ Classifier: Typing :: Typed
23
+ Requires-Python: >=3.9
24
+ Requires-Dist: numpy>=1.22
25
+ Requires-Dist: scipy>=1.8
26
+ Provides-Extra: benchmark
27
+ Requires-Dist: matplotlib>=3.5; extra == 'benchmark'
28
+ Requires-Dist: pandas>=1.4; extra == 'benchmark'
29
+ Provides-Extra: dev
30
+ Requires-Dist: matplotlib>=3.5; extra == 'dev'
31
+ Requires-Dist: mypy>=1.0; extra == 'dev'
32
+ Requires-Dist: pandas>=1.4; extra == 'dev'
33
+ Requires-Dist: pytest>=7.0; extra == 'dev'
34
+ Requires-Dist: ruff>=0.1; extra == 'dev'
35
+ Provides-Extra: test
36
+ Requires-Dist: pandas>=1.4; extra == 'test'
37
+ Requires-Dist: pytest>=7.0; extra == 'test'
38
+ Description-Content-Type: text/markdown
39
+
40
+ # RadonLab
41
+
42
+ **Monte Carlo Greeks for discontinuous payoffs**, done correctly and benchmarked
43
+ against closed-form references.
44
+
45
+ When an option's payoff is discontinuous (a digital that pays a fixed amount if
46
+ the underlying finishes above a strike, a barrier that knocks out on touch), the
47
+ textbook _pathwise_ (infinitesimal perturbation) estimator for its sensitivities
48
+ quietly breaks: the derivative of the payoff is zero almost everywhere, so the
49
+ estimate collapses toward zero. `radonlab` implements the established remedies,
50
+ tests each one against a known analytic answer, and benchmarks them side by side
51
+ so you can see _which method to use and what it costs_.
52
+
53
+ Pure NumPy/SciPy. Apache-2.0. No copyleft dependencies.
54
+
55
+ ## Companion C++ implementation
56
+
57
+ A header-only C++20 port lives at
58
+ [github.com/quantsingularity/radonlab-cpp](https://github.com/quantsingularity/radonlab-cpp).
59
+ The two libraries share the same methods and the same closed-form references, and
60
+ the C++ analytics are cross-checked against this library's values (which are
61
+ verified to machine precision by complex-step differentiation), so the two agree
62
+ to 1e-9 across languages. The C++ side additionally provides adjoint algorithmic
63
+ differentiation (a full Greek vector from one reverse sweep) and exact
64
+ second-order Greeks. This Python library is the reference and carries the research
65
+ extensions (Merton jump-diffusion and a path-dependent Malliavin delta).
66
+
67
+ ## What's inside
68
+
69
+ Estimators (all with per-path standard errors):
70
+
71
+ - **Likelihood-ratio method (LRM)**: differentiates the _density_, never the
72
+ payoff, so it is unbiased for digitals and other discontinuous payoffs.
73
+ Delta, vega and gamma.
74
+ - **Smoothing**: replaces the payoff with a `C¹` approximation of bandwidth `h`
75
+ and applies the pathwise method to it. A tunable bias/variance trade-off.
76
+ - **Conditional Monte Carlo**: for barriers, integrates out the crossing event
77
+ with the Brownian-bridge non-crossing probability, giving an estimator that is
78
+ unbiased for the _continuously-monitored_ price at any number of steps and
79
+ Lipschitz in spot (so its delta comes out by the pathwise method).
80
+ - **Pathwise** and **finite-difference (bump)** baselines, kept so their failure
81
+ modes on discontinuous payoffs are visible and measurable.
82
+
83
+ Closed-form Black-Scholes analytics (the ground truth) for European calls/puts,
84
+ cash-or-nothing and asset-or-nothing digitals, and continuously-monitored
85
+ down-and-out / down-and-in calls. Every explicit Greek formula is checked
86
+ against complex-step differentiation of the price to machine precision.
87
+
88
+ ## Install
89
+
90
+ ```bash
91
+ pip install -e ".[benchmark,test]"
92
+ ```
93
+
94
+ Runtime dependencies are just `numpy` and `scipy`. `pandas`/`matplotlib` are only
95
+ needed for the benchmark table and plots.
96
+
97
+ ## Quick start
98
+
99
+ ```python
100
+ from radonlab import GeometricBrownianMotion, CashOrNothingCall, Greek
101
+ from radonlab import likelihood_ratio, pathwise, analytics
102
+
103
+ model = GeometricBrownianMotion(S0=100, r=0.03, sigma=0.20, T=1.0)
104
+ payoff = CashOrNothingCall(strike=100)
105
+
106
+ # Ground truth
107
+ ref = analytics.cash_or_nothing_call(100, 100, 0.03, 0.20, 1.0, greek="delta")
108
+
109
+ # Likelihood ratio: unbiased for the digital
110
+ lrm = likelihood_ratio(model, payoff, Greek.DELTA, n_paths=1_000_000)
111
+ print(lrm) # delta=... +/- ... [likelihood-ratio]
112
+ print(lrm.confidence_interval(0.95))
113
+
114
+ # Naive pathwise: collapses to ~0, badly biased
115
+ pw = pathwise(model, payoff, Greek.DELTA, n_paths=1_000_000)
116
+ print(pw.value, "vs analytic", ref)
117
+ ```
118
+
119
+ ## The math, briefly
120
+
121
+ Under geometric Brownian motion `S_T = S₀·exp((r − q − ½σ²)T + σ√T·Z)`, with
122
+ `Z ~ N(0,1)`, a price is `P = e^{−rT} E[f(S_T)]`.
123
+
124
+ - **LRM** writes `∂P/∂θ = e^{−rT} E[f(S_T)·∂_θ log p(S_T;θ)]`. The score functions
125
+ are `Z/(S₀σ√T)` for delta, `(Z²−1)/σ − √T·Z` for vega, and
126
+ `(Z² − σ√T·Z − 1)/(S₀²σ²T)` for gamma. `f` is never differentiated, so a
127
+ jump in `f` is no problem.
128
+ - **Pathwise** writes `∂P/∂θ = e^{−rT} E[f′(S_T)·∂_θ S_T]`. Fine when `f` is
129
+ Lipschitz (vanilla), degenerate when `f` jumps (digital).
130
+ - **Conditional MC** for a down-and-out call multiplies the terminal payoff by
131
+ `∏ᵢ(1 − exp(−2(Xᵢ−b)(Xᵢ₊₁−b)/(σ²Δt)))`, the exact bridge probability of not
132
+ breaching `b = ln B` between simulated points.
133
+
134
+ Full references are in each module's docstring (Broadie-Glasserman 1996,
135
+ Glasserman 2003, Reiner-Rubinstein 1991, and the smoothed-perturbation and
136
+ Malliavin literature).
137
+
138
+ ## Benchmark
139
+
140
+ Reproduce with `python examples/benchmark_digital_delta.py` (1,000,000 paths,
141
+ seed 0). Delta of an at-the-money cash-or-nothing call, `S₀=K=100`, `r=3%`,
142
+ `σ=20%`, `T=1`. Analytic reference delta = **0.019333**. Ranked by standard
143
+ error, the metric that actually reflects an estimator's accuracy:
144
+
145
+ | method | value | std error | \|error\| vs analytic | biased? |
146
+ | --------------------------- | ------- | --------- | --------------------- | ------- |
147
+ | likelihood-ratio | 0.01939 | 2.84e-05 | 5.9e-05 | no |
148
+ | smoothing (h=default) | 0.01921 | 4.56e-05 | 1.2e-04 | no |
149
+ | finite-difference (1% bump) | 0.01934 | 9.49e-05 | 8.5e-06 | no |
150
+ | pathwise | 0.00000 | 0.00e+00 | 1.9e-02 | **yes** |
151
+
152
+ Two things to read off it. First, **pathwise is 100% wrong**: it returns
153
+ exactly zero, because the digital's derivative is zero almost everywhere.
154
+ Second, among the unbiased methods **the likelihood-ratio estimator has the
155
+ lowest variance** (about 3.3× smaller standard error than the 1% finite
156
+ difference) and needs no bump to tune.
157
+
158
+ And finite difference forces a bad choice: the same run sweeping the bump size
159
+ shows the standard error exploding as the bump shrinks, while a large bump
160
+ introduces its own bias:
161
+
162
+ | rel. bump | value | std error | \|error\| |
163
+ | --------- | -------- | --------- | -------------- |
164
+ | 1e-01 | 0.018620 | 2.36e-05 | 7.1e-04 (bias) |
165
+ | 1e-02 | 0.019311 | 9.49e-05 | 2.2e-05 |
166
+ | 1e-03 | 0.019161 | 3.04e-04 | 1.7e-04 |
167
+ | 1e-04 | 0.017274 | 9.15e-04 | 2.1e-03 |
168
+
169
+ The likelihood-ratio method sidesteps that trade-off entirely. This is the
170
+ whole reason the library exists.
171
+
172
+ ## Testing
173
+
174
+ ```bash
175
+ pytest
176
+ ```
177
+
178
+ The suite validates the analytics by complex-step differentiation, confirms each
179
+ Monte Carlo estimator agrees with the analytic Greek within a few standard
180
+ errors, and documents the pathwise failure on digitals as an explicit test.
181
+
182
+ ## Scope and honesty
183
+
184
+ This release covers the Black-Scholes / GBM world and, in `radonlab.merton`, the
185
+ Merton jump-diffusion model with a closed-form digital reference: it shows the
186
+ likelihood-ratio delta weight is unchanged by jumps and validates the estimator
187
+ against the closed form. It is a rigorous, tested core rather than a kitchen
188
+ sink: the estimators and their validation are real, and where a method is
189
+ expected to be biased (pathwise on a digital), the library shows it rather than
190
+ hiding it. It also includes a genuinely path-dependent frontier estimator in
191
+ `radonlab.asian`: the likelihood-ratio / Malliavin delta of a geometric
192
+ Asian digital, validated against the closed form, with a weight built from
193
+ the whole path. Stochastic volatility, arithmetic-Asian and lookback
194
+ payoffs, and a JIT/vectorized backend are natural next steps.
195
+
196
+ ## License
197
+
198
+ Apache-2.0. See [LICENSE](LICENSE).
@@ -0,0 +1,159 @@
1
+ # RadonLab
2
+
3
+ **Monte Carlo Greeks for discontinuous payoffs**, done correctly and benchmarked
4
+ against closed-form references.
5
+
6
+ When an option's payoff is discontinuous (a digital that pays a fixed amount if
7
+ the underlying finishes above a strike, a barrier that knocks out on touch), the
8
+ textbook _pathwise_ (infinitesimal perturbation) estimator for its sensitivities
9
+ quietly breaks: the derivative of the payoff is zero almost everywhere, so the
10
+ estimate collapses toward zero. `radonlab` implements the established remedies,
11
+ tests each one against a known analytic answer, and benchmarks them side by side
12
+ so you can see _which method to use and what it costs_.
13
+
14
+ Pure NumPy/SciPy. Apache-2.0. No copyleft dependencies.
15
+
16
+ ## Companion C++ implementation
17
+
18
+ A header-only C++20 port lives at
19
+ [github.com/quantsingularity/radonlab-cpp](https://github.com/quantsingularity/radonlab-cpp).
20
+ The two libraries share the same methods and the same closed-form references, and
21
+ the C++ analytics are cross-checked against this library's values (which are
22
+ verified to machine precision by complex-step differentiation), so the two agree
23
+ to 1e-9 across languages. The C++ side additionally provides adjoint algorithmic
24
+ differentiation (a full Greek vector from one reverse sweep) and exact
25
+ second-order Greeks. This Python library is the reference and carries the research
26
+ extensions (Merton jump-diffusion and a path-dependent Malliavin delta).
27
+
28
+ ## What's inside
29
+
30
+ Estimators (all with per-path standard errors):
31
+
32
+ - **Likelihood-ratio method (LRM)**: differentiates the _density_, never the
33
+ payoff, so it is unbiased for digitals and other discontinuous payoffs.
34
+ Delta, vega and gamma.
35
+ - **Smoothing**: replaces the payoff with a `C¹` approximation of bandwidth `h`
36
+ and applies the pathwise method to it. A tunable bias/variance trade-off.
37
+ - **Conditional Monte Carlo**: for barriers, integrates out the crossing event
38
+ with the Brownian-bridge non-crossing probability, giving an estimator that is
39
+ unbiased for the _continuously-monitored_ price at any number of steps and
40
+ Lipschitz in spot (so its delta comes out by the pathwise method).
41
+ - **Pathwise** and **finite-difference (bump)** baselines, kept so their failure
42
+ modes on discontinuous payoffs are visible and measurable.
43
+
44
+ Closed-form Black-Scholes analytics (the ground truth) for European calls/puts,
45
+ cash-or-nothing and asset-or-nothing digitals, and continuously-monitored
46
+ down-and-out / down-and-in calls. Every explicit Greek formula is checked
47
+ against complex-step differentiation of the price to machine precision.
48
+
49
+ ## Install
50
+
51
+ ```bash
52
+ pip install -e ".[benchmark,test]"
53
+ ```
54
+
55
+ Runtime dependencies are just `numpy` and `scipy`. `pandas`/`matplotlib` are only
56
+ needed for the benchmark table and plots.
57
+
58
+ ## Quick start
59
+
60
+ ```python
61
+ from radonlab import GeometricBrownianMotion, CashOrNothingCall, Greek
62
+ from radonlab import likelihood_ratio, pathwise, analytics
63
+
64
+ model = GeometricBrownianMotion(S0=100, r=0.03, sigma=0.20, T=1.0)
65
+ payoff = CashOrNothingCall(strike=100)
66
+
67
+ # Ground truth
68
+ ref = analytics.cash_or_nothing_call(100, 100, 0.03, 0.20, 1.0, greek="delta")
69
+
70
+ # Likelihood ratio: unbiased for the digital
71
+ lrm = likelihood_ratio(model, payoff, Greek.DELTA, n_paths=1_000_000)
72
+ print(lrm) # delta=... +/- ... [likelihood-ratio]
73
+ print(lrm.confidence_interval(0.95))
74
+
75
+ # Naive pathwise: collapses to ~0, badly biased
76
+ pw = pathwise(model, payoff, Greek.DELTA, n_paths=1_000_000)
77
+ print(pw.value, "vs analytic", ref)
78
+ ```
79
+
80
+ ## The math, briefly
81
+
82
+ Under geometric Brownian motion `S_T = S₀·exp((r − q − ½σ²)T + σ√T·Z)`, with
83
+ `Z ~ N(0,1)`, a price is `P = e^{−rT} E[f(S_T)]`.
84
+
85
+ - **LRM** writes `∂P/∂θ = e^{−rT} E[f(S_T)·∂_θ log p(S_T;θ)]`. The score functions
86
+ are `Z/(S₀σ√T)` for delta, `(Z²−1)/σ − √T·Z` for vega, and
87
+ `(Z² − σ√T·Z − 1)/(S₀²σ²T)` for gamma. `f` is never differentiated, so a
88
+ jump in `f` is no problem.
89
+ - **Pathwise** writes `∂P/∂θ = e^{−rT} E[f′(S_T)·∂_θ S_T]`. Fine when `f` is
90
+ Lipschitz (vanilla), degenerate when `f` jumps (digital).
91
+ - **Conditional MC** for a down-and-out call multiplies the terminal payoff by
92
+ `∏ᵢ(1 − exp(−2(Xᵢ−b)(Xᵢ₊₁−b)/(σ²Δt)))`, the exact bridge probability of not
93
+ breaching `b = ln B` between simulated points.
94
+
95
+ Full references are in each module's docstring (Broadie-Glasserman 1996,
96
+ Glasserman 2003, Reiner-Rubinstein 1991, and the smoothed-perturbation and
97
+ Malliavin literature).
98
+
99
+ ## Benchmark
100
+
101
+ Reproduce with `python examples/benchmark_digital_delta.py` (1,000,000 paths,
102
+ seed 0). Delta of an at-the-money cash-or-nothing call, `S₀=K=100`, `r=3%`,
103
+ `σ=20%`, `T=1`. Analytic reference delta = **0.019333**. Ranked by standard
104
+ error, the metric that actually reflects an estimator's accuracy:
105
+
106
+ | method | value | std error | \|error\| vs analytic | biased? |
107
+ | --------------------------- | ------- | --------- | --------------------- | ------- |
108
+ | likelihood-ratio | 0.01939 | 2.84e-05 | 5.9e-05 | no |
109
+ | smoothing (h=default) | 0.01921 | 4.56e-05 | 1.2e-04 | no |
110
+ | finite-difference (1% bump) | 0.01934 | 9.49e-05 | 8.5e-06 | no |
111
+ | pathwise | 0.00000 | 0.00e+00 | 1.9e-02 | **yes** |
112
+
113
+ Two things to read off it. First, **pathwise is 100% wrong**: it returns
114
+ exactly zero, because the digital's derivative is zero almost everywhere.
115
+ Second, among the unbiased methods **the likelihood-ratio estimator has the
116
+ lowest variance** (about 3.3× smaller standard error than the 1% finite
117
+ difference) and needs no bump to tune.
118
+
119
+ And finite difference forces a bad choice: the same run sweeping the bump size
120
+ shows the standard error exploding as the bump shrinks, while a large bump
121
+ introduces its own bias:
122
+
123
+ | rel. bump | value | std error | \|error\| |
124
+ | --------- | -------- | --------- | -------------- |
125
+ | 1e-01 | 0.018620 | 2.36e-05 | 7.1e-04 (bias) |
126
+ | 1e-02 | 0.019311 | 9.49e-05 | 2.2e-05 |
127
+ | 1e-03 | 0.019161 | 3.04e-04 | 1.7e-04 |
128
+ | 1e-04 | 0.017274 | 9.15e-04 | 2.1e-03 |
129
+
130
+ The likelihood-ratio method sidesteps that trade-off entirely. This is the
131
+ whole reason the library exists.
132
+
133
+ ## Testing
134
+
135
+ ```bash
136
+ pytest
137
+ ```
138
+
139
+ The suite validates the analytics by complex-step differentiation, confirms each
140
+ Monte Carlo estimator agrees with the analytic Greek within a few standard
141
+ errors, and documents the pathwise failure on digitals as an explicit test.
142
+
143
+ ## Scope and honesty
144
+
145
+ This release covers the Black-Scholes / GBM world and, in `radonlab.merton`, the
146
+ Merton jump-diffusion model with a closed-form digital reference: it shows the
147
+ likelihood-ratio delta weight is unchanged by jumps and validates the estimator
148
+ against the closed form. It is a rigorous, tested core rather than a kitchen
149
+ sink: the estimators and their validation are real, and where a method is
150
+ expected to be biased (pathwise on a digital), the library shows it rather than
151
+ hiding it. It also includes a genuinely path-dependent frontier estimator in
152
+ `radonlab.asian`: the likelihood-ratio / Malliavin delta of a geometric
153
+ Asian digital, validated against the closed form, with a weight built from
154
+ the whole path. Stochastic volatility, arithmetic-Asian and lookback
155
+ payoffs, and a JIT/vectorized backend are natural next steps.
156
+
157
+ ## License
158
+
159
+ Apache-2.0. See [LICENSE](LICENSE).