indian-options-analytics 0.1.0__py3-none-any.whl
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- indian_options_analytics/__init__.py +12 -0
- indian_options_analytics/black_scholes.py +154 -0
- indian_options_analytics/implied_volatility.py +40 -0
- indian_options_analytics/risk.py +89 -0
- indian_options_analytics/strategies.py +110 -0
- indian_options_analytics-0.1.0.dist-info/METADATA +141 -0
- indian_options_analytics-0.1.0.dist-info/RECORD +10 -0
- indian_options_analytics-0.1.0.dist-info/WHEEL +5 -0
- indian_options_analytics-0.1.0.dist-info/licenses/LICENSE +21 -0
- indian_options_analytics-0.1.0.dist-info/top_level.txt +1 -0
|
@@ -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,10 @@
|
|
|
1
|
+
indian_options_analytics/__init__.py,sha256=EwCRRr_UvX3BX-1St5M83kT5ZM2qaLascMzFVzPwbBE,576
|
|
2
|
+
indian_options_analytics/black_scholes.py,sha256=0TdpZq__47UkWVu00eW8Q6LXzzBK7-u_wkwEIZhLyj0,5730
|
|
3
|
+
indian_options_analytics/implied_volatility.py,sha256=Tu7HhuFFeacy5rLc4pdzfc2W_gyvoCM-mfwZaFF5Z94,1527
|
|
4
|
+
indian_options_analytics/risk.py,sha256=alaFX39HMj1lSZk8P_KIatDuQNFZCmzTtlBPceZn5q0,3282
|
|
5
|
+
indian_options_analytics/strategies.py,sha256=99U2N_GS13IKBiiUky-_uSxiys-SGS77Lck278o2QnI,3920
|
|
6
|
+
indian_options_analytics-0.1.0.dist-info/licenses/LICENSE,sha256=ObyROdz5Y14mNLZZ_0-n85YAL-CowRl35bIdHTai_so,1067
|
|
7
|
+
indian_options_analytics-0.1.0.dist-info/METADATA,sha256=JR0pbMhmXdkwcYX42wQptkKc_C6pWd5GX48rjA4_cN4,6379
|
|
8
|
+
indian_options_analytics-0.1.0.dist-info/WHEEL,sha256=mOdXR9C3wMVov7cSY8PY-XCzo3SmmWCHvGQr5csJoao,91
|
|
9
|
+
indian_options_analytics-0.1.0.dist-info/top_level.txt,sha256=aClRKKC71p1ry-94dPmW-hyAJSOMyFd7j7MDYrKE7Rw,25
|
|
10
|
+
indian_options_analytics-0.1.0.dist-info/RECORD,,
|
|
@@ -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 @@
|
|
|
1
|
+
indian_options_analytics
|