derivpricer 0.3.1__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.
- derivpricer-0.3.1/LICENSE +21 -0
- derivpricer-0.3.1/PKG-INFO +199 -0
- derivpricer-0.3.1/README.md +174 -0
- derivpricer-0.3.1/derivpricer/__init__.py +12 -0
- derivpricer-0.3.1/derivpricer/dates.py +262 -0
- derivpricer-0.3.1/derivpricer/engines/__init__.py +10 -0
- derivpricer-0.3.1/derivpricer/engines/analytic.py +143 -0
- derivpricer-0.3.1/derivpricer/engines/base.py +31 -0
- derivpricer-0.3.1/derivpricer/engines/fd.py +157 -0
- derivpricer-0.3.1/derivpricer/engines/mc.py +159 -0
- derivpricer-0.3.1/derivpricer/engines/tree.py +47 -0
- derivpricer-0.3.1/derivpricer/gui/__init__.py +0 -0
- derivpricer-0.3.1/derivpricer/gui/app.py +24 -0
- derivpricer-0.3.1/derivpricer/gui/assets/pricer_icon.png +0 -0
- derivpricer-0.3.1/derivpricer/gui/india_tab.py +377 -0
- derivpricer-0.3.1/derivpricer/gui/main_window.py +676 -0
- derivpricer-0.3.1/derivpricer/gui/multicurve_tab.py +368 -0
- derivpricer-0.3.1/derivpricer/gui/widgets.py +51 -0
- derivpricer-0.3.1/derivpricer/gui/worker.py +27 -0
- derivpricer-0.3.1/derivpricer/india/__init__.py +21 -0
- derivpricer-0.3.1/derivpricer/india/conventions.py +81 -0
- derivpricer-0.3.1/derivpricer/india/curves.py +133 -0
- derivpricer-0.3.1/derivpricer/india/data/india_market.json +170 -0
- derivpricer-0.3.1/derivpricer/india/data/sample_inr_quotes.json +133 -0
- derivpricer-0.3.1/derivpricer/india/nse.py +248 -0
- derivpricer-0.3.1/derivpricer/market/__init__.py +21 -0
- derivpricer-0.3.1/derivpricer/market/bootstrap.py +82 -0
- derivpricer-0.3.1/derivpricer/market/curves.py +107 -0
- derivpricer-0.3.1/derivpricer/market/data/sample_multicurve_quotes.json +504 -0
- derivpricer-0.3.1/derivpricer/market/dated.py +220 -0
- derivpricer-0.3.1/derivpricer/market/market_data.py +69 -0
- derivpricer-0.3.1/derivpricer/market/multicurve.py +451 -0
- derivpricer-0.3.1/derivpricer/market/vol.py +74 -0
- derivpricer-0.3.1/derivpricer/pricing.py +71 -0
- derivpricer-0.3.1/derivpricer/products/__init__.py +9 -0
- derivpricer-0.3.1/derivpricer/products/options.py +156 -0
- derivpricer-0.3.1/derivpricer/risk/__init__.py +3 -0
- derivpricer-0.3.1/derivpricer/risk/greeks.py +56 -0
- derivpricer-0.3.1/derivpricer.egg-info/PKG-INFO +199 -0
- derivpricer-0.3.1/derivpricer.egg-info/SOURCES.txt +47 -0
- derivpricer-0.3.1/derivpricer.egg-info/dependency_links.txt +1 -0
- derivpricer-0.3.1/derivpricer.egg-info/entry_points.txt +2 -0
- derivpricer-0.3.1/derivpricer.egg-info/requires.txt +9 -0
- derivpricer-0.3.1/derivpricer.egg-info/top_level.txt +1 -0
- derivpricer-0.3.1/pyproject.toml +40 -0
- derivpricer-0.3.1/setup.cfg +4 -0
- derivpricer-0.3.1/tests/test_india.py +188 -0
- derivpricer-0.3.1/tests/test_multicurve.py +155 -0
- derivpricer-0.3.1/tests/test_pricing.py +194 -0
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
MIT License
|
|
2
|
+
|
|
3
|
+
Copyright (c) 2026 Krish-PiTheta (Pi-Theta Analytics & Consulting LLP)
|
|
4
|
+
|
|
5
|
+
Permission is hereby granted, free of charge, to any person obtaining a copy
|
|
6
|
+
of this software and associated documentation files (the "Software"), to deal
|
|
7
|
+
in the Software without restriction, including without limitation the rights
|
|
8
|
+
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
|
9
|
+
copies of the Software, and to permit persons to whom the Software is
|
|
10
|
+
furnished to do so, subject to the following conditions:
|
|
11
|
+
|
|
12
|
+
The above copyright notice and this permission notice shall be included in all
|
|
13
|
+
copies or substantial portions of the Software.
|
|
14
|
+
|
|
15
|
+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
|
16
|
+
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
|
17
|
+
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
|
18
|
+
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
|
19
|
+
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
|
20
|
+
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
|
21
|
+
SOFTWARE.
|
|
@@ -0,0 +1,199 @@
|
|
|
1
|
+
Metadata-Version: 2.4
|
|
2
|
+
Name: derivpricer
|
|
3
|
+
Version: 0.3.1
|
|
4
|
+
Summary: Validated multi-engine derivatives pricer: FX & equity options, OIS multi-curve, Indian (NSE/CCIL) market conventions
|
|
5
|
+
Author: Krish-PiTheta (Pi-Theta Analytics & Consulting LLP)
|
|
6
|
+
License-Expression: MIT
|
|
7
|
+
Project-URL: Homepage, https://github.com/pi-theta-analytics-consulting/Derivatives-Pricer
|
|
8
|
+
Project-URL: Documentation, https://github.com/pi-theta-analytics-consulting/Derivatives-Pricer/blob/main/docs/TECHNICAL.md
|
|
9
|
+
Keywords: derivatives,option pricing,quantitative finance,monte carlo,finite difference,yield curve,NSE,INR
|
|
10
|
+
Classifier: Programming Language :: Python :: 3
|
|
11
|
+
Classifier: Topic :: Office/Business :: Financial :: Investment
|
|
12
|
+
Classifier: Intended Audience :: Financial and Insurance Industry
|
|
13
|
+
Classifier: Development Status :: 3 - Alpha
|
|
14
|
+
Requires-Python: >=3.10
|
|
15
|
+
Description-Content-Type: text/markdown
|
|
16
|
+
License-File: LICENSE
|
|
17
|
+
Requires-Dist: numpy>=1.24
|
|
18
|
+
Requires-Dist: scipy>=1.10
|
|
19
|
+
Provides-Extra: gui
|
|
20
|
+
Requires-Dist: PySide6>=6.5; extra == "gui"
|
|
21
|
+
Requires-Dist: matplotlib>=3.7; extra == "gui"
|
|
22
|
+
Provides-Extra: dev
|
|
23
|
+
Requires-Dist: pytest>=7.0; extra == "dev"
|
|
24
|
+
Dynamic: license-file
|
|
25
|
+
|
|
26
|
+
# Derivatives Pricer
|
|
27
|
+
<img src="https://raw.githubusercontent.com/pi-theta-analytics-consulting/Derivatives-Pricer/main/assets/3-GitHub-README-logo.svg" alt="Pi-Theta Analytics & Consulting LLP" width="360">
|
|
28
|
+
|
|
29
|
+
[](https://github.com/pi-theta-analytics-consulting/Derivatives-Pricer/actions/workflows/tests.yml)
|
|
30
|
+

|
|
31
|
+
[](https://github.com/pi-theta-analytics-consulting/Derivatives-Pricer/blob/main/LICENSE)
|
|
32
|
+
|
|
33
|
+
A validated, multi-engine derivatives pricing workbench in Python for FX and equity options, with
|
|
34
|
+
OIS / multi-curve discounting under collateral (USD, EUR, JPY, INR), **Indian-market support (NSE
|
|
35
|
+
expiry calendars, CCIL/FIMMDA MIBOR OIS conventions, NSE index and USDINR options on real dates)**
|
|
36
|
+
and a PySide6 desktop GUI.
|
|
37
|
+
|
|
38
|
+
Every engine is cross-checked against published benchmarks (Hull, Haug) and no-arbitrage
|
|
39
|
+
identities in 83 automated tests. Models, numerics and limitations are documented in
|
|
40
|
+
[docs/TECHNICAL.md](https://github.com/pi-theta-analytics-consulting/Derivatives-Pricer/blob/main/docs/TECHNICAL.md).
|
|
41
|
+
|
|
42
|
+

|
|
43
|
+
|
|
44
|
+
| India (NSE) tab | Multi-curve builder | Price vs spot |
|
|
45
|
+
|---|---|---|
|
|
46
|
+
|  |  |  |
|
|
47
|
+
|
|
48
|
+
> **Status:** v0.3.1, Phase 1 of a six-phase [roadmap](https://github.com/pi-theta-analytics-consulting/Derivatives-Pricer/blob/main/docs/ROADMAP.md) complete. A research and
|
|
49
|
+
> learning tool, not production software: dated calendars and day counts cover INR only so
|
|
50
|
+
> far (other currencies in Phase 2), smile is not in the dynamics, and the bundled market
|
|
51
|
+
> quotes are illustrative. See the [changelog](https://github.com/pi-theta-analytics-consulting/Derivatives-Pricer/blob/main/CHANGELOG.md).
|
|
52
|
+
|
|
53
|
+
## Install and run
|
|
54
|
+
|
|
55
|
+
```bash
|
|
56
|
+
# Python 3.10+ recommended
|
|
57
|
+
python -m venv .venv
|
|
58
|
+
# Windows: .venv\Scripts\activate macOS/Linux: source .venv/bin/activate
|
|
59
|
+
pip install -r requirements.txt
|
|
60
|
+
|
|
61
|
+
python main.py # launch the GUI
|
|
62
|
+
python -m pytest -q # run the 83 benchmark tests
|
|
63
|
+
python examples/quickstart.py # use the library from code
|
|
64
|
+
python examples/multicurve.py # multi-curve build and FX options on it
|
|
65
|
+
python examples/india_nse.py # NSE expiries, INR curves, NIFTY and USDINR options
|
|
66
|
+
```
|
|
67
|
+
|
|
68
|
+
Or install it as a package from PyPI (or straight from GitHub):
|
|
69
|
+
|
|
70
|
+
```bash
|
|
71
|
+
pip install derivpricer # library only (NumPy, SciPy)
|
|
72
|
+
pip install "derivpricer[gui]" # library + desktop GUI (PySide6, matplotlib)
|
|
73
|
+
derivpricer-gui # launch the GUI
|
|
74
|
+
|
|
75
|
+
# latest main from GitHub instead of PyPI:
|
|
76
|
+
pip install "derivpricer[gui] @ git+https://github.com/pi-theta-analytics-consulting/Derivatives-Pricer"
|
|
77
|
+
```
|
|
78
|
+
|
|
79
|
+
On Linux or Windows (WSL/WSLg), `./launch_pricer.sh` starts the GUI; it uses `$PRICER_PYTHON`
|
|
80
|
+
if set. Add `--with-claude` to also open a Claude Code terminal in the project folder (WSL).
|
|
81
|
+
|
|
82
|
+
## What's in Phase 1
|
|
83
|
+
|
|
84
|
+
| Area | Coverage |
|
|
85
|
+
|---|---|
|
|
86
|
+
| Asset classes | Equity (dividend yield), FX (Garman-Kohlhagen: domestic and foreign curves) |
|
|
87
|
+
| Products | Forward; European and American call/put; cash-or-nothing and asset-or-nothing digitals; single barriers (DO/DI/UO/UI) with rebate |
|
|
88
|
+
| Engines | Analytic (Black-Scholes, Reiner-Rubinstein barriers); CRR binomial tree; Crank-Nicolson finite difference (Rannacher start, American, continuous barriers); Monte Carlo (antithetic, Brownian-bridge barriers, Longstaff-Schwartz American) |
|
|
89
|
+
| Market data | Flat, zero and discount curves with log-linear interpolation; deposit and swap bootstrapper; flat and grid vol surfaces |
|
|
90
|
+
| Multi-curve | USD (SOFR), EUR (€STR), JPY (TONA), INR (MIBOR) OIS discount curves; EURIBOR 6M and TIBOR 6M projection curves on OIS discounting; FX-implied (collateral) curves from EURUSD, USDJPY, USDINR forwards; cross pairs triangulated |
|
|
91
|
+
| Risk | Bump-and-revalue delta, gamma, vega, theta, rho, carry-rho for any engine |
|
|
92
|
+
| GUI | Trade entry, market inputs (flat, single curve or multi-curve), engine choice and settings, results per unit and total, engine comparison, charts (price/Greeks vs spot, vol, time), single-curve builder, multi-curve builder |
|
|
93
|
+
|
|
94
|
+
### Engine / product matrix
|
|
95
|
+
|
|
96
|
+
| | Analytic | Tree | FD | MC |
|
|
97
|
+
|---|:-:|:-:|:-:|:-:|
|
|
98
|
+
| Forward | ✓ | | | ✓ |
|
|
99
|
+
| European | ✓ | ✓ | ✓ | ✓ |
|
|
100
|
+
| American | | ✓ | ✓ | ✓ (LSM) |
|
|
101
|
+
| Digital | ✓ | | ✓ | ✓ |
|
|
102
|
+
| Barrier | ✓ | | ✓ | ✓ |
|
|
103
|
+
|
|
104
|
+
## Validation
|
|
105
|
+
|
|
106
|
+
`tests/test_pricing.py` checks against published values and no-arbitrage identities:
|
|
107
|
+
|
|
108
|
+
* Hull's Black-Scholes example (4.7594 / 0.8086) and American put (≈4.28)
|
|
109
|
+
* All ten Haug (2007) Table 4-13 barrier values, matched by analytic, FD and MC engines
|
|
110
|
+
* Put-call parity, in/out barrier parity, digital = call-spread limit, cash + asset digital = call
|
|
111
|
+
* Bump Greeks vs closed-form Greeks
|
|
112
|
+
* Bootstrapped curve reprices every input deposit and swap exactly
|
|
113
|
+
* Multi-curve: every OIS, fixing, FRA, IBOR swap and FX forward reprices exactly; dual-curve collapses to single-curve when quotes coincide; cross forwards triangulate; MC barrier vs analytic on multi-curve inputs
|
|
114
|
+
* FD and MC with non-flat curves and smile vs analytic
|
|
115
|
+
|
|
116
|
+
## Project layout
|
|
117
|
+
|
|
118
|
+
```
|
|
119
|
+
derivpricer/ pricing library (core imports only NumPy/SciPy)
|
|
120
|
+
market/ curves, bootstrapping, multi-curve, vol surfaces, MarketData
|
|
121
|
+
data/ sample multi-curve quotes (illustrative)
|
|
122
|
+
products/ product definitions (payoffs as data)
|
|
123
|
+
engines/ analytic, tree, FD, Monte Carlo
|
|
124
|
+
risk/ Greeks
|
|
125
|
+
dates.py calendars, day counts, tenors, schedules
|
|
126
|
+
india/ NSE contracts, INR curves, data/india_market.json
|
|
127
|
+
pricing.py engine registry and price() facade
|
|
128
|
+
gui/ PySide6 application, optional [gui] extra (multicurve_tab.py, india_tab.py)
|
|
129
|
+
tests/ benchmark tests
|
|
130
|
+
examples/ scripted usage (quickstart, multi-curve, India/NSE)
|
|
131
|
+
docs/ROADMAP.md phase plan
|
|
132
|
+
docs/TECHNICAL.md technical documentation: models, numerics, conventions, validation, limitations
|
|
133
|
+
main.py GUI entry point
|
|
134
|
+
```
|
|
135
|
+
|
|
136
|
+
## Indian market (NSE / CCIL)
|
|
137
|
+
|
|
138
|
+
```python
|
|
139
|
+
import datetime as dt
|
|
140
|
+
from derivpricer.india import IndiaMarket, expiries, price_nse_option
|
|
141
|
+
|
|
142
|
+
exp = expiries("NIFTY", "2026-11-27")[0] # Tue 01-Dec-2026 weekly (holidays respected)
|
|
143
|
+
mkt = IndiaMarket.sample() # or IndiaMarket.from_json("my_inr_quotes.json")
|
|
144
|
+
r = price_nse_option("NIFTY", exp.date, 26000, "Call", spot=26000, vol=0.12, lots=2,
|
|
145
|
+
market=mkt, valuation=dt.datetime(2026, 11, 27, 15, 30))
|
|
146
|
+
print(r.price_lot, r.premium, r.greeks_total())
|
|
147
|
+
```
|
|
148
|
+
|
|
149
|
+
* **Calendars:** NSE F&O and currency-segment holidays, Mumbai settlement; real dates, ACT/365 and
|
|
150
|
+
other day counts, business-day rolls.
|
|
151
|
+
* **NSE options:** NIFTY weekly (Tuesday) and monthly; BANKNIFTY, FINNIFTY, MIDCPNIFTY monthly;
|
|
152
|
+
USDINR weekly and monthly. Holidays move expiries to the previous trading day. Lot sizes, T+1/T+2
|
|
153
|
+
settlement and intraday time to expiry.
|
|
154
|
+
* **INR curves:** MIBOR OIS (ACT/365, T+1, at maturity up to 1Y, semi-annual beyond), SOFR OIS and
|
|
155
|
+
the USD-collateral INR curve implied from USDINR forward points.
|
|
156
|
+
* **Configuration:** holidays, lot sizes and conventions are in
|
|
157
|
+
`derivpricer/india/data/india_market.json` with sources. **Verify against current circulars.**
|
|
158
|
+
|
|
159
|
+
## Multi-curve builder
|
|
160
|
+
|
|
161
|
+
`derivpricer/market/multicurve.py` builds, per currency:
|
|
162
|
+
|
|
163
|
+
| Curve | Instruments | Use |
|
|
164
|
+
|---|---|---|
|
|
165
|
+
| OIS discount curve (SOFR, €STR, TONA, MIBOR) | Overnight-index deposits, par OIS swaps | Discounting with same-currency collateral; equity discounting |
|
|
166
|
+
| Projection curve (EURIBOR 6M, TIBOR 6M) | Fixing, FRAs, par IBOR swaps, bootstrapped **with OIS discounting** | Index forwards for floating legs (caps, swaptions in Phase 2) |
|
|
167
|
+
| FX-implied curve (EUR, JPY, INR vs USD) | Outright FX forwards + USD SOFR curve | Discounting with USD collateral; holds the cross-currency basis |
|
|
168
|
+
|
|
169
|
+
`MultiCurveMarket.fx_market_data(pair, vol, collateral=...)` returns a `MarketData` whose
|
|
170
|
+
domestic (quote currency) and foreign (base currency) curves are picked by collateral:
|
|
171
|
+
with USD collateral, USDINR uses SOFR for USD and the forward-implied INR curve, so the
|
|
172
|
+
model forward matches the quoted FX forward exactly; with no collateral each currency uses
|
|
173
|
+
its own OIS. Every engine and the bump Greeks work on it unchanged.
|
|
174
|
+
|
|
175
|
+
Quotes live in a JSON file (rates in %, tenors in years). The bundled
|
|
176
|
+
`derivpricer/market/data/sample_multicurve_quotes.json` holds **illustrative numbers, not
|
|
177
|
+
live data**: load your own via the GUI (Multi-Curve tab → Load JSON) or
|
|
178
|
+
`MultiCurveMarket.from_json(path)`. In the GUI, build the curves, then set *Rates from* to
|
|
179
|
+
*Multi-curve* and pick the FX pair (or the currency for equity).
|
|
180
|
+
|
|
181
|
+
## Conventions and current limitations
|
|
182
|
+
|
|
183
|
+
* Generic products use year-fraction expiries; the India module uses real dates, calendars and day counts. Other currencies get dates in Phase 2.
|
|
184
|
+
* Prices are per unit of notional. For FX the price is in domestic currency per unit of foreign currency; the GUI also shows pips and % of foreign notional.
|
|
185
|
+
* Vol is Black implied vol at the strike. Barrier pricing under smile (local or stochastic vol) is Phase 3.
|
|
186
|
+
* The single-curve builder uses annual fixed legs. The multi-curve builder supports OIS, IBOR projection and FX-implied curves, but without day counts, spot lags or payment calendars (Phase 2, QuantLib). Long-dated cross-currency basis swaps are not yet an input: the FX-implied curve extrapolates flat-forward past the last FX forward.
|
|
187
|
+
* Barriers are continuously monitored. Discrete monitoring (Broadie-Glasserman shift) is Phase 3.
|
|
188
|
+
|
|
189
|
+
## Adding a product or engine
|
|
190
|
+
|
|
191
|
+
1. Define a frozen dataclass in `derivpricer/products/` with a vectorised `payoff(S)`.
|
|
192
|
+
2. Add the class to `supported` of each engine that can price it (FD and MC usually work straight away through `payoff`).
|
|
193
|
+
3. Add it to `PRODUCTS` and `_build_product()` in `derivpricer/gui/main_window.py`.
|
|
194
|
+
4. Add a benchmark test.
|
|
195
|
+
|
|
196
|
+
## Licence and author
|
|
197
|
+
|
|
198
|
+
MIT licence (see [LICENSE](https://github.com/pi-theta-analytics-consulting/Derivatives-Pricer/blob/main/LICENSE)). Built by [Krish-PiTheta](https://github.com/Krish-PiTheta),
|
|
199
|
+
Pi-Theta Analytics & Consulting LLP, with AI assistance (Claude Code).
|
|
@@ -0,0 +1,174 @@
|
|
|
1
|
+
# Derivatives Pricer
|
|
2
|
+
<img src="https://raw.githubusercontent.com/pi-theta-analytics-consulting/Derivatives-Pricer/main/assets/3-GitHub-README-logo.svg" alt="Pi-Theta Analytics & Consulting LLP" width="360">
|
|
3
|
+
|
|
4
|
+
[](https://github.com/pi-theta-analytics-consulting/Derivatives-Pricer/actions/workflows/tests.yml)
|
|
5
|
+

|
|
6
|
+
[](https://github.com/pi-theta-analytics-consulting/Derivatives-Pricer/blob/main/LICENSE)
|
|
7
|
+
|
|
8
|
+
A validated, multi-engine derivatives pricing workbench in Python for FX and equity options, with
|
|
9
|
+
OIS / multi-curve discounting under collateral (USD, EUR, JPY, INR), **Indian-market support (NSE
|
|
10
|
+
expiry calendars, CCIL/FIMMDA MIBOR OIS conventions, NSE index and USDINR options on real dates)**
|
|
11
|
+
and a PySide6 desktop GUI.
|
|
12
|
+
|
|
13
|
+
Every engine is cross-checked against published benchmarks (Hull, Haug) and no-arbitrage
|
|
14
|
+
identities in 83 automated tests. Models, numerics and limitations are documented in
|
|
15
|
+
[docs/TECHNICAL.md](https://github.com/pi-theta-analytics-consulting/Derivatives-Pricer/blob/main/docs/TECHNICAL.md).
|
|
16
|
+
|
|
17
|
+

|
|
18
|
+
|
|
19
|
+
| India (NSE) tab | Multi-curve builder | Price vs spot |
|
|
20
|
+
|---|---|---|
|
|
21
|
+
|  |  |  |
|
|
22
|
+
|
|
23
|
+
> **Status:** v0.3.1, Phase 1 of a six-phase [roadmap](https://github.com/pi-theta-analytics-consulting/Derivatives-Pricer/blob/main/docs/ROADMAP.md) complete. A research and
|
|
24
|
+
> learning tool, not production software: dated calendars and day counts cover INR only so
|
|
25
|
+
> far (other currencies in Phase 2), smile is not in the dynamics, and the bundled market
|
|
26
|
+
> quotes are illustrative. See the [changelog](https://github.com/pi-theta-analytics-consulting/Derivatives-Pricer/blob/main/CHANGELOG.md).
|
|
27
|
+
|
|
28
|
+
## Install and run
|
|
29
|
+
|
|
30
|
+
```bash
|
|
31
|
+
# Python 3.10+ recommended
|
|
32
|
+
python -m venv .venv
|
|
33
|
+
# Windows: .venv\Scripts\activate macOS/Linux: source .venv/bin/activate
|
|
34
|
+
pip install -r requirements.txt
|
|
35
|
+
|
|
36
|
+
python main.py # launch the GUI
|
|
37
|
+
python -m pytest -q # run the 83 benchmark tests
|
|
38
|
+
python examples/quickstart.py # use the library from code
|
|
39
|
+
python examples/multicurve.py # multi-curve build and FX options on it
|
|
40
|
+
python examples/india_nse.py # NSE expiries, INR curves, NIFTY and USDINR options
|
|
41
|
+
```
|
|
42
|
+
|
|
43
|
+
Or install it as a package from PyPI (or straight from GitHub):
|
|
44
|
+
|
|
45
|
+
```bash
|
|
46
|
+
pip install derivpricer # library only (NumPy, SciPy)
|
|
47
|
+
pip install "derivpricer[gui]" # library + desktop GUI (PySide6, matplotlib)
|
|
48
|
+
derivpricer-gui # launch the GUI
|
|
49
|
+
|
|
50
|
+
# latest main from GitHub instead of PyPI:
|
|
51
|
+
pip install "derivpricer[gui] @ git+https://github.com/pi-theta-analytics-consulting/Derivatives-Pricer"
|
|
52
|
+
```
|
|
53
|
+
|
|
54
|
+
On Linux or Windows (WSL/WSLg), `./launch_pricer.sh` starts the GUI; it uses `$PRICER_PYTHON`
|
|
55
|
+
if set. Add `--with-claude` to also open a Claude Code terminal in the project folder (WSL).
|
|
56
|
+
|
|
57
|
+
## What's in Phase 1
|
|
58
|
+
|
|
59
|
+
| Area | Coverage |
|
|
60
|
+
|---|---|
|
|
61
|
+
| Asset classes | Equity (dividend yield), FX (Garman-Kohlhagen: domestic and foreign curves) |
|
|
62
|
+
| Products | Forward; European and American call/put; cash-or-nothing and asset-or-nothing digitals; single barriers (DO/DI/UO/UI) with rebate |
|
|
63
|
+
| Engines | Analytic (Black-Scholes, Reiner-Rubinstein barriers); CRR binomial tree; Crank-Nicolson finite difference (Rannacher start, American, continuous barriers); Monte Carlo (antithetic, Brownian-bridge barriers, Longstaff-Schwartz American) |
|
|
64
|
+
| Market data | Flat, zero and discount curves with log-linear interpolation; deposit and swap bootstrapper; flat and grid vol surfaces |
|
|
65
|
+
| Multi-curve | USD (SOFR), EUR (€STR), JPY (TONA), INR (MIBOR) OIS discount curves; EURIBOR 6M and TIBOR 6M projection curves on OIS discounting; FX-implied (collateral) curves from EURUSD, USDJPY, USDINR forwards; cross pairs triangulated |
|
|
66
|
+
| Risk | Bump-and-revalue delta, gamma, vega, theta, rho, carry-rho for any engine |
|
|
67
|
+
| GUI | Trade entry, market inputs (flat, single curve or multi-curve), engine choice and settings, results per unit and total, engine comparison, charts (price/Greeks vs spot, vol, time), single-curve builder, multi-curve builder |
|
|
68
|
+
|
|
69
|
+
### Engine / product matrix
|
|
70
|
+
|
|
71
|
+
| | Analytic | Tree | FD | MC |
|
|
72
|
+
|---|:-:|:-:|:-:|:-:|
|
|
73
|
+
| Forward | ✓ | | | ✓ |
|
|
74
|
+
| European | ✓ | ✓ | ✓ | ✓ |
|
|
75
|
+
| American | | ✓ | ✓ | ✓ (LSM) |
|
|
76
|
+
| Digital | ✓ | | ✓ | ✓ |
|
|
77
|
+
| Barrier | ✓ | | ✓ | ✓ |
|
|
78
|
+
|
|
79
|
+
## Validation
|
|
80
|
+
|
|
81
|
+
`tests/test_pricing.py` checks against published values and no-arbitrage identities:
|
|
82
|
+
|
|
83
|
+
* Hull's Black-Scholes example (4.7594 / 0.8086) and American put (≈4.28)
|
|
84
|
+
* All ten Haug (2007) Table 4-13 barrier values, matched by analytic, FD and MC engines
|
|
85
|
+
* Put-call parity, in/out barrier parity, digital = call-spread limit, cash + asset digital = call
|
|
86
|
+
* Bump Greeks vs closed-form Greeks
|
|
87
|
+
* Bootstrapped curve reprices every input deposit and swap exactly
|
|
88
|
+
* Multi-curve: every OIS, fixing, FRA, IBOR swap and FX forward reprices exactly; dual-curve collapses to single-curve when quotes coincide; cross forwards triangulate; MC barrier vs analytic on multi-curve inputs
|
|
89
|
+
* FD and MC with non-flat curves and smile vs analytic
|
|
90
|
+
|
|
91
|
+
## Project layout
|
|
92
|
+
|
|
93
|
+
```
|
|
94
|
+
derivpricer/ pricing library (core imports only NumPy/SciPy)
|
|
95
|
+
market/ curves, bootstrapping, multi-curve, vol surfaces, MarketData
|
|
96
|
+
data/ sample multi-curve quotes (illustrative)
|
|
97
|
+
products/ product definitions (payoffs as data)
|
|
98
|
+
engines/ analytic, tree, FD, Monte Carlo
|
|
99
|
+
risk/ Greeks
|
|
100
|
+
dates.py calendars, day counts, tenors, schedules
|
|
101
|
+
india/ NSE contracts, INR curves, data/india_market.json
|
|
102
|
+
pricing.py engine registry and price() facade
|
|
103
|
+
gui/ PySide6 application, optional [gui] extra (multicurve_tab.py, india_tab.py)
|
|
104
|
+
tests/ benchmark tests
|
|
105
|
+
examples/ scripted usage (quickstart, multi-curve, India/NSE)
|
|
106
|
+
docs/ROADMAP.md phase plan
|
|
107
|
+
docs/TECHNICAL.md technical documentation: models, numerics, conventions, validation, limitations
|
|
108
|
+
main.py GUI entry point
|
|
109
|
+
```
|
|
110
|
+
|
|
111
|
+
## Indian market (NSE / CCIL)
|
|
112
|
+
|
|
113
|
+
```python
|
|
114
|
+
import datetime as dt
|
|
115
|
+
from derivpricer.india import IndiaMarket, expiries, price_nse_option
|
|
116
|
+
|
|
117
|
+
exp = expiries("NIFTY", "2026-11-27")[0] # Tue 01-Dec-2026 weekly (holidays respected)
|
|
118
|
+
mkt = IndiaMarket.sample() # or IndiaMarket.from_json("my_inr_quotes.json")
|
|
119
|
+
r = price_nse_option("NIFTY", exp.date, 26000, "Call", spot=26000, vol=0.12, lots=2,
|
|
120
|
+
market=mkt, valuation=dt.datetime(2026, 11, 27, 15, 30))
|
|
121
|
+
print(r.price_lot, r.premium, r.greeks_total())
|
|
122
|
+
```
|
|
123
|
+
|
|
124
|
+
* **Calendars:** NSE F&O and currency-segment holidays, Mumbai settlement; real dates, ACT/365 and
|
|
125
|
+
other day counts, business-day rolls.
|
|
126
|
+
* **NSE options:** NIFTY weekly (Tuesday) and monthly; BANKNIFTY, FINNIFTY, MIDCPNIFTY monthly;
|
|
127
|
+
USDINR weekly and monthly. Holidays move expiries to the previous trading day. Lot sizes, T+1/T+2
|
|
128
|
+
settlement and intraday time to expiry.
|
|
129
|
+
* **INR curves:** MIBOR OIS (ACT/365, T+1, at maturity up to 1Y, semi-annual beyond), SOFR OIS and
|
|
130
|
+
the USD-collateral INR curve implied from USDINR forward points.
|
|
131
|
+
* **Configuration:** holidays, lot sizes and conventions are in
|
|
132
|
+
`derivpricer/india/data/india_market.json` with sources. **Verify against current circulars.**
|
|
133
|
+
|
|
134
|
+
## Multi-curve builder
|
|
135
|
+
|
|
136
|
+
`derivpricer/market/multicurve.py` builds, per currency:
|
|
137
|
+
|
|
138
|
+
| Curve | Instruments | Use |
|
|
139
|
+
|---|---|---|
|
|
140
|
+
| OIS discount curve (SOFR, €STR, TONA, MIBOR) | Overnight-index deposits, par OIS swaps | Discounting with same-currency collateral; equity discounting |
|
|
141
|
+
| Projection curve (EURIBOR 6M, TIBOR 6M) | Fixing, FRAs, par IBOR swaps, bootstrapped **with OIS discounting** | Index forwards for floating legs (caps, swaptions in Phase 2) |
|
|
142
|
+
| FX-implied curve (EUR, JPY, INR vs USD) | Outright FX forwards + USD SOFR curve | Discounting with USD collateral; holds the cross-currency basis |
|
|
143
|
+
|
|
144
|
+
`MultiCurveMarket.fx_market_data(pair, vol, collateral=...)` returns a `MarketData` whose
|
|
145
|
+
domestic (quote currency) and foreign (base currency) curves are picked by collateral:
|
|
146
|
+
with USD collateral, USDINR uses SOFR for USD and the forward-implied INR curve, so the
|
|
147
|
+
model forward matches the quoted FX forward exactly; with no collateral each currency uses
|
|
148
|
+
its own OIS. Every engine and the bump Greeks work on it unchanged.
|
|
149
|
+
|
|
150
|
+
Quotes live in a JSON file (rates in %, tenors in years). The bundled
|
|
151
|
+
`derivpricer/market/data/sample_multicurve_quotes.json` holds **illustrative numbers, not
|
|
152
|
+
live data**: load your own via the GUI (Multi-Curve tab → Load JSON) or
|
|
153
|
+
`MultiCurveMarket.from_json(path)`. In the GUI, build the curves, then set *Rates from* to
|
|
154
|
+
*Multi-curve* and pick the FX pair (or the currency for equity).
|
|
155
|
+
|
|
156
|
+
## Conventions and current limitations
|
|
157
|
+
|
|
158
|
+
* Generic products use year-fraction expiries; the India module uses real dates, calendars and day counts. Other currencies get dates in Phase 2.
|
|
159
|
+
* Prices are per unit of notional. For FX the price is in domestic currency per unit of foreign currency; the GUI also shows pips and % of foreign notional.
|
|
160
|
+
* Vol is Black implied vol at the strike. Barrier pricing under smile (local or stochastic vol) is Phase 3.
|
|
161
|
+
* The single-curve builder uses annual fixed legs. The multi-curve builder supports OIS, IBOR projection and FX-implied curves, but without day counts, spot lags or payment calendars (Phase 2, QuantLib). Long-dated cross-currency basis swaps are not yet an input: the FX-implied curve extrapolates flat-forward past the last FX forward.
|
|
162
|
+
* Barriers are continuously monitored. Discrete monitoring (Broadie-Glasserman shift) is Phase 3.
|
|
163
|
+
|
|
164
|
+
## Adding a product or engine
|
|
165
|
+
|
|
166
|
+
1. Define a frozen dataclass in `derivpricer/products/` with a vectorised `payoff(S)`.
|
|
167
|
+
2. Add the class to `supported` of each engine that can price it (FD and MC usually work straight away through `payoff`).
|
|
168
|
+
3. Add it to `PRODUCTS` and `_build_product()` in `derivpricer/gui/main_window.py`.
|
|
169
|
+
4. Add a benchmark test.
|
|
170
|
+
|
|
171
|
+
## Licence and author
|
|
172
|
+
|
|
173
|
+
MIT licence (see [LICENSE](https://github.com/pi-theta-analytics-consulting/Derivatives-Pricer/blob/main/LICENSE)). Built by [Krish-PiTheta](https://github.com/Krish-PiTheta),
|
|
174
|
+
Pi-Theta Analytics & Consulting LLP, with AI assistance (Claude Code).
|
|
@@ -0,0 +1,12 @@
|
|
|
1
|
+
"""derivpricer - a modular derivatives pricing library.
|
|
2
|
+
|
|
3
|
+
Phase 1: market data (curves, bootstrapping, multi-curve, vol surfaces), FX & equity
|
|
4
|
+
forwards, European/American, digital and barrier options, with analytic,
|
|
5
|
+
binomial tree, finite-difference and Monte Carlo engines and bump Greeks.
|
|
6
|
+
"""
|
|
7
|
+
from .market import * # noqa: F401,F403
|
|
8
|
+
from .products import * # noqa: F401,F403
|
|
9
|
+
from .engines import * # noqa: F401,F403
|
|
10
|
+
from .pricing import price, available_engines, make_engine, PricingResult, ENGINE_REGISTRY # noqa: F401
|
|
11
|
+
|
|
12
|
+
__version__ = "0.3.1"
|
|
@@ -0,0 +1,262 @@
|
|
|
1
|
+
"""Dates, business-day calendars, tenors, day counts and schedules.
|
|
2
|
+
|
|
3
|
+
Currency-agnostic building blocks for dated (rather than year-fraction)
|
|
4
|
+
pricing. Market-specific holiday data and conventions live in configuration
|
|
5
|
+
files (see ``derivpricer/india``).
|
|
6
|
+
"""
|
|
7
|
+
from __future__ import annotations
|
|
8
|
+
|
|
9
|
+
import calendar as _cal
|
|
10
|
+
import datetime as dt
|
|
11
|
+
import re
|
|
12
|
+
import warnings
|
|
13
|
+
from enum import Enum
|
|
14
|
+
|
|
15
|
+
Date = dt.date
|
|
16
|
+
|
|
17
|
+
WEEKDAYS = {"MON": 0, "TUE": 1, "WED": 2, "THU": 3, "FRI": 4, "SAT": 5, "SUN": 6}
|
|
18
|
+
|
|
19
|
+
|
|
20
|
+
class CalendarCoverageWarning(UserWarning):
|
|
21
|
+
"""A date falls outside the years for which a calendar has holiday data."""
|
|
22
|
+
|
|
23
|
+
def __init__(self, calendar: str = "", year: int = 0):
|
|
24
|
+
super().__init__(f"Calendar {calendar} has no holiday data for {year}; only weekends are excluded")
|
|
25
|
+
self.calendar, self.year = calendar, year
|
|
26
|
+
|
|
27
|
+
|
|
28
|
+
def summarise_coverage(caught) -> list[str]:
|
|
29
|
+
"""Collapse recorded CalendarCoverageWarnings into one line per calendar."""
|
|
30
|
+
by_cal: dict[str, set] = {}
|
|
31
|
+
for w in caught:
|
|
32
|
+
m = getattr(w, "message", w)
|
|
33
|
+
if isinstance(m, CalendarCoverageWarning):
|
|
34
|
+
by_cal.setdefault(m.calendar, set()).add(m.year)
|
|
35
|
+
out = []
|
|
36
|
+
for name, yrs in sorted(by_cal.items()):
|
|
37
|
+
ys = sorted(yrs)
|
|
38
|
+
span = str(ys[0]) if len(ys) == 1 else f"{ys[0]}–{ys[-1]}"
|
|
39
|
+
out.append(f"{name}: no holiday data for {span} (weekends only); add these years to the calendar file")
|
|
40
|
+
return out
|
|
41
|
+
|
|
42
|
+
|
|
43
|
+
def to_date(x) -> Date:
|
|
44
|
+
if isinstance(x, dt.datetime):
|
|
45
|
+
return x.date()
|
|
46
|
+
if isinstance(x, dt.date):
|
|
47
|
+
return x
|
|
48
|
+
return dt.date.fromisoformat(str(x))
|
|
49
|
+
|
|
50
|
+
|
|
51
|
+
class BusinessDayConvention(str, Enum):
|
|
52
|
+
UNADJUSTED = "unadjusted"
|
|
53
|
+
FOLLOWING = "following"
|
|
54
|
+
MODIFIED_FOLLOWING = "modified_following"
|
|
55
|
+
PRECEDING = "preceding"
|
|
56
|
+
MODIFIED_PRECEDING = "modified_preceding"
|
|
57
|
+
|
|
58
|
+
|
|
59
|
+
class DayCount(str, Enum):
|
|
60
|
+
ACT_365F = "ACT/365F"
|
|
61
|
+
ACT_360 = "ACT/360"
|
|
62
|
+
ACT_364 = "ACT/364"
|
|
63
|
+
THIRTY_360 = "30/360"
|
|
64
|
+
|
|
65
|
+
|
|
66
|
+
# ======================================================================= calendar
|
|
67
|
+
class Calendar:
|
|
68
|
+
"""Weekend days plus a set of holidays.
|
|
69
|
+
|
|
70
|
+
``years`` lists the years for which the holiday list is complete. Dates
|
|
71
|
+
outside them are treated as weekends-only and trigger a
|
|
72
|
+
:class:`CalendarCoverageWarning` (once per calendar and year).
|
|
73
|
+
"""
|
|
74
|
+
|
|
75
|
+
def __init__(self, name: str, holidays=None, weekend=(5, 6), years=None, description: str = ""):
|
|
76
|
+
self.name = name
|
|
77
|
+
self.holidays: dict[Date, str] = {to_date(d): n for d, n in (holidays or {}).items()}
|
|
78
|
+
self.weekend = frozenset(weekend)
|
|
79
|
+
self.years = frozenset(years) if years is not None else frozenset(d.year for d in self.holidays)
|
|
80
|
+
self.description = description
|
|
81
|
+
self._warned: set[int] = set()
|
|
82
|
+
|
|
83
|
+
# -------------------------------------------------------------- queries
|
|
84
|
+
def covers(self, d) -> bool:
|
|
85
|
+
return to_date(d).year in self.years
|
|
86
|
+
|
|
87
|
+
def _check(self, d: Date):
|
|
88
|
+
if self.years and d.year not in self.years and d.year not in self._warned:
|
|
89
|
+
self._warned.add(d.year)
|
|
90
|
+
warnings.warn(CalendarCoverageWarning(self.name, d.year), stacklevel=3)
|
|
91
|
+
|
|
92
|
+
def is_holiday(self, d) -> bool:
|
|
93
|
+
return to_date(d) in self.holidays
|
|
94
|
+
|
|
95
|
+
def holiday_name(self, d) -> str | None:
|
|
96
|
+
return self.holidays.get(to_date(d))
|
|
97
|
+
|
|
98
|
+
def is_business_day(self, d) -> bool:
|
|
99
|
+
d = to_date(d)
|
|
100
|
+
self._check(d)
|
|
101
|
+
return d.weekday() not in self.weekend and d not in self.holidays
|
|
102
|
+
|
|
103
|
+
def holidays_between(self, start, end):
|
|
104
|
+
start, end = to_date(start), to_date(end)
|
|
105
|
+
return sorted((d, n) for d, n in self.holidays.items() if start <= d <= end)
|
|
106
|
+
|
|
107
|
+
# -------------------------------------------------------------- moves
|
|
108
|
+
def adjust(self, d, convention=BusinessDayConvention.FOLLOWING) -> Date:
|
|
109
|
+
d = to_date(d)
|
|
110
|
+
conv = BusinessDayConvention(convention)
|
|
111
|
+
if conv is BusinessDayConvention.UNADJUSTED or self.is_business_day(d):
|
|
112
|
+
return d
|
|
113
|
+
if conv in (BusinessDayConvention.FOLLOWING, BusinessDayConvention.MODIFIED_FOLLOWING):
|
|
114
|
+
out = self._roll(d, +1)
|
|
115
|
+
if conv is BusinessDayConvention.MODIFIED_FOLLOWING and out.month != d.month:
|
|
116
|
+
out = self._roll(d, -1)
|
|
117
|
+
return out
|
|
118
|
+
out = self._roll(d, -1)
|
|
119
|
+
if conv is BusinessDayConvention.MODIFIED_PRECEDING and out.month != d.month:
|
|
120
|
+
out = self._roll(d, +1)
|
|
121
|
+
return out
|
|
122
|
+
|
|
123
|
+
def _roll(self, d: Date, step: int) -> Date:
|
|
124
|
+
while not self.is_business_day(d):
|
|
125
|
+
d += dt.timedelta(days=step)
|
|
126
|
+
return d
|
|
127
|
+
|
|
128
|
+
def advance(self, d, n: int) -> Date:
|
|
129
|
+
"""Move ``n`` business days (n may be negative). n=0 rolls forward to a business day."""
|
|
130
|
+
d = to_date(d)
|
|
131
|
+
if n == 0:
|
|
132
|
+
return self._roll(d, +1)
|
|
133
|
+
step = 1 if n > 0 else -1
|
|
134
|
+
for _ in range(abs(n)):
|
|
135
|
+
d += dt.timedelta(days=step)
|
|
136
|
+
d = self._roll(d, step)
|
|
137
|
+
return d
|
|
138
|
+
|
|
139
|
+
def business_days_between(self, start, end) -> int:
|
|
140
|
+
"""Business days in (start, end]."""
|
|
141
|
+
start, end = to_date(start), to_date(end)
|
|
142
|
+
n, d = 0, start
|
|
143
|
+
while d < end:
|
|
144
|
+
d += dt.timedelta(days=1)
|
|
145
|
+
n += self.is_business_day(d)
|
|
146
|
+
return n
|
|
147
|
+
|
|
148
|
+
def last_business_day_of_month(self, year: int, month: int) -> Date:
|
|
149
|
+
return self._roll(Date(year, month, _cal.monthrange(year, month)[1]), -1)
|
|
150
|
+
|
|
151
|
+
def join(self, other: "Calendar", name: str | None = None) -> "Calendar":
|
|
152
|
+
"""Union calendar: a holiday in either is a holiday in both."""
|
|
153
|
+
hol = dict(self.holidays)
|
|
154
|
+
hol.update(other.holidays)
|
|
155
|
+
years = (self.years & other.years) if (self.years and other.years) else (self.years or other.years)
|
|
156
|
+
return Calendar(name or f"{self.name}+{other.name}", hol, self.weekend | other.weekend, years)
|
|
157
|
+
|
|
158
|
+
def __repr__(self):
|
|
159
|
+
yrs = ",".join(str(y) for y in sorted(self.years)) or "none"
|
|
160
|
+
return f"Calendar({self.name}, {len(self.holidays)} holidays, years {yrs})"
|
|
161
|
+
|
|
162
|
+
|
|
163
|
+
WEEKENDS_ONLY = Calendar("WEEKENDS", years=())
|
|
164
|
+
|
|
165
|
+
|
|
166
|
+
# ======================================================================= tenors
|
|
167
|
+
_TENOR = re.compile(r"^\s*(\d+)\s*([DWMY])\s*$", re.IGNORECASE)
|
|
168
|
+
|
|
169
|
+
|
|
170
|
+
def parse_tenor(tenor: str):
|
|
171
|
+
"""'3M' -> (3, 'M'). 'ON'/'O/N' -> (1, 'D'); 'TN' -> (2, 'D')."""
|
|
172
|
+
t = tenor.strip().upper().replace("/", "")
|
|
173
|
+
if t == "ON":
|
|
174
|
+
return 1, "D"
|
|
175
|
+
if t == "TN":
|
|
176
|
+
return 2, "D"
|
|
177
|
+
m = _TENOR.match(t)
|
|
178
|
+
if not m:
|
|
179
|
+
raise ValueError(f"Bad tenor {tenor!r}; use e.g. 1D, 2W, 3M, 5Y, ON")
|
|
180
|
+
return int(m.group(1)), m.group(2).upper()
|
|
181
|
+
|
|
182
|
+
|
|
183
|
+
def add_months(d: Date, months: int, end_of_month: bool = False) -> Date:
|
|
184
|
+
y, m = divmod(d.month - 1 + months, 12)
|
|
185
|
+
y, m = d.year + y, m + 1
|
|
186
|
+
last = _cal.monthrange(y, m)[1]
|
|
187
|
+
day = last if (end_of_month and d.day == _cal.monthrange(d.year, d.month)[1]) else min(d.day, last)
|
|
188
|
+
return Date(y, m, day)
|
|
189
|
+
|
|
190
|
+
|
|
191
|
+
def add_tenor(d, tenor: str, end_of_month: bool = False) -> Date:
|
|
192
|
+
"""Calendar-unadjusted date ``tenor`` after ``d``."""
|
|
193
|
+
d = to_date(d)
|
|
194
|
+
n, unit = parse_tenor(tenor)
|
|
195
|
+
if unit == "D":
|
|
196
|
+
return d + dt.timedelta(days=n)
|
|
197
|
+
if unit == "W":
|
|
198
|
+
return d + dt.timedelta(weeks=n)
|
|
199
|
+
if unit == "M":
|
|
200
|
+
return add_months(d, n, end_of_month)
|
|
201
|
+
return add_months(d, 12 * n, end_of_month)
|
|
202
|
+
|
|
203
|
+
|
|
204
|
+
def tenor_in_years(tenor: str) -> float:
|
|
205
|
+
n, unit = parse_tenor(tenor)
|
|
206
|
+
return {"D": n / 365.0, "W": 7 * n / 365.0, "M": n / 12.0, "Y": float(n)}[unit]
|
|
207
|
+
|
|
208
|
+
|
|
209
|
+
# ======================================================================= day counts
|
|
210
|
+
def year_fraction(d1, d2, day_count=DayCount.ACT_365F) -> float:
|
|
211
|
+
d1, d2 = to_date(d1), to_date(d2)
|
|
212
|
+
dc = DayCount(day_count)
|
|
213
|
+
days = (d2 - d1).days
|
|
214
|
+
if dc is DayCount.ACT_365F:
|
|
215
|
+
return days / 365.0
|
|
216
|
+
if dc is DayCount.ACT_360:
|
|
217
|
+
return days / 360.0
|
|
218
|
+
if dc is DayCount.ACT_364:
|
|
219
|
+
return days / 364.0
|
|
220
|
+
# 30/360 (bond basis)
|
|
221
|
+
D1, D2 = min(d1.day, 30), d2.day
|
|
222
|
+
if D1 == 30 and D2 == 31:
|
|
223
|
+
D2 = 30
|
|
224
|
+
return ((d2.year - d1.year) * 360 + (d2.month - d1.month) * 30 + (D2 - D1)) / 360.0
|
|
225
|
+
|
|
226
|
+
|
|
227
|
+
def time_from(valuation, d) -> float:
|
|
228
|
+
"""Curve time (ACT/365F) from the valuation date: the library's time axis for dated curves."""
|
|
229
|
+
return year_fraction(valuation, d, DayCount.ACT_365F)
|
|
230
|
+
|
|
231
|
+
|
|
232
|
+
# ======================================================================= schedules
|
|
233
|
+
def schedule(start, end, freq_months: int | None, cal: Calendar,
|
|
234
|
+
convention=BusinessDayConvention.MODIFIED_FOLLOWING, end_of_month: bool = False):
|
|
235
|
+
"""Accrual periods [(accrual_start, accrual_end), ...] from ``start`` to ``end``.
|
|
236
|
+
|
|
237
|
+
Generated backward from ``end`` (short front stub). ``freq_months=None``
|
|
238
|
+
gives a single period. Period ends are business-day adjusted; ``end`` is
|
|
239
|
+
expected to be adjusted already.
|
|
240
|
+
"""
|
|
241
|
+
start, end = to_date(start), to_date(end)
|
|
242
|
+
if end <= start:
|
|
243
|
+
raise ValueError("schedule end must be after start")
|
|
244
|
+
if not freq_months:
|
|
245
|
+
return [(start, end)]
|
|
246
|
+
unadj = [end]
|
|
247
|
+
k = 1
|
|
248
|
+
while True:
|
|
249
|
+
d = add_months(end, -freq_months * k, end_of_month)
|
|
250
|
+
if d <= start + dt.timedelta(days=7): # avoid a tiny stub: merge into the first period
|
|
251
|
+
break
|
|
252
|
+
unadj.append(d)
|
|
253
|
+
k += 1
|
|
254
|
+
dates = [start] + [cal.adjust(d, convention) for d in reversed(unadj[1:])] + [end]
|
|
255
|
+
return list(zip(dates[:-1], dates[1:]))
|
|
256
|
+
|
|
257
|
+
|
|
258
|
+
__all__ = [
|
|
259
|
+
"Date", "WEEKDAYS", "CalendarCoverageWarning", "summarise_coverage", "to_date", "BusinessDayConvention", "DayCount",
|
|
260
|
+
"Calendar", "WEEKENDS_ONLY", "parse_tenor", "add_months", "add_tenor", "tenor_in_years",
|
|
261
|
+
"year_fraction", "time_from", "schedule",
|
|
262
|
+
]
|