indian-options-analytics 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.
- indian_options_analytics-0.1.0/LICENSE +21 -0
- indian_options_analytics-0.1.0/PKG-INFO +141 -0
- indian_options_analytics-0.1.0/README.md +131 -0
- indian_options_analytics-0.1.0/pyproject.toml +16 -0
- indian_options_analytics-0.1.0/setup.cfg +4 -0
- indian_options_analytics-0.1.0/src/indian_options_analytics/__init__.py +12 -0
- indian_options_analytics-0.1.0/src/indian_options_analytics/black_scholes.py +154 -0
- indian_options_analytics-0.1.0/src/indian_options_analytics/implied_volatility.py +40 -0
- indian_options_analytics-0.1.0/src/indian_options_analytics/risk.py +89 -0
- indian_options_analytics-0.1.0/src/indian_options_analytics/strategies.py +110 -0
- indian_options_analytics-0.1.0/src/indian_options_analytics.egg-info/PKG-INFO +141 -0
- indian_options_analytics-0.1.0/src/indian_options_analytics.egg-info/SOURCES.txt +15 -0
- indian_options_analytics-0.1.0/src/indian_options_analytics.egg-info/dependency_links.txt +1 -0
- indian_options_analytics-0.1.0/src/indian_options_analytics.egg-info/top_level.txt +1 -0
- indian_options_analytics-0.1.0/tests/test_audit.py +164 -0
- indian_options_analytics-0.1.0/tests/test_pricing.py +119 -0
- indian_options_analytics-0.1.0/tests/test_strategy_risk.py +100 -0
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
MIT License
|
|
2
|
+
|
|
3
|
+
Copyright (c) 2026 JRMarketIQ
|
|
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,141 @@
|
|
|
1
|
+
Metadata-Version: 2.4
|
|
2
|
+
Name: indian-options-analytics
|
|
3
|
+
Version: 0.1.0
|
|
4
|
+
Summary: European option pricing, strategy payoffs, and portfolio risk
|
|
5
|
+
License-Expression: MIT
|
|
6
|
+
Requires-Python: >=3.10
|
|
7
|
+
Description-Content-Type: text/markdown
|
|
8
|
+
License-File: LICENSE
|
|
9
|
+
Dynamic: license-file
|
|
10
|
+
|
|
11
|
+
# indian-options-analytics
|
|
12
|
+
Open-source Python library for Indian options pricing, Greeks, strategy payoffs and risk analytics.
|
|
13
|
+
|
|
14
|
+
Python 3.10+ with zero runtime dependencies. The Black–Scholes model assumes
|
|
15
|
+
European exercise, lognormal spot dynamics, and constant volatility, continuously
|
|
16
|
+
compounded risk-free rate, and continuous dividend yield over each option's life.
|
|
17
|
+
|
|
18
|
+
## Install an existing wheel
|
|
19
|
+
|
|
20
|
+
Use a virtual environment. From the repository root in PowerShell, with the
|
|
21
|
+
wheel in `dist/`:
|
|
22
|
+
|
|
23
|
+
```powershell
|
|
24
|
+
python -m venv .venv
|
|
25
|
+
.\.venv\Scripts\python.exe -m pip install --no-index --no-deps dist/indian_options_analytics-0.1.0-py3-none-any.whl
|
|
26
|
+
```
|
|
27
|
+
|
|
28
|
+
The `0.1.0` release is in preparation. To build the wheel locally, see
|
|
29
|
+
[Build a wheel](#build-a-wheel).
|
|
30
|
+
|
|
31
|
+
## Run from source
|
|
32
|
+
|
|
33
|
+
From the repository root in PowerShell:
|
|
34
|
+
|
|
35
|
+
```powershell
|
|
36
|
+
$env:PYTHONPATH = "src"
|
|
37
|
+
python -B -m unittest discover -s tests -v
|
|
38
|
+
python -B examples/bull_call_spread.py
|
|
39
|
+
```
|
|
40
|
+
|
|
41
|
+
## Build a wheel
|
|
42
|
+
|
|
43
|
+
From the repository root, use a Python environment with pip. Pip's isolated
|
|
44
|
+
build needs access to `setuptools>=77` through a package index or local wheelhouse.
|
|
45
|
+
|
|
46
|
+
```powershell
|
|
47
|
+
python -m pip wheel --no-deps --wheel-dir dist .
|
|
48
|
+
```
|
|
49
|
+
|
|
50
|
+
## Pricing and Greeks
|
|
51
|
+
|
|
52
|
+
```python
|
|
53
|
+
from indian_options_analytics import greeks, implied_volatility, price
|
|
54
|
+
|
|
55
|
+
mark = price("call", 100, 105, 30 / 365, 0.25, rate=0.06, dividend_yield=0.02)
|
|
56
|
+
iv = implied_volatility("call", mark, 100, 105, 30 / 365, 0.06, 0.02)
|
|
57
|
+
g = greeks("call", 100, 105, 30 / 365, iv, 0.06, 0.02)
|
|
58
|
+
```
|
|
59
|
+
|
|
60
|
+
Use a consistent currency (for example, INR) for spot, strike and premiums
|
|
61
|
+
quoted per underlying unit. Time is in years. The examples use calendar
|
|
62
|
+
days divided by 365. Volatility, rate and dividend yield are annual decimals.
|
|
63
|
+
Spot, time and volatility are nonnegative. Strikes are strictly positive.
|
|
64
|
+
Finite negative rates and dividend yields are accepted.
|
|
65
|
+
|
|
66
|
+
| Field | Convention |
|
|
67
|
+
| --- | --- |
|
|
68
|
+
| Delta | Price sensitivity per unit move in spot |
|
|
69
|
+
| Gamma | Delta sensitivity per unit move in spot |
|
|
70
|
+
| Theta | Price sensitivity to one calendar year passing, equal to minus the time-to-expiry derivative |
|
|
71
|
+
| Theta daily | Annual Theta divided by 365 |
|
|
72
|
+
| Vega | Price sensitivity per 1.00 change in annualized volatility |
|
|
73
|
+
| Rho | Price sensitivity per 1.00 change in annual risk-free rate, with dividend yield fixed |
|
|
74
|
+
| Vega and Rho per point | Raw values divided by 100, for a 0.01 change |
|
|
75
|
+
|
|
76
|
+
At expiry, price is intrinsic. Expiry Theta is reported as NaN, and Delta
|
|
77
|
+
and Gamma at the strike are undefined. Expiry Vega and Rho are zero. At zero
|
|
78
|
+
volatility, price is the positive part of signed discounted spot minus
|
|
79
|
+
discounted strike. At equality, Delta, Gamma and Rho are undefined, Vega is
|
|
80
|
+
the right derivative, and Theta is zero if the deterministic spread has
|
|
81
|
+
zero time derivative and undefined otherwise. Undefined Greeks return NaN.
|
|
82
|
+
Spot sensitivities at zero spot use right derivatives.
|
|
83
|
+
|
|
84
|
+
With discounted spot `A` and strike `B`, the IV bracket uses call price bounds
|
|
85
|
+
`[max(A - B, 0), A]` and put bounds `[max(B - A, 0), B]`. The lower bound
|
|
86
|
+
maps to zero volatility and the upper bound to positive infinity. IV raises
|
|
87
|
+
`ValueError` for prices outside the bounds or when expiry or zero spot makes
|
|
88
|
+
volatility unidentifiable. Floating-point rounding can make prices near the
|
|
89
|
+
bounds indistinguishable from the bounds.
|
|
90
|
+
|
|
91
|
+
## Strategies and portfolio risk
|
|
92
|
+
|
|
93
|
+
Run [the bull call spread example](examples/bull_call_spread.py) for
|
|
94
|
+
breakevens, profit and loss limits, sizing, portfolio Delta, and a
|
|
95
|
+
full-repricing scenario.
|
|
96
|
+
|
|
97
|
+
- An `OptionLeg` has a signed contract quantity (positive long, negative
|
|
98
|
+
short), a positive multiplier in underlying units per contract, a
|
|
99
|
+
nonnegative premium per underlying unit, and nonnegative **total** leg
|
|
100
|
+
charges in cash. Aggregate any commissions, taxes and fees into that amount.
|
|
101
|
+
- Use `expiry_payoff` and `expiry_pnl` for legs sharing one underlying and
|
|
102
|
+
expiry. Payoff is signed intrinsic cash flow. P&L deducts signed premium
|
|
103
|
+
cash flow and total charges once. Premiums and fees are nominal cash
|
|
104
|
+
amounts without financing or reinvestment.
|
|
105
|
+
- Expiry cash flows and strategy metrics use the decimal spelling of inputs
|
|
106
|
+
for calculation and return floats. This preserves small charges when large
|
|
107
|
+
cash flows offset.
|
|
108
|
+
- `strategy_metrics` uses terminal spots from zero to infinity. It reports
|
|
109
|
+
isolated breakevens and closed zero-P&L intervals separately, plus
|
|
110
|
+
nonnegative maximum profit and loss amounts. Infinite endpoints and
|
|
111
|
+
unbounded gains or losses use `math.inf`. At reported roots, allow
|
|
112
|
+
floating-point rounding when comparing evaluated P&L with zero.
|
|
113
|
+
- `portfolio_greeks` weights each position by signed quantity times
|
|
114
|
+
multiplier. Positions share one underlying and may have different
|
|
115
|
+
maturities and implied volatilities.
|
|
116
|
+
- `scenario_pnl` reprices every position from the current market to a
|
|
117
|
+
shocked market. It applies an absolute parallel volatility shift and
|
|
118
|
+
subtracts elapsed years from remaining time. The horizon can reach the
|
|
119
|
+
first expiry. Historical premiums and charges are already sunk for this
|
|
120
|
+
calculation. Supply any new total cash charge as `scenario_charges`.
|
|
121
|
+
- `position_size` floors the cash risk budget divided by loss per identical
|
|
122
|
+
position or strategy bundle, typically `strategy_metrics(legs).max_loss`.
|
|
123
|
+
It returns zero for unbounded loss and raises for zero loss because the
|
|
124
|
+
loss budget alone sets no finite size. Per-bundle charges must scale
|
|
125
|
+
linearly for this calculation.
|
|
126
|
+
|
|
127
|
+
## Limitations
|
|
128
|
+
|
|
129
|
+
The model covers European options with a continuous dividend yield.
|
|
130
|
+
Strategy expiry analysis assumes a shared underlying and expiry. Portfolio
|
|
131
|
+
scenarios use a shared underlying and stop at the earliest expiry.
|
|
132
|
+
Contract specifications and transaction charges are supplied by the caller.
|
|
133
|
+
The library uses scalar inputs and double precision for model prices and Greeks.
|
|
134
|
+
|
|
135
|
+
## Contributing
|
|
136
|
+
|
|
137
|
+
See [CONTRIBUTING.md](CONTRIBUTING.md) for testing and pull request guidance,
|
|
138
|
+
[SECURITY.md](SECURITY.md) for vulnerability reporting, and
|
|
139
|
+
[CHANGELOG.md](CHANGELOG.md) for release notes.
|
|
140
|
+
|
|
141
|
+
Licensed under the MIT License. See [LICENSE](LICENSE).
|
|
@@ -0,0 +1,131 @@
|
|
|
1
|
+
# indian-options-analytics
|
|
2
|
+
Open-source Python library for Indian options pricing, Greeks, strategy payoffs and risk analytics.
|
|
3
|
+
|
|
4
|
+
Python 3.10+ with zero runtime dependencies. The Black–Scholes model assumes
|
|
5
|
+
European exercise, lognormal spot dynamics, and constant volatility, continuously
|
|
6
|
+
compounded risk-free rate, and continuous dividend yield over each option's life.
|
|
7
|
+
|
|
8
|
+
## Install an existing wheel
|
|
9
|
+
|
|
10
|
+
Use a virtual environment. From the repository root in PowerShell, with the
|
|
11
|
+
wheel in `dist/`:
|
|
12
|
+
|
|
13
|
+
```powershell
|
|
14
|
+
python -m venv .venv
|
|
15
|
+
.\.venv\Scripts\python.exe -m pip install --no-index --no-deps dist/indian_options_analytics-0.1.0-py3-none-any.whl
|
|
16
|
+
```
|
|
17
|
+
|
|
18
|
+
The `0.1.0` release is in preparation. To build the wheel locally, see
|
|
19
|
+
[Build a wheel](#build-a-wheel).
|
|
20
|
+
|
|
21
|
+
## Run from source
|
|
22
|
+
|
|
23
|
+
From the repository root in PowerShell:
|
|
24
|
+
|
|
25
|
+
```powershell
|
|
26
|
+
$env:PYTHONPATH = "src"
|
|
27
|
+
python -B -m unittest discover -s tests -v
|
|
28
|
+
python -B examples/bull_call_spread.py
|
|
29
|
+
```
|
|
30
|
+
|
|
31
|
+
## Build a wheel
|
|
32
|
+
|
|
33
|
+
From the repository root, use a Python environment with pip. Pip's isolated
|
|
34
|
+
build needs access to `setuptools>=77` through a package index or local wheelhouse.
|
|
35
|
+
|
|
36
|
+
```powershell
|
|
37
|
+
python -m pip wheel --no-deps --wheel-dir dist .
|
|
38
|
+
```
|
|
39
|
+
|
|
40
|
+
## Pricing and Greeks
|
|
41
|
+
|
|
42
|
+
```python
|
|
43
|
+
from indian_options_analytics import greeks, implied_volatility, price
|
|
44
|
+
|
|
45
|
+
mark = price("call", 100, 105, 30 / 365, 0.25, rate=0.06, dividend_yield=0.02)
|
|
46
|
+
iv = implied_volatility("call", mark, 100, 105, 30 / 365, 0.06, 0.02)
|
|
47
|
+
g = greeks("call", 100, 105, 30 / 365, iv, 0.06, 0.02)
|
|
48
|
+
```
|
|
49
|
+
|
|
50
|
+
Use a consistent currency (for example, INR) for spot, strike and premiums
|
|
51
|
+
quoted per underlying unit. Time is in years. The examples use calendar
|
|
52
|
+
days divided by 365. Volatility, rate and dividend yield are annual decimals.
|
|
53
|
+
Spot, time and volatility are nonnegative. Strikes are strictly positive.
|
|
54
|
+
Finite negative rates and dividend yields are accepted.
|
|
55
|
+
|
|
56
|
+
| Field | Convention |
|
|
57
|
+
| --- | --- |
|
|
58
|
+
| Delta | Price sensitivity per unit move in spot |
|
|
59
|
+
| Gamma | Delta sensitivity per unit move in spot |
|
|
60
|
+
| Theta | Price sensitivity to one calendar year passing, equal to minus the time-to-expiry derivative |
|
|
61
|
+
| Theta daily | Annual Theta divided by 365 |
|
|
62
|
+
| Vega | Price sensitivity per 1.00 change in annualized volatility |
|
|
63
|
+
| Rho | Price sensitivity per 1.00 change in annual risk-free rate, with dividend yield fixed |
|
|
64
|
+
| Vega and Rho per point | Raw values divided by 100, for a 0.01 change |
|
|
65
|
+
|
|
66
|
+
At expiry, price is intrinsic. Expiry Theta is reported as NaN, and Delta
|
|
67
|
+
and Gamma at the strike are undefined. Expiry Vega and Rho are zero. At zero
|
|
68
|
+
volatility, price is the positive part of signed discounted spot minus
|
|
69
|
+
discounted strike. At equality, Delta, Gamma and Rho are undefined, Vega is
|
|
70
|
+
the right derivative, and Theta is zero if the deterministic spread has
|
|
71
|
+
zero time derivative and undefined otherwise. Undefined Greeks return NaN.
|
|
72
|
+
Spot sensitivities at zero spot use right derivatives.
|
|
73
|
+
|
|
74
|
+
With discounted spot `A` and strike `B`, the IV bracket uses call price bounds
|
|
75
|
+
`[max(A - B, 0), A]` and put bounds `[max(B - A, 0), B]`. The lower bound
|
|
76
|
+
maps to zero volatility and the upper bound to positive infinity. IV raises
|
|
77
|
+
`ValueError` for prices outside the bounds or when expiry or zero spot makes
|
|
78
|
+
volatility unidentifiable. Floating-point rounding can make prices near the
|
|
79
|
+
bounds indistinguishable from the bounds.
|
|
80
|
+
|
|
81
|
+
## Strategies and portfolio risk
|
|
82
|
+
|
|
83
|
+
Run [the bull call spread example](examples/bull_call_spread.py) for
|
|
84
|
+
breakevens, profit and loss limits, sizing, portfolio Delta, and a
|
|
85
|
+
full-repricing scenario.
|
|
86
|
+
|
|
87
|
+
- An `OptionLeg` has a signed contract quantity (positive long, negative
|
|
88
|
+
short), a positive multiplier in underlying units per contract, a
|
|
89
|
+
nonnegative premium per underlying unit, and nonnegative **total** leg
|
|
90
|
+
charges in cash. Aggregate any commissions, taxes and fees into that amount.
|
|
91
|
+
- Use `expiry_payoff` and `expiry_pnl` for legs sharing one underlying and
|
|
92
|
+
expiry. Payoff is signed intrinsic cash flow. P&L deducts signed premium
|
|
93
|
+
cash flow and total charges once. Premiums and fees are nominal cash
|
|
94
|
+
amounts without financing or reinvestment.
|
|
95
|
+
- Expiry cash flows and strategy metrics use the decimal spelling of inputs
|
|
96
|
+
for calculation and return floats. This preserves small charges when large
|
|
97
|
+
cash flows offset.
|
|
98
|
+
- `strategy_metrics` uses terminal spots from zero to infinity. It reports
|
|
99
|
+
isolated breakevens and closed zero-P&L intervals separately, plus
|
|
100
|
+
nonnegative maximum profit and loss amounts. Infinite endpoints and
|
|
101
|
+
unbounded gains or losses use `math.inf`. At reported roots, allow
|
|
102
|
+
floating-point rounding when comparing evaluated P&L with zero.
|
|
103
|
+
- `portfolio_greeks` weights each position by signed quantity times
|
|
104
|
+
multiplier. Positions share one underlying and may have different
|
|
105
|
+
maturities and implied volatilities.
|
|
106
|
+
- `scenario_pnl` reprices every position from the current market to a
|
|
107
|
+
shocked market. It applies an absolute parallel volatility shift and
|
|
108
|
+
subtracts elapsed years from remaining time. The horizon can reach the
|
|
109
|
+
first expiry. Historical premiums and charges are already sunk for this
|
|
110
|
+
calculation. Supply any new total cash charge as `scenario_charges`.
|
|
111
|
+
- `position_size` floors the cash risk budget divided by loss per identical
|
|
112
|
+
position or strategy bundle, typically `strategy_metrics(legs).max_loss`.
|
|
113
|
+
It returns zero for unbounded loss and raises for zero loss because the
|
|
114
|
+
loss budget alone sets no finite size. Per-bundle charges must scale
|
|
115
|
+
linearly for this calculation.
|
|
116
|
+
|
|
117
|
+
## Limitations
|
|
118
|
+
|
|
119
|
+
The model covers European options with a continuous dividend yield.
|
|
120
|
+
Strategy expiry analysis assumes a shared underlying and expiry. Portfolio
|
|
121
|
+
scenarios use a shared underlying and stop at the earliest expiry.
|
|
122
|
+
Contract specifications and transaction charges are supplied by the caller.
|
|
123
|
+
The library uses scalar inputs and double precision for model prices and Greeks.
|
|
124
|
+
|
|
125
|
+
## Contributing
|
|
126
|
+
|
|
127
|
+
See [CONTRIBUTING.md](CONTRIBUTING.md) for testing and pull request guidance,
|
|
128
|
+
[SECURITY.md](SECURITY.md) for vulnerability reporting, and
|
|
129
|
+
[CHANGELOG.md](CHANGELOG.md) for release notes.
|
|
130
|
+
|
|
131
|
+
Licensed under the MIT License. See [LICENSE](LICENSE).
|
|
@@ -0,0 +1,16 @@
|
|
|
1
|
+
[build-system]
|
|
2
|
+
requires = ["setuptools>=77"]
|
|
3
|
+
build-backend = "setuptools.build_meta"
|
|
4
|
+
|
|
5
|
+
[project]
|
|
6
|
+
name = "indian-options-analytics"
|
|
7
|
+
version = "0.1.0"
|
|
8
|
+
description = "European option pricing, strategy payoffs, and portfolio risk"
|
|
9
|
+
readme = "README.md"
|
|
10
|
+
requires-python = ">=3.10"
|
|
11
|
+
license = "MIT"
|
|
12
|
+
license-files = ["LICENSE"]
|
|
13
|
+
dependencies = []
|
|
14
|
+
|
|
15
|
+
[tool.setuptools.packages.find]
|
|
16
|
+
where = ["src"]
|
|
@@ -0,0 +1,12 @@
|
|
|
1
|
+
"""Standalone European option pricing and risk analytics."""
|
|
2
|
+
|
|
3
|
+
from .black_scholes import Greeks, greeks, price
|
|
4
|
+
from .implied_volatility import implied_volatility
|
|
5
|
+
from .risk import Market, Position, portfolio_greeks, position_size, scenario_pnl
|
|
6
|
+
from .strategies import OptionLeg, StrategyMetrics, expiry_payoff, expiry_pnl, strategy_metrics
|
|
7
|
+
|
|
8
|
+
__all__ = [
|
|
9
|
+
"Greeks", "Market", "OptionLeg", "Position", "StrategyMetrics", "expiry_payoff",
|
|
10
|
+
"expiry_pnl", "greeks", "implied_volatility", "portfolio_greeks", "position_size",
|
|
11
|
+
"price", "scenario_pnl", "strategy_metrics",
|
|
12
|
+
]
|
|
@@ -0,0 +1,154 @@
|
|
|
1
|
+
"""Black–Scholes pricing with a continuous dividend yield."""
|
|
2
|
+
|
|
3
|
+
from dataclasses import dataclass
|
|
4
|
+
from math import erf, erfc, exp, isfinite, log, log1p, pi, sqrt
|
|
5
|
+
from typing import Literal
|
|
6
|
+
|
|
7
|
+
OptionKind = Literal["call", "put"]
|
|
8
|
+
|
|
9
|
+
|
|
10
|
+
def _validate_kind(kind: OptionKind) -> None:
|
|
11
|
+
if kind not in ("call", "put"):
|
|
12
|
+
raise ValueError("kind must be 'call' or 'put'")
|
|
13
|
+
|
|
14
|
+
|
|
15
|
+
def _nonnegative(label: str, value: float) -> None:
|
|
16
|
+
if not isfinite(value) or value < 0:
|
|
17
|
+
raise ValueError(f"{label} must be finite and nonnegative")
|
|
18
|
+
|
|
19
|
+
|
|
20
|
+
@dataclass(frozen=True)
|
|
21
|
+
class Greeks:
|
|
22
|
+
"""Sensitivities per underlying unit, with annual time and decimal rates."""
|
|
23
|
+
|
|
24
|
+
delta: float
|
|
25
|
+
gamma: float
|
|
26
|
+
theta: float
|
|
27
|
+
vega: float
|
|
28
|
+
rho: float
|
|
29
|
+
|
|
30
|
+
@property
|
|
31
|
+
def theta_daily(self) -> float:
|
|
32
|
+
return self.theta / 365
|
|
33
|
+
|
|
34
|
+
@property
|
|
35
|
+
def vega_per_point(self) -> float:
|
|
36
|
+
return self.vega / 100
|
|
37
|
+
|
|
38
|
+
@property
|
|
39
|
+
def rho_per_point(self) -> float:
|
|
40
|
+
return self.rho / 100
|
|
41
|
+
|
|
42
|
+
|
|
43
|
+
def _discounted(kind, spot, strike, time, volatility, rate, dividend_yield):
|
|
44
|
+
_validate_kind(kind)
|
|
45
|
+
_nonnegative("spot", spot)
|
|
46
|
+
_nonnegative("strike", strike)
|
|
47
|
+
_nonnegative("time", time)
|
|
48
|
+
_nonnegative("volatility", volatility)
|
|
49
|
+
if strike == 0 or not isfinite(rate) or not isfinite(dividend_yield):
|
|
50
|
+
raise ValueError("strike must be positive and rates must be finite")
|
|
51
|
+
if time == 0:
|
|
52
|
+
return spot, strike, 1.0
|
|
53
|
+
try:
|
|
54
|
+
spot_discount = exp(-dividend_yield * time) if spot else 0.0
|
|
55
|
+
strike_discount = exp(-rate * time)
|
|
56
|
+
discounted_strike = strike * strike_discount
|
|
57
|
+
discounted_spot = spot * spot_discount
|
|
58
|
+
except OverflowError as error:
|
|
59
|
+
raise ValueError("discount factors are outside floating-point range") from error
|
|
60
|
+
if not isfinite(discounted_spot) or not isfinite(discounted_strike):
|
|
61
|
+
raise ValueError("discounted inputs are outside floating-point range")
|
|
62
|
+
if discounted_strike == 0 or (spot > 0 and discounted_spot == 0):
|
|
63
|
+
raise ValueError("discounted inputs underflowed")
|
|
64
|
+
return discounted_spot, discounted_strike, spot_discount
|
|
65
|
+
|
|
66
|
+
|
|
67
|
+
def _cdf(value: float) -> float:
|
|
68
|
+
return erfc(-value / sqrt(2)) / 2
|
|
69
|
+
|
|
70
|
+
|
|
71
|
+
def _normal_terms(discounted_spot, discounted_strike, deviation):
|
|
72
|
+
ratio = (discounted_spot - discounted_strike) / discounted_strike
|
|
73
|
+
# Use the relative difference near the forward to retain precision.
|
|
74
|
+
if abs(ratio) < 0.5:
|
|
75
|
+
moneyness = log1p(ratio)
|
|
76
|
+
else:
|
|
77
|
+
moneyness = log(discounted_spot) - log(discounted_strike)
|
|
78
|
+
center = moneyness / deviation
|
|
79
|
+
return center + deviation / 2, center - deviation / 2
|
|
80
|
+
|
|
81
|
+
|
|
82
|
+
def _price(kind, discounted_spot, discounted_strike, deviation):
|
|
83
|
+
spread = discounted_spot - discounted_strike
|
|
84
|
+
sign = 1 if kind == "call" else -1
|
|
85
|
+
intrinsic = max(sign * spread, 0.0)
|
|
86
|
+
upper = discounted_spot if kind == "call" else discounted_strike
|
|
87
|
+
if deviation == 0 or discounted_spot == 0:
|
|
88
|
+
return intrinsic
|
|
89
|
+
if deviation == float("inf"):
|
|
90
|
+
return upper
|
|
91
|
+
d1, d2 = _normal_terms(discounted_spot, discounted_strike, deviation)
|
|
92
|
+
if discounted_spot == discounted_strike:
|
|
93
|
+
time_value = discounted_spot * erf(deviation / sqrt(8))
|
|
94
|
+
elif spread < 0:
|
|
95
|
+
time_value = discounted_spot * _cdf(d1) - discounted_strike * _cdf(d2)
|
|
96
|
+
else:
|
|
97
|
+
time_value = discounted_strike * _cdf(-d2) - discounted_spot * _cdf(-d1)
|
|
98
|
+
return min(upper, intrinsic + max(time_value, 0.0))
|
|
99
|
+
|
|
100
|
+
|
|
101
|
+
def price(
|
|
102
|
+
kind: OptionKind, spot: float, strike: float, time: float, volatility: float,
|
|
103
|
+
rate: float = 0.0, dividend_yield: float = 0.0,
|
|
104
|
+
) -> float:
|
|
105
|
+
"""Return the option value per unit. Time is in years."""
|
|
106
|
+
a, b, _ = _discounted(kind, spot, strike, time, volatility, rate, dividend_yield)
|
|
107
|
+
return _price(kind, a, b, volatility * sqrt(time))
|
|
108
|
+
|
|
109
|
+
|
|
110
|
+
def greeks(
|
|
111
|
+
kind: OptionKind, spot: float, strike: float, time: float, volatility: float,
|
|
112
|
+
rate: float = 0.0, dividend_yield: float = 0.0,
|
|
113
|
+
) -> Greeks:
|
|
114
|
+
"""Return analytic Greeks. Theta is dV/d(calendar time), or -dV/dT."""
|
|
115
|
+
a, b, discount = _discounted(kind, spot, strike, time, volatility, rate, dividend_yield)
|
|
116
|
+
sign = 1 if kind == "call" else -1
|
|
117
|
+
if time == 0:
|
|
118
|
+
delta = float(sign) if sign * (spot - strike) > 0 else 0.0
|
|
119
|
+
if spot == strike:
|
|
120
|
+
delta = float("nan")
|
|
121
|
+
gamma = float("nan") if spot == strike else 0.0
|
|
122
|
+
return Greeks(delta, gamma, float("nan"), 0.0, 0.0)
|
|
123
|
+
|
|
124
|
+
root_time = sqrt(time)
|
|
125
|
+
deviation = volatility * root_time
|
|
126
|
+
if spot == 0:
|
|
127
|
+
if kind == "call":
|
|
128
|
+
return Greeks(0.0, 0.0, 0.0, 0.0, 0.0)
|
|
129
|
+
try:
|
|
130
|
+
discount = exp(-dividend_yield * time)
|
|
131
|
+
except OverflowError:
|
|
132
|
+
discount = float("inf")
|
|
133
|
+
return Greeks(-discount, 0.0, rate * b, 0.0, -time * b)
|
|
134
|
+
if deviation == 0:
|
|
135
|
+
if a == b:
|
|
136
|
+
theta = 0.0 if dividend_yield == rate else float("nan")
|
|
137
|
+
return Greeks(
|
|
138
|
+
float("nan"), float("nan"), theta,
|
|
139
|
+
a * root_time / sqrt(2 * pi), float("nan"),
|
|
140
|
+
)
|
|
141
|
+
if sign * (a - b) <= 0:
|
|
142
|
+
return Greeks(0.0, 0.0, 0.0, 0.0, 0.0)
|
|
143
|
+
weight = float(sign)
|
|
144
|
+
return Greeks(
|
|
145
|
+
weight * discount, 0.0, weight * (dividend_yield * a - rate * b),
|
|
146
|
+
0.0, weight * time * b,
|
|
147
|
+
)
|
|
148
|
+
d1, d2 = _normal_terms(a, b, deviation)
|
|
149
|
+
density = exp(-0.5 * d1 * d1) / sqrt(2 * pi)
|
|
150
|
+
n1, n2 = sign * _cdf(sign * d1), sign * _cdf(sign * d2)
|
|
151
|
+
gamma = (discount * density / deviation) / spot
|
|
152
|
+
theta = -a * ((density * (volatility / 2)) / root_time)
|
|
153
|
+
theta += dividend_yield * (a * n1) - rate * (b * n2)
|
|
154
|
+
return Greeks(discount * n1, gamma, theta, a * density * root_time, time * (b * n2))
|
|
@@ -0,0 +1,40 @@
|
|
|
1
|
+
"""Bracketed Black–Scholes implied volatility."""
|
|
2
|
+
|
|
3
|
+
from math import sqrt
|
|
4
|
+
|
|
5
|
+
from .black_scholes import OptionKind, _discounted, _nonnegative, _price
|
|
6
|
+
|
|
7
|
+
|
|
8
|
+
def implied_volatility(
|
|
9
|
+
kind: OptionKind, market_price: float, spot: float, strike: float, time: float,
|
|
10
|
+
rate: float = 0.0, dividend_yield: float = 0.0,
|
|
11
|
+
) -> float:
|
|
12
|
+
"""Return annualized volatility. The upper price bound maps to infinity."""
|
|
13
|
+
_nonnegative("market_price", market_price)
|
|
14
|
+
a, b, _ = _discounted(kind, spot, strike, time, 0.0, rate, dividend_yield)
|
|
15
|
+
lower = _price(kind, a, b, 0.0)
|
|
16
|
+
upper = a if kind == "call" else b
|
|
17
|
+
if market_price < lower or market_price > upper:
|
|
18
|
+
raise ValueError("market_price is outside Black–Scholes bounds")
|
|
19
|
+
if time == 0 or lower == upper:
|
|
20
|
+
raise ValueError("volatility is unidentifiable at expiry or with coincident bounds")
|
|
21
|
+
if market_price == lower:
|
|
22
|
+
return 0.0
|
|
23
|
+
if market_price == upper:
|
|
24
|
+
return float("inf")
|
|
25
|
+
|
|
26
|
+
# Solve for volatility times sqrt(T), keeping the bracket independent of T.
|
|
27
|
+
low, high = 0.0, 1.0
|
|
28
|
+
while _price(kind, a, b, high) < market_price:
|
|
29
|
+
low, high = high, high * 2
|
|
30
|
+
while True:
|
|
31
|
+
mid = low + (high - low) / 2
|
|
32
|
+
if mid == low or mid == high:
|
|
33
|
+
return mid / sqrt(time)
|
|
34
|
+
estimate = _price(kind, a, b, mid)
|
|
35
|
+
if estimate == market_price or high - low <= 1e-12 * mid:
|
|
36
|
+
return mid / sqrt(time)
|
|
37
|
+
if estimate < market_price:
|
|
38
|
+
low = mid
|
|
39
|
+
else:
|
|
40
|
+
high = mid
|
|
@@ -0,0 +1,89 @@
|
|
|
1
|
+
"""Single-underlying portfolio sensitivities and full-repricing scenarios."""
|
|
2
|
+
|
|
3
|
+
from dataclasses import astuple, dataclass
|
|
4
|
+
from fractions import Fraction
|
|
5
|
+
from math import fsum, isfinite
|
|
6
|
+
from typing import Iterable
|
|
7
|
+
|
|
8
|
+
from .black_scholes import Greeks, _nonnegative, greeks, price
|
|
9
|
+
from .strategies import OptionLeg
|
|
10
|
+
|
|
11
|
+
|
|
12
|
+
@dataclass(frozen=True)
|
|
13
|
+
class Market:
|
|
14
|
+
spot: float
|
|
15
|
+
rate: float = 0.0
|
|
16
|
+
dividend_yield: float = 0.0
|
|
17
|
+
|
|
18
|
+
def __post_init__(self):
|
|
19
|
+
_nonnegative("spot", self.spot)
|
|
20
|
+
if not isfinite(self.rate) or not isfinite(self.dividend_yield):
|
|
21
|
+
raise ValueError("rates must be finite")
|
|
22
|
+
|
|
23
|
+
|
|
24
|
+
@dataclass(frozen=True)
|
|
25
|
+
class Position:
|
|
26
|
+
leg: OptionLeg
|
|
27
|
+
time: float
|
|
28
|
+
volatility: float
|
|
29
|
+
|
|
30
|
+
def __post_init__(self):
|
|
31
|
+
_nonnegative("time", self.time)
|
|
32
|
+
_nonnegative("volatility", self.volatility)
|
|
33
|
+
|
|
34
|
+
|
|
35
|
+
def portfolio_greeks(positions: Iterable[Position], market: Market) -> Greeks:
|
|
36
|
+
"""Sum each sensitivity using signed underlying units."""
|
|
37
|
+
exposures = {}
|
|
38
|
+
for position in positions:
|
|
39
|
+
leg = position.leg
|
|
40
|
+
key = (leg.kind, leg.strike, position.time, position.volatility if position.time else 0.0)
|
|
41
|
+
exposures[key] = exposures.get(key, Fraction(0)) + leg._exact_units()
|
|
42
|
+
|
|
43
|
+
rows = []
|
|
44
|
+
for (kind, strike, time, volatility), units in exposures.items():
|
|
45
|
+
if units:
|
|
46
|
+
sensitivities = greeks(
|
|
47
|
+
kind, market.spot, strike, time, volatility, market.rate, market.dividend_yield,
|
|
48
|
+
)
|
|
49
|
+
rows.append(tuple(float(units) * value for value in astuple(sensitivities)))
|
|
50
|
+
return Greeks(*(fsum(row[index] for row in rows) for index in range(5)))
|
|
51
|
+
|
|
52
|
+
|
|
53
|
+
def scenario_pnl(
|
|
54
|
+
positions: Iterable[Position], market: Market, shocked_market: Market, *,
|
|
55
|
+
elapsed: float = 0.0, volatility_shift: float = 0.0,
|
|
56
|
+
scenario_charges: float = 0.0,
|
|
57
|
+
) -> float:
|
|
58
|
+
"""Return change from current model marks to shocked marks, net of new charges."""
|
|
59
|
+
_nonnegative("elapsed", elapsed)
|
|
60
|
+
_nonnegative("scenario_charges", scenario_charges)
|
|
61
|
+
if not isfinite(volatility_shift):
|
|
62
|
+
raise ValueError("volatility_shift must be finite")
|
|
63
|
+
changes = []
|
|
64
|
+
for position in positions:
|
|
65
|
+
leg = position.leg
|
|
66
|
+
if elapsed > position.time:
|
|
67
|
+
raise ValueError("scenario cannot pass a position's expiry")
|
|
68
|
+
before = price(
|
|
69
|
+
leg.kind, market.spot, leg.strike, position.time, position.volatility,
|
|
70
|
+
market.rate, market.dividend_yield,
|
|
71
|
+
)
|
|
72
|
+
after = price(
|
|
73
|
+
leg.kind, shocked_market.spot, leg.strike, position.time - elapsed,
|
|
74
|
+
position.volatility + volatility_shift, shocked_market.rate,
|
|
75
|
+
shocked_market.dividend_yield,
|
|
76
|
+
)
|
|
77
|
+
changes.append(leg.units * (after - before))
|
|
78
|
+
return fsum(changes) - scenario_charges
|
|
79
|
+
|
|
80
|
+
|
|
81
|
+
def position_size(risk_budget: float, loss_per_unit: float) -> int:
|
|
82
|
+
"""Return the largest whole number of identical positions within a loss budget."""
|
|
83
|
+
_nonnegative("risk_budget", risk_budget)
|
|
84
|
+
if loss_per_unit == float("inf"):
|
|
85
|
+
return 0
|
|
86
|
+
_nonnegative("loss_per_unit", loss_per_unit)
|
|
87
|
+
if loss_per_unit == 0:
|
|
88
|
+
raise ValueError("zero loss provides no finite risk-based size")
|
|
89
|
+
return Fraction(str(risk_budget)) // Fraction(str(loss_per_unit))
|
|
@@ -0,0 +1,110 @@
|
|
|
1
|
+
"""Cash payoffs and exact piecewise-linear expiry analysis."""
|
|
2
|
+
|
|
3
|
+
from dataclasses import dataclass
|
|
4
|
+
from fractions import Fraction
|
|
5
|
+
from math import inf, isfinite
|
|
6
|
+
from typing import Iterable
|
|
7
|
+
|
|
8
|
+
from .black_scholes import OptionKind, _nonnegative, _validate_kind
|
|
9
|
+
|
|
10
|
+
|
|
11
|
+
@dataclass(frozen=True)
|
|
12
|
+
class OptionLeg:
|
|
13
|
+
kind: OptionKind
|
|
14
|
+
strike: float
|
|
15
|
+
quantity: int = 1
|
|
16
|
+
multiplier: float = 1.0
|
|
17
|
+
premium: float = 0.0
|
|
18
|
+
charges: float = 0.0
|
|
19
|
+
|
|
20
|
+
def __post_init__(self):
|
|
21
|
+
_validate_kind(self.kind)
|
|
22
|
+
if not isfinite(self.strike) or self.strike <= 0:
|
|
23
|
+
raise ValueError("strike must be finite and positive")
|
|
24
|
+
if type(self.quantity) is not int or self.quantity == 0:
|
|
25
|
+
raise ValueError("quantity must be a nonzero signed integer")
|
|
26
|
+
if not isfinite(self.multiplier) or self.multiplier <= 0:
|
|
27
|
+
raise ValueError("multiplier must be finite and positive")
|
|
28
|
+
_nonnegative("premium", self.premium)
|
|
29
|
+
_nonnegative("charges", self.charges)
|
|
30
|
+
|
|
31
|
+
@property
|
|
32
|
+
def units(self) -> float:
|
|
33
|
+
return self.quantity * self.multiplier
|
|
34
|
+
|
|
35
|
+
def _exact_units(self) -> Fraction:
|
|
36
|
+
return self.quantity * Fraction(str(self.multiplier))
|
|
37
|
+
|
|
38
|
+
def _intrinsic(self, spot: Fraction) -> Fraction:
|
|
39
|
+
spread = spot - Fraction(str(self.strike))
|
|
40
|
+
return max(spread if self.kind == "call" else -spread, Fraction(0))
|
|
41
|
+
|
|
42
|
+
|
|
43
|
+
def expiry_payoff(legs: Iterable[OptionLeg], spot: float) -> float:
|
|
44
|
+
"""Return signed settlement cash flow before premiums and charges."""
|
|
45
|
+
_nonnegative("spot", spot)
|
|
46
|
+
terminal = Fraction(str(spot))
|
|
47
|
+
return float(sum(leg._exact_units() * leg._intrinsic(terminal) for leg in legs))
|
|
48
|
+
|
|
49
|
+
|
|
50
|
+
def expiry_pnl(legs: Iterable[OptionLeg], spot: float) -> float:
|
|
51
|
+
"""Return settlement less signed entry premiums and total leg charges."""
|
|
52
|
+
_nonnegative("spot", spot)
|
|
53
|
+
terminal = Fraction(str(spot))
|
|
54
|
+
return float(sum(
|
|
55
|
+
leg._exact_units() * (leg._intrinsic(terminal) - Fraction(str(leg.premium)))
|
|
56
|
+
- Fraction(str(leg.charges))
|
|
57
|
+
for leg in legs
|
|
58
|
+
))
|
|
59
|
+
|
|
60
|
+
|
|
61
|
+
@dataclass(frozen=True)
|
|
62
|
+
class StrategyMetrics:
|
|
63
|
+
breakevens: tuple[float, ...]
|
|
64
|
+
breakeven_intervals: tuple[tuple[float, float], ...]
|
|
65
|
+
max_profit: float
|
|
66
|
+
max_loss: float
|
|
67
|
+
|
|
68
|
+
|
|
69
|
+
def strategy_metrics(legs: Iterable[OptionLeg]) -> StrategyMetrics:
|
|
70
|
+
"""Find isolated roots, flat zero intervals, and nonnegative gain/loss limits."""
|
|
71
|
+
# Decimal spellings preserve quoted premiums and strikes at exact zero plateaus.
|
|
72
|
+
value = slope = Fraction(0)
|
|
73
|
+
changes: dict[Fraction, Fraction] = {}
|
|
74
|
+
for leg in legs:
|
|
75
|
+
units = leg._exact_units()
|
|
76
|
+
strike = Fraction(str(leg.strike))
|
|
77
|
+
value -= units * Fraction(str(leg.premium)) + Fraction(str(leg.charges))
|
|
78
|
+
if leg.kind == "put":
|
|
79
|
+
value += units * strike
|
|
80
|
+
slope -= units
|
|
81
|
+
changes[strike] = changes.get(strike, Fraction(0)) + units
|
|
82
|
+
|
|
83
|
+
left = Fraction(0)
|
|
84
|
+
minimum = maximum = value
|
|
85
|
+
roots = set()
|
|
86
|
+
intervals = []
|
|
87
|
+
for right in [*sorted(changes), inf]:
|
|
88
|
+
if slope == 0 and value == 0:
|
|
89
|
+
if intervals and intervals[-1][1] == left:
|
|
90
|
+
intervals[-1] = (intervals[-1][0], right)
|
|
91
|
+
else:
|
|
92
|
+
intervals.append((left, right))
|
|
93
|
+
elif slope:
|
|
94
|
+
root = left - value / slope
|
|
95
|
+
if left <= root <= right:
|
|
96
|
+
roots.add(root)
|
|
97
|
+
if right == inf:
|
|
98
|
+
break
|
|
99
|
+
value += slope * (right - left)
|
|
100
|
+
minimum, maximum = min(minimum, value), max(maximum, value)
|
|
101
|
+
slope += changes[right]
|
|
102
|
+
left = right
|
|
103
|
+
|
|
104
|
+
return StrategyMetrics(
|
|
105
|
+
tuple(float(root) for root in sorted(roots)
|
|
106
|
+
if not any(start <= root <= end for start, end in intervals)),
|
|
107
|
+
tuple((float(start), float(end)) for start, end in intervals),
|
|
108
|
+
inf if slope > 0 else float(max(0, maximum)),
|
|
109
|
+
inf if slope < 0 else float(max(0, -minimum)),
|
|
110
|
+
)
|
|
@@ -0,0 +1,141 @@
|
|
|
1
|
+
Metadata-Version: 2.4
|
|
2
|
+
Name: indian-options-analytics
|
|
3
|
+
Version: 0.1.0
|
|
4
|
+
Summary: European option pricing, strategy payoffs, and portfolio risk
|
|
5
|
+
License-Expression: MIT
|
|
6
|
+
Requires-Python: >=3.10
|
|
7
|
+
Description-Content-Type: text/markdown
|
|
8
|
+
License-File: LICENSE
|
|
9
|
+
Dynamic: license-file
|
|
10
|
+
|
|
11
|
+
# indian-options-analytics
|
|
12
|
+
Open-source Python library for Indian options pricing, Greeks, strategy payoffs and risk analytics.
|
|
13
|
+
|
|
14
|
+
Python 3.10+ with zero runtime dependencies. The Black–Scholes model assumes
|
|
15
|
+
European exercise, lognormal spot dynamics, and constant volatility, continuously
|
|
16
|
+
compounded risk-free rate, and continuous dividend yield over each option's life.
|
|
17
|
+
|
|
18
|
+
## Install an existing wheel
|
|
19
|
+
|
|
20
|
+
Use a virtual environment. From the repository root in PowerShell, with the
|
|
21
|
+
wheel in `dist/`:
|
|
22
|
+
|
|
23
|
+
```powershell
|
|
24
|
+
python -m venv .venv
|
|
25
|
+
.\.venv\Scripts\python.exe -m pip install --no-index --no-deps dist/indian_options_analytics-0.1.0-py3-none-any.whl
|
|
26
|
+
```
|
|
27
|
+
|
|
28
|
+
The `0.1.0` release is in preparation. To build the wheel locally, see
|
|
29
|
+
[Build a wheel](#build-a-wheel).
|
|
30
|
+
|
|
31
|
+
## Run from source
|
|
32
|
+
|
|
33
|
+
From the repository root in PowerShell:
|
|
34
|
+
|
|
35
|
+
```powershell
|
|
36
|
+
$env:PYTHONPATH = "src"
|
|
37
|
+
python -B -m unittest discover -s tests -v
|
|
38
|
+
python -B examples/bull_call_spread.py
|
|
39
|
+
```
|
|
40
|
+
|
|
41
|
+
## Build a wheel
|
|
42
|
+
|
|
43
|
+
From the repository root, use a Python environment with pip. Pip's isolated
|
|
44
|
+
build needs access to `setuptools>=77` through a package index or local wheelhouse.
|
|
45
|
+
|
|
46
|
+
```powershell
|
|
47
|
+
python -m pip wheel --no-deps --wheel-dir dist .
|
|
48
|
+
```
|
|
49
|
+
|
|
50
|
+
## Pricing and Greeks
|
|
51
|
+
|
|
52
|
+
```python
|
|
53
|
+
from indian_options_analytics import greeks, implied_volatility, price
|
|
54
|
+
|
|
55
|
+
mark = price("call", 100, 105, 30 / 365, 0.25, rate=0.06, dividend_yield=0.02)
|
|
56
|
+
iv = implied_volatility("call", mark, 100, 105, 30 / 365, 0.06, 0.02)
|
|
57
|
+
g = greeks("call", 100, 105, 30 / 365, iv, 0.06, 0.02)
|
|
58
|
+
```
|
|
59
|
+
|
|
60
|
+
Use a consistent currency (for example, INR) for spot, strike and premiums
|
|
61
|
+
quoted per underlying unit. Time is in years. The examples use calendar
|
|
62
|
+
days divided by 365. Volatility, rate and dividend yield are annual decimals.
|
|
63
|
+
Spot, time and volatility are nonnegative. Strikes are strictly positive.
|
|
64
|
+
Finite negative rates and dividend yields are accepted.
|
|
65
|
+
|
|
66
|
+
| Field | Convention |
|
|
67
|
+
| --- | --- |
|
|
68
|
+
| Delta | Price sensitivity per unit move in spot |
|
|
69
|
+
| Gamma | Delta sensitivity per unit move in spot |
|
|
70
|
+
| Theta | Price sensitivity to one calendar year passing, equal to minus the time-to-expiry derivative |
|
|
71
|
+
| Theta daily | Annual Theta divided by 365 |
|
|
72
|
+
| Vega | Price sensitivity per 1.00 change in annualized volatility |
|
|
73
|
+
| Rho | Price sensitivity per 1.00 change in annual risk-free rate, with dividend yield fixed |
|
|
74
|
+
| Vega and Rho per point | Raw values divided by 100, for a 0.01 change |
|
|
75
|
+
|
|
76
|
+
At expiry, price is intrinsic. Expiry Theta is reported as NaN, and Delta
|
|
77
|
+
and Gamma at the strike are undefined. Expiry Vega and Rho are zero. At zero
|
|
78
|
+
volatility, price is the positive part of signed discounted spot minus
|
|
79
|
+
discounted strike. At equality, Delta, Gamma and Rho are undefined, Vega is
|
|
80
|
+
the right derivative, and Theta is zero if the deterministic spread has
|
|
81
|
+
zero time derivative and undefined otherwise. Undefined Greeks return NaN.
|
|
82
|
+
Spot sensitivities at zero spot use right derivatives.
|
|
83
|
+
|
|
84
|
+
With discounted spot `A` and strike `B`, the IV bracket uses call price bounds
|
|
85
|
+
`[max(A - B, 0), A]` and put bounds `[max(B - A, 0), B]`. The lower bound
|
|
86
|
+
maps to zero volatility and the upper bound to positive infinity. IV raises
|
|
87
|
+
`ValueError` for prices outside the bounds or when expiry or zero spot makes
|
|
88
|
+
volatility unidentifiable. Floating-point rounding can make prices near the
|
|
89
|
+
bounds indistinguishable from the bounds.
|
|
90
|
+
|
|
91
|
+
## Strategies and portfolio risk
|
|
92
|
+
|
|
93
|
+
Run [the bull call spread example](examples/bull_call_spread.py) for
|
|
94
|
+
breakevens, profit and loss limits, sizing, portfolio Delta, and a
|
|
95
|
+
full-repricing scenario.
|
|
96
|
+
|
|
97
|
+
- An `OptionLeg` has a signed contract quantity (positive long, negative
|
|
98
|
+
short), a positive multiplier in underlying units per contract, a
|
|
99
|
+
nonnegative premium per underlying unit, and nonnegative **total** leg
|
|
100
|
+
charges in cash. Aggregate any commissions, taxes and fees into that amount.
|
|
101
|
+
- Use `expiry_payoff` and `expiry_pnl` for legs sharing one underlying and
|
|
102
|
+
expiry. Payoff is signed intrinsic cash flow. P&L deducts signed premium
|
|
103
|
+
cash flow and total charges once. Premiums and fees are nominal cash
|
|
104
|
+
amounts without financing or reinvestment.
|
|
105
|
+
- Expiry cash flows and strategy metrics use the decimal spelling of inputs
|
|
106
|
+
for calculation and return floats. This preserves small charges when large
|
|
107
|
+
cash flows offset.
|
|
108
|
+
- `strategy_metrics` uses terminal spots from zero to infinity. It reports
|
|
109
|
+
isolated breakevens and closed zero-P&L intervals separately, plus
|
|
110
|
+
nonnegative maximum profit and loss amounts. Infinite endpoints and
|
|
111
|
+
unbounded gains or losses use `math.inf`. At reported roots, allow
|
|
112
|
+
floating-point rounding when comparing evaluated P&L with zero.
|
|
113
|
+
- `portfolio_greeks` weights each position by signed quantity times
|
|
114
|
+
multiplier. Positions share one underlying and may have different
|
|
115
|
+
maturities and implied volatilities.
|
|
116
|
+
- `scenario_pnl` reprices every position from the current market to a
|
|
117
|
+
shocked market. It applies an absolute parallel volatility shift and
|
|
118
|
+
subtracts elapsed years from remaining time. The horizon can reach the
|
|
119
|
+
first expiry. Historical premiums and charges are already sunk for this
|
|
120
|
+
calculation. Supply any new total cash charge as `scenario_charges`.
|
|
121
|
+
- `position_size` floors the cash risk budget divided by loss per identical
|
|
122
|
+
position or strategy bundle, typically `strategy_metrics(legs).max_loss`.
|
|
123
|
+
It returns zero for unbounded loss and raises for zero loss because the
|
|
124
|
+
loss budget alone sets no finite size. Per-bundle charges must scale
|
|
125
|
+
linearly for this calculation.
|
|
126
|
+
|
|
127
|
+
## Limitations
|
|
128
|
+
|
|
129
|
+
The model covers European options with a continuous dividend yield.
|
|
130
|
+
Strategy expiry analysis assumes a shared underlying and expiry. Portfolio
|
|
131
|
+
scenarios use a shared underlying and stop at the earliest expiry.
|
|
132
|
+
Contract specifications and transaction charges are supplied by the caller.
|
|
133
|
+
The library uses scalar inputs and double precision for model prices and Greeks.
|
|
134
|
+
|
|
135
|
+
## Contributing
|
|
136
|
+
|
|
137
|
+
See [CONTRIBUTING.md](CONTRIBUTING.md) for testing and pull request guidance,
|
|
138
|
+
[SECURITY.md](SECURITY.md) for vulnerability reporting, and
|
|
139
|
+
[CHANGELOG.md](CHANGELOG.md) for release notes.
|
|
140
|
+
|
|
141
|
+
Licensed under the MIT License. See [LICENSE](LICENSE).
|
|
@@ -0,0 +1,15 @@
|
|
|
1
|
+
LICENSE
|
|
2
|
+
README.md
|
|
3
|
+
pyproject.toml
|
|
4
|
+
src/indian_options_analytics/__init__.py
|
|
5
|
+
src/indian_options_analytics/black_scholes.py
|
|
6
|
+
src/indian_options_analytics/implied_volatility.py
|
|
7
|
+
src/indian_options_analytics/risk.py
|
|
8
|
+
src/indian_options_analytics/strategies.py
|
|
9
|
+
src/indian_options_analytics.egg-info/PKG-INFO
|
|
10
|
+
src/indian_options_analytics.egg-info/SOURCES.txt
|
|
11
|
+
src/indian_options_analytics.egg-info/dependency_links.txt
|
|
12
|
+
src/indian_options_analytics.egg-info/top_level.txt
|
|
13
|
+
tests/test_audit.py
|
|
14
|
+
tests/test_pricing.py
|
|
15
|
+
tests/test_strategy_risk.py
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
indian_options_analytics
|
|
@@ -0,0 +1,164 @@
|
|
|
1
|
+
"""Independent mathematical checks for boundary cases and multi-leg cash flows."""
|
|
2
|
+
|
|
3
|
+
import math
|
|
4
|
+
import unittest
|
|
5
|
+
from statistics import NormalDist
|
|
6
|
+
|
|
7
|
+
from indian_options_analytics import (
|
|
8
|
+
Greeks, Market, OptionLeg, Position, expiry_payoff, expiry_pnl, greeks,
|
|
9
|
+
implied_volatility, portfolio_greeks, position_size, price, scenario_pnl,
|
|
10
|
+
strategy_metrics,
|
|
11
|
+
)
|
|
12
|
+
|
|
13
|
+
|
|
14
|
+
class PricingAudit(unittest.TestCase):
|
|
15
|
+
def test_bounds_parity_and_monotonicity_across_market_regimes(self):
|
|
16
|
+
regimes = (
|
|
17
|
+
(15, 100, 1 / 365, -.1, .08),
|
|
18
|
+
(100, 100, 1e-8, .05, .05),
|
|
19
|
+
(102, 100, .7, -.04, -.03),
|
|
20
|
+
(500, 100, 15, .16, .09),
|
|
21
|
+
)
|
|
22
|
+
for spot, strike, time, rate, yield_ in regimes:
|
|
23
|
+
with self.subTest(spot=spot, time=time):
|
|
24
|
+
a, b = spot * math.exp(-yield_ * time), strike * math.exp(-rate * time)
|
|
25
|
+
previous = (max(a - b, 0), max(b - a, 0))
|
|
26
|
+
for vol in (0, .001, .15, .5, 2, 20, 100):
|
|
27
|
+
call = price("call", spot, strike, time, vol, rate, yield_)
|
|
28
|
+
put = price("put", spot, strike, time, vol, rate, yield_)
|
|
29
|
+
self.assertTrue(previous[0] <= call <= a)
|
|
30
|
+
self.assertTrue(previous[1] <= put <= b)
|
|
31
|
+
self.assertAlmostEqual(call - put, a - b, places=12)
|
|
32
|
+
previous = call, put
|
|
33
|
+
|
|
34
|
+
def test_iv_against_inverted_at_the_money_normal_cdf(self):
|
|
35
|
+
for mark, time in ((1e-8, 1e-6), (12, .3), (99.999999, 8)):
|
|
36
|
+
with self.subTest(mark=mark):
|
|
37
|
+
expected = 2 * NormalDist().inv_cdf((1 + mark / 100) / 2) / math.sqrt(time)
|
|
38
|
+
for kind in ("call", "put"):
|
|
39
|
+
found = implied_volatility(kind, mark, 100, 100, time)
|
|
40
|
+
self.assertAlmostEqual(found / expected, 1, places=6)
|
|
41
|
+
for mark in (math.nextafter(100, math.inf), math.nan, math.inf, -1):
|
|
42
|
+
with self.assertRaises(ValueError):
|
|
43
|
+
implied_volatility("put", mark, 100, 100, 1)
|
|
44
|
+
|
|
45
|
+
def test_theta_calendar_day_and_positive_carry_case(self):
|
|
46
|
+
# At zero carry and the money, V = S erf(sigma sqrt(T) / sqrt(8)).
|
|
47
|
+
t, sigma = .8, .25
|
|
48
|
+
step = 1e-5
|
|
49
|
+
|
|
50
|
+
def reference(time):
|
|
51
|
+
return 100 * math.erf(sigma * math.sqrt(time / 8))
|
|
52
|
+
|
|
53
|
+
daily = (reference(t - step) - reference(t + step)) / (2 * step * 365)
|
|
54
|
+
self.assertAlmostEqual(greeks("call", 100, 100, t, sigma).theta_daily, daily, places=8)
|
|
55
|
+
|
|
56
|
+
# A deterministic ITM put is worth K exp(-rT) minus spot.
|
|
57
|
+
put = greeks("put", 60, 100, 1, 0, .05)
|
|
58
|
+
self.assertAlmostEqual(put.theta, .05 * 100 * math.exp(-.05))
|
|
59
|
+
one_bp_change = 100 * (math.exp(-.0501) - math.exp(-.0499)) / 2
|
|
60
|
+
self.assertAlmostEqual(put.rho_per_point / 100, one_bp_change, places=10)
|
|
61
|
+
|
|
62
|
+
def test_all_greeks_against_independent_portfolio_derivatives(self):
|
|
63
|
+
spot, time, vol, rate, yield_ = 104, .8, .31, -.03, .04
|
|
64
|
+
positions = (
|
|
65
|
+
Position(OptionLeg("call", 100, 2, 25), time, vol),
|
|
66
|
+
Position(OptionLeg("put", 110, -1, 15), time, vol),
|
|
67
|
+
)
|
|
68
|
+
normal = NormalDist()
|
|
69
|
+
|
|
70
|
+
def reference(s, t, sigma, r):
|
|
71
|
+
total = 0
|
|
72
|
+
for strike, sign, units in ((100, 1, 50), (110, -1, -15)):
|
|
73
|
+
deviation = sigma * math.sqrt(t)
|
|
74
|
+
d2 = (math.log(s / strike) + (r - yield_ - sigma**2 / 2) * t) / deviation
|
|
75
|
+
discounted = (s * math.exp(-yield_ * t) * normal.cdf(sign * (d2 + deviation))
|
|
76
|
+
- strike * math.exp(-r * t) * normal.cdf(sign * d2))
|
|
77
|
+
total += units * sign * discounted
|
|
78
|
+
return total
|
|
79
|
+
|
|
80
|
+
inputs = [spot, time, vol, rate]
|
|
81
|
+
result = portfolio_greeks(iter(positions), Market(spot, rate, yield_))
|
|
82
|
+
for index, step, expected in (
|
|
83
|
+
(0, .001, result.delta), (1, 1e-5, -result.theta),
|
|
84
|
+
(2, 1e-5, result.vega), (3, 1e-5, result.rho),
|
|
85
|
+
):
|
|
86
|
+
high, low = inputs.copy(), inputs.copy()
|
|
87
|
+
high[index] += step
|
|
88
|
+
low[index] -= step
|
|
89
|
+
a, b = reference(*high), reference(*low)
|
|
90
|
+
self.assertAlmostEqual((a - b) / (2 * step), expected, delta=1e-5)
|
|
91
|
+
if index == 0:
|
|
92
|
+
self.assertAlmostEqual((a + b - 2 * reference(*inputs)) / step**2,
|
|
93
|
+
result.gamma, delta=1e-5)
|
|
94
|
+
self.assertAlmostEqual(result.vega_per_point, result.vega * .01)
|
|
95
|
+
self.assertAlmostEqual(result.rho_per_point, result.rho * .01)
|
|
96
|
+
|
|
97
|
+
def test_extreme_greeks_and_zero_spot(self):
|
|
98
|
+
# The dividend discount can overflow even though a zero-spot call is zero.
|
|
99
|
+
self.assertEqual(price("call", 0, 100, 1, .3, 0, -1000), 0)
|
|
100
|
+
self.assertEqual(greeks("call", 0, 100, 1, .3, 0, -1000), Greeks(0, 0, 0, 0, 0))
|
|
101
|
+
put = greeks("put", 0, 100, 1, .3, .05, -1000)
|
|
102
|
+
self.assertEqual(put.delta, -math.inf)
|
|
103
|
+
self.assertAlmostEqual(put.theta, .05 * 100 * math.exp(-.05))
|
|
104
|
+
# With huge finite carry terms and negligible put probability, Theta is zero.
|
|
105
|
+
put = greeks("put", 1e308, 1e307, .001, 1, dividend_yield=10)
|
|
106
|
+
self.assertTrue(math.isfinite(put.theta))
|
|
107
|
+
self.assertLessEqual(abs(put.theta), 1e-100)
|
|
108
|
+
|
|
109
|
+
|
|
110
|
+
class CashFlowAudit(unittest.TestCase):
|
|
111
|
+
def test_strategy_table_at_kinks_and_crossings(self):
|
|
112
|
+
call, put = "call", "put"
|
|
113
|
+
cases = (
|
|
114
|
+
("long call", [(call, 100, 1, 5)], (105,), math.inf, 5),
|
|
115
|
+
("short call", [(call, 100, -1, 5)], (105,), 5, math.inf),
|
|
116
|
+
("long put", [(put, 100, 1, 5)], (95,), 95, 5),
|
|
117
|
+
("short put", [(put, 100, -1, 5)], (95,), 5, 95),
|
|
118
|
+
("bull put spread", [(put, 100, 1, 2), (put, 110, -1, 6)], (106,), 4, 6),
|
|
119
|
+
("bear call spread", [(call, 100, -1, 6), (call, 110, 1, 2)], (104,), 4, 6),
|
|
120
|
+
("bear put spread", [(put, 100, -1, 2), (put, 110, 1, 6)], (106,), 6, 4),
|
|
121
|
+
("short straddle", [(call, 100, -1, 3), (put, 100, -1, 4)], (93, 107), 7, math.inf),
|
|
122
|
+
("long strangle", [(put, 95, 1, 2), (call, 105, 1, 3)], (90, 110), math.inf, 5),
|
|
123
|
+
("iron condor", [(put, 90, 1, 1), (put, 95, -1, 2),
|
|
124
|
+
(call, 105, -1, 2), (call, 110, 1, 1)], (93, 107), 2, 3),
|
|
125
|
+
)
|
|
126
|
+
for label, contracts, roots, profit, loss in cases:
|
|
127
|
+
with self.subTest(strategy=label):
|
|
128
|
+
legs = [OptionLeg(kind, k, qty, premium=p) for kind, k, qty, p in contracts]
|
|
129
|
+
metrics = strategy_metrics(legs)
|
|
130
|
+
self.assertEqual((metrics.breakevens, metrics.max_profit, metrics.max_loss),
|
|
131
|
+
(roots, profit, loss))
|
|
132
|
+
for root in roots:
|
|
133
|
+
self.assertEqual(expiry_pnl(legs, root), 0)
|
|
134
|
+
self.assertLess(expiry_pnl(legs, root - .25) * expiry_pnl(legs, root + .25), 0)
|
|
135
|
+
values = [expiry_pnl(legs, spot) for spot in {0, *(c[1] for c in contracts)}]
|
|
136
|
+
if math.isfinite(profit):
|
|
137
|
+
self.assertEqual(max(values), profit)
|
|
138
|
+
if math.isfinite(loss):
|
|
139
|
+
self.assertEqual(min(values), -loss)
|
|
140
|
+
|
|
141
|
+
def test_small_charges_survive_offsetting_large_cash_flows(self):
|
|
142
|
+
legs = (OptionLeg("call", 1, 2, 1e20, charges=3),
|
|
143
|
+
OptionLeg("call", 1, -1, 2e20, charges=4))
|
|
144
|
+
self.assertEqual(expiry_payoff(legs, 11), 0)
|
|
145
|
+
self.assertEqual(expiry_pnl(legs, 11), -7)
|
|
146
|
+
self.assertEqual(strategy_metrics(legs).max_loss, 7)
|
|
147
|
+
self.assertEqual(position_size(20, strategy_metrics(legs).max_loss), 2)
|
|
148
|
+
|
|
149
|
+
def test_net_flat_expired_options_have_zero_portfolio_greeks(self):
|
|
150
|
+
positions = (
|
|
151
|
+
Position(OptionLeg("put", 100, 3, .1), 0, .2),
|
|
152
|
+
Position(OptionLeg("put", 100, -1, .3), 0, .4),
|
|
153
|
+
)
|
|
154
|
+
self.assertEqual(portfolio_greeks(positions, Market(100)), Greeks(0, 0, 0, 0, 0))
|
|
155
|
+
self.assertTrue(math.isnan(portfolio_greeks(positions[:1], Market(100)).theta))
|
|
156
|
+
|
|
157
|
+
def test_multi_leg_scenario_at_expiry_against_cash_identity(self):
|
|
158
|
+
legs = (OptionLeg("call", 95, 2, 25, 8, 2),
|
|
159
|
+
OptionLeg("put", 106, -1, 10, 9, 3))
|
|
160
|
+
positions = tuple(Position(leg, .5, 0) for leg in legs)
|
|
161
|
+
# At zero rate and volatility initial net mark is 50*5 - 10*6.
|
|
162
|
+
# At expiry the shocked net settlement is 50*2 - 10*9.
|
|
163
|
+
self.assertEqual(scenario_pnl(positions, Market(100), Market(97),
|
|
164
|
+
elapsed=.5, scenario_charges=11), -191)
|
|
@@ -0,0 +1,119 @@
|
|
|
1
|
+
import math
|
|
2
|
+
import unittest
|
|
3
|
+
|
|
4
|
+
from indian_options_analytics import greeks, implied_volatility, price
|
|
5
|
+
|
|
6
|
+
|
|
7
|
+
class PricingTests(unittest.TestCase):
|
|
8
|
+
def test_fixed_reference_values(self):
|
|
9
|
+
self.assertAlmostEqual(price("call", 100, 100, 1, .2, .05), 10.4505835722, 9)
|
|
10
|
+
self.assertAlmostEqual(price("put", 100, 100, 1, .2, .05), 5.5735260223, 9)
|
|
11
|
+
self.assertAlmostEqual(price("call", 100, 100, 1, .2), 7.9655674554, 9)
|
|
12
|
+
|
|
13
|
+
def test_dividend_prices_against_discounted_payoff_integral(self):
|
|
14
|
+
spot, strike, time, vol, rate, dividend = 97, 105, .7, .31, -.02, .04
|
|
15
|
+
deviation = vol * math.sqrt(time)
|
|
16
|
+
drift = (rate - dividend - vol**2 / 2) * time
|
|
17
|
+
cutoff = (math.log(strike / spot) - drift) / deviation
|
|
18
|
+
for kind, sign, left, right in (
|
|
19
|
+
("call", 1, cutoff, 12), ("put", -1, -12, cutoff),
|
|
20
|
+
):
|
|
21
|
+
with self.subTest(kind=kind):
|
|
22
|
+
count = 4000
|
|
23
|
+
step = (right - left) / count
|
|
24
|
+
weighted = []
|
|
25
|
+
for i in range(count + 1):
|
|
26
|
+
z = left + step * i
|
|
27
|
+
terminal = spot * math.exp(drift + deviation * z)
|
|
28
|
+
weight = 1 if i in (0, count) else (4 if i % 2 else 2)
|
|
29
|
+
weighted.append(weight * max(sign * (terminal - strike), 0)
|
|
30
|
+
* math.exp(-z*z/2) / math.sqrt(2*math.pi))
|
|
31
|
+
expected = math.exp(-rate * time) * step / 3 * math.fsum(weighted)
|
|
32
|
+
self.assertAlmostEqual(price(kind, spot, strike, time, vol, rate, dividend),
|
|
33
|
+
expected, places=8)
|
|
34
|
+
|
|
35
|
+
def test_put_call_parity(self):
|
|
36
|
+
inputs = (113, 105, .4, .22, -.03, .02)
|
|
37
|
+
self.assertAlmostEqual(price("call", *inputs) - price("put", *inputs),
|
|
38
|
+
113 * math.exp(-.02 * .4) - 105 * math.exp(.03 * .4))
|
|
39
|
+
|
|
40
|
+
def test_expiry_and_zero_spot(self):
|
|
41
|
+
self.assertEqual(price("put", 0, 100, 0, .25, -.02, .03), 100)
|
|
42
|
+
self.assertEqual(price("call", 120, 100, 0, .25, -.02, .03), 20)
|
|
43
|
+
self.assertEqual(price("call", 0, 100, 1, .25), 0)
|
|
44
|
+
self.assertAlmostEqual(price("put", 0, 100, 1, .25, .05), 100 * math.exp(-.05))
|
|
45
|
+
|
|
46
|
+
def test_zero_volatility_and_its_delta(self):
|
|
47
|
+
g = greeks("call", 125, 100, 1, 0, .04, .02)
|
|
48
|
+
self.assertAlmostEqual(price("call", 125, 100, 1, 0, .04, .02),
|
|
49
|
+
125 * math.exp(-.02) - 100 * math.exp(-.04))
|
|
50
|
+
self.assertAlmostEqual(g.delta, math.exp(-.02))
|
|
51
|
+
self.assertEqual(g.gamma, 0)
|
|
52
|
+
self.assertEqual(g.vega, 0)
|
|
53
|
+
|
|
54
|
+
def test_expiry_and_deterministic_kink_greeks(self):
|
|
55
|
+
g = greeks("put", 100, 100, 0, .25)
|
|
56
|
+
self.assertTrue(all(math.isnan(value) for value in (g.delta, g.gamma, g.theta)))
|
|
57
|
+
self.assertEqual((g.vega, g.rho), (0, 0))
|
|
58
|
+
g = greeks("call", 100, 100, 1, 0)
|
|
59
|
+
self.assertTrue(all(math.isnan(value) for value in (g.delta, g.gamma, g.rho)))
|
|
60
|
+
self.assertEqual(g.theta, 0)
|
|
61
|
+
self.assertAlmostEqual(g.vega, 100 / math.sqrt(2 * math.pi))
|
|
62
|
+
|
|
63
|
+
def test_greeks_against_finite_differences(self):
|
|
64
|
+
inputs = [103, 99, .64, .25, .06, .025]
|
|
65
|
+
for kind in ("call", "put"):
|
|
66
|
+
with self.subTest(kind=kind):
|
|
67
|
+
g = greeks(kind, *inputs)
|
|
68
|
+
base = price(kind, *inputs)
|
|
69
|
+
for index, step, expected in (
|
|
70
|
+
(0, .01, g.delta), (2, 1e-5, -g.theta),
|
|
71
|
+
(3, 1e-5, g.vega), (4, 1e-5, g.rho),
|
|
72
|
+
):
|
|
73
|
+
above, below = inputs.copy(), inputs.copy()
|
|
74
|
+
above[index] += step
|
|
75
|
+
below[index] -= step
|
|
76
|
+
high, low = price(kind, *above), price(kind, *below)
|
|
77
|
+
self.assertAlmostEqual((high - low) / (2 * step), expected, 6)
|
|
78
|
+
if index == 0:
|
|
79
|
+
self.assertAlmostEqual((high - 2 * base + low) / step**2, g.gamma, 7)
|
|
80
|
+
self.assertAlmostEqual(g.theta_daily * 365, g.theta)
|
|
81
|
+
self.assertAlmostEqual(g.vega_per_point * 100, g.vega)
|
|
82
|
+
self.assertAlmostEqual(g.rho_per_point * 100, g.rho)
|
|
83
|
+
|
|
84
|
+
def test_invalid_parameters(self):
|
|
85
|
+
for inputs in (
|
|
86
|
+
("x", 100, 100, 1, .2), ("call", -1, 100, 1, .2),
|
|
87
|
+
("put", 100, 0, 1, .2), ("put", 100, 100, -1, .2),
|
|
88
|
+
("call", 100, 100, 1, math.nan), ("put", 100, 100, 1, .2, math.inf),
|
|
89
|
+
("call", 100, 100, 1, .2, -1000), ("put", 100, 100, 1, .2, 1000),
|
|
90
|
+
):
|
|
91
|
+
with self.subTest(inputs=inputs), self.assertRaises(ValueError):
|
|
92
|
+
price(*inputs)
|
|
93
|
+
|
|
94
|
+
|
|
95
|
+
class ImpliedVolatilityTests(unittest.TestCase):
|
|
96
|
+
def test_independent_reference(self):
|
|
97
|
+
self.assertAlmostEqual(implied_volatility("call", 7.9655674554058, 100, 100, 1), .2)
|
|
98
|
+
|
|
99
|
+
def test_round_trips(self):
|
|
100
|
+
for kind, vol, time, spot, strike in (
|
|
101
|
+
("put", .34, .38, 95, 104), ("call", 8, 1, 95, 104),
|
|
102
|
+
("call", .001, .0001, 100, 100), ("put", 1e-18, 1, 100, 100),
|
|
103
|
+
("call", .2, 1, 25, 100),
|
|
104
|
+
):
|
|
105
|
+
with self.subTest(kind=kind, vol=vol):
|
|
106
|
+
mark = price(kind, spot, strike, time, vol)
|
|
107
|
+
recovered = implied_volatility(kind, mark, spot, strike, time)
|
|
108
|
+
self.assertAlmostEqual(recovered / vol, 1, places=8)
|
|
109
|
+
|
|
110
|
+
def test_bounds_and_unidentifiable_cases(self):
|
|
111
|
+
floor, cap = 120 * math.exp(-.02) - 100 * math.exp(-.04), 120 * math.exp(-.02)
|
|
112
|
+
self.assertEqual(implied_volatility("call", floor, 120, 100, 1, .04, .02), 0)
|
|
113
|
+
self.assertEqual(implied_volatility("call", cap, 120, 100, 1, .04, .02), math.inf)
|
|
114
|
+
for mark in (floor - .001, cap + .001):
|
|
115
|
+
with self.assertRaises(ValueError):
|
|
116
|
+
implied_volatility("call", mark, 120, 100, 1, .04, .02)
|
|
117
|
+
for spot, time in ((100, 0), (0, 1)):
|
|
118
|
+
with self.assertRaises(ValueError):
|
|
119
|
+
implied_volatility("call", 0, spot, 100, time)
|
|
@@ -0,0 +1,100 @@
|
|
|
1
|
+
import math
|
|
2
|
+
import unittest
|
|
3
|
+
|
|
4
|
+
from indian_options_analytics import (
|
|
5
|
+
Market, OptionLeg, Position, expiry_payoff, expiry_pnl, portfolio_greeks,
|
|
6
|
+
position_size, price, scenario_pnl, strategy_metrics,
|
|
7
|
+
)
|
|
8
|
+
|
|
9
|
+
|
|
10
|
+
class StrategyTests(unittest.TestCase):
|
|
11
|
+
def test_spread_cash_flows_and_crossing(self):
|
|
12
|
+
legs = (
|
|
13
|
+
OptionLeg("call", 100, 2, 25, 6, 10),
|
|
14
|
+
OptionLeg("call", 110, -2, 25, 2, 5),
|
|
15
|
+
)
|
|
16
|
+
self.assertEqual(expiry_payoff(legs, 115), 500)
|
|
17
|
+
self.assertEqual([expiry_pnl(legs, s) for s in (95, 105, 115)], [-215, 35, 285])
|
|
18
|
+
metrics = strategy_metrics(iter(legs))
|
|
19
|
+
self.assertEqual((metrics.max_profit, metrics.max_loss), (285, 215))
|
|
20
|
+
self.assertEqual(metrics.breakevens, (104.3,))
|
|
21
|
+
root, = metrics.breakevens
|
|
22
|
+
self.assertAlmostEqual(expiry_pnl(legs, root), 0)
|
|
23
|
+
self.assertLess(expiry_pnl(legs, root - .01), 0)
|
|
24
|
+
self.assertGreater(expiry_pnl(legs, root + .01), 0)
|
|
25
|
+
|
|
26
|
+
def test_straddle_crosses_in_both_directions(self):
|
|
27
|
+
legs = (OptionLeg("call", 100, premium=3), OptionLeg("put", 100, premium=4))
|
|
28
|
+
metrics = strategy_metrics(legs)
|
|
29
|
+
self.assertEqual(metrics.breakevens, (93, 107))
|
|
30
|
+
self.assertEqual((metrics.max_profit, metrics.max_loss), (math.inf, 7))
|
|
31
|
+
for root in metrics.breakevens:
|
|
32
|
+
self.assertEqual(expiry_pnl(legs, root), 0)
|
|
33
|
+
self.assertLess(expiry_pnl(legs, root - .1) * expiry_pnl(legs, root + .1), 0)
|
|
34
|
+
|
|
35
|
+
def test_unbounded_loss_and_bounded_put(self):
|
|
36
|
+
short_call = strategy_metrics([OptionLeg("call", 100, -1, premium=3)])
|
|
37
|
+
self.assertEqual((short_call.max_profit, short_call.max_loss), (3, math.inf))
|
|
38
|
+
put = strategy_metrics([OptionLeg("put", 100, premium=4)])
|
|
39
|
+
self.assertEqual((put.max_profit, put.max_loss, put.breakevens), (96, 4, (96,)))
|
|
40
|
+
|
|
41
|
+
def test_zero_intervals_and_touching_roots(self):
|
|
42
|
+
self.assertEqual(strategy_metrics([]).breakeven_intervals, ((0, math.inf),))
|
|
43
|
+
self.assertEqual(strategy_metrics([OptionLeg("call", 5)]).breakeven_intervals, ((0, 5),))
|
|
44
|
+
self.assertEqual(strategy_metrics([OptionLeg("put", 5)]).breakeven_intervals,
|
|
45
|
+
((5, math.inf),))
|
|
46
|
+
legs = (OptionLeg("call", 5), OptionLeg("put", 5))
|
|
47
|
+
self.assertEqual(strategy_metrics(legs).breakevens, (5,))
|
|
48
|
+
self.assertEqual(expiry_pnl(legs, 5), 0)
|
|
49
|
+
self.assertEqual(strategy_metrics([OptionLeg("put", 5, premium=5)]).breakevens, (0,))
|
|
50
|
+
|
|
51
|
+
def test_invalid_legs(self):
|
|
52
|
+
for kwargs in ({"quantity": 0}, {"quantity": 1.5}, {"multiplier": -1},
|
|
53
|
+
{"premium": -1}, {"charges": math.inf}, {"strike": 0}):
|
|
54
|
+
inputs = {"kind": "call", "strike": 100, **kwargs}
|
|
55
|
+
with self.subTest(inputs=inputs), self.assertRaises(ValueError):
|
|
56
|
+
OptionLeg(**inputs)
|
|
57
|
+
|
|
58
|
+
|
|
59
|
+
class RiskTests(unittest.TestCase):
|
|
60
|
+
def setUp(self):
|
|
61
|
+
self.market = Market(100)
|
|
62
|
+
self.long = Position(OptionLeg("call", 100, 2, 25, 5, 10), 1, .2)
|
|
63
|
+
self.short = Position(OptionLeg("call", 100, -1, 50, 8, 4), 1, .2)
|
|
64
|
+
|
|
65
|
+
def test_weighted_greeks_against_portfolio_price_change(self):
|
|
66
|
+
g = portfolio_greeks([self.long], self.market)
|
|
67
|
+
delta = (price("call", 100.01, 100, 1, .2) - price("call", 99.99, 100, 1, .2))
|
|
68
|
+
self.assertAlmostEqual(g.delta, delta * 50 / .02, places=6)
|
|
69
|
+
cancelled = portfolio_greeks([self.long, self.short], self.market)
|
|
70
|
+
self.assertEqual((cancelled.delta, cancelled.gamma, cancelled.theta,
|
|
71
|
+
cancelled.vega, cancelled.rho), (0, 0, 0, 0, 0))
|
|
72
|
+
|
|
73
|
+
def test_expiry_scenario_and_charges(self):
|
|
74
|
+
result = scenario_pnl([self.long], self.market, Market(120),
|
|
75
|
+
elapsed=1, scenario_charges=3)
|
|
76
|
+
self.assertAlmostEqual(result, 50 * (20 - 7.9655674554058) - 3)
|
|
77
|
+
self.assertEqual(scenario_pnl([self.long], self.market, self.market), 0)
|
|
78
|
+
self.assertEqual(scenario_pnl([self.long, self.short], self.market, Market(120)), 0)
|
|
79
|
+
|
|
80
|
+
def test_scenario_reprices_all_shocked_inputs(self):
|
|
81
|
+
shocked = Market(104, .03, .02)
|
|
82
|
+
result = scenario_pnl([self.long], self.market, shocked,
|
|
83
|
+
elapsed=.25, volatility_shift=.1)
|
|
84
|
+
expected = 50 * (price("call", 104, 100, .75, .3, .03, .02)
|
|
85
|
+
- 7.9655674554058)
|
|
86
|
+
self.assertAlmostEqual(result, expected)
|
|
87
|
+
|
|
88
|
+
def test_invalid_scenarios(self):
|
|
89
|
+
for kwargs in ({"elapsed": 2}, {"elapsed": -.1}, {"volatility_shift": -.21},
|
|
90
|
+
{"scenario_charges": -1}):
|
|
91
|
+
with self.subTest(kwargs=kwargs), self.assertRaises(ValueError):
|
|
92
|
+
scenario_pnl([self.long], self.market, self.market, **kwargs)
|
|
93
|
+
|
|
94
|
+
def test_position_sizing(self):
|
|
95
|
+
self.assertEqual(position_size(1000, 215), 4)
|
|
96
|
+
self.assertEqual(position_size(.3, .1), 3)
|
|
97
|
+
self.assertEqual(position_size(1000, math.inf), 0)
|
|
98
|
+
self.assertEqual(position_size(0, 100), 0)
|
|
99
|
+
with self.assertRaises(ValueError):
|
|
100
|
+
position_size(1000, 0)
|