use super::*;
use crate::derivatives::pricing::black_greeks;
use crate::derivatives::{ContractKind, Right, OIL_FUTURE, POLICY_RATE_FUTURE, TERM_RATE_FUTURE, VIX_FUTURE};
pub const MARGIN_HALF_LIFE: f64 = 7.0;
pub const MAINTENANCE_RATIO: f64 = 1.1;
fn kind_code(kind: ContractKind) -> f64 {
match kind {
ContractKind::IndexFuture => 0.0,
ContractKind::VixFuture => 1.0,
ContractKind::PolicyRateFuture => 2.0,
ContractKind::TermRateFuture => 3.0,
_ => 4.0,
}
}
fn kind_of(code: f64) -> Option<ContractKind> {
match code as i64 {
_ if code.fract() != 0.0 => None,
0 => Some(ContractKind::IndexFuture),
1 => Some(ContractKind::VixFuture),
2 => Some(ContractKind::PolicyRateFuture),
3 => Some(ContractKind::TermRateFuture),
4 => Some(ContractKind::OilFuture),
_ => None,
}
}
pub const SCAN_MOVES: [f64; 7] = [-1.0, -2.0 / 3.0, -1.0 / 3.0, 0.0, 1.0 / 3.0, 2.0 / 3.0, 1.0];
pub const SCAN_VOL_SHIFTS: [f64; 3] = [-1.0, 0.0, 1.0];
pub const SCAN_VOL_SD: f64 = 0.07;
pub(crate) fn option_scan_tail(p: &crate::params::ModelParams) -> f64 {
let t = if p.margin_scan_option_tail != 0.0 { p.margin_scan_option_tail } else { p.margin_scan_tail };
if t == 0.0 {
1.0
} else {
t
}
}
#[derive(Debug, Clone, Copy, PartialEq)]
pub(crate) struct ScanOption {
pub(crate) right: Right,
pub(crate) carry_spot: f64,
pub(crate) strike: f64,
pub(crate) years: f64,
pub(crate) vol: f64,
pub(crate) rate: f64,
pub(crate) units: f64,
}
pub(crate) fn option_scan_loss(positions: &[ScanOption], index_move: f64, vol_shift: f64) -> f64 {
option_scan_loss_with(positions, 0.0, index_move, vol_shift)
}
pub(crate) fn option_scan_loss_with(positions: &[ScanOption], linear: f64, index_move: f64, vol_shift: f64) -> f64 {
if positions.is_empty() && linear == 0.0 {
return 0.0;
}
let now: Vec<f64> = positions
.iter()
.map(|p| black_greeks(p.right, p.carry_spot, p.strike, p.years, p.vol, p.rate).0)
.collect();
let mut worst: f64 = 0.0;
for &m in &SCAN_MOVES {
for &v in &SCAN_VOL_SHIFTS {
let mut loss = 0.0;
for (p, before) in positions.iter().zip(now.iter()) {
let spot = crate::mathx::max(1e-9, p.carry_spot + m * index_move);
let vol = crate::mathx::max(1e-6, p.vol * (1.0 + v * vol_shift));
let after = black_greeks(p.right, spot, p.strike, p.years, vol, p.rate).0;
loss += p.units * (before - after);
}
if linear != 0.0 {
loss -= crate::mathx::max(0.0, linear * m * index_move);
}
worst = crate::mathx::max(worst, loss);
}
}
worst
}
pub const RANGE_POINTS: [f64; 10] = [
-1.0,
-7.0 / 9.0,
-5.0 / 9.0,
-3.0 / 9.0,
-1.0 / 9.0,
1.0 / 9.0,
3.0 / 9.0,
5.0 / 9.0,
7.0 / 9.0,
1.0,
];
pub(crate) fn option_scan_loss_at(positions: &[ScanOption], linear: f64, moves: &[f64], vol_shift: f64) -> f64 {
if positions.is_empty() && linear == 0.0 {
return 0.0;
}
let now: Vec<f64> = positions
.iter()
.map(|p| black_greeks(p.right, p.carry_spot, p.strike, p.years, p.vol, p.rate).0)
.collect();
let mut worst: f64 = 0.0;
for &mv in moves {
for &v in &SCAN_VOL_SHIFTS {
let mut loss = 0.0;
for (p, before) in positions.iter().zip(now.iter()) {
let spot = crate::mathx::max(1e-9, p.carry_spot + mv);
let vol = crate::mathx::max(1e-6, p.vol * (1.0 + v * vol_shift));
let after = black_greeks(p.right, spot, p.strike, p.years, vol, p.rate).0;
loss += p.units * (before - after);
}
if linear != 0.0 {
loss -= crate::mathx::max(0.0, linear * mv);
}
worst = crate::mathx::max(worst, loss);
}
}
worst
}
pub(crate) fn option_contract_minimum(legs: &[ScanOption], per_unit: f64) -> f64 {
if per_unit == 0.0 {
return 0.0;
}
let mut total = 0.0;
for leg in legs {
let charge = per_unit * leg.units.abs();
total += if leg.units > 0.0 {
let value = leg.units * black_greeks(leg.right, leg.carry_spot, leg.strike, leg.years, leg.vol, leg.rate).0;
crate::mathx::min(charge, crate::mathx::max(0.0, value))
} else {
charge
};
}
total
}
#[derive(Debug, Clone, PartialEq)]
pub(crate) struct MarginEntry {
pub(crate) kind: ContractKind,
pub(crate) expiry: i64,
pub(crate) last: f64,
pub(crate) variance: f64,
pub(crate) changes: u32,
}
const ENTRY_WIDTH: usize = 5;
#[derive(Debug, Clone, Default)]
pub(crate) struct MarginState {
pub(crate) entries: Vec<MarginEntry>,
}
impl MarginState {
pub(crate) fn to_words(&self) -> Vec<f64> {
let mut out = Vec::with_capacity(1 + ENTRY_WIDTH * self.entries.len());
out.push(self.entries.len() as f64);
for e in &self.entries {
out.push(kind_code(e.kind));
out.push(e.expiry as f64);
out.push(e.last);
out.push(e.variance);
out.push(f64::from(e.changes));
}
out
}
pub(crate) fn set_words(&mut self, words: &[f64]) -> Result<(), String> {
let bad = |why: &str| format!("this snapshot's margin does not parse: {why}");
let Some(&count) = words.first() else {
return Err(bad("it is empty"));
};
if !(count.is_finite() && count >= 0.0 && count.fract() == 0.0 && count <= 1e6) {
return Err(bad(&format!("the entry count is {count}")));
}
let n = count as usize;
if words.len() != 1 + ENTRY_WIDTH * n {
return Err(bad(&format!("{} numbers for {n} entries", words.len())));
}
let mut entries = Vec::with_capacity(n);
for k in 0..n {
let w = &words[1 + ENTRY_WIDTH * k..1 + ENTRY_WIDTH * (k + 1)];
let kind = kind_of(w[0]).ok_or_else(|| bad(&format!("a kind is {}", w[0])))?;
if !(w[1].is_finite() && w[1].fract() == 0.0) {
return Err(bad(&format!("an expiry is {}", w[1])));
}
if !(w[2].is_finite() && w[3].is_finite() && w[3] >= 0.0) {
return Err(bad("a mark or a variance is not finite and not negative"));
}
if !(w[4].is_finite() && w[4] >= 0.0 && w[4].fract() == 0.0 && w[4] <= f64::from(u32::MAX)) {
return Err(bad(&format!("a change count is {}", w[4])));
}
entries.push(MarginEntry { kind, expiry: w[1] as i64, last: w[2], variance: w[3], changes: w[4] as u32 });
}
self.entries = entries;
Ok(())
}
}
pub(super) fn normal_quantile(p: f64) -> f64 {
let cdf = |x: f64| 0.5 * crate::mathx::erfc(-x / std::f64::consts::SQRT_2);
let (mut lo, mut hi) = (-10.0, 10.0);
for _ in 0..80 {
let mid = 0.5 * (lo + hi);
if cdf(mid) < p {
lo = mid;
} else {
hi = mid;
}
}
0.5 * (lo + hi)
}
impl Engine {
pub(super) fn margin_on(&self) -> bool {
self.params.margin_scan_coverage != 0.0
}
fn contract_marks(&self) -> Vec<(ContractKind, i64, f64)> {
let mut out = Vec::new();
if self.futures_on() {
out.extend(self.futures.contracts.iter().map(|c| (ContractKind::IndexFuture, c.expiry, c.mark)));
}
if self.vix_futures_on() {
out.extend(self.vix_futures.contracts.iter().map(|c| (ContractKind::VixFuture, c.expiry, c.mark)));
}
if self.rate_futures_on() {
out.extend(self.rate_futures.contracts.iter().map(|c| (c.kind, c.expiry, c.mark)));
}
if self.oil_futures_on() {
out.extend(self.oil_futures.contracts.iter().map(|c| (ContractKind::OilFuture, c.expiry, c.mark)));
}
out
}
fn margin_seed(&self, kind: ContractKind, mark: f64) -> f64 {
let sd = match kind {
ContractKind::IndexFuture => mark * self.market_vol.sigma_daily(),
ContractKind::VixFuture => mark * VIX_FUTURE.daily_sigma,
ContractKind::PolicyRateFuture => POLICY_RATE_FUTURE.daily_sigma,
ContractKind::TermRateFuture => TERM_RATE_FUTURE.daily_sigma,
_ => mark * OIL_FUTURE.daily_sigma,
};
sd * sd
}
pub(super) fn margin_close_update(&mut self) {
if !self.margin_on() {
return;
}
let decay = crate::mathx::pow(0.5, 1.0 / MARGIN_HALF_LIFE);
let marks = self.contract_marks();
let mut kept: Vec<MarginEntry> = Vec::with_capacity(marks.len());
for (kind, expiry, mark) in marks {
if !mark.is_finite() {
continue;
}
let old = self.margin.entries.iter().find(|e| e.kind == kind && e.expiry == expiry).cloned();
let entry = match old {
Some(mut e) => {
let x = mark - e.last;
e.variance = decay * e.variance + (1.0 - decay) * x * x;
e.changes = e.changes.saturating_add(1);
e.last = mark;
e
}
None => {
let front = kept
.iter()
.chain(self.margin.entries.iter())
.find(|e| e.kind == kind)
.map(|e| e.variance);
let variance = front.unwrap_or_else(|| self.margin_seed(kind, mark));
MarginEntry { kind, expiry, last: mark, variance, changes: 0 }
}
};
kept.push(entry);
}
self.margin.entries = kept;
}
pub(super) fn option_scan_size(&self, vix: f64, index: f64) -> (f64, f64) {
let p = &self.params;
let z = normal_quantile(0.5 + 0.5 * p.margin_scan_coverage) * option_scan_tail(p);
let sigma = vix / (100.0 * (1.0 + p.vix_variance_premium) * crate::mathx::sqrt(252.0));
(z * sigma * index, z * SCAN_VOL_SD)
}
pub(crate) fn initial_margin(&self, kind: ContractKind, expiry: i64, multiplier: f64) -> Option<f64> {
if !self.margin_on() {
return None;
}
let e = self.margin.entries.iter().find(|e| e.kind == kind && e.expiry == expiry)?;
let p = &self.params;
let tail = if p.margin_scan_tail == 0.0 { 1.0 } else { p.margin_scan_tail };
let z = normal_quantile(0.5 + 0.5 * p.margin_scan_coverage);
Some(multiplier * z * tail * crate::mathx::sqrt(e.variance))
}
pub fn margin_words(&self) -> Option<Vec<f64>> {
if self.margin_on() {
Some(self.margin.to_words())
} else {
None
}
}
pub fn set_margin_state(&mut self, words: Option<&[f64]>) -> Result<(), String> {
match words {
Some(_) if !self.margin_on() => Err(
"this snapshot carries the contracts' margin (margin), which only an engine with \
margin_scan_coverage set keeps, and this engine's is 0"
.to_string(),
),
Some(w) => {
let mut state = MarginState::default();
state.set_words(w)?;
self.margin = state;
Ok(())
}
None if self.margin_on() => Err(
"an engine with margin_scan_coverage set carries its contracts' margin (margin); this \
snapshot lacks it"
.to_string(),
),
None => {
self.margin = MarginState::default();
Ok(())
}
}
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn the_quantile_inverts_the_normal() {
assert!(normal_quantile(0.5).abs() < 1e-12);
assert!((normal_quantile(0.995) - 2.575_829_303_548_9).abs() < 1e-9);
assert!((normal_quantile(0.975) - 1.959_963_984_540_1).abs() < 1e-9);
}
fn option(right: Right, strike: f64, units: f64) -> ScanOption {
ScanOption { right, carry_spot: 1000.0, strike, years: 21.0 / 252.0, vol: 0.2, rate: 0.03, units }
}
#[test]
fn the_option_scan_margins_shorts_and_nets_offsetting_positions() {
let (m, v) = (30.0, 0.18);
let price = |o: &ScanOption| black_greeks(o.right, o.carry_spot, o.strike, o.years, o.vol, o.rate).0;
let short = option(Right::Call, 1000.0, -100.0);
let up = ScanOption { carry_spot: 1030.0, vol: 0.2 * 1.18, ..short };
let want = 100.0 * (price(&up) - price(&short));
assert!((option_scan_loss(&[short], m, v) - want).abs() < 1e-9 * want);
let long = option(Right::Put, 980.0, 100.0);
let premium = 100.0 * price(&long);
let l = option_scan_loss(&[long], m, v);
assert!(l > 0.0 && l < premium);
assert_eq!(option_scan_loss(&[short, option(Right::Call, 1000.0, 100.0)], m, v), 0.0);
let spread = [option(Right::Call, 1000.0, -100.0), option(Right::Call, 1010.0, 100.0)];
let s = option_scan_loss(&spread, m, v);
assert!(s > 0.0 && s <= 100.0 * 10.0);
assert!(s < option_scan_loss(&spread[..1], m, v));
assert!(option_scan_loss(&[short], 2.0 * m, v) > option_scan_loss(&[short], m, v));
assert_eq!(option_scan_loss(&[], m, v), 0.0);
}
#[test]
fn stock_offsets_an_options_loss_where_it_gains_and_asks_nothing_alone() {
let (m, v) = (30.0, 0.18);
let combo = option_scan_loss_with(&[option(Right::Call, 1000.0, -300.0)], 100.0, m, v);
let synthetic = option_scan_loss(&[option(Right::Put, 1000.0, -100.0), option(Right::Call, 1000.0, -200.0)], m, v);
assert!(synthetic > 0.0);
assert!((combo - synthetic).abs() <= 1e-9 * synthetic, "{combo} {synthetic}");
let naked = option_scan_loss(&[option(Right::Call, 1000.0, -100.0)], m, v);
let covered = option_scan_loss_with(&[option(Right::Call, 1000.0, -100.0)], 100.0, m, v);
assert!(covered < naked);
assert_eq!(option_scan_loss_with(&[], 100.0, m, v), 0.0);
assert_eq!(option_scan_loss_with(&[], -100.0, m, v), 0.0);
}
#[test]
fn the_range_points_span_the_range_at_ten_equal_steps() {
assert_eq!(RANGE_POINTS.len(), 10);
assert_eq!((RANGE_POINTS[0], RANGE_POINTS[9]), (-1.0, 1.0));
for w in RANGE_POINTS.windows(2) {
assert!((w[1] - w[0] - 2.0 / 9.0).abs() < 1e-15);
}
}
#[test]
fn the_range_scan_takes_a_strangle_at_the_ends_and_reproduces_the_seven_points() {
let price = |o: &ScanOption| black_greeks(o.right, o.carry_spot, o.strike, o.years, o.vol, o.rate).0;
let strangle = [option(Right::Call, 1100.0, -100.0), option(Right::Put, 900.0, -100.0)];
let size = 0.15 * 1000.0;
let moves = RANGE_POINTS.map(|x| x * size);
let got = option_scan_loss_at(&strangle, 0.0, &moves, 0.18);
let at = |mv: f64| {
strangle.iter().map(|o| {
let after = ScanOption { carry_spot: o.carry_spot + mv, vol: o.vol * 1.18, ..*o };
o.units * (price(o) - price(&after))
}).sum::<f64>()
};
let want = crate::mathx::max(at(size), at(-size));
assert!((got - want).abs() < 1e-9 * want);
assert!(got > option_scan_loss(&strangle, 30.0, 0.18));
let seven = SCAN_MOVES.map(|m| m * 30.0);
let stock = 50.0;
assert!((option_scan_loss_at(&strangle, stock, &seven, 0.18)
- option_scan_loss_with(&strangle, stock, 30.0, 0.18)).abs() < 1e-9);
assert_eq!(option_scan_loss_at(&[], 0.0, &moves, 0.18), 0.0);
}
#[test]
fn the_portfolio_minimum_charges_every_contract_and_a_long_no_more_than_its_value() {
let leg = |right, strike, units| ScanOption { right, carry_spot: 1000.0, strike, years: 0.1, vol: 0.2, rate: 0.0, units };
assert!((option_contract_minimum(&[leg(Right::Call, 1100.0, -100.0)], 0.375) - 37.5).abs() < 1e-9);
let strangle = [leg(Right::Call, 1100.0, -100.0), leg(Right::Put, 900.0, -100.0)];
assert!((option_contract_minimum(&strangle, 0.375) - 75.0).abs() < 1e-9);
let spread = [leg(Right::Call, 1100.0, -100.0), leg(Right::Call, 1050.0, 100.0)];
assert!((option_contract_minimum(&spread, 0.375) - 75.0).abs() < 1e-9);
let far = leg(Right::Call, 2000.0, 100.0);
let value = 100.0 * black_greeks(Right::Call, 1000.0, 2000.0, 0.1, 0.2, 0.0).0;
assert!(value < 37.5);
assert!((option_contract_minimum(&[far], 0.375) - value).abs() < 1e-12);
assert_eq!(option_contract_minimum(&strangle, 0.0), 0.0);
}
#[test]
fn the_words_round_trip() {
let s = MarginState {
entries: vec![
MarginEntry { kind: ContractKind::VixFuture, expiry: 35, last: 18.5, variance: 0.81, changes: 4 },
MarginEntry { kind: ContractKind::OilFuture, expiry: 56, last: 74.2, variance: 2.25, changes: 0 },
],
};
let words = s.to_words();
let mut back = MarginState::default();
back.set_words(&words).unwrap();
assert_eq!(back.entries, s.entries);
assert!(MarginState::default().set_words(&words[..words.len() - 1]).is_err());
}
}