1use std::{cell::RefCell, collections::HashMap, fmt::Debug, rc::Rc};
19
20use ahash::AHashMap;
21use nautilus_core::UnixNanos;
22use nautilus_model::{
23 data::greeks::{
24 GreeksData, OptionGreekValues, OptionValuationError, PortfolioGreeks,
25 black_scholes_greeks_checked, check_option_inputs, imply_vol_and_greeks_checked,
26 },
27 enums::{AssetClass, InstrumentClass, OptionKind, PositionSide, PriceType},
28 identifiers::{InstrumentId, StrategyId, Venue},
29 instruments::{Instrument, any::InstrumentAny},
30 position::Position,
31 types::Price,
32};
33use ustr::Ustr;
34
35use crate::{
36 actor::DataActorNative,
37 cache::{Cache, refs::PositionRef},
38 clock::Clock,
39 msgbus,
40 msgbus::TypedHandler,
41};
42
43pub type GreeksFilter = Box<dyn Fn(&GreeksData) -> bool>;
45
46#[derive(Clone)]
48pub enum GreeksFilterCallback {
49 Function(fn(&GreeksData) -> bool),
51 Closure(std::rc::Rc<dyn Fn(&GreeksData) -> bool>),
53}
54
55impl GreeksFilterCallback {
56 pub fn from_fn(f: fn(&GreeksData) -> bool) -> Self {
58 Self::Function(f)
59 }
60
61 pub fn from_closure<F>(f: F) -> Self
63 where
64 F: Fn(&GreeksData) -> bool + 'static,
65 {
66 Self::Closure(std::rc::Rc::new(f))
67 }
68
69 pub fn call(&self, data: &GreeksData) -> bool {
71 match self {
72 Self::Function(f) => f(data),
73 Self::Closure(f) => f(data),
74 }
75 }
76
77 pub fn to_greeks_filter(self) -> GreeksFilter {
79 match self {
80 Self::Function(f) => Box::new(f),
81 Self::Closure(f) => {
82 let f_clone = f.clone();
83 Box::new(move |data| f_clone(data))
84 }
85 }
86 }
87}
88
89impl Debug for GreeksFilterCallback {
90 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
91 match self {
92 Self::Function(_) => f.write_str("GreeksFilterCallback::Function"),
93 Self::Closure(_) => f.write_str("GreeksFilterCallback::Closure"),
94 }
95 }
96}
97
98#[derive(Debug, bon::Builder)]
100pub struct InstrumentGreeksParams {
101 pub instrument_id: InstrumentId,
103 #[builder(default = 0.0425)]
105 pub flat_interest_rate: f64,
106 pub flat_dividend_yield: Option<f64>,
108 #[builder(default = 0.0)]
110 pub spot_shock: f64,
111 #[builder(default = 0.0)]
113 pub vol_shock: f64,
114 #[builder(default = 0.0)]
116 pub time_to_expiry_shock: f64,
117 #[builder(default = false)]
119 pub use_cached_greeks: bool,
120 #[builder(default = false)]
122 pub update_vol: bool,
123 #[builder(default = false)]
125 pub cache_greeks: bool,
126 #[builder(default = false)]
128 pub publish_greeks: bool,
129 pub ts_event: Option<UnixNanos>,
131 pub position: Option<Position>,
133 #[builder(default = false)]
135 pub percent_greeks: bool,
136 pub index_instrument_id: Option<InstrumentId>,
138 pub beta_weights: Option<HashMap<InstrumentId, f64>>,
140 pub vega_time_weight_base: Option<i32>,
142 pub vol_index_instrument_id: Option<InstrumentId>,
144 pub vol_beta_weights: Option<HashMap<InstrumentId, f64>>,
146}
147
148impl InstrumentGreeksParams {
149 pub fn calculate(&self, calculator: &GreeksCalculator) -> anyhow::Result<GreeksData> {
155 calculator.instrument_greeks(
156 self.instrument_id,
157 Some(self.flat_interest_rate),
158 self.flat_dividend_yield,
159 Some(self.spot_shock),
160 Some(self.vol_shock),
161 Some(self.time_to_expiry_shock),
162 Some(self.use_cached_greeks),
163 Some(self.update_vol),
164 Some(self.cache_greeks),
165 Some(self.publish_greeks),
166 self.ts_event,
167 self.position.clone(),
168 Some(self.percent_greeks),
169 self.index_instrument_id,
170 self.beta_weights.as_ref(),
171 self.vega_time_weight_base,
172 self.vol_index_instrument_id,
173 self.vol_beta_weights.as_ref(),
174 )
175 }
176}
177
178#[derive(bon::Builder)]
180pub struct PortfolioGreeksParams {
181 pub underlyings: Option<Vec<String>>,
183 pub venue: Option<Venue>,
185 pub instrument_id: Option<InstrumentId>,
187 pub strategy_id: Option<StrategyId>,
189 pub side: Option<PositionSide>,
191 #[builder(default = 0.0425)]
193 pub flat_interest_rate: f64,
194 pub flat_dividend_yield: Option<f64>,
196 #[builder(default = 0.0)]
198 pub spot_shock: f64,
199 #[builder(default = 0.0)]
201 pub vol_shock: f64,
202 #[builder(default = 0.0)]
204 pub time_to_expiry_shock: f64,
205 #[builder(default = false)]
207 pub use_cached_greeks: bool,
208 #[builder(default = false)]
210 pub update_vol: bool,
211 #[builder(default = false)]
213 pub cache_greeks: bool,
214 #[builder(default = false)]
216 pub publish_greeks: bool,
217 #[builder(default = false)]
219 pub percent_greeks: bool,
220 pub index_instrument_id: Option<InstrumentId>,
222 pub beta_weights: Option<HashMap<InstrumentId, f64>>,
224 pub greeks_filter: Option<GreeksFilterCallback>,
226 pub vega_time_weight_base: Option<i32>,
228 pub vol_index_instrument_id: Option<InstrumentId>,
230 pub vol_beta_weights: Option<HashMap<InstrumentId, f64>>,
232}
233
234impl Debug for PortfolioGreeksParams {
235 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
236 f.debug_struct(stringify!(PortfolioGreeksParams))
237 .field("underlyings", &self.underlyings)
238 .field("venue", &self.venue)
239 .field("instrument_id", &self.instrument_id)
240 .field("strategy_id", &self.strategy_id)
241 .field("side", &self.side)
242 .field("flat_interest_rate", &self.flat_interest_rate)
243 .field("flat_dividend_yield", &self.flat_dividend_yield)
244 .field("spot_shock", &self.spot_shock)
245 .field("vol_shock", &self.vol_shock)
246 .field("time_to_expiry_shock", &self.time_to_expiry_shock)
247 .field("use_cached_greeks", &self.use_cached_greeks)
248 .field("update_vol", &self.update_vol)
249 .field("cache_greeks", &self.cache_greeks)
250 .field("publish_greeks", &self.publish_greeks)
251 .field("percent_greeks", &self.percent_greeks)
252 .field("index_instrument_id", &self.index_instrument_id)
253 .field("beta_weights", &self.beta_weights)
254 .field("greeks_filter", &self.greeks_filter)
255 .field("vega_time_weight_base", &self.vega_time_weight_base)
256 .field("vol_index_instrument_id", &self.vol_index_instrument_id)
257 .field("vol_beta_weights", &self.vol_beta_weights)
258 .finish()
259 }
260}
261
262impl PortfolioGreeksParams {
263 pub fn calculate(&self, calculator: &GreeksCalculator) -> anyhow::Result<PortfolioGreeks> {
269 let greeks_filter = self
270 .greeks_filter
271 .as_ref()
272 .map(|f| f.clone().to_greeks_filter());
273
274 calculator.portfolio_greeks(
275 self.underlyings.as_deref(),
276 self.venue,
277 self.instrument_id,
278 self.strategy_id,
279 self.side,
280 Some(self.flat_interest_rate),
281 self.flat_dividend_yield,
282 Some(self.spot_shock),
283 Some(self.vol_shock),
284 Some(self.time_to_expiry_shock),
285 Some(self.use_cached_greeks),
286 Some(self.update_vol),
287 Some(self.cache_greeks),
288 Some(self.publish_greeks),
289 Some(self.percent_greeks),
290 self.index_instrument_id,
291 self.beta_weights.as_ref(),
292 greeks_filter.as_ref(),
293 self.vega_time_weight_base,
294 self.vol_index_instrument_id,
295 self.vol_beta_weights.as_ref(),
296 )
297 }
298}
299
300#[allow(dead_code)]
317#[derive(Debug)]
318pub struct GreeksCalculator {
319 cache: Rc<RefCell<Cache>>,
320 clock: Rc<RefCell<dyn Clock>>,
321 cached_futures_spreads: RefCell<AHashMap<InstrumentId, (InstrumentId, Price)>>,
322 cross_venue_underlyings: RefCell<AHashMap<Ustr, InstrumentId>>,
323}
324
325impl GreeksCalculator {
326 pub fn new(cache: Rc<RefCell<Cache>>, clock: Rc<RefCell<dyn Clock>>) -> Self {
328 Self {
329 cache,
330 clock,
331 cached_futures_spreads: RefCell::new(AHashMap::new()),
332 cross_venue_underlyings: RefCell::new(AHashMap::new()),
333 }
334 }
335
336 pub fn from_actor(actor: &impl DataActorNative) -> Self {
342 Self::new(actor.cache_rc(), actor.clock_rc())
343 }
344
345 #[expect(clippy::too_many_arguments)]
368 pub fn instrument_greeks(
369 &self,
370 instrument_id: InstrumentId,
371 flat_interest_rate: Option<f64>,
372 flat_dividend_yield: Option<f64>,
373 spot_shock: Option<f64>,
374 vol_shock: Option<f64>,
375 time_to_expiry_shock: Option<f64>,
376 use_cached_greeks: Option<bool>,
377 update_vol: Option<bool>,
378 cache_greeks: Option<bool>,
379 publish_greeks: Option<bool>,
380 ts_event: Option<UnixNanos>,
381 position: Option<Position>,
382 percent_greeks: Option<bool>,
383 index_instrument_id: Option<InstrumentId>,
384 beta_weights: Option<&HashMap<InstrumentId, f64>>,
385 vega_time_weight_base: Option<i32>,
386 vol_index_instrument_id: Option<InstrumentId>,
387 vol_beta_weights: Option<&HashMap<InstrumentId, f64>>,
388 ) -> anyhow::Result<GreeksData> {
389 let flat_interest_rate = flat_interest_rate.unwrap_or(0.0425);
391 let spot_shock = spot_shock.unwrap_or(0.0);
392 let vol_shock = vol_shock.unwrap_or(0.0);
393 let time_to_expiry_shock = time_to_expiry_shock.unwrap_or(0.0);
394 let use_cached_greeks = use_cached_greeks.unwrap_or(false);
395 let update_vol = update_vol.unwrap_or(false);
396 let cache_greeks = cache_greeks.unwrap_or(false);
397 let publish_greeks = publish_greeks.unwrap_or(false);
398 let ts_event = ts_event.unwrap_or_default();
399 let percent_greeks = percent_greeks.unwrap_or(false);
400
401 let instrument = {
402 let cache = self.cache.borrow();
403 cache.try_instrument(&instrument_id)?.clone()
404 };
405
406 if instrument.instrument_class() == InstrumentClass::OptionSpread {
407 return Err(OptionValuationError::UnsupportedSpread(instrument_id).into());
408 }
409
410 if instrument.instrument_class() != InstrumentClass::Option {
411 return self.calculate_non_option_greeks(
412 &instrument,
413 instrument_id,
414 spot_shock,
415 ts_event,
416 position,
417 percent_greeks,
418 index_instrument_id,
419 beta_weights,
420 );
421 }
422
423 let ts_event = self.check_option_valuation(
424 &instrument,
425 ts_event,
426 spot_shock,
427 vol_shock,
428 time_to_expiry_shock,
429 )?;
430
431 let has_shocks = spot_shock != 0.0 || vol_shock != 0.0 || time_to_expiry_shock != 0.0;
432
433 if use_cached_greeks
435 && !has_shocks
436 && let Some(mut cached_greeks) = self.cache.borrow().greeks(&instrument_id)
437 {
438 check_option_greeks_data(&cached_greeks)?;
439 if let Some(pos) = position {
440 cached_greeks.pnl = cached_greeks.price - pos.avg_px_open.as_f64();
441 }
442
443 check_option_greeks_data(&cached_greeks)?;
444
445 return Ok(cached_greeks);
446 }
447
448 let underlying_instrument_id =
449 self.resolve_underlying_instrument_id(&instrument, instrument_id)?;
450 let (greeks_data, db_dr, is_fresh) = self.calculate_option_greeks(
451 &instrument,
452 instrument_id,
453 underlying_instrument_id,
454 flat_interest_rate,
455 flat_dividend_yield,
456 use_cached_greeks,
457 update_vol,
458 ts_event,
459 percent_greeks,
460 index_instrument_id,
461 beta_weights,
462 vega_time_weight_base,
463 vol_index_instrument_id,
464 vol_beta_weights,
465 )?;
466
467 let shocked_greeks = if has_shocks {
468 Some(self.apply_option_greeks_shocks(
469 &greeks_data,
470 underlying_instrument_id,
471 db_dr,
472 spot_shock,
473 vol_shock,
474 time_to_expiry_shock,
475 percent_greeks,
476 index_instrument_id,
477 beta_weights,
478 vega_time_weight_base,
479 vol_index_instrument_id,
480 vol_beta_weights,
481 )?)
482 } else {
483 None
484 };
485
486 let final_greeks = shocked_greeks.as_ref().unwrap_or(&greeks_data);
487 check_option_greeks_data(final_greeks)?;
488 let pnl = position.map_or(final_greeks.pnl, |pos| {
489 final_greeks.price - pos.avg_px_open.as_f64()
490 });
491
492 check_greeks_values(pnl, final_greeks.price, final_greeks.greeks)?;
493
494 if is_fresh {
495 self.store_option_greeks(
496 &greeks_data,
497 underlying_instrument_id.symbol.as_str(),
498 cache_greeks,
499 publish_greeks,
500 );
501 }
502
503 let mut greeks_data = shocked_greeks.unwrap_or(greeks_data);
504 greeks_data.pnl = pnl;
505
506 Ok(greeks_data)
507 }
508
509 fn check_option_valuation(
510 &self,
511 instrument: &InstrumentAny,
512 ts_event: UnixNanos,
513 spot_shock: f64,
514 vol_shock: f64,
515 time_to_expiry_shock: f64,
516 ) -> Result<UnixNanos, OptionValuationError> {
517 let valuation_time = if ts_event == UnixNanos::default() {
518 self.clock.borrow().timestamp_ns()
519 } else {
520 ts_event
521 };
522
523 let expiration = instrument
524 .expiration_ns()
525 .ok_or(OptionValuationError::InvalidInput("expiration"))?;
526
527 if valuation_time >= expiration {
528 return Err(OptionValuationError::Expired(instrument.id()));
529 }
530
531 for (name, value) in [
532 ("spot shock", spot_shock),
533 ("volatility shock", vol_shock),
534 ("time to expiry shock", time_to_expiry_shock),
535 ] {
536 if !value.is_finite() {
537 return Err(OptionValuationError::InvalidInput(name));
538 }
539 }
540
541 Ok(valuation_time)
542 }
543
544 fn store_option_greeks(&self, data: &GreeksData, underlying: &str, cache: bool, publish: bool) {
545 if cache && let Err(e) = self.cache.borrow_mut().add_greeks(data.clone()) {
546 log::error!("Failed to add GreeksData to cache: {e}");
547 }
548
549 if publish {
550 let topic = greeks_topic(underlying, &data.instrument_id.to_string()).into();
551 msgbus::publish_greeks(topic, data);
552 }
553 }
554
555 fn resolve_underlying_instrument_id(
556 &self,
557 instrument: &InstrumentAny,
558 instrument_id: InstrumentId,
559 ) -> anyhow::Result<InstrumentId> {
560 let Some(underlying) = instrument.underlying() else {
561 anyhow::bail!("Instrument {instrument_id} has no underlying identifier");
562 };
563
564 let same_venue_id = InstrumentId::from(format!("{underlying}.{}", instrument_id.venue));
565 let cache = self.cache.borrow();
566 let mut cross_venue_underlyings = self.cross_venue_underlyings.borrow_mut();
567
568 let remembered_id = cross_venue_underlyings
570 .get(&underlying)
571 .copied()
572 .filter(|id| cache.instrument(id).is_some());
573
574 if remembered_id.is_none() {
575 cross_venue_underlyings.remove(&underlying);
576 }
577
578 if cache.instrument(&same_venue_id).is_some()
580 || self
581 .cached_futures_spreads
582 .borrow()
583 .contains_key(&same_venue_id)
584 {
585 return Ok(same_venue_id);
586 }
587
588 if let Some(underlying_id) = remembered_id {
589 return Ok(underlying_id);
590 }
591
592 let mut matches: Vec<InstrumentId> = cache
594 .instrument_ids(None)
595 .into_iter()
596 .filter(|id| id.symbol.inner() == underlying)
597 .copied()
598 .collect();
599
600 match matches.len() {
601 0 => Ok(same_venue_id),
602 1 => {
603 cross_venue_underlyings.insert(underlying, matches[0]);
604 Ok(matches[0])
605 }
606 _ => {
607 matches.sort();
608 let names = matches
609 .iter()
610 .map(ToString::to_string)
611 .collect::<Vec<_>>()
612 .join(", ");
613 anyhow::bail!("Ambiguous underlying for option {instrument_id}: {names}")
614 }
615 }
616 }
617
618 #[expect(clippy::too_many_arguments)]
619 fn calculate_non_option_greeks(
620 &self,
621 instrument: &InstrumentAny,
622 instrument_id: InstrumentId,
623 spot_shock: f64,
624 ts_event: UnixNanos,
625 position: Option<Position>,
626 percent_greeks: bool,
627 index_instrument_id: Option<InstrumentId>,
628 beta_weights: Option<&HashMap<InstrumentId, f64>>,
629 ) -> anyhow::Result<GreeksData> {
630 let multiplier = instrument.multiplier();
631 let underlying_instrument_id = instrument.id();
632 let underlying_price = self
633 .get_price(&underlying_instrument_id)
634 .ok_or_else(|| anyhow::anyhow!("No price available for {underlying_instrument_id}"))?;
635 let (delta, _, _) = self.modify_greeks(
636 1.0,
637 0.0,
638 underlying_instrument_id,
639 underlying_price + spot_shock,
640 underlying_price,
641 percent_greeks,
642 index_instrument_id,
643 beta_weights,
644 0.0,
645 0.0,
646 0,
647 None,
648 0.0,
649 None,
650 None,
651 None,
652 None,
653 )?;
654 let mut greeks_data =
655 GreeksData::from_delta(instrument_id, delta, multiplier.as_f64(), ts_event);
656
657 if let Some(pos) = position {
658 greeks_data.pnl = (underlying_price + spot_shock) - pos.avg_px_open.as_f64();
659 greeks_data.price = greeks_data.pnl;
660 }
661
662 Ok(greeks_data)
663 }
664
665 #[expect(clippy::too_many_arguments)]
666 fn calculate_option_greeks(
667 &self,
668 instrument: &InstrumentAny,
669 instrument_id: InstrumentId,
670 underlying_instrument_id: InstrumentId,
671 flat_interest_rate: f64,
672 flat_dividend_yield: Option<f64>,
673 use_cached_greeks: bool,
674 update_vol: bool,
675 ts_event: UnixNanos,
676 percent_greeks: bool,
677 index_instrument_id: Option<InstrumentId>,
678 beta_weights: Option<&HashMap<InstrumentId, f64>>,
679 vega_time_weight_base: Option<i32>,
680 vol_index_instrument_id: Option<InstrumentId>,
681 vol_beta_weights: Option<&HashMap<InstrumentId, f64>>,
682 ) -> anyhow::Result<(GreeksData, f64, bool)> {
683 if use_cached_greeks {
684 let cache = self.cache.borrow();
685 if let Some(cached_greeks) = cache.greeks(&instrument_id) {
686 check_option_greeks_data(&cached_greeks)?;
687 let db_dr = f64::from(u8::from(
688 flat_dividend_yield.is_some()
689 || cache
690 .yield_curve(&underlying_instrument_id.to_string())
691 .is_some(),
692 ));
693 return Ok((cached_greeks, db_dr, false));
694 }
695 }
696
697 let utc_now_ns = if ts_event == UnixNanos::default() {
698 self.clock.borrow().timestamp_ns()
699 } else {
700 ts_event
701 };
702
703 let utc_now = utc_now_ns.to_datetime_utc();
704 let expiry_utc = instrument
705 .expiration_ns()
706 .map_or_default(|ns| ns.to_datetime_utc());
707 let expiry_int = expiry_utc
708 .strftime("%Y%m%d")
709 .to_string()
710 .parse::<i32>()
711 .unwrap_or(0);
712 let raw_days = utc_now.duration_until(expiry_utc).as_hours() / 24;
713 let expiry_in_days = raw_days.max(1) as i32;
714 let expiry_in_years = expiry_in_days as f64 / 365.25;
715 let currency = instrument.quote_currency().code.to_string();
716
717 let cache = self.cache.borrow();
718 let yield_curve = cache.yield_curve(¤cy);
719
720 let interest_rate = match yield_curve {
721 Some(yield_curve) => yield_curve(expiry_in_years),
722 None => flat_interest_rate,
723 };
724
725 let dividend_curve = cache.yield_curve(&underlying_instrument_id.to_string());
726 drop(cache);
727
728 let (cost_of_carry, db_dr) = if let Some(dividend_curve) = dividend_curve {
729 (interest_rate - dividend_curve(expiry_in_years), 1.0)
730 } else if let Some(div_yield) = flat_dividend_yield {
731 (interest_rate - div_yield, 1.0)
732 } else {
733 (0.0, 0.0)
734 };
735
736 let multiplier = instrument.multiplier();
737 let is_call = instrument.option_kind().unwrap_or(OptionKind::Call) == OptionKind::Call;
738 let strike = instrument.strike_price().unwrap_or_default().as_f64();
739 let option_price = self
740 .get_price(&instrument_id)
741 .ok_or_else(|| anyhow::anyhow!("No price available for {instrument_id}"))?;
742 let underlying_price = self.get_underlying_price(&underlying_instrument_id)?;
743
744 if let Some(vol_index_id) = vol_index_instrument_id {
745 self.get_price(&vol_index_id)
746 .ok_or_else(|| anyhow::anyhow!("No price available for {vol_index_id}"))?;
747 }
748
749 let seed_vol = if update_vol {
750 self.cache
751 .borrow()
752 .greeks(&instrument_id)
753 .map(|greeks| greeks.vol)
754 } else {
755 None
756 };
757
758 let greeks = imply_vol_and_greeks_checked(
759 underlying_price,
760 interest_rate,
761 cost_of_carry,
762 is_call,
763 strike,
764 expiry_in_years,
765 option_price,
766 db_dr,
767 seed_vol,
768 )?;
769
770 let (delta, gamma, vega) = self.modify_greeks(
771 greeks.delta,
772 greeks.gamma,
773 underlying_instrument_id,
774 underlying_price,
775 underlying_price,
776 percent_greeks,
777 index_instrument_id,
778 beta_weights,
779 greeks.vega,
780 greeks.vol,
781 expiry_in_days,
782 vega_time_weight_base,
783 greeks.vol,
784 vol_index_instrument_id,
785 vol_beta_weights,
786 None,
787 None,
788 )?;
789
790 let greeks_data = GreeksData::new(
791 instrument_id,
792 is_call,
793 strike,
794 expiry_int,
795 expiry_in_days,
796 expiry_in_years,
797 multiplier.as_f64(),
798 1.0,
799 underlying_price,
800 interest_rate,
801 cost_of_carry,
802 greeks.vol,
803 0.0,
804 greeks.price,
805 OptionGreekValues {
806 delta,
807 gamma,
808 vega,
809 theta: greeks.theta,
810 rho: greeks.rho,
811 },
812 greeks.itm_prob,
813 utc_now_ns,
814 utc_now_ns,
815 );
816
817 check_option_greeks_data(&greeks_data)?;
818
819 Ok((greeks_data, db_dr, true))
820 }
821
822 #[expect(clippy::too_many_arguments)]
823 fn apply_option_greeks_shocks(
824 &self,
825 greeks_data: &GreeksData,
826 underlying_instrument_id: InstrumentId,
827 db_dr: f64,
828 spot_shock: f64,
829 vol_shock: f64,
830 time_to_expiry_shock: f64,
831 percent_greeks: bool,
832 index_instrument_id: Option<InstrumentId>,
833 beta_weights: Option<&HashMap<InstrumentId, f64>>,
834 vega_time_weight_base: Option<i32>,
835 vol_index_instrument_id: Option<InstrumentId>,
836 vol_beta_weights: Option<&HashMap<InstrumentId, f64>>,
837 ) -> anyhow::Result<GreeksData> {
838 let underlying_price = greeks_data.underlying_price;
839 let shocked_underlying_price = underlying_price + spot_shock;
840 let shocked_vol = greeks_data.vol + vol_shock;
841 let shocked_time_to_expiry = greeks_data.expiry_in_years - time_to_expiry_shock;
842 let shocked_expiry_in_days = (shocked_time_to_expiry * 365.25) as i32;
843
844 let greeks = black_scholes_greeks_checked(
845 shocked_underlying_price,
846 greeks_data.interest_rate,
847 greeks_data.cost_of_carry,
848 shocked_vol,
849 greeks_data.is_call,
850 greeks_data.strike,
851 shocked_time_to_expiry,
852 db_dr,
853 )?;
854 let (delta, gamma, vega) = self.modify_greeks(
855 greeks.delta,
856 greeks.gamma,
857 underlying_instrument_id,
858 shocked_underlying_price,
859 underlying_price,
860 percent_greeks,
861 index_instrument_id,
862 beta_weights,
863 greeks.vega,
864 shocked_vol,
865 shocked_expiry_in_days,
866 vega_time_weight_base,
867 greeks_data.vol,
868 vol_index_instrument_id,
869 vol_beta_weights,
870 None,
871 None,
872 )?;
873 Ok(GreeksData::new(
874 greeks_data.instrument_id,
875 greeks_data.is_call,
876 greeks_data.strike,
877 greeks_data.expiry,
878 shocked_expiry_in_days,
879 shocked_time_to_expiry,
880 greeks_data.multiplier,
881 greeks_data.quantity,
882 shocked_underlying_price,
883 greeks_data.interest_rate,
884 greeks_data.cost_of_carry,
885 shocked_vol,
886 0.0,
887 greeks.price,
888 OptionGreekValues {
889 delta,
890 gamma,
891 vega,
892 theta: greeks.theta,
893 rho: greeks.rho,
894 },
895 greeks.itm_prob,
896 greeks_data.ts_event,
897 greeks_data.ts_event,
898 ))
899 }
900
901 fn get_underlying_price(&self, underlying_instrument_id: &InstrumentId) -> anyhow::Result<f64> {
902 if let Some(underlying_price) = self.get_price(underlying_instrument_id) {
903 return Ok(underlying_price);
904 }
905
906 let is_future_or_absent = {
909 let cache = self.cache.borrow();
910 cache
911 .instrument(underlying_instrument_id)
912 .is_none_or(|inst| inst.instrument_class() == InstrumentClass::Future)
913 };
914
915 if is_future_or_absent
916 && let Some(underlying_price) =
917 self.get_cached_futures_spread_price(*underlying_instrument_id)
918 {
919 return Ok(underlying_price.as_f64());
920 }
921
922 anyhow::bail!("No price available for {underlying_instrument_id}")
923 }
924
925 #[expect(clippy::too_many_arguments)]
951 pub fn modify_greeks(
952 &self,
953 delta_input: f64,
954 gamma_input: f64,
955 underlying_instrument_id: InstrumentId,
956 underlying_price: f64,
957 unshocked_underlying_price: f64,
958 percent_greeks: bool,
959 index_instrument_id: Option<InstrumentId>,
960 beta_weights: Option<&HashMap<InstrumentId, f64>>,
961 vega_input: f64,
962 vol: f64,
963 expiry_in_days: i32,
964 vega_time_weight_base: Option<i32>,
965 unshocked_vol: f64,
966 vol_index_instrument_id: Option<InstrumentId>,
967 vol_beta_weights: Option<&HashMap<InstrumentId, f64>>,
968 index_price: Option<f64>,
969 vol_index_price: Option<f64>,
970 ) -> anyhow::Result<(f64, f64, f64)> {
971 let mut delta = delta_input;
972 let mut gamma = gamma_input;
973 let mut vega = vega_input;
974
975 let mut used_index_price = index_price
976 .or_else(|| index_instrument_id.and_then(|index_id| self.get_price(&index_id)));
977 let mut used_index_vol = vol_index_price;
978 if used_index_vol.is_none()
979 && let Some(vol_index_id) = vol_index_instrument_id
980 {
981 used_index_vol = Some(
982 self.get_price(&vol_index_id)
983 .ok_or_else(|| anyhow::anyhow!("No price available for {vol_index_id}"))?,
984 );
985 }
986
987 if used_index_price.is_some() {
988 let mut beta = 1.0;
989 if let Some(weights) = beta_weights
990 && let Some(&weight) = weights.get(&underlying_instrument_id)
991 {
992 beta = weight;
993 }
994
995 if let Some(ref mut idx_price) = used_index_price {
996 #[expect(clippy::float_cmp, reason = "exact-equality baseline check")]
997 if underlying_price != unshocked_underlying_price {
998 *idx_price += 1.0 / beta
999 * (*idx_price / unshocked_underlying_price)
1000 * (underlying_price - unshocked_underlying_price);
1001 }
1002
1003 let delta_multiplier = beta * underlying_price / *idx_price;
1004 delta *= delta_multiplier;
1005 gamma *= delta_multiplier.powi(2);
1006 }
1007 }
1008
1009 if used_index_vol.is_some() {
1010 let mut vega_beta = 1.0;
1011
1012 let used_vol = if unshocked_vol == 0.0 {
1013 vol
1014 } else {
1015 unshocked_vol
1016 };
1017
1018 if let Some(weights) = vol_beta_weights
1019 && let Some(&weight) = weights.get(&underlying_instrument_id)
1020 {
1021 vega_beta = weight;
1022 }
1023
1024 if let Some(ref mut idx_vol) = used_index_vol {
1025 *idx_vol *= 0.01;
1026
1027 #[expect(clippy::float_cmp, reason = "exact-equality baseline check")]
1028 if vol != used_vol && used_vol != 0.0 {
1029 *idx_vol += 1.0 / vega_beta * (*idx_vol / used_vol) * (vol - used_vol);
1030 }
1031
1032 if *idx_vol != 0.0 {
1033 vega *= vega_beta * vol / *idx_vol;
1034 }
1035 }
1036 }
1037
1038 if percent_greeks {
1039 if let Some(idx_price) = used_index_price {
1040 delta *= idx_price / 100.0;
1041 gamma *= (idx_price / 100.0).powi(2);
1042 } else {
1043 delta *= underlying_price / 100.0;
1044 gamma *= (underlying_price / 100.0).powi(2);
1045 }
1046
1047 if let Some(idx_vol) = used_index_vol {
1048 vega *= idx_vol / 100.0;
1049 } else {
1050 vega *= vol / 100.0;
1051 }
1052 }
1053
1054 if let Some(time_base) = vega_time_weight_base
1056 && expiry_in_days > 0
1057 {
1058 let time_weight = (time_base as f64 / expiry_in_days as f64).sqrt();
1059 vega *= time_weight;
1060 }
1061
1062 Ok((delta, gamma, vega))
1063 }
1064
1065 #[expect(clippy::too_many_arguments)]
1080 pub fn portfolio_greeks(
1081 &self,
1082 underlyings: Option<&[String]>,
1083 venue: Option<Venue>,
1084 instrument_id: Option<InstrumentId>,
1085 strategy_id: Option<StrategyId>,
1086 side: Option<PositionSide>,
1087 flat_interest_rate: Option<f64>,
1088 flat_dividend_yield: Option<f64>,
1089 spot_shock: Option<f64>,
1090 vol_shock: Option<f64>,
1091 time_to_expiry_shock: Option<f64>,
1092 use_cached_greeks: Option<bool>,
1093 update_vol: Option<bool>,
1094 cache_greeks: Option<bool>,
1095 publish_greeks: Option<bool>,
1096 percent_greeks: Option<bool>,
1097 index_instrument_id: Option<InstrumentId>,
1098 beta_weights: Option<&HashMap<InstrumentId, f64>>,
1099 greeks_filter: Option<&GreeksFilter>,
1100 vega_time_weight_base: Option<i32>,
1101 vol_index_instrument_id: Option<InstrumentId>,
1102 vol_beta_weights: Option<&HashMap<InstrumentId, f64>>,
1103 ) -> anyhow::Result<PortfolioGreeks> {
1104 let ts_event = self.clock.borrow().timestamp_ns();
1105 let mut portfolio_greeks =
1106 PortfolioGreeks::new(0.0, 0.0, 0.0, 0.0, 0.0, 0.0, ts_event, ts_event);
1107
1108 let flat_interest_rate = flat_interest_rate.unwrap_or(0.0425);
1110 let spot_shock = spot_shock.unwrap_or(0.0);
1111 let vol_shock = vol_shock.unwrap_or(0.0);
1112 let time_to_expiry_shock = time_to_expiry_shock.unwrap_or(0.0);
1113 let use_cached_greeks = use_cached_greeks.unwrap_or(false);
1114 let update_vol = update_vol.unwrap_or(false);
1115 let cache_greeks = cache_greeks.unwrap_or(false);
1116 let publish_greeks = publish_greeks.unwrap_or(false);
1117 let percent_greeks = percent_greeks.unwrap_or(false);
1118
1119 let open_positions: Vec<Position> = {
1121 let cache = self.cache.borrow();
1122 cache
1123 .positions_open(
1124 venue.as_ref(),
1125 instrument_id.as_ref(),
1126 strategy_id.as_ref(),
1127 None, side,
1129 )
1130 .iter()
1131 .map(PositionRef::cloned)
1132 .collect()
1133 };
1134
1135 for position in open_positions {
1136 let position_instrument_id = position.instrument_id;
1137
1138 if let Some(underlyings_list) = underlyings {
1139 let mut skip_position = true;
1140
1141 for underlying in underlyings_list {
1142 if position_instrument_id
1143 .symbol
1144 .as_str()
1145 .starts_with(underlying)
1146 {
1147 skip_position = false;
1148 break;
1149 }
1150 }
1151
1152 if skip_position {
1153 continue;
1154 }
1155 }
1156
1157 let quantity = position.signed_qty.as_f64();
1158 let instrument_greeks = self.instrument_greeks(
1159 position_instrument_id,
1160 Some(flat_interest_rate),
1161 flat_dividend_yield,
1162 Some(spot_shock),
1163 Some(vol_shock),
1164 Some(time_to_expiry_shock),
1165 Some(use_cached_greeks),
1166 Some(update_vol),
1167 Some(cache_greeks),
1168 Some(publish_greeks),
1169 Some(ts_event),
1170 Some(position),
1171 Some(percent_greeks),
1172 index_instrument_id,
1173 beta_weights,
1174 vega_time_weight_base,
1175 vol_index_instrument_id,
1176 vol_beta_weights,
1177 )?;
1178 let position_portfolio_greeks = quantity * &instrument_greeks.to_portfolio_greeks();
1179
1180 let position_greeks = GreeksData {
1181 pnl: position_portfolio_greeks.pnl,
1182 price: position_portfolio_greeks.price,
1183 greeks: position_portfolio_greeks.greeks,
1184 ..instrument_greeks
1185 };
1186
1187 if greeks_filter.is_none_or(|filter| filter(&position_greeks)) {
1189 portfolio_greeks = portfolio_greeks + position_portfolio_greeks;
1190 check_greeks_values(
1191 portfolio_greeks.pnl,
1192 portfolio_greeks.price,
1193 portfolio_greeks.greeks,
1194 )?;
1195 }
1196 }
1197
1198 Ok(portfolio_greeks)
1199 }
1200
1201 pub fn cache_futures_spread(
1207 &self,
1208 call_instrument_id: InstrumentId,
1209 put_instrument_id: InstrumentId,
1210 futures_instrument_id: InstrumentId,
1211 ) -> anyhow::Result<Price> {
1212 let cache = self.cache.borrow();
1213 let call_instrument = cache.instrument(&call_instrument_id).cloned();
1214 let put_instrument = cache.instrument(&put_instrument_id).cloned();
1215 let reference_future_instrument = cache.instrument(&futures_instrument_id).cloned();
1216 drop(cache);
1217
1218 let Some(call_instrument) = call_instrument else {
1219 anyhow::bail!(
1220 "Cannot cache futures spread: missing option instrument {call_instrument_id}"
1221 );
1222 };
1223
1224 let Some(put_instrument) = put_instrument else {
1225 anyhow::bail!(
1226 "Cannot cache futures spread: missing option instrument {put_instrument_id}"
1227 );
1228 };
1229
1230 let Some(reference_future_instrument) = reference_future_instrument else {
1231 anyhow::bail!(
1232 "Cannot cache futures spread: no reference futures instrument for {futures_instrument_id}"
1233 );
1234 };
1235
1236 if call_instrument.instrument_class() != InstrumentClass::Option
1237 || put_instrument.instrument_class() != InstrumentClass::Option
1238 {
1239 anyhow::bail!(
1240 "Cannot cache futures spread: non-option instruments provided call_instrument_id={call_instrument_id} put_instrument_id={put_instrument_id}"
1241 );
1242 }
1243
1244 if call_instrument.option_kind() != Some(OptionKind::Call)
1245 || put_instrument.option_kind() != Some(OptionKind::Put)
1246 {
1247 anyhow::bail!(
1248 "Cannot cache futures spread: expected call/put pair call_instrument_id={call_instrument_id} put_instrument_id={put_instrument_id}"
1249 );
1250 }
1251
1252 let Some(call_underlying) = call_instrument.underlying() else {
1253 anyhow::bail!(
1254 "Cannot cache futures spread: missing call underlying for {call_instrument_id}"
1255 );
1256 };
1257
1258 let Some(put_underlying) = put_instrument.underlying() else {
1259 anyhow::bail!(
1260 "Cannot cache futures spread: missing put underlying for {put_instrument_id}"
1261 );
1262 };
1263
1264 if call_underlying != put_underlying {
1265 anyhow::bail!(
1266 "Cannot cache futures spread: option underlyings differ call_instrument_id={call_instrument_id} put_instrument_id={put_instrument_id}"
1267 );
1268 }
1269
1270 if call_instrument.strike_price() != put_instrument.strike_price() {
1271 anyhow::bail!(
1272 "Cannot cache futures spread: strike prices differ call_instrument_id={call_instrument_id} put_instrument_id={put_instrument_id}"
1273 );
1274 }
1275
1276 if call_instrument.expiration_ns() != put_instrument.expiration_ns() {
1277 anyhow::bail!(
1278 "Cannot cache futures spread: expiration dates differ call_instrument_id={call_instrument_id} put_instrument_id={put_instrument_id}"
1279 );
1280 }
1281
1282 let reference_future_price = self.get_price_object(&futures_instrument_id).ok_or_else(|| {
1283 anyhow::anyhow!(
1284 "Cannot cache futures spread: no reference futures price for {futures_instrument_id}"
1285 )
1286 })?;
1287
1288 let call_price = self.get_price(&call_instrument_id).ok_or_else(|| {
1289 anyhow::anyhow!(
1290 "Cannot cache futures spread: missing option price for {call_instrument_id}"
1291 )
1292 })?;
1293
1294 let put_price = self.get_price(&put_instrument_id).ok_or_else(|| {
1295 anyhow::anyhow!(
1296 "Cannot cache futures spread: missing option price for {put_instrument_id}"
1297 )
1298 })?;
1299
1300 let underlying_instrument_id =
1301 InstrumentId::from(format!("{call_underlying}.{}", call_instrument_id.venue));
1302
1303 {
1305 let cache = self.cache.borrow();
1306 if let Some(underlying) = cache.instrument(&underlying_instrument_id)
1307 && underlying.instrument_class() != InstrumentClass::Future
1308 {
1309 anyhow::bail!(
1310 "Cannot cache futures spread: underlying {underlying_instrument_id} is not a futures contract"
1311 );
1312 }
1313 }
1314
1315 let implied_future_price =
1316 self.calculate_implied_future_price(&call_instrument, call_price, put_price);
1317 let spread = implied_future_price - reference_future_price.as_f64();
1318 let spread_price = reference_future_instrument.make_price(spread);
1319
1320 self.cached_futures_spreads.borrow_mut().insert(
1321 underlying_instrument_id,
1322 (futures_instrument_id, spread_price),
1323 );
1324
1325 Ok(reference_future_price + spread_price)
1326 }
1327
1328 fn calculate_implied_future_price(
1329 &self,
1330 call_instrument: &InstrumentAny,
1331 call_price: f64,
1332 put_price: f64,
1333 ) -> f64 {
1334 let expiry_utc = call_instrument
1335 .expiration_ns()
1336 .map_or_default(|ns| ns.to_datetime_utc());
1337 let now = self.clock.borrow().timestamp_ns().to_datetime_utc();
1338 let expiry_in_days = (now.duration_until(expiry_utc).as_hours() / 24).max(1) as i32;
1339 let expiry_in_years = expiry_in_days as f64 / 365.25;
1340 let currency = call_instrument.quote_currency().code.to_string();
1341 let interest_rate = self
1342 .cache
1343 .borrow()
1344 .yield_curve(¤cy)
1345 .map_or(0.0425, |yield_curve| yield_curve(expiry_in_years));
1346 let strike = call_instrument.strike_price().unwrap_or_default().as_f64();
1347
1348 strike + (interest_rate * expiry_in_years).exp() * (call_price - put_price)
1349 }
1350
1351 #[must_use]
1353 pub fn get_cached_futures_spread_price(
1354 &self,
1355 underlying_instrument_id: InstrumentId,
1356 ) -> Option<Price> {
1357 let (futures_instrument_id, spread) = self
1358 .cached_futures_spreads
1359 .borrow()
1360 .get(&underlying_instrument_id)
1361 .copied()?;
1362 let reference_future_price = self.get_price_object(&futures_instrument_id)?;
1363
1364 Some(reference_future_price + spread)
1365 }
1366
1367 fn get_price_object(&self, instrument_id: &InstrumentId) -> Option<Price> {
1368 let cache = self.cache.borrow();
1369 let price = cache
1370 .price(instrument_id, PriceType::Mid)
1371 .or_else(|| cache.price(instrument_id, PriceType::Last));
1372
1373 if let Some(instrument) = cache.instrument(instrument_id)
1377 && instrument.asset_class() == AssetClass::Index
1378 {
1379 if instrument.instrument_class() == InstrumentClass::Future && price.is_some() {
1380 return price;
1381 }
1382
1383 if let Some(index_price) = cache.index_price(instrument_id) {
1384 return Some(index_price.value);
1385 }
1386 }
1387
1388 price
1389 }
1390
1391 fn get_price(&self, instrument_id: &InstrumentId) -> Option<f64> {
1392 self.get_price_object(instrument_id)
1393 .map(|price| price.as_f64())
1394 }
1395
1396 pub fn subscribe_greeks<F>(&self, underlying: &str, handler: Option<F>)
1401 where
1402 F: Fn(&GreeksData) + 'static,
1403 {
1404 let pattern = greeks_topic(underlying, "*").into();
1405
1406 if let Some(custom_handler) = handler {
1407 let typed_handler = TypedHandler::from(custom_handler);
1408 msgbus::subscribe_greeks(pattern, typed_handler, None);
1409 } else {
1410 let cache_ref = self.cache.clone();
1411 let typed_handler = TypedHandler::from(move |greeks: &GreeksData| {
1412 if let Err(e) = cache_ref.borrow_mut().add_greeks(greeks.clone()) {
1413 log::error!("Failed to add GreeksData to cache: {e}");
1414 }
1415 });
1416
1417 msgbus::subscribe_greeks(pattern, typed_handler, None);
1418 }
1419 }
1420}
1421
1422fn greeks_topic(underlying: &str, instrument_id: &str) -> String {
1424 format!("data.GreeksData.underlying={underlying}.instrument_id={instrument_id}")
1425}
1426
1427fn check_option_greeks_data(data: &GreeksData) -> Result<(), OptionValuationError> {
1428 check_option_inputs(
1429 data.underlying_price,
1430 data.interest_rate,
1431 data.cost_of_carry,
1432 data.vol,
1433 data.strike,
1434 data.expiry_in_years,
1435 )?;
1436 check_greeks_values(data.pnl, data.price, data.greeks)?;
1437 if !(0.0..=1.0).contains(&data.itm_prob)
1438 || data.price < 0.0
1439 || !data.multiplier.is_finite()
1440 || !data.quantity.is_finite()
1441 {
1442 return Err(OptionValuationError::InvalidResult);
1443 }
1444
1445 Ok(())
1446}
1447
1448fn check_greeks_values(
1449 pnl: f64,
1450 price: f64,
1451 greeks: OptionGreekValues,
1452) -> Result<(), OptionValuationError> {
1453 if [
1454 pnl,
1455 price,
1456 greeks.delta,
1457 greeks.gamma,
1458 greeks.vega,
1459 greeks.theta,
1460 greeks.rho,
1461 ]
1462 .iter()
1463 .any(|value| !value.is_finite())
1464 {
1465 return Err(OptionValuationError::InvalidResult);
1466 }
1467
1468 Ok(())
1469}
1470
1471#[cfg(test)]
1472mod tests {
1473 use std::{cell::RefCell, collections::HashMap, rc::Rc};
1474
1475 use jiff::{Timestamp, civil::Date, tz::Offset};
1476 use nautilus_model::{
1477 data::{IndexPriceUpdate, QuoteTick, YieldCurve},
1478 enums::{AssetClass, OmsType, OptionKind, OrderSide, PositionSide},
1479 events::order::spec::OrderFilledSpec,
1480 identifiers::{
1481 ClientOrderId, InstrumentId, PositionId, StrategyId, Symbol, TradeId, Venue,
1482 },
1483 instruments::{
1484 Equity, FuturesContract, OptionContract,
1485 any::InstrumentAny,
1486 stubs::{crypto_option_spread_btc_deribit, option_spread},
1487 },
1488 types::{Currency, Price, Quantity},
1489 };
1490 use rstest::rstest;
1491 use rust_decimal::Decimal;
1492 use ustr::Ustr;
1493
1494 use super::*;
1495 use crate::{cache::Cache, clock::VirtualClock};
1496
1497 fn utc_timestamp(year: i16, month: i8, day: i8, hour: i8, minute: i8, second: i8) -> Timestamp {
1498 Offset::UTC
1499 .to_timestamp(
1500 Date::new(year, month, day)
1501 .unwrap()
1502 .at(hour, minute, second, 0),
1503 )
1504 .unwrap()
1505 }
1506
1507 fn create_test_calculator() -> GreeksCalculator {
1508 let cache = Rc::new(RefCell::new(Cache::new(None, None)));
1509 let clock = Rc::new(RefCell::new(VirtualClock::new()));
1510 GreeksCalculator::new(cache, clock)
1511 }
1512
1513 #[rstest]
1514 fn test_greeks_calculator_debug() {
1515 let calculator = create_test_calculator();
1516
1517 let debug_str = format!("{calculator:?}");
1518
1519 assert!(debug_str.starts_with("GreeksCalculator {"), "{debug_str}");
1520 assert!(debug_str.contains("cache:"), "{debug_str}");
1521 assert!(debug_str.contains("clock:"), "{debug_str}");
1522 assert!(
1523 debug_str.contains("cached_futures_spreads: RefCell { value: {} }"),
1524 "{debug_str}"
1525 );
1526 assert!(
1527 debug_str.contains("cross_venue_underlyings: RefCell { value: {} }"),
1528 "{debug_str}"
1529 );
1530 }
1531
1532 #[rstest]
1533 fn test_instrument_greeks_params_builder_default() {
1534 let instrument_id = InstrumentId::from("AAPL.NASDAQ");
1535
1536 let params = InstrumentGreeksParams::builder()
1537 .instrument_id(instrument_id)
1538 .build();
1539
1540 assert_eq!(params.instrument_id, instrument_id);
1541 assert_eq!(params.flat_interest_rate, 0.0425);
1542 assert_eq!(params.flat_dividend_yield, None);
1543 assert_eq!(params.spot_shock, 0.0);
1544 assert_eq!(params.vol_shock, 0.0);
1545 assert_eq!(params.time_to_expiry_shock, 0.0);
1546 assert!(!params.use_cached_greeks);
1547 assert!(!params.cache_greeks);
1548 assert!(!params.publish_greeks);
1549 assert_eq!(params.ts_event, None);
1550 assert_eq!(params.position, None);
1551 assert!(!params.percent_greeks);
1552 assert_eq!(params.index_instrument_id, None);
1553 assert_eq!(params.beta_weights, None);
1554 assert_eq!(params.vol_index_instrument_id, None);
1555 assert_eq!(params.vol_beta_weights, None);
1556 }
1557
1558 #[rstest]
1559 fn test_instrument_greeks_params_builder_custom_values() {
1560 let instrument_id = InstrumentId::from("AAPL.NASDAQ");
1561 let index_id = InstrumentId::from("SPY.NASDAQ");
1562 let vol_index_id = InstrumentId::from("VIX.XCBF");
1563 let mut beta_weights = HashMap::new();
1564 beta_weights.insert(instrument_id, 1.2);
1565 let mut vol_beta_weights = HashMap::new();
1566 vol_beta_weights.insert(instrument_id, 0.8);
1567
1568 let params = InstrumentGreeksParams::builder()
1569 .instrument_id(instrument_id)
1570 .flat_interest_rate(0.05)
1571 .flat_dividend_yield(0.02)
1572 .spot_shock(0.01)
1573 .vol_shock(0.05)
1574 .time_to_expiry_shock(0.1)
1575 .use_cached_greeks(true)
1576 .cache_greeks(true)
1577 .publish_greeks(true)
1578 .percent_greeks(true)
1579 .index_instrument_id(index_id)
1580 .beta_weights(beta_weights.clone())
1581 .vol_index_instrument_id(vol_index_id)
1582 .vol_beta_weights(vol_beta_weights.clone())
1583 .build();
1584
1585 assert_eq!(params.instrument_id, instrument_id);
1586 assert_eq!(params.flat_interest_rate, 0.05);
1587 assert_eq!(params.flat_dividend_yield, Some(0.02));
1588 assert_eq!(params.spot_shock, 0.01);
1589 assert_eq!(params.vol_shock, 0.05);
1590 assert_eq!(params.time_to_expiry_shock, 0.1);
1591 assert!(params.use_cached_greeks);
1592 assert!(params.cache_greeks);
1593 assert!(params.publish_greeks);
1594 assert!(params.percent_greeks);
1595 assert_eq!(params.index_instrument_id, Some(index_id));
1596 assert_eq!(params.beta_weights, Some(beta_weights));
1597 assert_eq!(params.vol_index_instrument_id, Some(vol_index_id));
1598 assert_eq!(params.vol_beta_weights, Some(vol_beta_weights));
1599 }
1600
1601 #[rstest]
1602 fn test_instrument_greeks_params_debug() {
1603 let instrument_id = InstrumentId::from("AAPL.NASDAQ");
1604
1605 let params = InstrumentGreeksParams::builder()
1606 .instrument_id(instrument_id)
1607 .build();
1608
1609 let debug_str = format!("{params:?}");
1610 assert!(debug_str.contains("InstrumentGreeksParams"));
1611 assert!(debug_str.contains("AAPL.NASDAQ"));
1612 }
1613
1614 #[rstest]
1615 fn test_portfolio_greeks_params_builder_default() {
1616 let params = PortfolioGreeksParams::builder().build();
1617
1618 assert_eq!(params.underlyings, None);
1619 assert_eq!(params.venue, None);
1620 assert_eq!(params.instrument_id, None);
1621 assert_eq!(params.strategy_id, None);
1622 assert_eq!(params.side, None);
1623 assert_eq!(params.flat_interest_rate, 0.0425);
1624 assert_eq!(params.flat_dividend_yield, None);
1625 assert_eq!(params.spot_shock, 0.0);
1626 assert_eq!(params.vol_shock, 0.0);
1627 assert_eq!(params.time_to_expiry_shock, 0.0);
1628 assert!(!params.use_cached_greeks);
1629 assert!(!params.cache_greeks);
1630 assert!(!params.publish_greeks);
1631 assert!(!params.percent_greeks);
1632 assert_eq!(params.index_instrument_id, None);
1633 assert_eq!(params.beta_weights, None);
1634 assert_eq!(params.vol_index_instrument_id, None);
1635 assert_eq!(params.vol_beta_weights, None);
1636 }
1637
1638 #[rstest]
1639 fn test_portfolio_greeks_params_builder_custom_values() {
1640 let venue = Venue::from("NASDAQ");
1641 let instrument_id = InstrumentId::from("AAPL.NASDAQ");
1642 let strategy_id = StrategyId::from("test-strategy");
1643 let index_id = InstrumentId::from("SPY.NASDAQ");
1644 let vol_index_id = InstrumentId::from("VIX.XCBF");
1645 let underlyings = vec!["AAPL".to_string(), "MSFT".to_string()];
1646 let mut beta_weights = HashMap::new();
1647 beta_weights.insert(instrument_id, 1.2);
1648 let mut vol_beta_weights = HashMap::new();
1649 vol_beta_weights.insert(instrument_id, 0.8);
1650
1651 let params = PortfolioGreeksParams::builder()
1652 .underlyings(underlyings.clone())
1653 .venue(venue)
1654 .instrument_id(instrument_id)
1655 .strategy_id(strategy_id)
1656 .side(PositionSide::Long)
1657 .flat_interest_rate(0.05)
1658 .flat_dividend_yield(0.02)
1659 .spot_shock(0.01)
1660 .vol_shock(0.05)
1661 .time_to_expiry_shock(0.1)
1662 .use_cached_greeks(true)
1663 .cache_greeks(true)
1664 .publish_greeks(true)
1665 .percent_greeks(true)
1666 .index_instrument_id(index_id)
1667 .beta_weights(beta_weights.clone())
1668 .vol_index_instrument_id(vol_index_id)
1669 .vol_beta_weights(vol_beta_weights.clone())
1670 .build();
1671
1672 assert_eq!(params.underlyings, Some(underlyings));
1673 assert_eq!(params.venue, Some(venue));
1674 assert_eq!(params.instrument_id, Some(instrument_id));
1675 assert_eq!(params.strategy_id, Some(strategy_id));
1676 assert_eq!(params.side, Some(PositionSide::Long));
1677 assert_eq!(params.flat_interest_rate, 0.05);
1678 assert_eq!(params.flat_dividend_yield, Some(0.02));
1679 assert_eq!(params.spot_shock, 0.01);
1680 assert_eq!(params.vol_shock, 0.05);
1681 assert_eq!(params.time_to_expiry_shock, 0.1);
1682 assert!(params.use_cached_greeks);
1683 assert!(params.cache_greeks);
1684 assert!(params.publish_greeks);
1685 assert!(params.percent_greeks);
1686 assert_eq!(params.index_instrument_id, Some(index_id));
1687 assert_eq!(params.beta_weights, Some(beta_weights));
1688 assert_eq!(params.vol_index_instrument_id, Some(vol_index_id));
1689 assert_eq!(params.vol_beta_weights, Some(vol_beta_weights));
1690 }
1691
1692 #[rstest]
1693 fn test_portfolio_greeks_params_debug() {
1694 let venue = Venue::from("NASDAQ");
1695
1696 let params = PortfolioGreeksParams::builder().venue(venue).build();
1697
1698 let debug_str = format!("{params:?}");
1699 assert!(debug_str.contains("PortfolioGreeksParams"));
1700 assert!(debug_str.contains("NASDAQ"));
1701 }
1702
1703 #[rstest]
1704 fn test_portfolio_greeks_params_builder_fluent_api() {
1705 let instrument_id = InstrumentId::from("AAPL.NASDAQ");
1706
1707 let params = PortfolioGreeksParams::builder()
1708 .instrument_id(instrument_id)
1709 .flat_interest_rate(0.05)
1710 .spot_shock(0.01)
1711 .percent_greeks(true)
1712 .build();
1713
1714 assert_eq!(params.instrument_id, Some(instrument_id));
1715 assert_eq!(params.flat_interest_rate, 0.05);
1716 assert_eq!(params.spot_shock, 0.01);
1717 assert!(params.percent_greeks);
1718 }
1719
1720 #[rstest]
1721 fn test_instrument_greeks_params_builder_fluent_chaining() {
1722 let instrument_id = InstrumentId::from("TSLA.NASDAQ");
1723
1724 let params = InstrumentGreeksParams::builder()
1726 .instrument_id(instrument_id)
1727 .flat_interest_rate(0.03)
1728 .spot_shock(0.02)
1729 .vol_shock(0.1)
1730 .use_cached_greeks(true)
1731 .percent_greeks(true)
1732 .build();
1733
1734 assert_eq!(params.instrument_id, instrument_id);
1735 assert_eq!(params.flat_interest_rate, 0.03);
1736 assert_eq!(params.spot_shock, 0.02);
1737 assert_eq!(params.vol_shock, 0.1);
1738 assert!(params.use_cached_greeks);
1739 assert!(params.percent_greeks);
1740 }
1741
1742 #[rstest]
1743 fn test_portfolio_greeks_params_builder_with_underlyings() {
1744 let underlyings = vec!["AAPL".to_string(), "MSFT".to_string(), "GOOGL".to_string()];
1745
1746 let params = PortfolioGreeksParams::builder()
1747 .underlyings(underlyings.clone())
1748 .flat_interest_rate(0.04)
1749 .build();
1750
1751 assert_eq!(params.underlyings, Some(underlyings));
1752 assert_eq!(params.flat_interest_rate, 0.04);
1753 }
1754
1755 #[rstest]
1756 fn test_builders_with_empty_beta_weights() {
1757 let instrument_id = InstrumentId::from("NVDA.NASDAQ");
1758 let empty_beta_weights = HashMap::new();
1759
1760 let instrument_params = InstrumentGreeksParams::builder()
1761 .instrument_id(instrument_id)
1762 .beta_weights(empty_beta_weights.clone())
1763 .vol_beta_weights(empty_beta_weights.clone())
1764 .build();
1765
1766 let portfolio_params = PortfolioGreeksParams::builder()
1767 .beta_weights(empty_beta_weights.clone())
1768 .vol_beta_weights(empty_beta_weights.clone())
1769 .build();
1770
1771 assert_eq!(
1772 instrument_params.beta_weights,
1773 Some(empty_beta_weights.clone())
1774 );
1775 assert_eq!(portfolio_params.beta_weights, Some(empty_beta_weights));
1776 assert_eq!(instrument_params.vol_beta_weights, Some(HashMap::new()));
1777 assert_eq!(portfolio_params.vol_beta_weights, Some(HashMap::new()));
1778 }
1779
1780 #[rstest]
1781 fn test_builders_with_all_shocks() {
1782 let instrument_id = InstrumentId::from("AMD.NASDAQ");
1783
1784 let instrument_params = InstrumentGreeksParams::builder()
1785 .instrument_id(instrument_id)
1786 .spot_shock(0.05)
1787 .vol_shock(0.1)
1788 .time_to_expiry_shock(0.01)
1789 .build();
1790
1791 let portfolio_params = PortfolioGreeksParams::builder()
1792 .spot_shock(0.05)
1793 .vol_shock(0.1)
1794 .time_to_expiry_shock(0.01)
1795 .build();
1796
1797 assert_eq!(instrument_params.spot_shock, 0.05);
1798 assert_eq!(instrument_params.vol_shock, 0.1);
1799 assert_eq!(instrument_params.time_to_expiry_shock, 0.01);
1800
1801 assert_eq!(portfolio_params.spot_shock, 0.05);
1802 assert_eq!(portfolio_params.vol_shock, 0.1);
1803 assert_eq!(portfolio_params.time_to_expiry_shock, 0.01);
1804 }
1805
1806 #[rstest]
1807 fn test_builders_with_all_boolean_flags() {
1808 let instrument_id = InstrumentId::from("META.NASDAQ");
1809
1810 let instrument_params = InstrumentGreeksParams::builder()
1811 .instrument_id(instrument_id)
1812 .use_cached_greeks(true)
1813 .cache_greeks(true)
1814 .publish_greeks(true)
1815 .percent_greeks(true)
1816 .build();
1817
1818 let portfolio_params = PortfolioGreeksParams::builder()
1819 .use_cached_greeks(true)
1820 .cache_greeks(true)
1821 .publish_greeks(true)
1822 .percent_greeks(true)
1823 .build();
1824
1825 assert!(instrument_params.use_cached_greeks);
1826 assert!(instrument_params.cache_greeks);
1827 assert!(instrument_params.publish_greeks);
1828 assert!(instrument_params.percent_greeks);
1829
1830 assert!(portfolio_params.use_cached_greeks);
1831 assert!(portfolio_params.cache_greeks);
1832 assert!(portfolio_params.publish_greeks);
1833 assert!(portfolio_params.percent_greeks);
1834 }
1835
1836 #[rstest]
1837 fn test_greeks_filter_callback_function() {
1838 fn filter_positive_delta(data: &GreeksData) -> bool {
1840 data.delta > 0.0
1841 }
1842
1843 let filter = GreeksFilterCallback::from_fn(filter_positive_delta);
1844
1845 let greeks_data = GreeksData::from_delta(
1847 InstrumentId::from("TEST.NASDAQ"),
1848 0.5,
1849 1.0,
1850 UnixNanos::default(),
1851 );
1852
1853 assert!(filter.call(&greeks_data));
1854
1855 let debug_str = format!("{filter:?}");
1857 assert!(debug_str.contains("GreeksFilterCallback::Function"));
1858 }
1859
1860 #[rstest]
1861 fn test_greeks_filter_callback_closure() {
1862 let min_delta = 0.3;
1864 let filter =
1865 GreeksFilterCallback::from_closure(move |data: &GreeksData| data.delta > min_delta);
1866
1867 let greeks_data = GreeksData::from_delta(
1869 InstrumentId::from("TEST.NASDAQ"),
1870 0.5,
1871 1.0,
1872 UnixNanos::default(),
1873 );
1874
1875 assert!(filter.call(&greeks_data));
1876
1877 let debug_str = format!("{filter:?}");
1879 assert!(debug_str.contains("GreeksFilterCallback::Closure"));
1880 }
1881
1882 #[rstest]
1883 fn test_greeks_filter_callback_clone() {
1884 fn filter_fn(data: &GreeksData) -> bool {
1885 data.delta > 0.0
1886 }
1887
1888 let filter1 = GreeksFilterCallback::from_fn(filter_fn);
1889 let filter2 = filter1.clone();
1890
1891 let greeks_data = GreeksData::from_delta(
1892 InstrumentId::from("TEST.NASDAQ"),
1893 0.5,
1894 1.0,
1895 UnixNanos::default(),
1896 );
1897
1898 assert!(filter1.call(&greeks_data));
1899 assert!(filter2.call(&greeks_data));
1900 }
1901
1902 #[rstest]
1903 fn test_portfolio_greeks_params_with_filter() {
1904 fn filter_high_delta(data: &GreeksData) -> bool {
1905 data.delta.abs() > 0.1
1906 }
1907
1908 let filter = GreeksFilterCallback::from_fn(filter_high_delta);
1909
1910 let params = PortfolioGreeksParams::builder()
1911 .greeks_filter(filter)
1912 .flat_interest_rate(0.05)
1913 .build();
1914
1915 assert!(params.greeks_filter.is_some());
1916 assert_eq!(params.flat_interest_rate, 0.05);
1917
1918 let greeks_data = GreeksData::from_delta(
1920 InstrumentId::from("TEST.NASDAQ"),
1921 0.5,
1922 1.0,
1923 UnixNanos::default(),
1924 );
1925
1926 let filter_ref = params.greeks_filter.as_ref().unwrap();
1927 assert!(filter_ref.call(&greeks_data));
1928 }
1929
1930 #[rstest]
1931 fn test_portfolio_greeks_params_with_closure_filter() {
1932 let min_gamma = 0.01;
1933 let filter =
1934 GreeksFilterCallback::from_closure(move |data: &GreeksData| data.gamma > min_gamma);
1935
1936 let params = PortfolioGreeksParams::builder()
1937 .greeks_filter(filter)
1938 .build();
1939
1940 assert!(params.greeks_filter.is_some());
1941
1942 let debug_str = format!("{params:?}");
1944 assert!(debug_str.contains("greeks_filter"));
1945 }
1946
1947 #[rstest]
1948 fn test_greeks_filter_to_greeks_filter_conversion() {
1949 fn filter_fn(data: &GreeksData) -> bool {
1950 data.delta > 0.0
1951 }
1952
1953 let callback = GreeksFilterCallback::from_fn(filter_fn);
1954 let greeks_filter = callback.to_greeks_filter();
1955
1956 let greeks_data = GreeksData::from_delta(
1957 InstrumentId::from("TEST.NASDAQ"),
1958 0.5,
1959 1.0,
1960 UnixNanos::default(),
1961 );
1962
1963 assert!(greeks_filter(&greeks_data));
1964 }
1965
1966 fn option_with_expiration(instrument_id: &str, expiration_ns: UnixNanos) -> OptionContract {
1967 let activation_ns = UnixNanos::from(utc_timestamp(2021, 9, 17, 0, 0, 0));
1968 OptionContract::builder()
1969 .instrument_id(InstrumentId::from(instrument_id))
1970 .raw_symbol(Symbol::from("AAPL211217C00150000"))
1971 .asset_class(AssetClass::Equity)
1972 .exchange(Ustr::from("GMNI"))
1973 .underlying(Ustr::from("AAPL"))
1974 .option_kind(OptionKind::Call)
1975 .strike_price(Price::from("149.0"))
1976 .currency(Currency::from("USD"))
1977 .activation_ns(activation_ns)
1978 .expiration_ns(expiration_ns)
1979 .price_precision(2)
1980 .price_increment(Price::from("0.01"))
1981 .multiplier(Quantity::from(100))
1982 .lot_size(Quantity::from(1))
1983 .ts_event(UnixNanos::default())
1984 .ts_init(UnixNanos::default())
1985 .build()
1986 .unwrap()
1987 }
1988
1989 fn equity_aapl_opra() -> Equity {
1990 Equity::builder()
1991 .instrument_id(InstrumentId::from("AAPL.OPRA"))
1992 .raw_symbol(Symbol::from("AAPL"))
1993 .isin(Ustr::from("US0378331005"))
1994 .currency(Currency::from("USD"))
1995 .price_precision(2)
1996 .price_increment(Price::from("0.01"))
1997 .ts_event(UnixNanos::default())
1998 .ts_init(UnixNanos::default())
1999 .build()
2000 .unwrap()
2001 }
2002
2003 #[rstest]
2004 fn test_resolve_underlying_instrument_id_errors_without_underlying() {
2005 let instrument = InstrumentAny::Equity(equity_aapl_opra());
2006 let error = create_test_calculator()
2007 .resolve_underlying_instrument_id(&instrument, InstrumentId::from("AAPL.OPRA"))
2008 .unwrap_err();
2009
2010 assert_eq!(
2011 error.to_string(),
2012 "Instrument AAPL.OPRA has no underlying identifier"
2013 );
2014 }
2015
2016 fn equity_with_id(instrument_id: &str) -> Equity {
2017 let instrument_id = InstrumentId::from(instrument_id);
2018 Equity::builder()
2019 .instrument_id(instrument_id)
2020 .raw_symbol(instrument_id.symbol)
2021 .currency(Currency::from("USD"))
2022 .price_precision(2)
2023 .price_increment(Price::from("0.01"))
2024 .ts_event(UnixNanos::default())
2025 .ts_init(UnixNanos::default())
2026 .build()
2027 .unwrap()
2028 }
2029
2030 fn calculator_with_option_and_equities(
2031 option: OptionContract,
2032 equity_ids: &[&str],
2033 ) -> GreeksCalculator {
2034 let cache = Rc::new(RefCell::new(Cache::new(None, None)));
2035 cache
2036 .borrow_mut()
2037 .add_instrument(InstrumentAny::OptionContract(option))
2038 .unwrap();
2039
2040 for equity_id in equity_ids {
2041 cache
2042 .borrow_mut()
2043 .add_instrument(InstrumentAny::Equity(equity_with_id(equity_id)))
2044 .unwrap();
2045 }
2046
2047 let clock = Rc::new(RefCell::new(VirtualClock::new()));
2048 GreeksCalculator::new(cache, clock)
2049 }
2050
2051 #[rstest]
2052 #[case::same_venue_preferred(&["AAPL.XNAS", "AAPL.OPRA", "AAPL.ARCX"], "AAPL.OPRA")]
2053 #[case::unique_cross_venue_match(&["AAPL.XNAS", "MSFT.XNAS"], "AAPL.XNAS")]
2054 #[case::no_match_keeps_option_venue(&["MSFT.XNAS"], "AAPL.OPRA")]
2055 fn test_resolve_underlying_instrument_id(#[case] equity_ids: &[&str], #[case] expected: &str) {
2056 let option = option_with_expiration("AAPL250417C00150000.OPRA", UnixNanos::default());
2057 let option_id = option.id();
2058 let instrument = InstrumentAny::OptionContract(option.clone());
2059 let calculator = calculator_with_option_and_equities(option, equity_ids);
2060
2061 let underlying_id = calculator
2062 .resolve_underlying_instrument_id(&instrument, option_id)
2063 .unwrap();
2064
2065 assert_eq!(underlying_id, InstrumentId::from(expected));
2066 }
2067
2068 #[rstest]
2069 fn test_resolve_underlying_instrument_id_errors_when_cross_venue_match_is_ambiguous() {
2070 let option = option_with_expiration("AAPL250417C00150000.OPRA", UnixNanos::default());
2071 let option_id = option.id();
2072 let instrument = InstrumentAny::OptionContract(option.clone());
2073 let calculator = calculator_with_option_and_equities(option, &["AAPL.XNAS", "AAPL.ARCX"]);
2074
2075 let error = calculator
2076 .resolve_underlying_instrument_id(&instrument, option_id)
2077 .unwrap_err();
2078
2079 assert_eq!(
2080 error.to_string(),
2081 "Ambiguous underlying for option AAPL250417C00150000.OPRA: AAPL.ARCX, AAPL.XNAS"
2082 );
2083 }
2084
2085 #[rstest]
2086 fn test_resolve_underlying_instrument_id_reuses_cross_venue_match() {
2087 let option = option_with_expiration("AAPL250417C00150000.OPRA", UnixNanos::default());
2088 let option_id = option.id();
2089 let instrument = InstrumentAny::OptionContract(option.clone());
2090 let calculator = calculator_with_option_and_equities(option, &["AAPL.XNAS"]);
2091 let first = calculator
2092 .resolve_underlying_instrument_id(&instrument, option_id)
2093 .unwrap();
2094
2095 calculator
2096 .cache
2097 .borrow_mut()
2098 .add_instrument(InstrumentAny::Equity(equity_with_id("AAPL.ARCX")))
2099 .unwrap();
2100 let second = calculator
2101 .resolve_underlying_instrument_id(&instrument, option_id)
2102 .unwrap();
2103
2104 assert_eq!(first, InstrumentId::from("AAPL.XNAS"));
2105 assert_eq!(second, InstrumentId::from("AAPL.XNAS"));
2106 }
2107
2108 #[rstest]
2109 fn test_resolve_underlying_instrument_id_rescans_after_match_is_purged() {
2110 let option = option_with_expiration("AAPL250417C00150000.OPRA", UnixNanos::default());
2111 let option_id = option.id();
2112 let instrument = InstrumentAny::OptionContract(option.clone());
2113 let calculator = calculator_with_option_and_equities(option, &["AAPL.XNAS"]);
2114 calculator
2115 .resolve_underlying_instrument_id(&instrument, option_id)
2116 .unwrap();
2117
2118 {
2119 let mut cache = calculator.cache.borrow_mut();
2120 cache
2121 .add_instrument(InstrumentAny::Equity(equity_with_id("AAPL.ARCX")))
2122 .unwrap();
2123 cache.purge_instrument(InstrumentId::from("AAPL.XNAS"));
2124 }
2125
2126 let underlying_id = calculator
2127 .resolve_underlying_instrument_id(&instrument, option_id)
2128 .unwrap();
2129
2130 assert_eq!(underlying_id, InstrumentId::from("AAPL.ARCX"));
2131 }
2132
2133 #[rstest]
2134 #[case::no_underlying_cached(&[])]
2135 #[case::same_venue_cached(&["AAPL.OPRA"])]
2136 fn test_resolve_underlying_instrument_id_forgets_match_once_purged(
2137 #[case] cached_while_purged: &[&str],
2138 ) {
2139 let option = option_with_expiration("AAPL250417C00150000.OPRA", UnixNanos::default());
2140 let option_id = option.id();
2141 let instrument = InstrumentAny::OptionContract(option.clone());
2142 let calculator = calculator_with_option_and_equities(option, &["AAPL.XNAS"]);
2143 calculator
2144 .resolve_underlying_instrument_id(&instrument, option_id)
2145 .unwrap();
2146
2147 {
2148 let mut cache = calculator.cache.borrow_mut();
2149 cache.purge_instrument(InstrumentId::from("AAPL.XNAS"));
2150 for equity_id in cached_while_purged {
2151 cache
2152 .add_instrument(InstrumentAny::Equity(equity_with_id(equity_id)))
2153 .unwrap();
2154 }
2155 }
2156
2157 calculator
2158 .resolve_underlying_instrument_id(&instrument, option_id)
2159 .unwrap();
2160
2161 {
2162 let mut cache = calculator.cache.borrow_mut();
2163 for equity_id in cached_while_purged {
2164 cache.purge_instrument(InstrumentId::from(*equity_id));
2165 }
2166
2167 for equity_id in ["AAPL.XNAS", "AAPL.ARCX"] {
2168 cache
2169 .add_instrument(InstrumentAny::Equity(equity_with_id(equity_id)))
2170 .unwrap();
2171 }
2172 }
2173
2174 let error = calculator
2175 .resolve_underlying_instrument_id(&instrument, option_id)
2176 .unwrap_err();
2177
2178 assert_eq!(
2179 error.to_string(),
2180 "Ambiguous underlying for option AAPL250417C00150000.OPRA: AAPL.ARCX, AAPL.XNAS"
2181 );
2182 }
2183
2184 #[rstest]
2185 fn test_instrument_greeks_reads_cached_greeks_when_underlying_is_ambiguous() {
2186 let option =
2187 option_with_expiration("AAPL250417C00150000.OPRA", UnixNanos::from(1_000_000_000));
2188 let option_id = option.id();
2189 let position = position_from_fill(
2190 &InstrumentAny::OptionContract(option.clone()),
2191 "P-GREEKS-1",
2192 "O-GREEKS-1",
2193 "T-GREEKS-1",
2194 OrderSide::Buy,
2195 1,
2196 "9.00",
2197 );
2198 let calculator = calculator_with_option_and_equities(option, &["AAPL.XNAS", "AAPL.ARCX"]);
2199 let mut cached_greeks = GreeksData::from_delta(option_id, 0.5, 100.0, UnixNanos::default());
2200 cached_greeks.price = 10.5;
2201 cached_greeks.underlying_price = 150.0;
2202 cached_greeks.strike = 150.0;
2203 cached_greeks.vol = 0.2;
2204 cached_greeks.expiry_in_years = 1.0;
2205 calculator
2206 .cache
2207 .borrow_mut()
2208 .add_greeks(cached_greeks.clone())
2209 .unwrap();
2210
2211 let greeks = calculator
2212 .instrument_greeks(
2213 option_id,
2214 None,
2215 None,
2216 None,
2217 None,
2218 None,
2219 Some(true),
2220 None,
2221 None,
2222 None,
2223 None,
2224 Some(position),
2225 None,
2226 None,
2227 None,
2228 None,
2229 None,
2230 None,
2231 )
2232 .unwrap();
2233
2234 assert_eq!(greeks.instrument_id, option_id);
2235 assert_eq!(greeks.greeks, cached_greeks.greeks);
2236 assert_eq!(greeks.pnl, 1.5);
2237 }
2238
2239 #[rstest]
2240 fn test_instrument_greeks_prices_underlying_on_another_venue() {
2241 let now = utc_timestamp(2025, 3, 8, 12, 0, 0);
2242 let expiry = now + jiff::SignedDuration::from_hours(24 * 30);
2243 let now_ns = UnixNanos::from(now);
2244 let expiry_ns = UnixNanos::from(expiry);
2245 let option = option_with_expiration("AAPL250417C00150000.OPRA", expiry_ns);
2246 let option_id = option.id();
2247 let same_venue_cache = setup_cache_with_option_and_quotes(
2248 option.clone(),
2249 InstrumentId::from("AAPL.OPRA"),
2250 now_ns,
2251 );
2252 let cross_venue_cache = Rc::new(RefCell::new(Cache::new(None, None)));
2253 cross_venue_cache
2254 .borrow_mut()
2255 .add_instrument(InstrumentAny::OptionContract(option))
2256 .unwrap();
2257 cross_venue_cache
2258 .borrow_mut()
2259 .add_instrument(InstrumentAny::Equity(equity_with_id("AAPL.XNAS")))
2260 .unwrap();
2261
2262 for (instrument_id, bid, ask) in [
2263 (option_id, "10.50", "10.60"),
2264 (InstrumentId::from("AAPL.XNAS"), "150.00", "150.10"),
2265 ] {
2266 cross_venue_cache
2267 .borrow_mut()
2268 .add_quote(QuoteTick::new(
2269 instrument_id,
2270 Price::from(bid),
2271 Price::from(ask),
2272 Quantity::from(100),
2273 Quantity::from(100),
2274 now_ns,
2275 now_ns,
2276 ))
2277 .unwrap();
2278 }
2279
2280 let greeks_for = |cache: Rc<RefCell<Cache>>| {
2281 let clock = Rc::new(RefCell::new(VirtualClock::new()));
2282 GreeksCalculator::new(cache, clock)
2283 .instrument_greeks(
2284 option_id,
2285 None,
2286 None,
2287 None,
2288 None,
2289 None,
2290 None,
2291 None,
2292 None,
2293 None,
2294 Some(now_ns),
2295 None,
2296 None,
2297 None,
2298 None,
2299 None,
2300 None,
2301 None,
2302 )
2303 .unwrap()
2304 };
2305
2306 let expected = greeks_for(same_venue_cache);
2307 let greeks = greeks_for(cross_venue_cache);
2308
2309 assert_eq!(greeks.underlying_price, expected.underlying_price);
2310 assert_eq!(greeks.vol, expected.vol);
2311 assert_eq!(greeks.price, expected.price);
2312 assert_eq!(greeks.greeks, expected.greeks);
2313 }
2314
2315 fn future_with_expiration(
2316 instrument_id: &str,
2317 underlying: &str,
2318 expiration_ns: UnixNanos,
2319 ) -> FuturesContract {
2320 FuturesContract::builder()
2321 .instrument_id(InstrumentId::from(instrument_id))
2322 .raw_symbol(Symbol::from(underlying))
2323 .asset_class(AssetClass::Index)
2324 .exchange(Ustr::from("XCME"))
2325 .underlying(Ustr::from(underlying))
2326 .activation_ns(UnixNanos::default())
2327 .expiration_ns(expiration_ns)
2328 .currency(Currency::from("USD"))
2329 .price_precision(2)
2330 .price_increment(Price::from("0.25"))
2331 .multiplier(Quantity::from(1))
2332 .lot_size(Quantity::from(1))
2333 .ts_event(UnixNanos::default())
2334 .ts_init(UnixNanos::default())
2335 .build()
2336 .unwrap()
2337 }
2338
2339 fn future_option_with_expiration(
2340 instrument_id: &str,
2341 raw_symbol: &str,
2342 underlying: &str,
2343 option_kind: OptionKind,
2344 strike: &str,
2345 expiration_ns: UnixNanos,
2346 ) -> OptionContract {
2347 OptionContract::builder()
2348 .instrument_id(InstrumentId::from(instrument_id))
2349 .raw_symbol(Symbol::from(raw_symbol))
2350 .asset_class(AssetClass::Index)
2351 .exchange(Ustr::from("XCME"))
2352 .underlying(Ustr::from(underlying))
2353 .option_kind(option_kind)
2354 .strike_price(Price::from(strike))
2355 .currency(Currency::from("USD"))
2356 .activation_ns(UnixNanos::default())
2357 .expiration_ns(expiration_ns)
2358 .price_precision(2)
2359 .price_increment(Price::from("0.01"))
2360 .multiplier(Quantity::from(1))
2361 .lot_size(Quantity::from(1))
2362 .ts_event(UnixNanos::default())
2363 .ts_init(UnixNanos::default())
2364 .build()
2365 .unwrap()
2366 }
2367
2368 fn setup_cache_with_option_and_quotes(
2369 option: OptionContract,
2370 underlying_id: InstrumentId,
2371 now_ns: UnixNanos,
2372 ) -> Rc<RefCell<Cache>> {
2373 let option_id = option.id();
2374 let cache = Rc::new(RefCell::new(Cache::new(None, None)));
2375 cache
2376 .borrow_mut()
2377 .add_instrument(InstrumentAny::OptionContract(option))
2378 .unwrap();
2379 cache
2380 .borrow_mut()
2381 .add_instrument(InstrumentAny::Equity(equity_aapl_opra()))
2382 .unwrap();
2383
2384 let option_quote = QuoteTick::new(
2385 option_id,
2386 Price::from("10.50"),
2387 Price::from("10.60"),
2388 Quantity::from(100),
2389 Quantity::from(100),
2390 now_ns,
2391 now_ns,
2392 );
2393
2394 let underlying_quote = QuoteTick::new(
2395 underlying_id,
2396 Price::from("150.00"),
2397 Price::from("150.10"),
2398 Quantity::from(100),
2399 Quantity::from(100),
2400 now_ns,
2401 now_ns,
2402 );
2403 cache.borrow_mut().add_quote(option_quote).unwrap();
2404 cache.borrow_mut().add_quote(underlying_quote).unwrap();
2405 cache
2406 }
2407
2408 fn position_from_fill(
2409 instrument: &InstrumentAny,
2410 position_id: &str,
2411 client_order_id: &str,
2412 trade_id: &str,
2413 side: OrderSide,
2414 quantity: u64,
2415 price: &str,
2416 ) -> Position {
2417 let fill = OrderFilledSpec::builder()
2418 .instrument_id(instrument.id())
2419 .client_order_id(ClientOrderId::from(client_order_id))
2420 .trade_id(TradeId::from(trade_id))
2421 .order_side(side)
2422 .last_qty(Quantity::from(quantity))
2423 .last_px(Price::from(price))
2424 .currency(Currency::USD())
2425 .position_id(PositionId::from(position_id))
2426 .build();
2427 Position::new(instrument, fill)
2428 }
2429
2430 fn calculate_portfolio_greeks(
2431 calculator: &GreeksCalculator,
2432 side: Option<PositionSide>,
2433 ) -> anyhow::Result<PortfolioGreeks> {
2434 calculator.portfolio_greeks(
2435 None, None, None, None, side, None, None, None, None, None, None, None, None, None,
2436 None, None, None, None, None, None, None,
2437 )
2438 }
2439
2440 fn assert_portfolio_greeks_eq(actual: &PortfolioGreeks, expected: &PortfolioGreeks) {
2441 assert_eq!(actual.ts_init, expected.ts_init);
2442 assert_eq!(actual.ts_event, expected.ts_event);
2443 assert_eq!(actual.pnl, expected.pnl);
2444 assert_eq!(actual.price, expected.price);
2445 assert_eq!(actual.delta, expected.delta);
2446 assert_eq!(actual.gamma, expected.gamma);
2447 assert_eq!(actual.vega, expected.vega);
2448 assert_eq!(actual.theta, expected.theta);
2449 assert_eq!(actual.rho, expected.rho);
2450 }
2451
2452 #[rstest]
2453 #[case::neither(false, false)]
2454 #[case::cache(true, false)]
2455 #[case::publish(false, true)]
2456 #[case::cache_and_publish(true, true)]
2457 fn test_portfolio_greeks_cache_and_publish(
2458 #[case] cache_greeks: bool,
2459 #[case] publish_greeks: bool,
2460 ) {
2461 msgbus::set_message_bus(Rc::new(RefCell::new(msgbus::MessageBus::default())));
2462 let (calculator, position, now_ns) = portfolio_option_calculator();
2463 let option_id = position.instrument_id;
2464 let expected = InstrumentGreeksParams::builder()
2465 .instrument_id(option_id)
2466 .ts_event(now_ns)
2467 .build()
2468 .calculate(&calculator)
2469 .unwrap();
2470 let published = Rc::new(RefCell::new(Vec::new()));
2471 let captured = published.clone();
2472 calculator.subscribe_greeks("AAPL", None::<fn(&GreeksData)>);
2473 calculator.subscribe_greeks(
2474 "AAPL",
2475 Some(move |data: &GreeksData| {
2476 captured.borrow_mut().push(data.clone());
2477 }),
2478 );
2479
2480 let result = PortfolioGreeksParams::builder()
2481 .cache_greeks(cache_greeks)
2482 .publish_greeks(publish_greeks)
2483 .build()
2484 .calculate(&calculator)
2485 .unwrap();
2486 let cached = calculator.cache.borrow().greeks(&option_id);
2487 msgbus::set_message_bus(Rc::new(RefCell::new(msgbus::MessageBus::default())));
2488
2489 let mut expected_position = expected.clone();
2490 expected_position.pnl = expected_position.price - position.avg_px_open.as_f64();
2491 assert_portfolio_greeks_eq(
2492 &result,
2493 &(position.signed_qty.as_f64() * &expected_position.to_portfolio_greeks()),
2494 );
2495 assert_eq!(cached.is_some(), cache_greeks || publish_greeks);
2496 assert_eq!(published.borrow().len(), usize::from(publish_greeks));
2497
2498 for actual in cached.iter().chain(published.borrow().iter()) {
2499 assert_greeks_eq(actual, &expected);
2500 }
2501 }
2502
2503 #[rstest]
2504 #[case::underlying("AAPL", 1)]
2505 #[case::underlying_prefix("AAP", 0)]
2506 #[case::all_underlyings("*", 1)]
2507 fn test_subscribe_greeks_matches_underlying_symbol_exactly(
2508 #[case] underlying: &str,
2509 #[case] expected_count: usize,
2510 ) {
2511 msgbus::set_message_bus(Rc::new(RefCell::new(msgbus::MessageBus::default())));
2512 let (calculator, option_id, now_ns) = option_calculator();
2513 let received = Rc::new(RefCell::new(Vec::new()));
2514 let captured = received.clone();
2515 calculator.subscribe_greeks(
2516 underlying,
2517 Some(move |data: &GreeksData| captured.borrow_mut().push(data.instrument_id)),
2518 );
2519
2520 InstrumentGreeksParams::builder()
2521 .instrument_id(option_id)
2522 .publish_greeks(true)
2523 .ts_event(now_ns)
2524 .build()
2525 .calculate(&calculator)
2526 .unwrap();
2527 msgbus::set_message_bus(Rc::new(RefCell::new(msgbus::MessageBus::default())));
2528
2529 assert_eq!(*received.borrow(), vec![option_id; expected_count]);
2530 }
2531
2532 #[rstest]
2533 fn test_publish_greeks_topic_includes_underlying_and_instrument_id() {
2534 msgbus::set_message_bus(Rc::new(RefCell::new(msgbus::MessageBus::default())));
2535 let (calculator, option_id, now_ns) = option_calculator();
2536 let received = Rc::new(RefCell::new(Vec::new()));
2537 let captured = received.clone();
2538 let topic = "data.GreeksData.underlying=AAPL.instrument_id=AAPL250417C00150000.OPRA";
2539
2540 let handler = TypedHandler::from(move |data: &GreeksData| {
2541 captured.borrow_mut().push(data.instrument_id);
2542 });
2543
2544 msgbus::subscribe_greeks(topic.into(), handler, None);
2545
2546 InstrumentGreeksParams::builder()
2547 .instrument_id(option_id)
2548 .publish_greeks(true)
2549 .ts_event(now_ns)
2550 .build()
2551 .calculate(&calculator)
2552 .unwrap();
2553 msgbus::set_message_bus(Rc::new(RefCell::new(msgbus::MessageBus::default())));
2554
2555 assert_eq!(*received.borrow(), vec![option_id]);
2556 }
2557
2558 #[rstest]
2559 fn test_portfolio_greeks_filter_reenters_calculator_and_caches() {
2560 let (calculator, position, now_ns) = portfolio_option_calculator();
2561 let option_id = position.instrument_id;
2562 let expected = InstrumentGreeksParams::builder()
2563 .instrument_id(option_id)
2564 .ts_event(now_ns)
2565 .build()
2566 .calculate(&calculator)
2567 .unwrap();
2568 let calculator = Rc::new(calculator);
2569 let captured = calculator.clone();
2570 let observed = Rc::new(RefCell::new(Vec::new()));
2571 let captured_observed = observed.clone();
2572
2573 let filter = GreeksFilterCallback::from_closure(move |data| {
2574 InstrumentGreeksParams::builder()
2575 .instrument_id(data.instrument_id)
2576 .ts_event(now_ns)
2577 .cache_greeks(true)
2578 .build()
2579 .calculate(&captured)
2580 .unwrap();
2581 captured_observed.borrow_mut().push(data.clone());
2582 true
2583 });
2584
2585 let result = PortfolioGreeksParams::builder()
2586 .greeks_filter(filter)
2587 .build()
2588 .calculate(&calculator)
2589 .unwrap();
2590
2591 let mut expected_position = expected.clone();
2592 expected_position.pnl = expected_position.price - position.avg_px_open.as_f64();
2593 let expected_portfolio =
2594 position.signed_qty.as_f64() * &expected_position.to_portfolio_greeks();
2595 assert_portfolio_greeks_eq(&result, &expected_portfolio);
2596 assert_greeks_eq(
2597 &calculator.cache.borrow().greeks(&option_id).unwrap(),
2598 &expected,
2599 );
2600 expected_position.pnl = expected_portfolio.pnl;
2601 expected_position.price = expected_portfolio.price;
2602 expected_position.greeks = expected_portfolio.greeks;
2603 let observed = observed.borrow();
2604 assert_eq!(observed.len(), 1);
2605 assert_greeks_eq(&observed[0], &expected_position);
2606 }
2607
2608 fn portfolio_option_calculator() -> (GreeksCalculator, Position, UnixNanos) {
2609 let (calculator, option_id, now_ns) = option_calculator();
2610 let clock = Rc::new(RefCell::new(VirtualClock::new()));
2611 clock.borrow_mut().set_time(now_ns);
2612 let calculator = GreeksCalculator::new(calculator.cache, clock);
2613 let instrument = calculator
2614 .cache
2615 .borrow()
2616 .instrument(&option_id)
2617 .cloned()
2618 .unwrap();
2619 let position = position_from_fill(
2620 &instrument,
2621 "P-OPTION",
2622 "O-OPTION",
2623 "T-OPTION",
2624 OrderSide::Buy,
2625 3,
2626 "9.00",
2627 );
2628 calculator
2629 .cache
2630 .borrow_mut()
2631 .add_position(&position, OmsType::Hedging)
2632 .unwrap();
2633
2634 (calculator, position, now_ns)
2635 }
2636
2637 fn assert_greeks_eq(actual: &GreeksData, expected: &GreeksData) {
2638 assert_eq!(actual.ts_init, expected.ts_init);
2639 assert_eq!(actual.ts_event, expected.ts_event);
2640 assert_eq!(actual.instrument_id, expected.instrument_id);
2641 assert_eq!(actual.is_call, expected.is_call);
2642 assert_eq!(actual.strike, expected.strike);
2643 assert_eq!(actual.expiry, expected.expiry);
2644 assert_eq!(actual.expiry_in_days, expected.expiry_in_days);
2645 assert_eq!(actual.expiry_in_years, expected.expiry_in_years);
2646 assert_eq!(actual.multiplier, expected.multiplier);
2647 assert_eq!(actual.quantity, expected.quantity);
2648 assert_eq!(actual.underlying_price, expected.underlying_price);
2649 assert_eq!(actual.interest_rate, expected.interest_rate);
2650 assert_eq!(actual.cost_of_carry, expected.cost_of_carry);
2651 assert_eq!(actual.vol, expected.vol);
2652 assert_eq!(actual.pnl, expected.pnl);
2653 assert_eq!(actual.price, expected.price);
2654 assert_eq!(actual.greeks, expected.greeks);
2655 assert_eq!(actual.itm_prob, expected.itm_prob);
2656 }
2657
2658 #[rstest]
2659 #[case(OrderSide::Buy, 3, [300.0, 300.0, 150.0])]
2660 #[case(OrderSide::Sell, 2, [-200.0, -200.0, -100.0])]
2661 fn test_portfolio_greeks_scales_futures_multiplier(
2662 #[case] side: OrderSide,
2663 #[case] quantity: u64,
2664 #[case] expected: [f64; 3],
2665 ) {
2666 let now_ns = UnixNanos::from(1_700_000_000_000_000_000);
2667 let mut future =
2668 future_with_expiration("ES.GLBX", "ES", UnixNanos::from(1_800_000_000_000_000_000));
2669 future.multiplier = Quantity::from(50);
2670 let instrument = InstrumentAny::FuturesContract(future);
2671 let instrument_id = instrument.id();
2672 let position = position_from_fill(
2673 &instrument,
2674 "P-FUTURE",
2675 "O-FUTURE",
2676 "T-FUTURE",
2677 side,
2678 quantity,
2679 "100.00",
2680 );
2681 let cache = Rc::new(RefCell::new(Cache::default()));
2682 cache.borrow_mut().add_instrument(instrument).unwrap();
2683 cache
2684 .borrow_mut()
2685 .add_position(&position, OmsType::Hedging)
2686 .unwrap();
2687 cache
2688 .borrow_mut()
2689 .add_quote(QuoteTick::new(
2690 instrument_id,
2691 Price::from("101.75"),
2692 Price::from("102.25"),
2693 Quantity::from(100),
2694 Quantity::from(100),
2695 now_ns,
2696 now_ns,
2697 ))
2698 .unwrap();
2699 let clock = Rc::new(RefCell::new(VirtualClock::new()));
2700 clock.borrow_mut().set_time(now_ns);
2701 let calculator = GreeksCalculator::new(cache, clock);
2702
2703 let result = calculate_portfolio_greeks(&calculator, None).unwrap();
2704
2705 assert_portfolio_greeks_eq(
2706 &result,
2707 &PortfolioGreeks::new(
2708 expected[0],
2709 expected[1],
2710 expected[2],
2711 0.0,
2712 0.0,
2713 0.0,
2714 now_ns,
2715 now_ns,
2716 ),
2717 );
2718 }
2719
2720 #[rstest]
2721 fn test_portfolio_greeks_ignores_closed_position_with_missing_price() {
2722 let now = utc_timestamp(2025, 3, 8, 12, 0, 0);
2723 let expiry = now + jiff::SignedDuration::from_hours(24 * 30);
2724 let now_ns = UnixNanos::from(now);
2725 let expiry_ns = UnixNanos::from(expiry);
2726 let open_option = option_with_expiration("AAPL250417C00150000.OPRA", expiry_ns);
2727 let open_option_id = open_option.id();
2728 let underlying_id = InstrumentId::from("AAPL.OPRA");
2729 let cache = setup_cache_with_option_and_quotes(open_option.clone(), underlying_id, now_ns);
2730 let closed_future = future_with_expiration("CLOSED.GLBX", "CLOSED", expiry_ns);
2731 let closed_future_id = closed_future.id();
2732 let open_instrument = InstrumentAny::OptionContract(open_option);
2733 let closed_instrument = InstrumentAny::FuturesContract(closed_future);
2734
2735 let open_position = position_from_fill(
2736 &open_instrument,
2737 "P-OPEN",
2738 "O-OPEN",
2739 "T-OPEN",
2740 OrderSide::Buy,
2741 2,
2742 "10.50",
2743 );
2744 let mut closed_position = position_from_fill(
2745 &closed_instrument,
2746 "P-CLOSED",
2747 "O-CLOSED-OPEN",
2748 "T-CLOSED-OPEN",
2749 OrderSide::Buy,
2750 1,
2751 "100.00",
2752 );
2753 cache
2754 .borrow_mut()
2755 .add_instrument(closed_instrument)
2756 .unwrap();
2757 cache
2758 .borrow_mut()
2759 .add_position(&open_position, OmsType::Hedging)
2760 .unwrap();
2761 cache
2762 .borrow_mut()
2763 .add_position(&closed_position, OmsType::Hedging)
2764 .unwrap();
2765 let closing_fill = OrderFilledSpec::builder()
2766 .instrument_id(closed_future_id)
2767 .client_order_id(ClientOrderId::from("O-CLOSED-CLOSE"))
2768 .trade_id(TradeId::from("T-CLOSED-CLOSE"))
2769 .order_side(OrderSide::Sell)
2770 .last_qty(Quantity::from(1))
2771 .last_px(Price::from("101.00"))
2772 .currency(Currency::USD())
2773 .position_id(PositionId::from("P-CLOSED"))
2774 .build();
2775 closed_position.apply(&closing_fill);
2776 cache
2777 .borrow_mut()
2778 .update_position(&closed_position)
2779 .unwrap();
2780
2781 assert!(closed_position.is_closed());
2785 assert_eq!(
2786 cache
2787 .borrow()
2788 .positions_open(None, None, None, None, None)
2789 .len(),
2790 1
2791 );
2792
2793 let clock = Rc::new(RefCell::new(VirtualClock::new()));
2794 clock.borrow_mut().set_time(now_ns);
2795 let calculator = GreeksCalculator::new(cache, clock);
2796 let expected = calculator
2797 .instrument_greeks(
2798 open_option_id,
2799 None,
2800 None,
2801 None,
2802 None,
2803 None,
2804 None,
2805 None,
2806 None,
2807 None,
2808 Some(now_ns),
2809 Some(open_position.clone()),
2810 None,
2811 None,
2812 None,
2813 None,
2814 None,
2815 None,
2816 )
2817 .unwrap();
2818 let expected = open_position.signed_qty.as_f64() * &expected.to_portfolio_greeks();
2819
2820 assert_ne!(expected.delta, 0.0);
2821 assert_portfolio_greeks_eq(
2822 &calculate_portfolio_greeks(&calculator, None).unwrap(),
2823 &expected,
2824 );
2825 assert_portfolio_greeks_eq(
2826 &calculate_portfolio_greeks(&calculator, Some(PositionSide::Flat)).unwrap(),
2827 &PortfolioGreeks::new(0.0, 0.0, 0.0, 0.0, 0.0, 0.0, now_ns, now_ns),
2828 );
2829 }
2830
2831 #[rstest]
2832 fn test_portfolio_greeks_preserves_open_position_aggregate_and_side_filters() {
2833 let now = utc_timestamp(2025, 3, 8, 12, 0, 0);
2834 let expiry = now + jiff::SignedDuration::from_hours(24 * 30);
2835 let now_ns = UnixNanos::from(now);
2836 let expiry_ns = UnixNanos::from(expiry);
2837 let long_option = option_with_expiration("AAPL250417C00145000.OPRA", expiry_ns);
2838 let short_option = option_with_expiration("AAPL250417C00155000.OPRA", expiry_ns);
2839 let long_instrument = InstrumentAny::OptionContract(long_option.clone());
2840 let short_instrument = InstrumentAny::OptionContract(short_option.clone());
2841 let underlying_id = InstrumentId::from("AAPL.OPRA");
2842 let cache = setup_cache_with_option_and_quotes(long_option, underlying_id, now_ns);
2843 cache
2844 .borrow_mut()
2845 .add_instrument(short_instrument.clone())
2846 .unwrap();
2847 cache
2848 .borrow_mut()
2849 .add_quote(QuoteTick::new(
2850 short_option.id(),
2851 Price::from("3.50"),
2852 Price::from("3.60"),
2853 Quantity::from(100),
2854 Quantity::from(100),
2855 now_ns,
2856 now_ns,
2857 ))
2858 .unwrap();
2859 let long_position = position_from_fill(
2860 &long_instrument,
2861 "P-LONG",
2862 "O-LONG",
2863 "T-LONG",
2864 OrderSide::Buy,
2865 3,
2866 "10.50",
2867 );
2868 let short_position = position_from_fill(
2869 &short_instrument,
2870 "P-SHORT",
2871 "O-SHORT",
2872 "T-SHORT",
2873 OrderSide::Sell,
2874 2,
2875 "3.50",
2876 );
2877 cache
2878 .borrow_mut()
2879 .add_position(&long_position, OmsType::Hedging)
2880 .unwrap();
2881 cache
2882 .borrow_mut()
2883 .add_position(&short_position, OmsType::Hedging)
2884 .unwrap();
2885
2886 let clock = Rc::new(RefCell::new(VirtualClock::new()));
2887 clock.borrow_mut().set_time(now_ns);
2888 let calculator = GreeksCalculator::new(cache, clock);
2889 let long_greeks = calculator
2890 .instrument_greeks(
2891 long_instrument.id(),
2892 None,
2893 None,
2894 None,
2895 None,
2896 None,
2897 None,
2898 None,
2899 None,
2900 None,
2901 Some(now_ns),
2902 Some(long_position.clone()),
2903 None,
2904 None,
2905 None,
2906 None,
2907 None,
2908 None,
2909 )
2910 .unwrap();
2911 let short_greeks = calculator
2912 .instrument_greeks(
2913 short_instrument.id(),
2914 None,
2915 None,
2916 None,
2917 None,
2918 None,
2919 None,
2920 None,
2921 None,
2922 None,
2923 Some(now_ns),
2924 Some(short_position.clone()),
2925 None,
2926 None,
2927 None,
2928 None,
2929 None,
2930 None,
2931 )
2932 .unwrap();
2933 let expected_long = long_position.signed_qty.as_f64() * &long_greeks.to_portfolio_greeks();
2934 let expected_short =
2935 short_position.signed_qty.as_f64() * &short_greeks.to_portfolio_greeks();
2936 let expected = expected_long + expected_short;
2937
2938 assert_ne!(expected.pnl, 0.0);
2939 assert_ne!(expected.price, 0.0);
2940 assert_ne!(expected.delta, 0.0);
2941 assert_ne!(expected.gamma, 0.0);
2942 assert_ne!(expected.vega, 0.0);
2943 assert_ne!(expected.theta, 0.0);
2944 assert_portfolio_greeks_eq(
2945 &calculate_portfolio_greeks(&calculator, None).unwrap(),
2946 &expected,
2947 );
2948 assert_portfolio_greeks_eq(
2949 &calculate_portfolio_greeks(&calculator, Some(PositionSide::Long)).unwrap(),
2950 &(long_position.signed_qty.as_f64() * &long_greeks.to_portfolio_greeks()),
2951 );
2952 assert_portfolio_greeks_eq(
2953 &calculate_portfolio_greeks(&calculator, Some(PositionSide::Short)).unwrap(),
2954 &(short_position.signed_qty.as_f64() * &short_greeks.to_portfolio_greeks()),
2955 );
2956 }
2957
2958 #[rstest]
2959 #[case(true, [-200.0, -1700.0, -1600.0, -1500.0, -1400.0, 1300.0, -1200.0])]
2960 #[case(false, [600.0, 900.0, 1200.0, 1500.0, 1800.0, -2100.0, 2400.0])]
2961 fn test_portfolio_greeks_scales_before_filter(
2962 #[case] include_short: bool,
2963 #[case] expected: [f64; 7],
2964 ) {
2965 let now_ns = UnixNanos::from(1_700_000_000_000_000_000);
2966 let expiry_ns = UnixNanos::from(1_800_000_000_000_000_000);
2967 let long_option = option_with_expiration("AAPL250417C00145000.OPRA", expiry_ns);
2968 let short_option = option_with_expiration("AAPL250417C00155000.OPRA", expiry_ns);
2969 let long_id = long_option.id();
2970 let short_id = short_option.id();
2971 let cache = Rc::new(RefCell::new(Cache::default()));
2972 let observed = Rc::new(RefCell::new(Vec::new()));
2973
2974 for (option, side, quantity, entry, price, greeks) in [
2975 (
2976 long_option,
2977 OrderSide::Buy,
2978 3,
2979 "1.00",
2980 3.0,
2981 OptionGreekValues {
2982 delta: 4.0,
2983 gamma: 5.0,
2984 vega: 6.0,
2985 theta: -7.0,
2986 rho: 8.0,
2987 },
2988 ),
2989 (
2990 short_option,
2991 OrderSide::Sell,
2992 2,
2993 "9.00",
2994 13.0,
2995 OptionGreekValues {
2996 delta: 14.0,
2997 gamma: 15.0,
2998 vega: 16.0,
2999 theta: -17.0,
3000 rho: 18.0,
3001 },
3002 ),
3003 ] {
3004 let instrument = InstrumentAny::OptionContract(option);
3005 let position = position_from_fill(
3006 &instrument,
3007 instrument.id().symbol.as_str(),
3008 instrument.id().symbol.as_str(),
3009 instrument.id().symbol.as_str(),
3010 side,
3011 quantity,
3012 entry,
3013 );
3014
3015 let data = GreeksData {
3016 instrument_id: instrument.id(),
3017 is_call: false,
3018 strike: 19.0,
3019 expiry: 20_271_015,
3020 expiry_in_days: 23,
3021 expiry_in_years: 0.25,
3022 multiplier: 100.0,
3023 quantity: 1.0,
3024 underlying_price: 29.0,
3025 interest_rate: 0.05,
3026 cost_of_carry: 0.02,
3027 vol: 0.5,
3028 pnl: 31.0,
3029 price,
3030 greeks,
3031 itm_prob: 0.75,
3032 ts_event: UnixNanos::from(13),
3033 ts_init: UnixNanos::from(11),
3034 };
3035
3036 let mut cache = cache.borrow_mut();
3037 cache.add_instrument(instrument).unwrap();
3038 cache.add_position(&position, OmsType::Hedging).unwrap();
3039 cache.add_greeks(data).unwrap();
3040 }
3041
3042 let clock = Rc::new(RefCell::new(VirtualClock::new()));
3043 clock.borrow_mut().set_time(now_ns);
3044 let calculator = GreeksCalculator::new(cache.clone(), clock);
3045 let captured = observed.clone();
3046 let filter: GreeksFilter = Box::new(move |data| {
3047 captured.borrow_mut().push(data.clone());
3048 include_short || data.delta > 0.0
3049 });
3050
3051 let result = calculator
3052 .portfolio_greeks(
3053 None,
3054 None,
3055 None,
3056 None,
3057 None,
3058 None,
3059 None,
3060 None,
3061 None,
3062 None,
3063 Some(true),
3064 None,
3065 None,
3066 None,
3067 None,
3068 None,
3069 None,
3070 Some(&filter),
3071 None,
3072 None,
3073 None,
3074 )
3075 .unwrap();
3076
3077 assert_eq!(result.ts_init, now_ns);
3078 assert_eq!(result.ts_event, now_ns);
3079 assert_eq!(
3080 [
3081 result.pnl,
3082 result.price,
3083 result.delta,
3084 result.gamma,
3085 result.vega,
3086 result.theta,
3087 result.rho
3088 ],
3089 expected
3090 );
3091 let mut observed = observed.borrow_mut();
3092 observed.sort_by_key(|data| data.instrument_id);
3093 assert_eq!(observed.len(), 2);
3094
3095 for (data, id, values) in [
3096 (
3097 &observed[0],
3098 long_id,
3099 [600.0, 900.0, 1200.0, 1500.0, 1800.0, -2100.0, 2400.0],
3100 ),
3101 (
3102 &observed[1],
3103 short_id,
3104 [-800.0, -2600.0, -2800.0, -3000.0, -3200.0, 3400.0, -3600.0],
3105 ),
3106 ] {
3107 assert_eq!(
3108 [
3109 data.pnl, data.price, data.delta, data.gamma, data.vega, data.theta, data.rho
3110 ],
3111 values
3112 );
3113 assert_eq!(data.ts_init, UnixNanos::from(11));
3114 assert_eq!(data.ts_event, UnixNanos::from(13));
3115 assert_eq!(data.instrument_id, id);
3116 assert!(!data.is_call);
3117 assert_eq!(data.strike, 19.0);
3118 assert_eq!(data.expiry, 20_271_015);
3119 assert_eq!(data.expiry_in_days, 23);
3120 assert_eq!(data.expiry_in_years, 0.25);
3121 assert_eq!(data.multiplier, 100.0);
3122 assert_eq!(data.quantity, 1.0);
3123 assert_eq!(data.underlying_price, 29.0);
3124 assert_eq!(data.interest_rate, 0.05);
3125 assert_eq!(data.cost_of_carry, 0.02);
3126 assert_eq!(data.vol, 0.5);
3127 assert_eq!(data.itm_prob, 0.75);
3128 }
3129
3130 for (id, price, greeks) in [
3131 (
3132 long_id,
3133 3.0,
3134 OptionGreekValues {
3135 delta: 4.0,
3136 gamma: 5.0,
3137 vega: 6.0,
3138 theta: -7.0,
3139 rho: 8.0,
3140 },
3141 ),
3142 (
3143 short_id,
3144 13.0,
3145 OptionGreekValues {
3146 delta: 14.0,
3147 gamma: 15.0,
3148 vega: 16.0,
3149 theta: -17.0,
3150 rho: 18.0,
3151 },
3152 ),
3153 ] {
3154 let cached = cache.borrow().greeks(&id).unwrap();
3155 assert_eq!(cached.pnl, 31.0);
3156 assert_eq!(cached.price, price);
3157 assert_eq!(cached.greeks, greeks);
3158 }
3159 }
3160
3161 #[rstest]
3162 fn test_expiry_in_days_multi_day_unchanged() {
3163 let now = utc_timestamp(2025, 3, 8, 12, 0, 0);
3164 let expiry = now + jiff::SignedDuration::from_hours(24 * (30));
3165 let now_ns = UnixNanos::from(now);
3166 let expiry_ns = UnixNanos::from(expiry);
3167 let option = option_with_expiration("AAPL250417C00150000.OPRA", expiry_ns);
3168 let option_id = option.id();
3169 let underlying_id = InstrumentId::from("AAPL.OPRA");
3170 let cache = setup_cache_with_option_and_quotes(option, underlying_id, now_ns);
3171 let clock = Rc::new(RefCell::new(VirtualClock::new()));
3172 let calculator = GreeksCalculator::new(cache, clock);
3173
3174 let greeks = calculator
3175 .instrument_greeks(
3176 option_id,
3177 None,
3178 None,
3179 None,
3180 None,
3181 None,
3182 None,
3183 None,
3184 None,
3185 None,
3186 Some(now_ns),
3187 None,
3188 None,
3189 None,
3190 None,
3191 None,
3192 None,
3193 None,
3194 )
3195 .unwrap();
3196
3197 assert_eq!(greeks.expiry_in_days, 30);
3198 assert!((greeks.expiry_in_years - 30.0 / 365.25).abs() < 1e-9);
3199 }
3200
3201 #[rstest]
3202 fn test_expiry_in_days_same_day_clamped_to_one() {
3203 let now = utc_timestamp(2025, 3, 8, 12, 0, 0);
3204 let expiry_same_day = utc_timestamp(2025, 3, 8, 18, 0, 0);
3205 let now_ns = UnixNanos::from(now);
3206 let expiry_ns = UnixNanos::from(expiry_same_day);
3207 let option = option_with_expiration("AAPL250308C00150000.OPRA", expiry_ns);
3208 let option_id = option.id();
3209 let underlying_id = InstrumentId::from("AAPL.OPRA");
3210 let cache = setup_cache_with_option_and_quotes(option, underlying_id, now_ns);
3211 let clock = Rc::new(RefCell::new(VirtualClock::new()));
3212 let calculator = GreeksCalculator::new(cache, clock);
3213
3214 let greeks = calculator
3215 .instrument_greeks(
3216 option_id,
3217 None,
3218 None,
3219 None,
3220 None,
3221 None,
3222 None,
3223 None,
3224 None,
3225 None,
3226 Some(now_ns),
3227 None,
3228 None,
3229 None,
3230 None,
3231 None,
3232 None,
3233 None,
3234 )
3235 .unwrap();
3236
3237 assert_eq!(greeks.expiry_in_days, 1);
3238 assert!((greeks.expiry_in_years - 1.0 / 365.25).abs() < 1e-9);
3239 }
3240
3241 #[rstest]
3242 fn test_instrument_greeks_beta_weights_vega_to_vol_index() {
3243 let now = utc_timestamp(2025, 3, 8, 12, 0, 0);
3244 let expiry = now + jiff::SignedDuration::from_hours(24 * (30));
3245 let now_ns = UnixNanos::from(now);
3246 let expiry_ns = UnixNanos::from(expiry);
3247 let option = option_with_expiration("AAPL250417C00150000.OPRA", expiry_ns);
3248 let option_id = option.id();
3249 let underlying_id = InstrumentId::from("AAPL.OPRA");
3250 let vol_index_id = InstrumentId::from("VIX.XCBF");
3251 let cache = setup_cache_with_option_and_quotes(option, underlying_id, now_ns);
3252 cache
3253 .borrow_mut()
3254 .add_quote(QuoteTick::new(
3255 vol_index_id,
3256 Price::from("25.00"),
3257 Price::from("25.00"),
3258 Quantity::from(100),
3259 Quantity::from(100),
3260 now_ns,
3261 now_ns,
3262 ))
3263 .unwrap();
3264
3265 let clock = Rc::new(RefCell::new(VirtualClock::new()));
3266 let calculator = GreeksCalculator::new(cache, clock);
3267 let greeks = calculator
3268 .instrument_greeks(
3269 option_id,
3270 None,
3271 None,
3272 None,
3273 None,
3274 None,
3275 None,
3276 None,
3277 None,
3278 None,
3279 Some(now_ns),
3280 None,
3281 None,
3282 None,
3283 None,
3284 None,
3285 None,
3286 None,
3287 )
3288 .unwrap();
3289
3290 let mut vol_beta_weights = HashMap::new();
3291 vol_beta_weights.insert(underlying_id, 0.75);
3292 let vol_weighted_greeks = calculator
3293 .instrument_greeks(
3294 option_id,
3295 None,
3296 None,
3297 None,
3298 None,
3299 None,
3300 None,
3301 None,
3302 None,
3303 None,
3304 Some(now_ns),
3305 None,
3306 None,
3307 None,
3308 None,
3309 None,
3310 Some(vol_index_id),
3311 Some(&vol_beta_weights),
3312 )
3313 .unwrap();
3314
3315 let expected_vega = greeks.vega * 0.75 * (greeks.vol * 100.0) / 25.0;
3316 assert_eq!(
3317 (vol_weighted_greeks.delta * 1e12).round(),
3318 (greeks.delta * 1e12).round()
3319 );
3320 assert_eq!(
3321 (vol_weighted_greeks.gamma * 1e12).round(),
3322 (greeks.gamma * 1e12).round()
3323 );
3324 assert_eq!(
3325 (vol_weighted_greeks.vega * 1e12).round(),
3326 (expected_vega * 1e12).round()
3327 );
3328 }
3329
3330 #[rstest]
3331 fn test_instrument_greeks_errors_when_vol_index_price_missing() {
3332 let now = utc_timestamp(2025, 3, 8, 12, 0, 0);
3333 let expiry = now + jiff::SignedDuration::from_hours(24 * (30));
3334 let now_ns = UnixNanos::from(now);
3335 let expiry_ns = UnixNanos::from(expiry);
3336 let option = option_with_expiration("AAPL250417C00150000.OPRA", expiry_ns);
3337 let option_id = option.id();
3338 let underlying_id = InstrumentId::from("AAPL.OPRA");
3339 let vol_index_id = InstrumentId::from("VIX.XCBF");
3340 let cache = setup_cache_with_option_and_quotes(option, underlying_id, now_ns);
3341
3342 let clock = Rc::new(RefCell::new(VirtualClock::new()));
3343 let calculator = GreeksCalculator::new(cache, clock);
3344 let error = calculator
3345 .instrument_greeks(
3346 option_id,
3347 None,
3348 None,
3349 None,
3350 None,
3351 None,
3352 None,
3353 None,
3354 None,
3355 None,
3356 Some(now_ns),
3357 None,
3358 None,
3359 None,
3360 None,
3361 None,
3362 Some(vol_index_id),
3363 None,
3364 )
3365 .unwrap_err();
3366
3367 assert_eq!(error.to_string(), "No price available for VIX.XCBF");
3368 }
3369
3370 #[rstest]
3371 fn test_modify_greeks_errors_when_vol_index_price_missing() {
3372 let calculator = create_test_calculator();
3373 let underlying_id = InstrumentId::from("AAPL.OPRA");
3374 let vol_index_id = InstrumentId::from("VIX.XCBF");
3375
3376 let error = calculator
3377 .modify_greeks(
3378 1.0,
3379 2.0,
3380 underlying_id,
3381 150.0,
3382 150.0,
3383 false,
3384 None,
3385 None,
3386 2.0,
3387 0.30,
3388 0,
3389 None,
3390 0.0,
3391 Some(vol_index_id),
3392 None,
3393 None,
3394 None,
3395 )
3396 .unwrap_err();
3397
3398 assert_eq!(error.to_string(), "No price available for VIX.XCBF");
3399 }
3400
3401 #[rstest]
3402 fn test_modify_greeks_accepts_explicit_index_prices() {
3403 let calculator = create_test_calculator();
3404 let underlying_id = InstrumentId::from("AAPL.OPRA");
3405 let mut beta_weights = HashMap::new();
3406 beta_weights.insert(underlying_id, 0.5);
3407 let mut vol_beta_weights = HashMap::new();
3408 vol_beta_weights.insert(underlying_id, 0.75);
3409
3410 let (delta, gamma, vega) = calculator
3411 .modify_greeks(
3412 1.0,
3413 2.0,
3414 underlying_id,
3415 150.0,
3416 150.0,
3417 false,
3418 None,
3419 Some(&beta_weights),
3420 2.0,
3421 0.30,
3422 0,
3423 None,
3424 0.0,
3425 None,
3426 Some(&vol_beta_weights),
3427 Some(200.0),
3428 Some(25.0),
3429 )
3430 .unwrap();
3431
3432 assert_eq!((delta * 1e12).round(), 375_000_000_000.0);
3433 assert_eq!((gamma * 1e12).round(), 281_250_000_000.0);
3434 assert_eq!((vega * 1e12).round(), 1_800_000_000_000.0);
3435
3436 let (delta, gamma, vega) = calculator
3437 .modify_greeks(
3438 1.0,
3439 2.0,
3440 underlying_id,
3441 150.0,
3442 150.0,
3443 true,
3444 None,
3445 Some(&beta_weights),
3446 2.0,
3447 0.30,
3448 0,
3449 None,
3450 0.0,
3451 None,
3452 Some(&vol_beta_weights),
3453 Some(200.0),
3454 Some(25.0),
3455 )
3456 .unwrap();
3457
3458 assert_eq!((delta * 1e12).round(), 750_000_000_000.0);
3459 assert_eq!((gamma * 1e12).round(), 1_125_000_000_000.0);
3460 assert_eq!((vega * 1e12).round(), 4_500_000_000.0);
3461 }
3462
3463 #[rstest]
3464 fn test_instrument_greeks_errors_when_future_underlying_price_missing_without_cached_spread() {
3465 let now = utc_timestamp(2024, 2, 14, 16, 0, 0);
3466 let expiry = utc_timestamp(2024, 3, 15, 16, 0, 0);
3467 let now_ns = UnixNanos::from(now);
3468 let expiry_ns = UnixNanos::from(expiry);
3469
3470 let future = future_with_expiration("ESH4.GLBX", "ESH4", expiry_ns);
3471 let call_option = future_option_with_expiration(
3472 "ESH4C150.GLBX",
3473 "ESH4C150",
3474 "ESH4",
3475 OptionKind::Call,
3476 "150.00",
3477 expiry_ns,
3478 );
3479 let put_option = future_option_with_expiration(
3480 "ESH4P150.GLBX",
3481 "ESH4P150",
3482 "ESH4",
3483 OptionKind::Put,
3484 "150.00",
3485 expiry_ns,
3486 );
3487
3488 let cache = Rc::new(RefCell::new(Cache::new(None, None)));
3489 cache
3490 .borrow_mut()
3491 .add_instrument(InstrumentAny::FuturesContract(future))
3492 .unwrap();
3493 cache
3494 .borrow_mut()
3495 .add_instrument(InstrumentAny::OptionContract(call_option.clone()))
3496 .unwrap();
3497 cache
3498 .borrow_mut()
3499 .add_instrument(InstrumentAny::OptionContract(put_option.clone()))
3500 .unwrap();
3501
3502 let call_quote = QuoteTick::new(
3503 call_option.id(),
3504 Price::from("8.50"),
3505 Price::from("8.50"),
3506 Quantity::from(100),
3507 Quantity::from(100),
3508 now_ns,
3509 now_ns,
3510 );
3511
3512 let put_quote = QuoteTick::new(
3513 put_option.id(),
3514 Price::from("3.33"),
3515 Price::from("3.33"),
3516 Quantity::from(100),
3517 Quantity::from(100),
3518 now_ns,
3519 now_ns,
3520 );
3521 cache.borrow_mut().add_quote(call_quote).unwrap();
3522 cache.borrow_mut().add_quote(put_quote).unwrap();
3523
3524 let clock = Rc::new(RefCell::new(VirtualClock::new()));
3525 clock.borrow_mut().set_time(now_ns);
3526 let calculator = GreeksCalculator::new(cache, clock);
3527
3528 let error = calculator
3529 .instrument_greeks(
3530 call_option.id(),
3531 Some(0.0425),
3532 None,
3533 None,
3534 None,
3535 None,
3536 None,
3537 None,
3538 None,
3539 None,
3540 Some(now_ns),
3541 None,
3542 None,
3543 None,
3544 None,
3545 None,
3546 None,
3547 None,
3548 )
3549 .unwrap_err();
3550
3551 assert_eq!(error.to_string(), "No price available for ESH4.GLBX");
3552 }
3553
3554 #[rstest]
3555 fn test_cache_futures_spread_returns_price_to_reference_future() {
3556 let now = utc_timestamp(2024, 2, 14, 16, 0, 0);
3557 let expiry = utc_timestamp(2024, 3, 15, 16, 0, 0);
3558 let now_ns = UnixNanos::from(now);
3559 let expiry_ns = UnixNanos::from(expiry);
3560
3561 let future = future_with_expiration("ESH4.GLBX", "ESH4", expiry_ns);
3562 let reference_future = future_with_expiration("ESM4.GLBX", "ESM4", expiry_ns);
3563 let call_option = future_option_with_expiration(
3564 "ESH4C150.GLBX",
3565 "ESH4C150",
3566 "ESH4",
3567 OptionKind::Call,
3568 "150.00",
3569 expiry_ns,
3570 );
3571 let put_option = future_option_with_expiration(
3572 "ESH4P150.GLBX",
3573 "ESH4P150",
3574 "ESH4",
3575 OptionKind::Put,
3576 "150.00",
3577 expiry_ns,
3578 );
3579
3580 let cache = Rc::new(RefCell::new(Cache::new(None, None)));
3581 cache
3582 .borrow_mut()
3583 .add_instrument(InstrumentAny::FuturesContract(future))
3584 .unwrap();
3585 cache
3586 .borrow_mut()
3587 .add_instrument(InstrumentAny::FuturesContract(reference_future.clone()))
3588 .unwrap();
3589 cache
3590 .borrow_mut()
3591 .add_instrument(InstrumentAny::OptionContract(call_option.clone()))
3592 .unwrap();
3593 cache
3594 .borrow_mut()
3595 .add_instrument(InstrumentAny::OptionContract(put_option.clone()))
3596 .unwrap();
3597
3598 let call_quote = QuoteTick::new(
3599 call_option.id(),
3600 Price::from("8.50"),
3601 Price::from("8.50"),
3602 Quantity::from(100),
3603 Quantity::from(100),
3604 now_ns,
3605 now_ns,
3606 );
3607
3608 let put_quote = QuoteTick::new(
3609 put_option.id(),
3610 Price::from("3.33"),
3611 Price::from("3.33"),
3612 Quantity::from(100),
3613 Quantity::from(100),
3614 now_ns,
3615 now_ns,
3616 );
3617
3618 let reference_future_quote = QuoteTick::new(
3619 reference_future.id(),
3620 Price::from("155.00"),
3621 Price::from("155.00"),
3622 Quantity::from(100),
3623 Quantity::from(100),
3624 now_ns,
3625 now_ns,
3626 );
3627 cache.borrow_mut().add_quote(call_quote).unwrap();
3628 cache.borrow_mut().add_quote(put_quote).unwrap();
3629 cache
3630 .borrow_mut()
3631 .add_quote(reference_future_quote)
3632 .unwrap();
3633
3634 let clock = Rc::new(RefCell::new(VirtualClock::new()));
3635 clock.borrow_mut().set_time(now_ns);
3636 let calculator = GreeksCalculator::new(cache, clock);
3637
3638 let cached_future_price = calculator
3639 .cache_futures_spread(call_option.id(), put_option.id(), reference_future.id())
3640 .unwrap();
3641
3642 let expected_underlying = 150.0 + (0.0425_f64 * (30.0 / 365.25)).exp() * (8.50 - 3.33);
3643 let expected_cached_underlying = reference_future.make_price(expected_underlying);
3644 assert_eq!(cached_future_price, expected_cached_underlying);
3645 assert_eq!(
3646 calculator.get_cached_futures_spread_price(InstrumentId::from("ESH4.GLBX")),
3647 Some(expected_cached_underlying)
3648 );
3649 }
3650
3651 #[rstest]
3652 fn test_instrument_greeks_uses_cached_futures_spread_when_underlying_price_missing() {
3653 let now = utc_timestamp(2024, 2, 14, 16, 0, 0);
3654 let expiry = utc_timestamp(2024, 3, 15, 16, 0, 0);
3655 let now_ns = UnixNanos::from(now);
3656 let expiry_ns = UnixNanos::from(expiry);
3657
3658 let future = future_with_expiration("ESH4.GLBX", "ESH4", expiry_ns);
3659 let reference_future = future_with_expiration("ESM4.GLBX", "ESM4", expiry_ns);
3660 let call_option = future_option_with_expiration(
3661 "ESH4C150.GLBX",
3662 "ESH4C150",
3663 "ESH4",
3664 OptionKind::Call,
3665 "150.00",
3666 expiry_ns,
3667 );
3668 let put_option = future_option_with_expiration(
3669 "ESH4P150.GLBX",
3670 "ESH4P150",
3671 "ESH4",
3672 OptionKind::Put,
3673 "150.00",
3674 expiry_ns,
3675 );
3676 let target_call_option = future_option_with_expiration(
3677 "ESH4C152.GLBX",
3678 "ESH4C152",
3679 "ESH4",
3680 OptionKind::Call,
3681 "152.00",
3682 expiry_ns,
3683 );
3684
3685 let cache = Rc::new(RefCell::new(Cache::new(None, None)));
3686 cache
3687 .borrow_mut()
3688 .add_instrument(InstrumentAny::FuturesContract(future))
3689 .unwrap();
3690 cache
3691 .borrow_mut()
3692 .add_instrument(InstrumentAny::FuturesContract(reference_future.clone()))
3693 .unwrap();
3694 cache
3695 .borrow_mut()
3696 .add_instrument(InstrumentAny::OptionContract(call_option.clone()))
3697 .unwrap();
3698 cache
3699 .borrow_mut()
3700 .add_instrument(InstrumentAny::OptionContract(put_option.clone()))
3701 .unwrap();
3702 cache
3703 .borrow_mut()
3704 .add_instrument(InstrumentAny::OptionContract(target_call_option.clone()))
3705 .unwrap();
3706
3707 let call_quote = QuoteTick::new(
3708 call_option.id(),
3709 Price::from("8.50"),
3710 Price::from("8.50"),
3711 Quantity::from(100),
3712 Quantity::from(100),
3713 now_ns,
3714 now_ns,
3715 );
3716
3717 let put_quote = QuoteTick::new(
3718 put_option.id(),
3719 Price::from("3.33"),
3720 Price::from("3.33"),
3721 Quantity::from(100),
3722 Quantity::from(100),
3723 now_ns,
3724 now_ns,
3725 );
3726
3727 let target_call_quote = QuoteTick::new(
3728 target_call_option.id(),
3729 Price::from("6.75"),
3730 Price::from("6.75"),
3731 Quantity::from(100),
3732 Quantity::from(100),
3733 now_ns,
3734 now_ns,
3735 );
3736
3737 let reference_future_quote = QuoteTick::new(
3738 reference_future.id(),
3739 Price::from("155.00"),
3740 Price::from("155.00"),
3741 Quantity::from(100),
3742 Quantity::from(100),
3743 now_ns,
3744 now_ns,
3745 );
3746 cache.borrow_mut().add_quote(call_quote).unwrap();
3747 cache.borrow_mut().add_quote(put_quote).unwrap();
3748 cache.borrow_mut().add_quote(target_call_quote).unwrap();
3749 cache
3750 .borrow_mut()
3751 .add_quote(reference_future_quote)
3752 .unwrap();
3753
3754 let clock = Rc::new(RefCell::new(VirtualClock::new()));
3755 clock.borrow_mut().set_time(now_ns);
3756 let calculator = GreeksCalculator::new(cache, clock);
3757 calculator
3758 .cache_futures_spread(call_option.id(), put_option.id(), reference_future.id())
3759 .unwrap();
3760
3761 let greeks = calculator
3762 .instrument_greeks(
3763 target_call_option.id(),
3764 Some(0.0425),
3765 None,
3766 None,
3767 None,
3768 None,
3769 None,
3770 None,
3771 None,
3772 None,
3773 Some(now_ns),
3774 None,
3775 None,
3776 None,
3777 None,
3778 None,
3779 None,
3780 None,
3781 )
3782 .unwrap();
3783
3784 let expected_underlying = reference_future
3785 .make_price(150.0 + (0.0425_f64 * (30.0 / 365.25)).exp() * (8.50 - 3.33))
3786 .as_f64();
3787 assert_eq!(greeks.underlying_price, expected_underlying);
3788 }
3789
3790 #[rstest]
3791 fn test_instrument_greeks_uses_index_price_for_index_underlying() {
3792 let now = utc_timestamp(2024, 2, 14, 16, 0, 0);
3793 let expiry = utc_timestamp(2024, 3, 15, 16, 0, 0);
3794 let now_ns = UnixNanos::from(now);
3795 let expiry_ns = UnixNanos::from(expiry);
3796
3797 let future = future_with_expiration("ESH4.GLBX", "ESH4", expiry_ns);
3798 let call_option = future_option_with_expiration(
3799 "ESH4C150.GLBX",
3800 "ESH4C150",
3801 "ESH4",
3802 OptionKind::Call,
3803 "150.00",
3804 expiry_ns,
3805 );
3806
3807 let cache = Rc::new(RefCell::new(Cache::new(None, None)));
3808 cache
3809 .borrow_mut()
3810 .add_instrument(InstrumentAny::FuturesContract(future))
3811 .unwrap();
3812 cache
3813 .borrow_mut()
3814 .add_instrument(InstrumentAny::OptionContract(call_option.clone()))
3815 .unwrap();
3816
3817 let call_quote = QuoteTick::new(
3818 call_option.id(),
3819 Price::from("8.50"),
3820 Price::from("8.50"),
3821 Quantity::from(100),
3822 Quantity::from(100),
3823 now_ns,
3824 now_ns,
3825 );
3826 cache.borrow_mut().add_quote(call_quote).unwrap();
3827 cache
3828 .borrow_mut()
3829 .add_index_price(IndexPriceUpdate::new(
3830 InstrumentId::from("ESH4.GLBX"),
3831 Price::from("157.25"),
3832 now_ns,
3833 now_ns,
3834 ))
3835 .unwrap();
3836
3837 let clock = Rc::new(RefCell::new(VirtualClock::new()));
3838 clock.borrow_mut().set_time(now_ns);
3839 let calculator = GreeksCalculator::new(cache, clock);
3840
3841 let greeks = calculator
3842 .instrument_greeks(
3843 call_option.id(),
3844 Some(0.0425),
3845 None,
3846 None,
3847 None,
3848 None,
3849 None,
3850 None,
3851 None,
3852 None,
3853 Some(now_ns),
3854 None,
3855 None,
3856 None,
3857 None,
3858 None,
3859 None,
3860 None,
3861 )
3862 .unwrap();
3863
3864 assert_eq!(greeks.underlying_price, 157.25);
3865 }
3866
3867 #[rstest]
3868 fn test_instrument_greeks_prefers_quote_over_index_price_for_index_future() {
3869 let now = utc_timestamp(2024, 2, 14, 16, 0, 0);
3870 let expiry = utc_timestamp(2024, 3, 15, 16, 0, 0);
3871 let now_ns = UnixNanos::from(now);
3872 let expiry_ns = UnixNanos::from(expiry);
3873
3874 let future = future_with_expiration("ESH4.GLBX", "ESH4", expiry_ns);
3875 let call_option = future_option_with_expiration(
3876 "ESH4C5500.GLBX",
3877 "ESH4C5500",
3878 "ESH4",
3879 OptionKind::Call,
3880 "5500.00",
3881 expiry_ns,
3882 );
3883
3884 let cache = Rc::new(RefCell::new(Cache::new(None, None)));
3885 cache
3886 .borrow_mut()
3887 .add_instrument(InstrumentAny::FuturesContract(future))
3888 .unwrap();
3889 cache
3890 .borrow_mut()
3891 .add_instrument(InstrumentAny::OptionContract(call_option.clone()))
3892 .unwrap();
3893
3894 let future_quote = QuoteTick::new(
3896 InstrumentId::from("ESH4.GLBX"),
3897 Price::from("158.50"),
3898 Price::from("159.50"),
3899 Quantity::from(100),
3900 Quantity::from(100),
3901 now_ns,
3902 now_ns,
3903 );
3904 cache.borrow_mut().add_quote(future_quote).unwrap();
3905 cache
3906 .borrow_mut()
3907 .add_index_price(IndexPriceUpdate::new(
3908 InstrumentId::from("ESH4.GLBX"),
3909 Price::from("157.25"),
3910 now_ns,
3911 now_ns,
3912 ))
3913 .unwrap();
3914
3915 let call_quote = QuoteTick::new(
3916 call_option.id(),
3917 Price::from("8.50"),
3918 Price::from("8.50"),
3919 Quantity::from(100),
3920 Quantity::from(100),
3921 now_ns,
3922 now_ns,
3923 );
3924 cache.borrow_mut().add_quote(call_quote).unwrap();
3925
3926 let clock = Rc::new(RefCell::new(VirtualClock::new()));
3927 clock.borrow_mut().set_time(now_ns);
3928 let calculator = GreeksCalculator::new(cache, clock);
3929
3930 let greeks = calculator
3931 .instrument_greeks(
3932 call_option.id(),
3933 Some(0.0425),
3934 None,
3935 None,
3936 None,
3937 None,
3938 None,
3939 None,
3940 None,
3941 None,
3942 Some(now_ns),
3943 None,
3944 None,
3945 None,
3946 None,
3947 None,
3948 None,
3949 None,
3950 )
3951 .unwrap();
3952
3953 assert_eq!(greeks.underlying_price, 159.0);
3955 }
3956
3957 fn option_calculator() -> (GreeksCalculator, InstrumentId, UnixNanos) {
3960 let now = utc_timestamp(2025, 3, 8, 12, 0, 0);
3961 let expiry = now + jiff::SignedDuration::from_hours(24 * 30);
3962 let now_ns = UnixNanos::from(now);
3963 let option = option_with_expiration("AAPL250417C00150000.OPRA", UnixNanos::from(expiry));
3964 let option_id = option.id();
3965 let cache =
3966 setup_cache_with_option_and_quotes(option, InstrumentId::from("AAPL.OPRA"), now_ns);
3967 let clock = Rc::new(RefCell::new(VirtualClock::new()));
3968
3969 (GreeksCalculator::new(cache, clock), option_id, now_ns)
3970 }
3971
3972 fn option_greeks_with_shocks(
3973 calculator: &GreeksCalculator,
3974 option_id: InstrumentId,
3975 ts_event: UnixNanos,
3976 spot_shock: Option<f64>,
3977 vol_shock: Option<f64>,
3978 time_to_expiry_shock: Option<f64>,
3979 ) -> GreeksData {
3980 calculator
3981 .instrument_greeks(
3982 option_id,
3983 None,
3984 None,
3985 spot_shock,
3986 vol_shock,
3987 time_to_expiry_shock,
3988 None,
3989 None,
3990 None,
3991 None,
3992 Some(ts_event),
3993 None,
3994 None,
3995 None,
3996 None,
3997 None,
3998 None,
3999 None,
4000 )
4001 .unwrap()
4002 }
4003
4004 #[rstest]
4005 #[case::spot(Some(5.0), None, None)]
4006 #[case::vol(None, Some(0.05), None)]
4007 #[case::time_to_expiry(None, None, Some(0.01))]
4008 fn test_instrument_greeks_applies_each_shock_dimension_on_its_own(
4009 #[case] spot_shock: Option<f64>,
4010 #[case] vol_shock: Option<f64>,
4011 #[case] time_to_expiry_shock: Option<f64>,
4012 ) {
4013 let (calculator, option_id, now_ns) = option_calculator();
4014
4015 let unshocked = option_greeks_with_shocks(&calculator, option_id, now_ns, None, None, None);
4016 let shocked = option_greeks_with_shocks(
4017 &calculator,
4018 option_id,
4019 now_ns,
4020 spot_shock,
4021 vol_shock,
4022 time_to_expiry_shock,
4023 );
4024
4025 assert_ne!(
4026 scaled(shocked.price),
4027 scaled(unshocked.price),
4028 "a single non-zero shock must still reprice the option"
4029 );
4030 }
4031
4032 #[rstest]
4033 fn test_instrument_greeks_leaves_the_price_unshocked_when_every_shock_is_zero() {
4034 let (calculator, option_id, now_ns) = option_calculator();
4035
4036 let unshocked = option_greeks_with_shocks(&calculator, option_id, now_ns, None, None, None);
4037 let zero_shocks = option_greeks_with_shocks(
4038 &calculator,
4039 option_id,
4040 now_ns,
4041 Some(0.0),
4042 Some(0.0),
4043 Some(0.0),
4044 );
4045
4046 assert_eq!(scaled(zero_shocks.price), scaled(unshocked.price));
4047 }
4048
4049 #[rstest]
4050 fn test_instrument_greeks_pnl_is_price_less_the_position_open_price() {
4051 let (calculator, option_id, now_ns) = option_calculator();
4052 let instrument = calculator
4053 .cache
4054 .borrow()
4055 .instrument(&option_id)
4056 .cloned()
4057 .unwrap();
4058 let position = position_from_fill(
4059 &instrument,
4060 "P-GREEKS-1",
4061 "O-GREEKS-1",
4062 "T-GREEKS-1",
4063 OrderSide::Buy,
4064 1,
4065 "9.00",
4066 );
4067
4068 let unshocked = option_greeks_with_shocks(&calculator, option_id, now_ns, None, None, None);
4069 let with_position = calculator
4070 .instrument_greeks(
4071 option_id,
4072 None,
4073 None,
4074 None,
4075 None,
4076 None,
4077 None,
4078 None,
4079 None,
4080 None,
4081 Some(now_ns),
4082 Some(position),
4083 None,
4084 None,
4085 None,
4086 None,
4087 None,
4088 None,
4089 )
4090 .unwrap();
4091
4092 assert_eq!(scaled(with_position.price), scaled(unshocked.price));
4093 assert_eq!(
4094 scaled(with_position.pnl),
4095 scaled(unshocked.price - 9.0),
4096 "pnl must subtract the position open price from the option price"
4097 );
4098 assert_eq!(scaled(unshocked.pnl), 0.0);
4099 }
4100
4101 #[rstest]
4102 fn test_instrument_greeks_records_the_shocked_market_state() {
4103 let (calculator, option_id, now_ns) = option_calculator();
4104
4105 let unshocked = option_greeks_with_shocks(&calculator, option_id, now_ns, None, None, None);
4106 let shocked = option_greeks_with_shocks(
4107 &calculator,
4108 option_id,
4109 now_ns,
4110 Some(5.0),
4111 Some(0.05),
4112 Some(0.01),
4113 );
4114
4115 assert_eq!(scaled(unshocked.underlying_price), 150_050_000_000_000.0);
4117 assert_eq!(scaled(shocked.underlying_price), 155_050_000_000_000.0);
4118 assert_eq!(scaled(shocked.vol), scaled(unshocked.vol + 0.05));
4119 assert_eq!(
4120 scaled(shocked.expiry_in_years),
4121 scaled(unshocked.expiry_in_years - 0.01)
4122 );
4123 assert_eq!(unshocked.expiry_in_days, 30);
4124 assert_eq!(shocked.expiry_in_days, 26);
4125 }
4126
4127 #[rstest]
4128 fn test_instrument_greeks_cost_of_carry_subtracts_the_flat_dividend_yield() {
4129 let (calculator, option_id, now_ns) = option_calculator();
4130
4131 let greeks = calculator
4132 .instrument_greeks(
4133 option_id,
4134 Some(0.05),
4135 Some(0.02),
4136 None,
4137 None,
4138 None,
4139 None,
4140 None,
4141 None,
4142 None,
4143 Some(now_ns),
4144 None,
4145 None,
4146 None,
4147 None,
4148 None,
4149 None,
4150 None,
4151 )
4152 .unwrap();
4153
4154 assert_eq!(scaled(greeks.interest_rate), 50_000_000_000.0);
4155 assert_eq!(scaled(greeks.cost_of_carry), 30_000_000_000.0);
4156 }
4157
4158 #[rstest]
4159 fn test_instrument_greeks_cost_of_carry_is_zero_without_a_dividend_yield() {
4160 let (calculator, option_id, now_ns) = option_calculator();
4161
4162 let greeks = calculator
4163 .instrument_greeks(
4164 option_id,
4165 Some(0.05),
4166 None,
4167 None,
4168 None,
4169 None,
4170 None,
4171 None,
4172 None,
4173 None,
4174 Some(now_ns),
4175 None,
4176 None,
4177 None,
4178 None,
4179 None,
4180 None,
4181 None,
4182 )
4183 .unwrap();
4184
4185 assert_eq!(scaled(greeks.cost_of_carry), 0.0);
4186 }
4187
4188 #[rstest]
4189 fn test_instrument_greeks_reports_the_option_kind() {
4190 let now = utc_timestamp(2025, 3, 8, 12, 0, 0);
4191 let expiry = now + jiff::SignedDuration::from_hours(24 * 30);
4192 let now_ns = UnixNanos::from(now);
4193 let underlying_id = InstrumentId::from("AAPL.OPRA");
4194 let mut put = option_with_expiration("AAPL250417P00150000.OPRA", UnixNanos::from(expiry));
4195 put.option_kind = OptionKind::Put;
4196 let put_id = put.id();
4197 let cache = setup_cache_with_option_and_quotes(put, underlying_id, now_ns);
4198 cache
4199 .borrow_mut()
4200 .add_quote(QuoteTick::new(
4201 put_id,
4202 Price::from("10.50"),
4203 Price::from("10.60"),
4204 Quantity::from(100),
4205 Quantity::from(100),
4206 now_ns,
4207 now_ns,
4208 ))
4209 .unwrap();
4210 let calculator = GreeksCalculator::new(cache, Rc::new(RefCell::new(VirtualClock::new())));
4211
4212 let greeks = option_greeks_with_shocks(&calculator, put_id, now_ns, None, None, None);
4213
4214 assert!(!greeks.is_call);
4215 }
4216
4217 fn equity_calculator() -> (GreeksCalculator, InstrumentId, UnixNanos) {
4220 let now_ns = UnixNanos::from(utc_timestamp(2025, 3, 8, 12, 0, 0));
4221 let cache = Rc::new(RefCell::new(Cache::new(None, None)));
4222 let equity = equity_aapl_opra();
4223 let equity_id = equity.id();
4224 cache
4225 .borrow_mut()
4226 .add_instrument(InstrumentAny::Equity(equity))
4227 .unwrap();
4228 cache
4229 .borrow_mut()
4230 .add_quote(QuoteTick::new(
4231 equity_id,
4232 Price::from("150.00"),
4233 Price::from("150.10"),
4234 Quantity::from(100),
4235 Quantity::from(100),
4236 now_ns,
4237 now_ns,
4238 ))
4239 .unwrap();
4240 let clock = Rc::new(RefCell::new(VirtualClock::new()));
4241
4242 (GreeksCalculator::new(cache, clock), equity_id, now_ns)
4243 }
4244
4245 #[rstest]
4246 fn test_instrument_greeks_for_a_non_option_shocks_the_spot_and_prices_the_position() {
4247 let (calculator, equity_id, now_ns) = equity_calculator();
4248 let instrument = calculator
4249 .cache
4250 .borrow()
4251 .instrument(&equity_id)
4252 .cloned()
4253 .unwrap();
4254 let position = position_from_fill(
4255 &instrument,
4256 "P-EQUITY-1",
4257 "O-EQUITY-1",
4258 "T-EQUITY-1",
4259 OrderSide::Buy,
4260 10,
4261 "140.00",
4262 );
4263
4264 let greeks = calculator
4265 .instrument_greeks(
4266 equity_id,
4267 None,
4268 None,
4269 Some(5.0),
4270 None,
4271 None,
4272 None,
4273 None,
4274 None,
4275 None,
4276 Some(now_ns),
4277 Some(position),
4278 None,
4279 None,
4280 None,
4281 None,
4282 None,
4283 None,
4284 )
4285 .unwrap();
4286
4287 assert_eq!(scaled(greeks.pnl), 15_050_000_000_000.0);
4289 assert_eq!(scaled(greeks.price), 15_050_000_000_000.0);
4290 }
4291
4292 #[rstest]
4293 fn test_instrument_greeks_for_a_non_option_scales_percent_delta_by_the_shocked_spot() {
4294 let (calculator, equity_id, now_ns) = equity_calculator();
4295
4296 let greeks = calculator
4297 .instrument_greeks(
4298 equity_id,
4299 None,
4300 None,
4301 Some(5.0),
4302 None,
4303 None,
4304 None,
4305 None,
4306 None,
4307 None,
4308 Some(now_ns),
4309 None,
4310 Some(true),
4311 None,
4312 None,
4313 None,
4314 None,
4315 None,
4316 )
4317 .unwrap();
4318
4319 assert_eq!(scaled(greeks.delta), 1_550_500_000_000.0);
4321 }
4322
4323 #[rstest]
4324 fn test_instrument_greeks_cost_of_carry_prefers_the_dividend_curve_over_the_flat_yield() {
4325 let (calculator, option_id, now_ns) = option_calculator();
4326 calculator
4327 .cache
4328 .borrow_mut()
4329 .add_yield_curve(YieldCurve::new(
4330 "AAPL.OPRA".to_string(),
4331 vec![0.0, 5.0, 10.0],
4332 vec![0.02, 0.02, 0.02],
4333 now_ns,
4334 now_ns,
4335 ))
4336 .unwrap();
4337
4338 let greeks = calculator
4339 .instrument_greeks(
4340 option_id,
4341 Some(0.05),
4342 Some(0.04),
4343 None,
4344 None,
4345 None,
4346 None,
4347 None,
4348 None,
4349 None,
4350 Some(now_ns),
4351 None,
4352 None,
4353 None,
4354 None,
4355 None,
4356 None,
4357 None,
4358 )
4359 .unwrap();
4360
4361 assert_eq!(scaled(greeks.interest_rate), 50_000_000_000.0);
4362 assert_eq!(
4363 scaled(greeks.cost_of_carry),
4364 30_000_000_000.0,
4365 "the dividend curve must take precedence over the flat dividend yield"
4366 );
4367 }
4368
4369 fn scaled(value: f64) -> f64 {
4371 (value * 1e12).round()
4372 }
4373
4374 #[rstest]
4375 fn test_modify_greeks_reprices_the_index_when_the_underlying_is_shocked() {
4376 let calculator = create_test_calculator();
4377 let underlying_id = InstrumentId::from("AAPL.OPRA");
4378 let mut beta_weights = HashMap::new();
4379 beta_weights.insert(underlying_id, 0.5);
4380
4381 let (delta, gamma, vega) = calculator
4382 .modify_greeks(
4383 1.0,
4384 2.0,
4385 underlying_id,
4386 165.0,
4387 150.0,
4388 false,
4389 None,
4390 Some(&beta_weights),
4391 3.0,
4392 0.30,
4393 0,
4394 None,
4395 0.0,
4396 None,
4397 None,
4398 Some(200.0),
4399 None,
4400 )
4401 .unwrap();
4402
4403 assert_eq!(scaled(delta), 343_750_000_000.0);
4406 assert_eq!(scaled(gamma), 236_328_125_000.0);
4407 assert_eq!(scaled(vega), 3_000_000_000_000.0);
4408 }
4409
4410 #[rstest]
4411 fn test_modify_greeks_reprices_the_vol_index_when_the_vol_is_shocked() {
4412 let calculator = create_test_calculator();
4413 let underlying_id = InstrumentId::from("AAPL.OPRA");
4414 let mut vol_beta_weights = HashMap::new();
4415 vol_beta_weights.insert(underlying_id, 0.75);
4416
4417 let (delta, gamma, vega) = calculator
4418 .modify_greeks(
4419 1.0,
4420 2.0,
4421 underlying_id,
4422 150.0,
4423 150.0,
4424 false,
4425 None,
4426 None,
4427 2.0,
4428 0.35,
4429 0,
4430 None,
4431 0.30,
4432 None,
4433 Some(&vol_beta_weights),
4434 None,
4435 Some(25.0),
4436 )
4437 .unwrap();
4438
4439 assert_eq!(scaled(delta), 1_000_000_000_000.0);
4440 assert_eq!(scaled(gamma), 2_000_000_000_000.0);
4441 assert_eq!(scaled(vega), 1_718_181_818_182.0);
4442 }
4443
4444 #[rstest]
4445 fn test_modify_greeks_uses_the_shocked_vol_as_the_baseline_when_unshocked_vol_is_zero() {
4446 let calculator = create_test_calculator();
4447
4448 let (_, _, vega) = calculator
4449 .modify_greeks(
4450 1.0,
4451 2.0,
4452 InstrumentId::from("AAPL.OPRA"),
4453 150.0,
4454 150.0,
4455 false,
4456 None,
4457 None,
4458 2.0,
4459 0.40,
4460 0,
4461 None,
4462 0.0,
4463 None,
4464 None,
4465 None,
4466 Some(25.0),
4467 )
4468 .unwrap();
4469
4470 assert_eq!(scaled(vega), 3_200_000_000_000.0);
4472 }
4473
4474 #[rstest]
4475 fn test_modify_greeks_leaves_vega_untouched_for_a_zero_vol_index() {
4476 let calculator = create_test_calculator();
4477
4478 let (_, _, vega) = calculator
4479 .modify_greeks(
4480 1.0,
4481 2.0,
4482 InstrumentId::from("AAPL.OPRA"),
4483 150.0,
4484 150.0,
4485 false,
4486 None,
4487 None,
4488 2.0,
4489 0.40,
4490 0,
4491 None,
4492 0.0,
4493 None,
4494 None,
4495 None,
4496 Some(0.0),
4497 )
4498 .unwrap();
4499
4500 assert_eq!(scaled(vega), 2_000_000_000_000.0);
4501 }
4502
4503 #[rstest]
4504 fn test_modify_greeks_percent_scaling_falls_back_to_the_underlying_and_vol() {
4505 let calculator = create_test_calculator();
4506
4507 let (delta, gamma, vega) = calculator
4508 .modify_greeks(
4509 1.0,
4510 2.0,
4511 InstrumentId::from("AAPL.OPRA"),
4512 150.0,
4513 150.0,
4514 true,
4515 None,
4516 None,
4517 2.0,
4518 0.30,
4519 0,
4520 None,
4521 0.0,
4522 None,
4523 None,
4524 None,
4525 None,
4526 )
4527 .unwrap();
4528
4529 assert_eq!(scaled(delta), 1_500_000_000_000.0);
4530 assert_eq!(scaled(gamma), 4_500_000_000_000.0);
4531 assert_eq!(scaled(vega), 6_000_000_000.0);
4532 }
4533
4534 #[rstest]
4535 fn test_modify_greeks_applies_vega_time_weighting() {
4536 let calculator = create_test_calculator();
4537
4538 let (_, _, vega) = calculator
4539 .modify_greeks(
4540 1.0,
4541 2.0,
4542 InstrumentId::from("AAPL.OPRA"),
4543 150.0,
4544 150.0,
4545 false,
4546 None,
4547 None,
4548 2.0,
4549 0.30,
4550 120,
4551 Some(30),
4552 0.0,
4553 None,
4554 None,
4555 None,
4556 None,
4557 )
4558 .unwrap();
4559
4560 assert_eq!(scaled(vega), 1_000_000_000_000.0);
4562 }
4563
4564 #[rstest]
4565 fn test_modify_greeks_skips_vega_time_weighting_without_days_to_expiry() {
4566 let calculator = create_test_calculator();
4567
4568 let (_, _, vega) = calculator
4569 .modify_greeks(
4570 1.0,
4571 2.0,
4572 InstrumentId::from("AAPL.OPRA"),
4573 150.0,
4574 150.0,
4575 false,
4576 None,
4577 None,
4578 2.0,
4579 0.30,
4580 0,
4581 Some(30),
4582 0.0,
4583 None,
4584 None,
4585 None,
4586 None,
4587 )
4588 .unwrap();
4589
4590 assert_eq!(scaled(vega), 2_000_000_000_000.0);
4591 }
4592
4593 const SPREAD_CALL_ID: &str = "ESH4C150.GLBX";
4594 const SPREAD_PUT_ID: &str = "ESH4P150.GLBX";
4595 const SPREAD_REFERENCE_ID: &str = "ESM4.GLBX";
4596 const SPREAD_UNDERLYING_ID: &str = "ESH4.GLBX";
4597
4598 fn spread_now_ns() -> UnixNanos {
4599 UnixNanos::from(utc_timestamp(2024, 2, 14, 16, 0, 0))
4600 }
4601
4602 fn spread_expiry_ns() -> UnixNanos {
4603 UnixNanos::from(utc_timestamp(2024, 3, 15, 16, 0, 0))
4604 }
4605
4606 fn spread_call() -> OptionContract {
4607 future_option_with_expiration(
4608 SPREAD_CALL_ID,
4609 "ESH4C150",
4610 "ESH4",
4611 OptionKind::Call,
4612 "150.00",
4613 spread_expiry_ns(),
4614 )
4615 }
4616
4617 fn spread_put() -> OptionContract {
4618 future_option_with_expiration(
4619 SPREAD_PUT_ID,
4620 "ESH4P150",
4621 "ESH4",
4622 OptionKind::Put,
4623 "150.00",
4624 spread_expiry_ns(),
4625 )
4626 }
4627
4628 fn spread_reference_future() -> FuturesContract {
4629 future_with_expiration(SPREAD_REFERENCE_ID, "ESM4", spread_expiry_ns())
4630 }
4631
4632 fn spread_quote(instrument_id: InstrumentId, price: &str) -> QuoteTick {
4633 let price = Price::from(price);
4634
4635 QuoteTick::new(
4636 instrument_id,
4637 price,
4638 price,
4639 Quantity::from(100),
4640 Quantity::from(100),
4641 spread_now_ns(),
4642 spread_now_ns(),
4643 )
4644 }
4645
4646 fn spread_calculator(
4652 instruments: Vec<InstrumentAny>,
4653 quotes: Vec<QuoteTick>,
4654 ) -> GreeksCalculator {
4655 let cache = Rc::new(RefCell::new(Cache::new(None, None)));
4656 for instrument in instruments {
4657 cache.borrow_mut().add_instrument(instrument).unwrap();
4658 }
4659
4660 for quote in quotes {
4661 cache.borrow_mut().add_quote(quote).unwrap();
4662 }
4663
4664 let clock = Rc::new(RefCell::new(VirtualClock::new()));
4665 clock.borrow_mut().set_time(spread_now_ns());
4666
4667 GreeksCalculator::new(cache, clock)
4668 }
4669
4670 fn spread_instruments() -> Vec<InstrumentAny> {
4671 vec![
4672 InstrumentAny::OptionContract(spread_call()),
4673 InstrumentAny::OptionContract(spread_put()),
4674 InstrumentAny::FuturesContract(spread_reference_future()),
4675 ]
4676 }
4677
4678 fn spread_quotes() -> Vec<QuoteTick> {
4679 vec![
4680 spread_quote(InstrumentId::from(SPREAD_CALL_ID), "8.50"),
4681 spread_quote(InstrumentId::from(SPREAD_PUT_ID), "3.33"),
4682 spread_quote(InstrumentId::from(SPREAD_REFERENCE_ID), "155.00"),
4683 ]
4684 }
4685
4686 fn cache_spread_error(instruments: Vec<InstrumentAny>, quotes: Vec<QuoteTick>) -> String {
4687 spread_calculator(instruments, quotes)
4688 .cache_futures_spread(
4689 InstrumentId::from(SPREAD_CALL_ID),
4690 InstrumentId::from(SPREAD_PUT_ID),
4691 InstrumentId::from(SPREAD_REFERENCE_ID),
4692 )
4693 .unwrap_err()
4694 .to_string()
4695 }
4696
4697 #[rstest]
4698 fn test_cache_futures_spread_errors_when_call_instrument_missing() {
4699 let instruments = vec![
4700 InstrumentAny::OptionContract(spread_put()),
4701 InstrumentAny::FuturesContract(spread_reference_future()),
4702 ];
4703
4704 assert_eq!(
4705 cache_spread_error(instruments, spread_quotes()),
4706 "Cannot cache futures spread: missing option instrument ESH4C150.GLBX"
4707 );
4708 }
4709
4710 #[rstest]
4711 fn test_cache_futures_spread_errors_when_put_instrument_missing() {
4712 let instruments = vec![
4713 InstrumentAny::OptionContract(spread_call()),
4714 InstrumentAny::FuturesContract(spread_reference_future()),
4715 ];
4716
4717 assert_eq!(
4718 cache_spread_error(instruments, spread_quotes()),
4719 "Cannot cache futures spread: missing option instrument ESH4P150.GLBX"
4720 );
4721 }
4722
4723 #[rstest]
4724 fn test_cache_futures_spread_errors_when_reference_future_instrument_missing() {
4725 let instruments = vec![
4726 InstrumentAny::OptionContract(spread_call()),
4727 InstrumentAny::OptionContract(spread_put()),
4728 ];
4729
4730 assert_eq!(
4731 cache_spread_error(instruments, spread_quotes()),
4732 "Cannot cache futures spread: no reference futures instrument for ESM4.GLBX"
4733 );
4734 }
4735
4736 #[rstest]
4737 fn test_cache_futures_spread_errors_when_call_leg_is_not_an_option() {
4738 let non_option = future_with_expiration(SPREAD_CALL_ID, "ESH4", spread_expiry_ns());
4739 let instruments = vec![
4740 InstrumentAny::FuturesContract(non_option),
4741 InstrumentAny::OptionContract(spread_put()),
4742 InstrumentAny::FuturesContract(spread_reference_future()),
4743 ];
4744
4745 assert_eq!(
4746 cache_spread_error(instruments, spread_quotes()),
4747 "Cannot cache futures spread: non-option instruments provided \
4748 call_instrument_id=ESH4C150.GLBX put_instrument_id=ESH4P150.GLBX"
4749 );
4750 }
4751
4752 #[rstest]
4753 fn test_cache_futures_spread_errors_when_legs_are_not_a_call_put_pair() {
4754 let second_put = future_option_with_expiration(
4755 SPREAD_CALL_ID,
4756 "ESH4P150",
4757 "ESH4",
4758 OptionKind::Put,
4759 "150.00",
4760 spread_expiry_ns(),
4761 );
4762 let instruments = vec![
4763 InstrumentAny::OptionContract(second_put),
4764 InstrumentAny::OptionContract(spread_put()),
4765 InstrumentAny::FuturesContract(spread_reference_future()),
4766 ];
4767
4768 assert_eq!(
4769 cache_spread_error(instruments, spread_quotes()),
4770 "Cannot cache futures spread: expected call/put pair \
4771 call_instrument_id=ESH4C150.GLBX put_instrument_id=ESH4P150.GLBX"
4772 );
4773 }
4774
4775 #[rstest]
4776 fn test_cache_futures_spread_errors_when_underlyings_differ() {
4777 let mismatched_put = future_option_with_expiration(
4778 SPREAD_PUT_ID,
4779 "ESM4P150",
4780 "ESM4",
4781 OptionKind::Put,
4782 "150.00",
4783 spread_expiry_ns(),
4784 );
4785 let instruments = vec![
4786 InstrumentAny::OptionContract(spread_call()),
4787 InstrumentAny::OptionContract(mismatched_put),
4788 InstrumentAny::FuturesContract(spread_reference_future()),
4789 ];
4790
4791 assert_eq!(
4792 cache_spread_error(instruments, spread_quotes()),
4793 "Cannot cache futures spread: option underlyings differ \
4794 call_instrument_id=ESH4C150.GLBX put_instrument_id=ESH4P150.GLBX"
4795 );
4796 }
4797
4798 #[rstest]
4799 fn test_cache_futures_spread_errors_when_strike_prices_differ() {
4800 let mismatched_put = future_option_with_expiration(
4801 SPREAD_PUT_ID,
4802 "ESH4P155",
4803 "ESH4",
4804 OptionKind::Put,
4805 "155.00",
4806 spread_expiry_ns(),
4807 );
4808 let instruments = vec![
4809 InstrumentAny::OptionContract(spread_call()),
4810 InstrumentAny::OptionContract(mismatched_put),
4811 InstrumentAny::FuturesContract(spread_reference_future()),
4812 ];
4813
4814 assert_eq!(
4815 cache_spread_error(instruments, spread_quotes()),
4816 "Cannot cache futures spread: strike prices differ \
4817 call_instrument_id=ESH4C150.GLBX put_instrument_id=ESH4P150.GLBX"
4818 );
4819 }
4820
4821 #[rstest]
4822 fn test_cache_futures_spread_errors_when_expirations_differ() {
4823 let mismatched_put = future_option_with_expiration(
4824 SPREAD_PUT_ID,
4825 "ESH4P150",
4826 "ESH4",
4827 OptionKind::Put,
4828 "150.00",
4829 UnixNanos::from(utc_timestamp(2024, 6, 21, 16, 0, 0)),
4830 );
4831 let instruments = vec![
4832 InstrumentAny::OptionContract(spread_call()),
4833 InstrumentAny::OptionContract(mismatched_put),
4834 InstrumentAny::FuturesContract(spread_reference_future()),
4835 ];
4836
4837 assert_eq!(
4838 cache_spread_error(instruments, spread_quotes()),
4839 "Cannot cache futures spread: expiration dates differ \
4840 call_instrument_id=ESH4C150.GLBX put_instrument_id=ESH4P150.GLBX"
4841 );
4842 }
4843
4844 #[rstest]
4845 fn test_cache_futures_spread_errors_when_reference_future_price_missing() {
4846 let quotes = vec![
4847 spread_quote(InstrumentId::from(SPREAD_CALL_ID), "8.50"),
4848 spread_quote(InstrumentId::from(SPREAD_PUT_ID), "3.33"),
4849 ];
4850
4851 assert_eq!(
4852 cache_spread_error(spread_instruments(), quotes),
4853 "Cannot cache futures spread: no reference futures price for ESM4.GLBX"
4854 );
4855 }
4856
4857 #[rstest]
4858 fn test_cache_futures_spread_errors_when_call_price_missing() {
4859 let quotes = vec![
4860 spread_quote(InstrumentId::from(SPREAD_PUT_ID), "3.33"),
4861 spread_quote(InstrumentId::from(SPREAD_REFERENCE_ID), "155.00"),
4862 ];
4863
4864 assert_eq!(
4865 cache_spread_error(spread_instruments(), quotes),
4866 "Cannot cache futures spread: missing option price for ESH4C150.GLBX"
4867 );
4868 }
4869
4870 #[rstest]
4871 fn test_cache_futures_spread_errors_when_put_price_missing() {
4872 let quotes = vec![
4873 spread_quote(InstrumentId::from(SPREAD_CALL_ID), "8.50"),
4874 spread_quote(InstrumentId::from(SPREAD_REFERENCE_ID), "155.00"),
4875 ];
4876
4877 assert_eq!(
4878 cache_spread_error(spread_instruments(), quotes),
4879 "Cannot cache futures spread: missing option price for ESH4P150.GLBX"
4880 );
4881 }
4882
4883 #[rstest]
4884 fn test_cache_futures_spread_errors_when_cached_underlying_is_not_a_future() {
4885 let underlying_equity = Equity::builder()
4886 .instrument_id(InstrumentId::from(SPREAD_UNDERLYING_ID))
4887 .raw_symbol(Symbol::from("ESH4"))
4888 .currency(Currency::from("USD"))
4889 .price_precision(2)
4890 .price_increment(Price::from("0.01"))
4891 .ts_event(UnixNanos::default())
4892 .ts_init(UnixNanos::default())
4893 .build()
4894 .unwrap();
4895
4896 let mut instruments = spread_instruments();
4897 instruments.push(InstrumentAny::Equity(underlying_equity));
4898
4899 assert_eq!(
4900 cache_spread_error(instruments, spread_quotes()),
4901 "Cannot cache futures spread: underlying ESH4.GLBX is not a futures contract"
4902 );
4903 }
4904
4905 #[rstest]
4906 fn test_cache_futures_spread_leaves_no_entry_when_validation_fails() {
4907 let calculator = spread_calculator(
4908 vec![
4909 InstrumentAny::OptionContract(spread_call()),
4910 InstrumentAny::OptionContract(spread_put()),
4911 ],
4912 spread_quotes(),
4913 );
4914
4915 calculator
4916 .cache_futures_spread(
4917 InstrumentId::from(SPREAD_CALL_ID),
4918 InstrumentId::from(SPREAD_PUT_ID),
4919 InstrumentId::from(SPREAD_REFERENCE_ID),
4920 )
4921 .unwrap_err();
4922
4923 assert_eq!(
4924 calculator.get_cached_futures_spread_price(InstrumentId::from(SPREAD_UNDERLYING_ID)),
4925 None
4926 );
4927 }
4928
4929 #[rstest]
4930 fn test_resolve_underlying_instrument_id_prefers_cached_futures_spread_over_cross_venue_match()
4931 {
4932 let mut instruments = spread_instruments();
4933 instruments.push(InstrumentAny::FuturesContract(future_with_expiration(
4934 "ESH4.XCME",
4935 "ESH4",
4936 spread_expiry_ns(),
4937 )));
4938 let calculator = spread_calculator(instruments, spread_quotes());
4939 calculator
4940 .cache_futures_spread(
4941 InstrumentId::from(SPREAD_CALL_ID),
4942 InstrumentId::from(SPREAD_PUT_ID),
4943 InstrumentId::from(SPREAD_REFERENCE_ID),
4944 )
4945 .unwrap();
4946
4947 let underlying_id = calculator
4948 .resolve_underlying_instrument_id(
4949 &InstrumentAny::OptionContract(spread_call()),
4950 InstrumentId::from(SPREAD_CALL_ID),
4951 )
4952 .unwrap();
4953
4954 assert_eq!(underlying_id, InstrumentId::from(SPREAD_UNDERLYING_ID));
4955 }
4956
4957 #[rstest]
4958 fn test_get_cached_futures_spread_price_returns_none_for_unknown_underlying() {
4959 let calculator = spread_calculator(spread_instruments(), spread_quotes());
4960
4961 assert_eq!(
4962 calculator.get_cached_futures_spread_price(InstrumentId::from("CLZ4.NYMEX")),
4963 None
4964 );
4965 }
4966
4967 #[cfg(feature = "defi")]
4968 #[rstest]
4969 fn test_instrument_greeks_converts_mid_of_max_float_precision_quote() {
4970 let now = utc_timestamp(2025, 3, 8, 12, 0, 0);
4971 let now_ns = UnixNanos::from(now);
4972 let expiry_ns = UnixNanos::from(now + jiff::SignedDuration::from_hours(24 * 30));
4973 let future = future_with_expiration("ES.GLBX", "ES", expiry_ns);
4974 let instrument = InstrumentAny::FuturesContract(future.clone());
4975 let cache = Rc::new(RefCell::new(Cache::new(None, None)));
4976 cache
4977 .borrow_mut()
4978 .add_instrument(instrument.clone())
4979 .unwrap();
4980
4981 let quote = QuoteTick::new(
4982 future.id(),
4983 Price::from("100.0000000000000000"),
4984 Price::from("100.0000000000000001"),
4985 Quantity::from(1),
4986 Quantity::from(1),
4987 now_ns,
4988 now_ns,
4989 );
4990 cache.borrow_mut().add_quote(quote).unwrap();
4991 let position =
4992 position_from_fill(&instrument, "P-1", "O-1", "T-1", OrderSide::Buy, 1, "99.00");
4993 let clock = Rc::new(RefCell::new(VirtualClock::new()));
4994 clock.borrow_mut().set_time(now_ns);
4995 let calculator = GreeksCalculator::new(cache, clock);
4996
4997 let greeks = calculator
4998 .instrument_greeks(
4999 future.id(),
5000 None,
5001 None,
5002 None,
5003 None,
5004 None,
5005 None,
5006 None,
5007 None,
5008 None,
5009 Some(now_ns),
5010 Some(position),
5011 None,
5012 None,
5013 None,
5014 None,
5015 None,
5016 None,
5017 )
5018 .unwrap();
5019
5020 assert_eq!(greeks.delta, 1.0);
5021 assert_eq!(greeks.pnl, 1.0);
5022 assert_eq!(greeks.price, 1.0);
5023 }
5024
5025 #[rstest]
5026 #[case(false, -1)]
5027 #[case(false, 0)]
5028 #[case(true, -1)]
5029 #[case(true, 0)]
5030 fn test_instrument_greeks_rejects_expired_options_before_cached_return(
5031 #[case] cached: bool,
5032 #[case] offset_ns: i64,
5033 #[values(false, true)] clock_default: bool,
5034 ) {
5035 let now_ns = UnixNanos::from(1_000_000_000);
5036 let expiry_ns = UnixNanos::from((1_000_000_000_i64 + offset_ns) as u64);
5037 let option = option_with_expiration("AAPL250417C00150000.OPRA", expiry_ns);
5038 let id = option.id();
5039 let calculator = calculator_with_option_and_equities(option, &[]);
5040 let clock = Rc::new(RefCell::new(VirtualClock::new()));
5041 clock.borrow_mut().set_time(now_ns);
5042 let calculator = GreeksCalculator::new(calculator.cache, clock);
5043
5044 if cached {
5045 let mut data = GreeksData::from_delta(id, 0.5, 100.0, now_ns);
5046 data.underlying_price = 150.0;
5047 data.strike = 150.0;
5048 data.vol = 0.2;
5049 data.expiry_in_years = 1.0;
5050 calculator.cache.borrow_mut().add_greeks(data).unwrap();
5051 }
5052
5053 let mut params = InstrumentGreeksParams::builder()
5054 .instrument_id(id)
5055 .ts_event(now_ns)
5056 .use_cached_greeks(cached)
5057 .build();
5058
5059 if clock_default {
5060 params.ts_event = None;
5061 }
5062
5063 let result = params.calculate(&calculator).unwrap_err();
5064 assert_eq!(
5065 result.downcast_ref::<OptionValuationError>(),
5066 Some(&OptionValuationError::Expired(id))
5067 );
5068 }
5069
5070 #[rstest]
5071 #[case(InstrumentAny::OptionSpread(option_spread()))]
5072 #[case(InstrumentAny::CryptoOptionSpread(crypto_option_spread_btc_deribit()))]
5073 fn test_instrument_greeks_rejects_option_spreads(#[case] instrument: InstrumentAny) {
5074 let id = instrument.id();
5075 let calculator = create_test_calculator();
5076 calculator
5077 .cache
5078 .borrow_mut()
5079 .add_instrument(instrument)
5080 .unwrap();
5081 let result = InstrumentGreeksParams::builder()
5082 .instrument_id(id)
5083 .build()
5084 .calculate(&calculator)
5085 .unwrap_err();
5086 assert_eq!(
5087 result.downcast_ref::<OptionValuationError>(),
5088 Some(&OptionValuationError::UnsupportedSpread(id))
5089 );
5090 }
5091
5092 #[rstest]
5093 #[case(-200.0, 0.0, 0.0, "underlying price")]
5094 #[case(0.0, -2.0, 0.0, "volatility")]
5095 #[case(0.0, 0.0, 1.0, "time to expiry")]
5096 #[case(f64::NAN, 0.0, 0.0, "spot shock")]
5097 #[case(0.0, f64::INFINITY, 0.0, "volatility shock")]
5098 #[case(0.0, 0.0, f64::NAN, "time to expiry shock")]
5099 fn test_instrument_greeks_rejects_invalid_shocks_without_caching(
5100 #[case] spot: f64,
5101 #[case] vol: f64,
5102 #[case] time: f64,
5103 #[case] input: &'static str,
5104 ) {
5105 let (calculator, id, now) = option_calculator();
5106 let result = InstrumentGreeksParams::builder()
5107 .instrument_id(id)
5108 .ts_event(now)
5109 .spot_shock(spot)
5110 .vol_shock(vol)
5111 .time_to_expiry_shock(time)
5112 .cache_greeks(true)
5113 .build()
5114 .calculate(&calculator)
5115 .unwrap_err();
5116 assert_eq!(
5117 result.downcast_ref::<OptionValuationError>(),
5118 Some(&OptionValuationError::InvalidInput(input))
5119 );
5120 assert!(calculator.cache.borrow().greeks(&id).is_none());
5121 }
5122
5123 #[rstest]
5124 fn test_instrument_greeks_rejects_unattainable_price() {
5125 let (calculator, id, now) = option_calculator();
5126 calculator
5127 .cache
5128 .borrow_mut()
5129 .add_quote(QuoteTick::new(
5130 id,
5131 Price::from("200.00"),
5132 Price::from("201.00"),
5133 Quantity::from(100),
5134 Quantity::from(100),
5135 now,
5136 now,
5137 ))
5138 .unwrap();
5139 let result = InstrumentGreeksParams::builder()
5140 .instrument_id(id)
5141 .ts_event(now)
5142 .cache_greeks(true)
5143 .build()
5144 .calculate(&calculator)
5145 .unwrap_err();
5146 assert_eq!(
5147 result.downcast_ref::<OptionValuationError>(),
5148 Some(&OptionValuationError::ImpliedVolatilityUnavailable)
5149 );
5150 assert!(calculator.cache.borrow().greeks(&id).is_none());
5151 }
5152
5153 #[rstest]
5154 #[case(false)]
5155 #[case(true)]
5156 fn test_instrument_greeks_rho_uses_explicit_carry_source(#[case] dividend_linked: bool) {
5157 let (calculator, id, now) = option_calculator();
5158 let mut params = InstrumentGreeksParams::builder()
5159 .instrument_id(id)
5160 .ts_event(now)
5161 .flat_interest_rate(0.05)
5162 .build();
5163 params.flat_dividend_yield = dividend_linked.then_some(0.05);
5164 let greeks = params.calculate(&calculator).unwrap();
5165 let expected = if dividend_linked {
5166 greeks.expiry_in_years
5167 * greeks.strike
5168 * (-greeks.interest_rate * greeks.expiry_in_years).exp()
5169 * greeks.itm_prob
5170 * 0.01
5171 } else {
5172 -greeks.expiry_in_years * greeks.price * 0.01
5173 };
5174
5175 assert_eq!(greeks.cost_of_carry, 0.0);
5176 assert!((greeks.rho - expected).abs() < 1e-12);
5177 }
5178
5179 #[rstest]
5180 fn test_portfolio_greeks_propagates_invalid_valuation() {
5181 let (calculator, position, now) = portfolio_option_calculator();
5182 let id = position.instrument_id;
5183 calculator
5184 .cache
5185 .borrow_mut()
5186 .add_quote(QuoteTick::new(
5187 id,
5188 Price::from("200.00"),
5189 Price::from("201.00"),
5190 Quantity::from(100),
5191 Quantity::from(100),
5192 now,
5193 now,
5194 ))
5195 .unwrap();
5196 let result = PortfolioGreeksParams::builder()
5197 .instrument_id(id)
5198 .build()
5199 .calculate(&calculator)
5200 .unwrap_err();
5201 assert_eq!(
5202 result.downcast_ref::<OptionValuationError>(),
5203 Some(&OptionValuationError::ImpliedVolatilityUnavailable)
5204 );
5205 }
5206
5207 #[rstest]
5208 #[case::unshocked(0.0)]
5209 #[case::shocked(1.0)]
5210 fn test_instrument_greeks_cached_valuation_does_not_publish(#[case] spot_shock: f64) {
5211 msgbus::set_message_bus(Rc::new(RefCell::new(msgbus::MessageBus::default())));
5212 let (calculator, id, now) = option_calculator();
5213 let base = InstrumentGreeksParams::builder()
5214 .instrument_id(id)
5215 .ts_event(now)
5216 .cache_greeks(true)
5217 .build()
5218 .calculate(&calculator)
5219 .unwrap();
5220 let observed = Rc::new(RefCell::new(Vec::new()));
5221 let captured = Rc::clone(&observed);
5222 calculator.subscribe_greeks(
5223 "AAPL",
5224 Some(move |data: &GreeksData| {
5225 captured.borrow_mut().push(data.clone());
5226 }),
5227 );
5228
5229 let result = InstrumentGreeksParams::builder()
5230 .instrument_id(id)
5231 .ts_event(UnixNanos::from(now.as_u64() + 1_000_000_000))
5232 .use_cached_greeks(true)
5233 .spot_shock(spot_shock)
5234 .cache_greeks(true)
5235 .publish_greeks(true)
5236 .build()
5237 .calculate(&calculator)
5238 .unwrap();
5239 let cached = calculator.cache.borrow().greeks(&id).unwrap();
5240
5241 assert!(observed.borrow().is_empty());
5242 assert_greeks_eq(&cached, &base);
5243 assert_eq!(result.underlying_price, base.underlying_price + spot_shock);
5244 assert_eq!(result.ts_event, base.ts_event);
5245 }
5246
5247 #[rstest]
5248 fn test_instrument_greeks_rejects_invalid_shocks_without_publishing() {
5249 let (calculator, id, now) = option_calculator();
5250 let observed = Rc::new(RefCell::new(Vec::new()));
5251 let captured = Rc::clone(&observed);
5252 calculator.subscribe_greeks(
5253 "AAPL",
5254 Some(move |data: &GreeksData| {
5255 captured.borrow_mut().push(data.clone());
5256 }),
5257 );
5258
5259 let mut params = InstrumentGreeksParams::builder()
5260 .instrument_id(id)
5261 .ts_event(now)
5262 .spot_shock(-200.0)
5263 .cache_greeks(true)
5264 .publish_greeks(true)
5265 .build();
5266 let e = params.calculate(&calculator).unwrap_err();
5267 assert_eq!(
5268 e.downcast_ref::<OptionValuationError>(),
5269 Some(&OptionValuationError::InvalidInput("underlying price"))
5270 );
5271 assert_eq!(observed.borrow().len(), 0);
5272 assert!(calculator.cache.borrow().greeks(&id).is_none());
5273 params.spot_shock = 1.0;
5274 let result = params.calculate(&calculator).unwrap();
5275 let cached = calculator.cache.borrow().greeks(&id).unwrap();
5276 let observed = observed.borrow();
5277 assert_eq!(observed.len(), 1);
5278 assert_greeks_eq(&observed[0], &cached);
5279 assert_eq!(cached.underlying_price, 150.05);
5280 assert_eq!(result.underlying_price, 151.05);
5281 }
5282
5283 #[rstest]
5284 #[case("probability below zero", -0.1)]
5285 #[case("probability above one", 1.1)]
5286 #[case("price", -1.0)]
5287 #[case("multiplier", f64::NAN)]
5288 #[case("quantity", f64::INFINITY)]
5289 fn test_instrument_greeks_rejects_invalid_cached_results(
5290 #[case] field: &str,
5291 #[case] value: f64,
5292 ) {
5293 let (calculator, id, now) = option_calculator();
5294 let mut data = InstrumentGreeksParams::builder()
5295 .instrument_id(id)
5296 .ts_event(now)
5297 .build()
5298 .calculate(&calculator)
5299 .unwrap();
5300
5301 match field {
5302 "probability below zero" | "probability above one" => data.itm_prob = value,
5303 "price" => data.price = value,
5304 "multiplier" => data.multiplier = value,
5305 "quantity" => data.quantity = value,
5306 _ => unreachable!(),
5307 }
5308
5309 calculator.cache.borrow_mut().add_greeks(data).unwrap();
5310 let error = InstrumentGreeksParams::builder()
5311 .instrument_id(id)
5312 .ts_event(now)
5313 .use_cached_greeks(true)
5314 .build()
5315 .calculate(&calculator)
5316 .unwrap_err();
5317 assert_eq!(
5318 error.downcast_ref::<OptionValuationError>(),
5319 Some(&OptionValuationError::InvalidResult)
5320 );
5321 }
5322
5323 #[rstest]
5324 fn test_instrument_greeks_rejects_invalid_cached_volatility_seed() {
5325 let (calculator, id, now) = option_calculator();
5326 let mut data = InstrumentGreeksParams::builder()
5327 .instrument_id(id)
5328 .ts_event(now)
5329 .build()
5330 .calculate(&calculator)
5331 .unwrap();
5332 data.vol = f64::NAN;
5333 calculator.cache.borrow_mut().add_greeks(data).unwrap();
5334 let error = InstrumentGreeksParams::builder()
5335 .instrument_id(id)
5336 .ts_event(now)
5337 .update_vol(true)
5338 .build()
5339 .calculate(&calculator)
5340 .unwrap_err();
5341 assert_eq!(
5342 error.downcast_ref::<OptionValuationError>(),
5343 Some(&OptionValuationError::InvalidInput("volatility"))
5344 );
5345 }
5346
5347 #[rstest]
5348 fn test_portfolio_greeks_rejects_overflow_after_scaling() {
5349 let (calculator, position, now) = portfolio_option_calculator();
5350 let id = position.instrument_id;
5351 let mut data = InstrumentGreeksParams::builder()
5352 .instrument_id(id)
5353 .ts_event(now)
5354 .build()
5355 .calculate(&calculator)
5356 .unwrap();
5357 data.multiplier = f64::MAX;
5358 calculator.cache.borrow_mut().add_greeks(data).unwrap();
5359 let error = PortfolioGreeksParams::builder()
5360 .instrument_id(id)
5361 .use_cached_greeks(true)
5362 .build()
5363 .calculate(&calculator)
5364 .unwrap_err();
5365 assert_eq!(
5366 error.downcast_ref::<OptionValuationError>(),
5367 Some(&OptionValuationError::InvalidResult)
5368 );
5369 }
5370
5371 #[rstest]
5372 fn test_instrument_greeks_projects_extreme_decimal_price() {
5373 let (calculator, mut position, now) = portfolio_option_calculator();
5374 let id = position.instrument_id;
5375 position.avg_px_open = Decimal::MAX;
5376 let observed = Rc::new(RefCell::new(Vec::new()));
5377 let captured = Rc::clone(&observed);
5378 calculator.subscribe_greeks(
5379 "AAPL",
5380 Some(move |data: &GreeksData| {
5381 captured.borrow_mut().push(data.clone());
5382 }),
5383 );
5384
5385 let result = InstrumentGreeksParams::builder()
5386 .instrument_id(id)
5387 .ts_event(now)
5388 .position(position)
5389 .spot_shock(1.0)
5390 .cache_greeks(true)
5391 .publish_greeks(true)
5392 .build()
5393 .calculate(&calculator)
5394 .unwrap();
5395 assert_eq!(result.pnl, result.price - Decimal::MAX.as_f64());
5396 let cached = calculator.cache.borrow().greeks(&id).unwrap();
5397 assert_eq!(observed.borrow().len(), 1);
5398 assert_greeks_eq(&observed.borrow()[0], &cached);
5399 }
5400
5401 #[rstest]
5402 fn test_instrument_greeks_rho_uses_dividend_curve_source() {
5403 let (calculator, id, now) = option_calculator();
5404 calculator
5405 .cache
5406 .borrow_mut()
5407 .add_yield_curve(YieldCurve::new(
5408 "AAPL.OPRA".to_string(),
5409 vec![0.0],
5410 vec![0.05],
5411 now,
5412 now,
5413 ))
5414 .unwrap();
5415 let result = InstrumentGreeksParams::builder()
5416 .instrument_id(id)
5417 .ts_event(now)
5418 .flat_interest_rate(0.05)
5419 .build()
5420 .calculate(&calculator)
5421 .unwrap();
5422 assert_eq!(result.cost_of_carry, 0.0);
5423 let reference = result.expiry_in_years
5424 * result.strike
5425 * (-result.interest_rate * result.expiry_in_years).exp()
5426 * result.itm_prob
5427 * 0.01;
5428 assert!((result.rho - reference).abs() < 1e-12);
5429 }
5430
5431 #[rstest]
5432 fn test_instrument_greeks_shocked_cache_uses_current_carry_sensitivity() {
5433 let (calculator, id, now) = option_calculator();
5434 let base = InstrumentGreeksParams::builder()
5435 .instrument_id(id)
5436 .ts_event(now)
5437 .cache_greeks(true)
5438 .build()
5439 .calculate(&calculator)
5440 .unwrap();
5441 let mut params = InstrumentGreeksParams::builder()
5442 .instrument_id(id)
5443 .ts_event(now)
5444 .use_cached_greeks(true)
5445 .spot_shock(1.0)
5446 .build();
5447 params.flat_dividend_yield = Some(base.interest_rate);
5448 let result = params.calculate(&calculator).unwrap();
5449 assert_eq!(result.cost_of_carry, 0.0);
5450 let reference = result.expiry_in_years
5451 * result.strike
5452 * (-result.interest_rate * result.expiry_in_years).exp()
5453 * result.itm_prob
5454 * 0.01;
5455 assert!((result.rho - reference).abs() < 1e-12);
5456 assert_eq!(base.rho, -base.expiry_in_years * base.price * 0.01);
5457 }
5458
5459 #[rstest]
5460 #[case(false)]
5461 #[case(true)]
5462 fn test_instrument_greeks_rejects_nonfinite_transformed_sensitivities(
5463 #[case] beta_weight: bool,
5464 ) {
5465 let (calculator, id, now) = option_calculator();
5466 let mut params = InstrumentGreeksParams::builder()
5467 .instrument_id(id)
5468 .ts_event(now)
5469 .cache_greeks(true)
5470 .build();
5471
5472 if beta_weight {
5473 let underlying = InstrumentId::from("AAPL.OPRA");
5474 params.index_instrument_id = Some(underlying);
5475 params.beta_weights = Some(HashMap::from([(underlying, f64::NAN)]));
5476 } else {
5477 params.vega_time_weight_base = Some(-1);
5478 }
5479
5480 let e = params.calculate(&calculator).unwrap_err();
5481 assert_eq!(
5482 e.downcast_ref::<OptionValuationError>(),
5483 Some(&OptionValuationError::InvalidResult)
5484 );
5485 assert!(calculator.cache.borrow().greeks(&id).is_none());
5486 }
5487}