1#[derive(Debug, Clone, Copy, PartialEq, Eq)]
8pub enum OptionKind {
9 Call,
10 Put,
11}
12
13#[derive(Debug, Clone, Copy, PartialEq, Eq)]
14pub enum OptionStyle {
15 European,
16 American,
17}
18
19#[derive(Debug, Clone, Copy, PartialEq, Eq)]
20pub enum DerivativesError {
21 InvalidInput,
22 InvalidSteps,
23 NonRecombiningTree,
24}
25
26#[repr(C)]
27#[derive(Debug, Clone, Copy, PartialEq)]
28pub struct BlackScholesResult {
29 pub price: f64,
30 pub delta: f64,
31 pub gamma: f64,
32 pub vega: f64,
33 pub theta: f64,
34 pub rho: f64,
35}
36
37pub const MAX_BINOMIAL_STEPS: usize = 1024;
38
39fn finite_positive(x: f64) -> bool {
40 x.is_finite() && x > 0.0
41}
42
43fn finite_nonnegative(x: f64) -> bool {
44 x.is_finite() && x >= 0.0
45}
46
47fn validate_option_inputs(
48 spot: f64,
49 strike: f64,
50 risk_free_rate: f64,
51 dividend_yield: f64,
52 volatility: f64,
53 time_years: f64,
54) -> Result<(), DerivativesError> {
55 if !finite_positive(spot)
56 || !finite_positive(strike)
57 || !risk_free_rate.is_finite()
58 || !dividend_yield.is_finite()
59 || !finite_positive(volatility)
60 || !finite_nonnegative(time_years)
61 {
62 return Err(DerivativesError::InvalidInput);
63 }
64 Ok(())
65}
66
67fn payoff(kind: OptionKind, underlying: f64, strike: f64) -> f64 {
68 match kind {
69 OptionKind::Call => (underlying - strike).max(0.0),
70 OptionKind::Put => (strike - underlying).max(0.0),
71 }
72}
73
74fn normal_pdf(x: f64) -> f64 {
75 const INV_SQRT_2PI: f64 = 0.398_942_280_401_432_7;
76 INV_SQRT_2PI * (-0.5 * x * x).exp()
77}
78
79pub fn normal_cdf(x: f64) -> f64 {
81 if x >= 8.0 {
82 return 1.0;
83 }
84 if x <= -8.0 {
85 return 0.0;
86 }
87
88 let z = x.abs();
89 let t = 1.0 / (1.0 + 0.231_641_9 * z);
90 let poly = (((((1.330_274_429 * t - 1.821_255_978) * t) + 1.781_477_937) * t - 0.356_563_782)
91 * t
92 + 0.319_381_530)
93 * t;
94 let cdf = 1.0 - normal_pdf(z) * poly;
95 if x >= 0.0 {
96 cdf
97 } else {
98 1.0 - cdf
99 }
100}
101
102pub fn black_scholes_price_and_greeks(
107 kind: OptionKind,
108 spot: f64,
109 strike: f64,
110 risk_free_rate: f64,
111 dividend_yield: f64,
112 volatility: f64,
113 time_years: f64,
114) -> Result<BlackScholesResult, DerivativesError> {
115 validate_option_inputs(
116 spot,
117 strike,
118 risk_free_rate,
119 dividend_yield,
120 volatility,
121 time_years,
122 )?;
123
124 if time_years == 0.0 {
125 return Ok(BlackScholesResult {
126 price: payoff(kind, spot, strike),
127 delta: match kind {
128 OptionKind::Call if spot > strike => 1.0,
129 OptionKind::Call => 0.0,
130 OptionKind::Put if spot < strike => -1.0,
131 OptionKind::Put => 0.0,
132 },
133 gamma: 0.0,
134 vega: 0.0,
135 theta: 0.0,
136 rho: 0.0,
137 });
138 }
139
140 let sqrt_t = time_years.sqrt();
141 let sigma_sqrt_t = volatility * sqrt_t;
142 let d1 = ((spot / strike).ln()
143 + (risk_free_rate - dividend_yield + 0.5 * volatility * volatility) * time_years)
144 / sigma_sqrt_t;
145 let d2 = d1 - sigma_sqrt_t;
146 let discount_r = (-risk_free_rate * time_years).exp();
147 let discount_q = (-dividend_yield * time_years).exp();
148 let nd1 = normal_cdf(d1);
149 let nd2 = normal_cdf(d2);
150 let pdf_d1 = normal_pdf(d1);
151
152 let common_theta = -(spot * discount_q * pdf_d1 * volatility) / (2.0 * sqrt_t);
153 let result = match kind {
154 OptionKind::Call => BlackScholesResult {
155 price: spot * discount_q * nd1 - strike * discount_r * nd2,
156 delta: discount_q * nd1,
157 gamma: discount_q * pdf_d1 / (spot * sigma_sqrt_t),
158 vega: spot * discount_q * pdf_d1 * sqrt_t,
159 theta: common_theta - risk_free_rate * strike * discount_r * nd2
160 + dividend_yield * spot * discount_q * nd1,
161 rho: strike * time_years * discount_r * nd2,
162 },
163 OptionKind::Put => {
164 let n_minus_d1 = normal_cdf(-d1);
165 let n_minus_d2 = normal_cdf(-d2);
166 BlackScholesResult {
167 price: strike * discount_r * n_minus_d2 - spot * discount_q * n_minus_d1,
168 delta: -discount_q * n_minus_d1,
169 gamma: discount_q * pdf_d1 / (spot * sigma_sqrt_t),
170 vega: spot * discount_q * pdf_d1 * sqrt_t,
171 theta: common_theta + risk_free_rate * strike * discount_r * n_minus_d2
172 - dividend_yield * spot * discount_q * n_minus_d1,
173 rho: -strike * time_years * discount_r * n_minus_d2,
174 }
175 }
176 };
177
178 if result.price.is_finite()
179 && result.delta.is_finite()
180 && result.gamma.is_finite()
181 && result.vega.is_finite()
182 && result.theta.is_finite()
183 && result.rho.is_finite()
184 {
185 Ok(result)
186 } else {
187 Err(DerivativesError::InvalidInput)
188 }
189}
190
191pub fn put_call_parity(
194 call_price: f64,
195 put_price: f64,
196 spot: f64,
197 strike: f64,
198 risk_free_rate: f64,
199 dividend_yield: f64,
200 time_years: f64,
201) -> Result<f64, DerivativesError> {
202 if !call_price.is_finite()
203 || !put_price.is_finite()
204 || !finite_positive(spot)
205 || !finite_positive(strike)
206 || !risk_free_rate.is_finite()
207 || !dividend_yield.is_finite()
208 || !finite_nonnegative(time_years)
209 {
210 return Err(DerivativesError::InvalidInput);
211 }
212
213 Ok(call_price
214 - put_price
215 - (spot * (-dividend_yield * time_years).exp()
216 - strike * (-risk_free_rate * time_years).exp()))
217}
218
219pub fn parity_implied_call_price(
221 put_price: f64,
222 spot: f64,
223 strike: f64,
224 risk_free_rate: f64,
225 dividend_yield: f64,
226 time_years: f64,
227) -> Result<f64, DerivativesError> {
228 if !put_price.is_finite()
229 || !finite_positive(spot)
230 || !finite_positive(strike)
231 || !risk_free_rate.is_finite()
232 || !dividend_yield.is_finite()
233 || !finite_nonnegative(time_years)
234 {
235 return Err(DerivativesError::InvalidInput);
236 }
237 Ok(put_price + spot * (-dividend_yield * time_years).exp()
238 - strike * (-risk_free_rate * time_years).exp())
239}
240
241pub fn parity_implied_put_price(
243 call_price: f64,
244 spot: f64,
245 strike: f64,
246 risk_free_rate: f64,
247 dividend_yield: f64,
248 time_years: f64,
249) -> Result<f64, DerivativesError> {
250 if !call_price.is_finite()
251 || !finite_positive(spot)
252 || !finite_positive(strike)
253 || !risk_free_rate.is_finite()
254 || !dividend_yield.is_finite()
255 || !finite_nonnegative(time_years)
256 {
257 return Err(DerivativesError::InvalidInput);
258 }
259 Ok(call_price - spot * (-dividend_yield * time_years).exp()
260 + strike * (-risk_free_rate * time_years).exp())
261}
262
263pub fn binomial_option_price(
269 kind: OptionKind,
270 style: OptionStyle,
271 spot: f64,
272 strike: f64,
273 risk_free_rate: f64,
274 dividend_yield: f64,
275 volatility: f64,
276 time_years: f64,
277 steps: usize,
278) -> Result<f64, DerivativesError> {
279 validate_option_inputs(
280 spot,
281 strike,
282 risk_free_rate,
283 dividend_yield,
284 volatility,
285 time_years,
286 )?;
287 if steps == 0 || steps > MAX_BINOMIAL_STEPS {
288 return Err(DerivativesError::InvalidSteps);
289 }
290 if time_years == 0.0 {
291 return Ok(payoff(kind, spot, strike));
292 }
293
294 let dt = time_years / steps as f64;
295 let sqrt_dt = dt.sqrt();
296 let up = (volatility * sqrt_dt).exp();
297 let down = 1.0 / up;
298 let growth = ((risk_free_rate - dividend_yield) * dt).exp();
299 let denom = up - down;
300 if denom <= 0.0 || !denom.is_finite() {
301 return Err(DerivativesError::NonRecombiningTree);
302 }
303 let p = (growth - down) / denom;
304 if !p.is_finite() || !(0.0..=1.0).contains(&p) {
305 return Err(DerivativesError::NonRecombiningTree);
306 }
307
308 let discount = (-risk_free_rate * dt).exp();
309 let ratio = up / down;
310 let mut values = [0.0_f64; MAX_BINOMIAL_STEPS + 1];
311
312 let mut underlying = spot * down.powi(steps as i32);
313 for slot in values.iter_mut().take(steps + 1) {
314 *slot = payoff(kind, underlying, strike);
315 underlying *= ratio;
316 }
317
318 for step in (0..steps).rev() {
319 let mut node_underlying = spot * down.powi(step as i32);
320 for node in 0..=step {
321 let continuation = discount * (p * values[node + 1] + (1.0 - p) * values[node]);
322 values[node] = match style {
323 OptionStyle::European => continuation,
324 OptionStyle::American => continuation.max(payoff(kind, node_underlying, strike)),
325 };
326 node_underlying *= ratio;
327 }
328 }
329
330 if values[0].is_finite() {
331 Ok(values[0])
332 } else {
333 Err(DerivativesError::InvalidInput)
334 }
335}
336
337#[cfg(test)]
338mod tests {
339 use super::*;
340
341 fn approx_eq(a: f64, b: f64, tol: f64) -> bool {
342 (a - b).abs() <= tol
343 }
344
345 #[test]
346 fn black_scholes_put_call_parity_residual_is_small() {
347 let call =
348 black_scholes_price_and_greeks(OptionKind::Call, 100.0, 100.0, 0.05, 0.01, 0.2, 1.0)
349 .unwrap();
350 let put =
351 black_scholes_price_and_greeks(OptionKind::Put, 100.0, 100.0, 0.05, 0.01, 0.2, 1.0)
352 .unwrap();
353
354 let residual =
355 put_call_parity(call.price, put.price, 100.0, 100.0, 0.05, 0.01, 1.0).unwrap();
356 assert!(residual.abs() < 1e-6);
357 }
358
359 #[test]
360 fn black_scholes_atm_call_is_in_known_bounds() {
361 let result =
362 black_scholes_price_and_greeks(OptionKind::Call, 100.0, 100.0, 0.05, 0.0, 0.2, 1.0)
363 .unwrap();
364
365 assert!(result.price > 10.40 && result.price < 10.47);
366 assert!(result.gamma > 0.018 && result.gamma < 0.020);
367 assert!(result.vega > 37.0 && result.vega < 38.0);
368 }
369
370 #[test]
371 fn deltas_have_expected_signs() {
372 let call =
373 black_scholes_price_and_greeks(OptionKind::Call, 100.0, 105.0, 0.03, 0.0, 0.25, 0.75)
374 .unwrap();
375 let put =
376 black_scholes_price_and_greeks(OptionKind::Put, 100.0, 105.0, 0.03, 0.0, 0.25, 0.75)
377 .unwrap();
378
379 assert!(call.delta > 0.0 && call.delta < 1.0);
380 assert!(put.delta < 0.0 && put.delta > -1.0);
381 }
382
383 #[test]
384 fn american_put_is_at_least_european_put_in_binomial_tree() {
385 let european = binomial_option_price(
386 OptionKind::Put,
387 OptionStyle::European,
388 100.0,
389 105.0,
390 0.04,
391 0.0,
392 0.25,
393 1.0,
394 256,
395 )
396 .unwrap();
397 let american = binomial_option_price(
398 OptionKind::Put,
399 OptionStyle::American,
400 100.0,
401 105.0,
402 0.04,
403 0.0,
404 0.25,
405 1.0,
406 256,
407 )
408 .unwrap();
409
410 assert!(american >= european);
411 }
412
413 #[test]
414 fn binomial_european_call_converges_near_black_scholes() {
415 let bs =
416 black_scholes_price_and_greeks(OptionKind::Call, 100.0, 100.0, 0.05, 0.0, 0.2, 1.0)
417 .unwrap();
418 let tree = binomial_option_price(
419 OptionKind::Call,
420 OptionStyle::European,
421 100.0,
422 100.0,
423 0.05,
424 0.0,
425 0.2,
426 1.0,
427 512,
428 )
429 .unwrap();
430
431 assert!(approx_eq(tree, bs.price, 0.05));
432 }
433
434 #[test]
435 fn rejects_invalid_volatility_and_steps() {
436 let bad_vol =
437 black_scholes_price_and_greeks(OptionKind::Call, 100.0, 100.0, 0.05, 0.0, 0.0, 1.0);
438 assert_eq!(bad_vol, Err(DerivativesError::InvalidInput));
439
440 let bad_steps = binomial_option_price(
441 OptionKind::Call,
442 OptionStyle::European,
443 100.0,
444 100.0,
445 0.05,
446 0.0,
447 0.2,
448 1.0,
449 0,
450 );
451 assert_eq!(bad_steps, Err(DerivativesError::InvalidSteps));
452 }
453}