Coverage for features/options_greeks.py: 100%

138 statements  

« prev     ^ index     » next       coverage.py v7.17.3, created at 2026-11-22 12:55 +0000

1"""Pure Black-Scholes-Merton option pricing/greeks/implied-volatility - the 

2real-math foundation for greeks-aware options position sizing 

3(portfolio/options_strategy.py), per the user's explicit requirement: real 

4Black-Scholes greeks/IV computed from actual option chain data (when IB is 

5enabled), not proxies. 

6 

7Stdlib only (math.erf for the normal CDF - no scipy dependency), same 

8"pure function, no I/O" convention as features/bond_features.py and 

9features/macro_features.py. Every function is a straight textbook 

10implementation, unit-tested against known closed-form values 

11(tests/test_options_greeks.py) and the put-call parity invariant. 

12 

13`right` is always "call" or "put" (case-insensitive), matching the 

14vocabulary portfolio/options_strategy.py's chain rows use. 

15 

16V4.7 (development/Problems.md - early-assignment/corporate-action 

17modeling) added baw_american_price(), a Barone-Adesi-Whaley American- 

18exercise approximation built entirely from this module's own European 

19bs_price()/_d1_d2()/_normal_cdf() - see its own docstring for the 

20degrade-to-European safety contract. Everything above it in this file 

21remains pure European BSM, unchanged. 

22""" 

23 

24from __future__ import annotations 

25 

26import math 

27from typing import Any 

28 

29_SQRT_2PI = math.sqrt(2.0 * math.pi) 

30 

31 

32def _normal_pdf(x: float) -> float: 

33 return math.exp(-0.5 * x * x) / _SQRT_2PI 

34 

35 

36def _normal_cdf(x: float) -> float: 

37 return 0.5 * (1.0 + math.erf(x / math.sqrt(2.0))) 

38 

39 

40def _d1_d2(spot: float, strike: float, time_to_expiry_years: float, risk_free_rate: float, volatility: float, dividend_yield: float) -> tuple[float, float]: 

41 variance_term = volatility * math.sqrt(time_to_expiry_years) 

42 d1 = ( 

43 math.log(spot / strike) + (risk_free_rate - dividend_yield + 0.5 * volatility * volatility) * time_to_expiry_years 

44 ) / variance_term 

45 d2 = d1 - variance_term 

46 return d1, d2 

47 

48 

49def bs_price( 

50 spot: float, 

51 strike: float, 

52 time_to_expiry_years: float, 

53 risk_free_rate: float, 

54 volatility: float, 

55 dividend_yield: float, 

56 right: str, 

57) -> float: 

58 """European option price under Black-Scholes-Merton with a continuous 

59 dividend yield. Callers must ensure spot/strike/time_to_expiry_years/ 

60 volatility are all strictly positive - this function does not 

61 neutral-default (unlike features/bond_features.py's pure functions): 

62 an option price is meaningless for a degenerate input, so callers 

63 (options_greeks.implied_volatility(), portfolio/options_strategy.py) 

64 are responsible for filtering those cases before calling in.""" 

65 d1, d2 = _d1_d2(spot, strike, time_to_expiry_years, risk_free_rate, volatility, dividend_yield) 

66 discounted_spot = spot * math.exp(-dividend_yield * time_to_expiry_years) 

67 discounted_strike = strike * math.exp(-risk_free_rate * time_to_expiry_years) 

68 if right.lower() == "call": 

69 return discounted_spot * _normal_cdf(d1) - discounted_strike * _normal_cdf(d2) 

70 return discounted_strike * _normal_cdf(-d2) - discounted_spot * _normal_cdf(-d1) 

71 

72 

73def delta(spot: float, strike: float, time_to_expiry_years: float, risk_free_rate: float, volatility: float, dividend_yield: float, right: str) -> float: 

74 """dPrice/dSpot. Calls: [0, 1]. Puts: [-1, 0].""" 

75 d1, _ = _d1_d2(spot, strike, time_to_expiry_years, risk_free_rate, volatility, dividend_yield) 

76 discount = math.exp(-dividend_yield * time_to_expiry_years) 

77 if right.lower() == "call": 

78 return discount * _normal_cdf(d1) 

79 return discount * (_normal_cdf(d1) - 1.0) 

80 

81 

82def gamma(spot: float, strike: float, time_to_expiry_years: float, risk_free_rate: float, volatility: float, dividend_yield: float) -> float: 

83 """d^2Price/dSpot^2 - identical for calls and puts (no `right` param).""" 

84 d1, _ = _d1_d2(spot, strike, time_to_expiry_years, risk_free_rate, volatility, dividend_yield) 

85 return math.exp(-dividend_yield * time_to_expiry_years) * _normal_pdf(d1) / (spot * volatility * math.sqrt(time_to_expiry_years)) 

86 

87 

88def vega(spot: float, strike: float, time_to_expiry_years: float, risk_free_rate: float, volatility: float, dividend_yield: float) -> float: 

89 """dPrice/dVolatility, per 1.0 (100 percentage points) of volatility - 

90 identical for calls and puts (no `right` param). Divide by 100 for the 

91 conventional "per 1 vol point" quoting convention if needed.""" 

92 d1, _ = _d1_d2(spot, strike, time_to_expiry_years, risk_free_rate, volatility, dividend_yield) 

93 return spot * math.exp(-dividend_yield * time_to_expiry_years) * _normal_pdf(d1) * math.sqrt(time_to_expiry_years) 

94 

95 

96def theta(spot: float, strike: float, time_to_expiry_years: float, risk_free_rate: float, volatility: float, dividend_yield: float, right: str) -> float: 

97 """dPrice/dTime, annualized (divide by 365 for a per-calendar-day 

98 figure).""" 

99 d1, d2 = _d1_d2(spot, strike, time_to_expiry_years, risk_free_rate, volatility, dividend_yield) 

100 discounted_spot = spot * math.exp(-dividend_yield * time_to_expiry_years) 

101 discounted_strike = strike * math.exp(-risk_free_rate * time_to_expiry_years) 

102 decay_term = -(discounted_spot * _normal_pdf(d1) * volatility) / (2.0 * math.sqrt(time_to_expiry_years)) 

103 if right.lower() == "call": 

104 return decay_term - risk_free_rate * discounted_strike * _normal_cdf(d2) + dividend_yield * discounted_spot * _normal_cdf(d1) 

105 return decay_term + risk_free_rate * discounted_strike * _normal_cdf(-d2) - dividend_yield * discounted_spot * _normal_cdf(-d1) 

106 

107 

108def rho(spot: float, strike: float, time_to_expiry_years: float, risk_free_rate: float, volatility: float, dividend_yield: float, right: str) -> float: 

109 """dPrice/dRiskFreeRate, per 1.0 (100 percentage points) of rate.""" 

110 _, d2 = _d1_d2(spot, strike, time_to_expiry_years, risk_free_rate, volatility, dividend_yield) 

111 discounted_strike = strike * math.exp(-risk_free_rate * time_to_expiry_years) 

112 if right.lower() == "call": 

113 return discounted_strike * time_to_expiry_years * _normal_cdf(d2) 

114 return -discounted_strike * time_to_expiry_years * _normal_cdf(-d2) 

115 

116 

117def compute_greeks( 

118 spot: float, 

119 strike: float, 

120 time_to_expiry_years: float, 

121 risk_free_rate: float, 

122 volatility: float, 

123 dividend_yield: float, 

124 right: str, 

125) -> dict[str, Any]: 

126 """Single call site wrapping the 5 functions above, for 

127 portfolio/options_strategy.py/main.py call-site brevity.""" 

128 return { 

129 "delta": delta(spot, strike, time_to_expiry_years, risk_free_rate, volatility, dividend_yield, right), 

130 "gamma": gamma(spot, strike, time_to_expiry_years, risk_free_rate, volatility, dividend_yield), 

131 "theta": theta(spot, strike, time_to_expiry_years, risk_free_rate, volatility, dividend_yield, right), 

132 "vega": vega(spot, strike, time_to_expiry_years, risk_free_rate, volatility, dividend_yield), 

133 "rho": rho(spot, strike, time_to_expiry_years, risk_free_rate, volatility, dividend_yield, right), 

134 "iv": volatility, 

135 } 

136 

137 

138def implied_volatility( 

139 option_price: float, 

140 spot: float, 

141 strike: float, 

142 time_to_expiry_years: float, 

143 risk_free_rate: float, 

144 dividend_yield: float, 

145 right: str, 

146 max_iterations: int = 100, 

147 tolerance: float = 1e-6, 

148) -> float | None: 

149 """Safeguarded Newton-Raphson (Newton step when it stays inside the 

150 current bracket, bisection step otherwise) - vega can be ~0 deep 

151 ITM/OTM or near expiry, which would blow up pure Newton-Raphson. 

152 bs_price() is monotonically increasing in volatility for T>0, so the 

153 [low, high] bracket only ever narrows and bisection alone is already 

154 guaranteed to converge; Newton just speeds that up when it's safe to 

155 use. 

156 

157 Returns None (never raises, never NaN) when: option_price is 

158 non-positive, any of spot/strike/time_to_expiry_years is non-positive, 

159 option_price violates the no-arbitrage intrinsic-value bound, the 

160 market price falls outside the achievable range for the search 

161 bracket [1e-6, 5.0] (500% vol), or the solver fails to converge within 

162 max_iterations - same "None = failed to compute, never a crash" 

163 convention as features/bond_features.py::empirical_duration_beta().""" 

164 if option_price is None or option_price <= 0.0 or spot <= 0.0 or strike <= 0.0 or time_to_expiry_years <= 0.0: 

165 return None 

166 

167 right_normalized = right.lower() 

168 discounted_spot = spot * math.exp(-dividend_yield * time_to_expiry_years) 

169 discounted_strike = strike * math.exp(-risk_free_rate * time_to_expiry_years) 

170 intrinsic = max(discounted_spot - discounted_strike, 0.0) if right_normalized == "call" else max(discounted_strike - discounted_spot, 0.0) 

171 if option_price < intrinsic - tolerance: 

172 return None 

173 

174 low, high = 1e-6, 5.0 

175 price_at_low = bs_price(spot, strike, time_to_expiry_years, risk_free_rate, low, dividend_yield, right_normalized) - option_price 

176 price_at_high = bs_price(spot, strike, time_to_expiry_years, risk_free_rate, high, dividend_yield, right_normalized) - option_price 

177 if price_at_low > 0.0 or price_at_high < 0.0: 

178 return None 

179 

180 sigma = 0.2 

181 for _ in range(max_iterations): 

182 price_diff = bs_price(spot, strike, time_to_expiry_years, risk_free_rate, sigma, dividend_yield, right_normalized) - option_price 

183 if abs(price_diff) < tolerance: 

184 return sigma 

185 

186 if price_diff > 0.0: 

187 high = sigma 

188 else: 

189 low = sigma 

190 

191 option_vega = vega(spot, strike, time_to_expiry_years, risk_free_rate, sigma, dividend_yield) 

192 newton_sigma = sigma - price_diff / option_vega if option_vega > 1e-10 else None 

193 if newton_sigma is not None and low < newton_sigma < high: 

194 sigma = newton_sigma 

195 else: 

196 sigma = (low + high) / 2.0 

197 

198 return None 

199 

200 

201def baw_american_price( 

202 spot: float, 

203 strike: float, 

204 time_to_expiry_years: float, 

205 risk_free_rate: float, 

206 dividend_yield: float, 

207 volatility: float, 

208 right: str, 

209 max_iterations: int = 100, 

210 tolerance: float = 1e-6, 

211) -> float: 

212 """Barone-Adesi & Whaley (1987) quadratic approximation for American 

213 option prices - "Efficient Analytic Approximation of American Option 

214 Values," Journal of Finance 42(2). Built entirely from this module's 

215 existing bs_price()/_d1_d2()/_normal_cdf() - the European price IS the 

216 approximation's own building block, not a separately-derived formula. 

217 Verified numerically against a 3000-step CRR binomial tree across 

218 several call/put/ITM/OTM/dividend combinations during development 

219 (differences of a few cents on option prices in the $6-14 range, 

220 consistent with BAW's known ~1-2% approximation error). 

221 

222 Never raises. Degrades to the European bs_price() value whenever: the 

223 dividend yield is non-positive for a call (a call should never be 

224 exercised early with zero dividend drag - the standard textbook 

225 shortcut, not an approximation gap), any input is degenerate 

226 (time/vol/spot/strike non-positive - returns intrinsic value in that 

227 case instead), or the critical-price search fails to find a 

228 bracketing sign change / doesn't converge within max_iterations. This 

229 is a SAFE direction to degrade in: the American price is always >= the 

230 European price, so under-pricing by falling back to the European 

231 value never overstates risk in the direction that matters for a short 

232 option holder (the whole reason this function exists). 

233 

234 Uses a safeguarded bisection search for the critical price (rather 

235 than implied_volatility()'s Newton-primary approach) - the BAW 

236 matching condition has no simple closed-form derivative the way vega 

237 is for the IV solve, so bisection (guaranteed convergence given a 

238 verified sign-changing bracket, checked explicitly before iterating) 

239 is the more directly verifiable choice for a per-bar risk signal that 

240 must never silently mis-converge.""" 

241 right_normalized = right.lower() 

242 if time_to_expiry_years <= 0.0 or volatility <= 0.0 or spot <= 0.0 or strike <= 0.0: 

243 return max(spot - strike, 0.0) if right_normalized == "call" else max(strike - spot, 0.0) 

244 

245 european_price = bs_price(spot, strike, time_to_expiry_years, risk_free_rate, volatility, dividend_yield, right_normalized) 

246 

247 if right_normalized == "call" and dividend_yield <= 0.0: 

248 return european_price 

249 

250 cost_of_carry = risk_free_rate - dividend_yield 

251 variance = volatility * volatility 

252 big_m = 2.0 * risk_free_rate / variance 

253 big_n = 2.0 * cost_of_carry / variance 

254 big_k = 1.0 - math.exp(-risk_free_rate * time_to_expiry_years) 

255 if big_k <= 0.0: 

256 return european_price 

257 

258 discriminant = (big_n - 1.0) ** 2 + 4.0 * big_m / big_k # >= (n - 1)^2: M and K are both positive here 

259 

260 if right_normalized == "call": 

261 q_root = (-(big_n - 1.0) + math.sqrt(discriminant)) / 2.0 # > 0 whenever M / K > 0 

262 

263 def matching_residual(critical_price: float) -> float: 

264 d1, _ = _d1_d2(critical_price, strike, time_to_expiry_years, risk_free_rate, volatility, dividend_yield) 

265 euro_at_critical = bs_price( 

266 critical_price, strike, time_to_expiry_years, risk_free_rate, volatility, dividend_yield, "call" 

267 ) 

268 term = (1.0 - math.exp(-dividend_yield * time_to_expiry_years) * _normal_cdf(d1)) * critical_price / q_root 

269 return critical_price - strike - euro_at_critical - term 

270 

271 low, high = strike, max(strike, spot) * 50.0 

272 else: 

273 q_root = (-(big_n - 1.0) - math.sqrt(discriminant)) / 2.0 # < 0 whenever M / K > 0 

274 

275 def matching_residual(critical_price: float) -> float: 

276 d1, _ = _d1_d2(critical_price, strike, time_to_expiry_years, risk_free_rate, volatility, dividend_yield) 

277 euro_at_critical = bs_price( 

278 critical_price, strike, time_to_expiry_years, risk_free_rate, volatility, dividend_yield, "put" 

279 ) 

280 term = (1.0 - math.exp(-dividend_yield * time_to_expiry_years) * _normal_cdf(-d1)) * critical_price / q_root 

281 return strike - critical_price - euro_at_critical + term 

282 

283 low, high = 1e-6, strike 

284 

285 residual_low = matching_residual(low) 

286 residual_high = matching_residual(high) 

287 if residual_low == 0.0: 

288 critical_price = low 

289 elif residual_high == 0.0: 

290 critical_price = high 

291 elif (residual_low > 0.0) == (residual_high > 0.0): 

292 return european_price 

293 else: 

294 critical_price = None 

295 for _ in range(max_iterations): 

296 midpoint = (low + high) / 2.0 

297 residual_mid = matching_residual(midpoint) 

298 if abs(residual_mid) < tolerance: 

299 critical_price = midpoint 

300 break 

301 if (residual_mid > 0.0) == (residual_low > 0.0): 

302 low = midpoint 

303 residual_low = residual_mid 

304 else: 

305 high = midpoint 

306 if critical_price is None: 

307 return european_price 

308 

309 if right_normalized == "call": 

310 if spot >= critical_price: 

311 return max(spot - strike, 0.0) 

312 d1, _ = _d1_d2(critical_price, strike, time_to_expiry_years, risk_free_rate, volatility, dividend_yield) 

313 coefficient = (critical_price / q_root) * ( 

314 1.0 - math.exp(-dividend_yield * time_to_expiry_years) * _normal_cdf(d1) 

315 ) 

316 return european_price + coefficient * (spot / critical_price) ** q_root 

317 

318 if spot <= critical_price: 

319 return max(strike - spot, 0.0) 

320 d1, _ = _d1_d2(critical_price, strike, time_to_expiry_years, risk_free_rate, volatility, dividend_yield) 

321 coefficient = -(critical_price / q_root) * ( 

322 1.0 - math.exp(-dividend_yield * time_to_expiry_years) * _normal_cdf(-d1) 

323 ) 

324 return european_price + coefficient * (spot / critical_price) ** q_root