Skip to main content

YieldCurve

Struct YieldCurve 

Source
pub struct YieldCurve { /* private fields */ }
Expand description

A canonical discount curve anchored at reference_date.

State is the pillar (times, dfs) vectors only — dfs[0] = 1.0 at times[0] = 0.0 always. compounding is the quoting convention used by zero_rate / forward_rate; changing it never changes discounting.

Implementations§

Source§

impl YieldCurve

Source

pub fn flat( rate: f64, reference_date: NaiveDate, day_count: DayCountConvention, compounding: Compounding, ) -> Result<Self, CurveError>

Flat curve at a single rate quoted in compounding.

Examples found in repository?
examples/local_vol_calibration.rs (line 85)
34fn main() {
35    common::title("LOCAL VOLATILITY — quotes -> implied surface -> Dupire -> reprice");
36
37    let maturities = [
38        (NaiveDate::from_ymd_opt(2026, 7, 2).unwrap(), 0.23),
39        (NaiveDate::from_ymd_opt(2027, 1, 1).unwrap(), 0.25),
40    ];
41
42    common::section("Step 1: generate market quotes from a known skew");
43    println!("  sigma(K, T) = base(T) - 0.001 * (K - 100)");
44    let mut quotes = Vec::new();
45    for (maturity, base_vol) in maturities {
46        let t = (maturity - asof()).num_days() as f64 / 365.0;
47        for i in 0..13 {
48            let strike = 70.0 + 5.0 * i as f64;
49            let vol = true_vol(strike, base_vol);
50            let price = bs_price(SPOT, strike, RATE, 0.0, vol, t, PutOrCall::Call);
51            let mut option = EquityOptionBuilder::new()
52                .spot(SPOT)
53                .strike(strike)
54                .flat_vol(0.2) // placeholder: the solve does not use it
55                .flat_rate(RATE)
56                .valuation_date(asof())
57                .maturity_date(maturity)
58                .vanilla(PutOrCall::Call)
59                .build();
60            option.base.current_price = Quote::new(price);
61            quotes.push(Box::new(option));
62        }
63    }
64    println!("  {} quotes across {} expiries", quotes.len(), maturities.len());
65
66    common::section("Step 2: back out implied vols and build the surface");
67    let surface = build_implied_vol_surface(&quotes).expect("calibration failed");
68    println!("{surface}");
69
70    common::section("Step 3: check the surface recovers the input smile");
71    for (t, base_vol) in [(182.0 / 365.0, 0.23), (1.0, 0.25)] {
72        for strike in [70.0, 85.0, 100.0, 115.0, 130.0] {
73            let recovered = surface.vol(strike, SPOT, t);
74            common::check(
75                &format!("T={t:.3} K={strike}"),
76                recovered,
77                true_vol(strike, base_vol),
78                1e-6,
79            );
80        }
81    }
82
83    common::section("Step 4: Dupire local volatility from that surface");
84    let curve =
85        YieldCurve::flat(RATE, asof(), DayCountConvention::Act365, Compounding::Continuous).unwrap();
86    let lv = LocalVol::new(&surface, &curve, SPOT, 0.0, 0.0);
87    println!("  {:>8} {:>12} {:>12} {:>12}", "level", "t=0.25", "t=0.50", "t=1.00");
88    for level in [70.0, 85.0, 100.0, 115.0, 130.0] {
89        println!(
90            "  {level:>8.1} {:>12.4} {:>12.4} {:>12.4}",
91            lv.vol(level, 0.25),
92            lv.vol(level, 0.50),
93            lv.vol(level, 1.00)
94        );
95    }
96    common::note("local vol is steeper in strike than implied vol (the 'twice the slope' rule)");
97    common::note("the far wings are noisy: Dupire takes numerical derivatives of a");
98    common::note("piecewise-linear surface with flat extrapolation — trust the interior.");
99
100    common::section("Step 5: reprice the calibrating vanillas through local vol MC");
101    common::table_header();
102    for strike in [90.0, 100.0, 110.0] {
103        let expected = bs_price(SPOT, strike, RATE, 0.0, true_vol(strike, 0.25), 1.0, PutOrCall::Call);
104        common::row(
105            &format!("local vol MC, K={strike}"),
106            &EquityOptionBuilder::new()
107                .spot(SPOT)
108                .strike(strike)
109                .vol_surface(surface.clone())
110                .flat_rate(RATE)
111                .valuation_date(asof())
112                .maturity_date(NaiveDate::from_ymd_opt(2027, 1, 1).unwrap())
113                .vanilla(PutOrCall::Call)
114                .engine(Engine::MonteCarlo)
115                .model(McModel::LocalVol)
116                .paths(50_000)
117                .build(),
118        );
119        println!("{:<34} {expected:>12.6}  <- Black-Scholes target at the quoted smile vol", "");
120    }
121
122    common::section("Local vol on the finite difference engine (no sampling noise)");
123    common::table_header();
124    for strike in [90.0, 100.0, 110.0] {
125        common::row(
126            &format!("local vol FD, K={strike}"),
127            &EquityOptionBuilder::new()
128                .spot(SPOT)
129                .strike(strike)
130                .vol_surface(surface.clone())
131                .flat_rate(RATE)
132                .valuation_date(asof())
133                .maturity_date(NaiveDate::from_ymd_opt(2027, 1, 1).unwrap())
134                .vanilla(PutOrCall::Call)
135                .engine(Engine::FiniteDifference)
136                .model(McModel::LocalVol)
137                .build(),
138        );
139    }
140
141    common::section("Sanity: a flat surface must give flat local vol");
142    let flat = VolSurface::flat(0.25, asof(), DayCountConvention::Act365).unwrap();
143    let flat_lv = LocalVol::new(&flat, &curve, SPOT, 0.0, 0.0);
144    for (level, t) in [(70.0, 0.25), (100.0, 1.0), (130.0, 2.0)] {
145        common::check(&format!("sigma_loc({level}, {t})"), flat_lv.vol(level, t), 0.25, 1e-6);
146    }
147
148    common::section("Term structure: local vol is the forward variance");
149    let term = VolSurface::from_strike_smiles(
150        &[Tenor::YearFraction(0.5), Tenor::YearFraction(1.0)],
151        &[vec![(100.0, 0.20)], vec![(100.0, 0.25)]],
152        asof(),
153        DayCountConvention::Act365,
154    )
155    .unwrap();
156    let term_lv = LocalVol::new(&term, &curve, SPOT, 0.0, 0.0);
157    // (0.25^2 * 1 - 0.20^2 * 0.5) / 0.5 = 0.085
158    common::check(
159        "sigma_loc between pillars = sqrt(fwd variance)",
160        term_lv.vol(100.0, 0.75),
161        0.085_f64.sqrt(),
162        1e-3,
163    );
164    println!();
165}
Source

pub fn from_zero_rates( tenors: &[Tenor], rates: &[f64], reference_date: NaiveDate, day_count: DayCountConvention, compounding: Compounding, interpolation: InterpolationMethod, ) -> Result<Self, CurveError>

Curve from zero rates quoted in compounding.

Source

pub fn from_discount_factors( tenors: &[Tenor], dfs: &[f64], reference_date: NaiveDate, day_count: DayCountConvention, compounding: Compounding, interpolation: InterpolationMethod, ) -> Result<Self, CurveError>

Curve directly from discount factors.

Source

pub fn from_forward_rates( tenors: &[Tenor], forwards: &[f64], reference_date: NaiveDate, day_count: DayCountConvention, compounding: Compounding, interpolation: InterpolationMethod, ) -> Result<Self, CurveError>

Curve from forward rates: forwards[i] applies between tenor i-1 (or the reference date for i = 0) and tenor i, quoted in compounding.

Source

pub fn from_input( input: &CurveInput, reference_date: NaiveDate, ) -> Result<Self, CurveError>

Build from a deserialized CurveInput, anchored at reference_date.

Source

pub fn df(&self, t: f64) -> f64

Discount factor at year fraction t from the reference date. t <= 0 returns 1.0; beyond the last pillar the last continuously compounded zero rate is extrapolated flat.

Source

pub fn df_date(&self, date: NaiveDate) -> f64

Discount factor at an absolute date (via the curve’s day count).

Source

pub fn zero_rate(&self, t: f64) -> f64

Zero rate at t in the curve’s quoting convention.

Source

pub fn zero_rate_with(&self, t: f64, compounding: Compounding) -> f64

Zero rate at t in an explicit convention.

Source

pub fn forward_rate(&self, t1: f64, t2: f64) -> Result<f64, CurveError>

Forward rate between t1 and t2 in the curve’s quoting convention.

Source

pub fn forward_rate_with( &self, t1: f64, t2: f64, compounding: Compounding, ) -> Result<f64, CurveError>

Forward rate between t1 and t2 in an explicit convention (Simple gives the FRA-style forward).

Source

pub fn reference_date(&self) -> NaiveDate

Source

pub fn day_count(&self) -> DayCountConvention

Source

pub fn compounding(&self) -> Compounding

Source

pub fn pillars(&self) -> Vec<CurvePillar>

The curve’s pillars (excluding the synthetic t=0 node) with derived continuously compounded zero rates — for inspection and display; always computed fresh from the stored dfs so it cannot disagree with what df(t) returns.

Trait Implementations§

Source§

impl Clone for YieldCurve

Source§

fn clone(&self) -> YieldCurve

Returns a duplicate of the value. Read more
1.0.0 (const: unstable) · Source§

fn clone_from(&mut self, source: &Self)

Performs copy-assignment from source. Read more
Source§

impl Debug for YieldCurve

Source§

fn fmt(&self, f: &mut Formatter<'_>) -> Result

Formats the value using the given formatter. Read more
Source§

impl Display for YieldCurve

Source§

fn fmt(&self, f: &mut Formatter<'_>) -> Result

Formats the value using the given formatter. Read more
Source§

impl Serialize for YieldCurve

Source§

fn serialize<__S>(&self, __serializer: __S) -> Result<__S::Ok, __S::Error>
where __S: Serializer,

Serialize this value into the given Serde serializer. Read more

Auto Trait Implementations§

Blanket Implementations§

Source§

impl<T> Any for T
where T: 'static + ?Sized,

Source§

fn type_id(&self) -> TypeId

Gets the TypeId of self. Read more
Source§

impl<T> Borrow<T> for T
where T: ?Sized,

Source§

fn borrow(&self) -> &T

Immutably borrows from an owned value. Read more
Source§

impl<T> BorrowMut<T> for T
where T: ?Sized,

Source§

fn borrow_mut(&mut self) -> &mut T

Mutably borrows from an owned value. Read more
Source§

impl<T> CloneToUninit for T
where T: Clone,

Source§

unsafe fn clone_to_uninit(&self, dest: *mut u8)

🔬This is a nightly-only experimental API. (clone_to_uninit)
Performs copy-assignment from self to dest. Read more
Source§

impl<T> From<T> for T

Source§

fn from(t: T) -> T

Returns the argument unchanged.

Source§

impl<T, U> Into<U> for T
where U: From<T>,

Source§

fn into(self) -> U

Calls U::from(self).

That is, this conversion is whatever the implementation of From<T> for U chooses to do.

Source§

impl<T> Pointable for T

Source§

const ALIGN: usize

The alignment of pointer.
Source§

type Init = T

The type for initializers.
Source§

unsafe fn init(init: <T as Pointable>::Init) -> usize

Initializes a with the given initializer. Read more
Source§

unsafe fn deref<'a>(ptr: usize) -> &'a T

Dereferences the given pointer. Read more
Source§

unsafe fn deref_mut<'a>(ptr: usize) -> &'a mut T

Mutably dereferences the given pointer. Read more
Source§

unsafe fn drop(ptr: usize)

Drops the object pointed to by the given pointer. Read more
Source§

impl<T> ToOwned for T
where T: Clone,

Source§

type Owned = T

The resulting type after obtaining ownership.
Source§

fn to_owned(&self) -> T

Creates owned data from borrowed data, usually by cloning. Read more
Source§

fn clone_into(&self, target: &mut T)

Uses borrowed data to replace owned data, usually by cloning. Read more
Source§

impl<T> ToString for T
where T: Display + ?Sized,

Source§

fn to_string(&self) -> String

Converts the given value to a String. Read more
Source§

impl<T, U> TryFrom<U> for T
where U: Into<T>,

Source§

type Error = Infallible

The type returned in the event of a conversion error.
Source§

fn try_from(value: U) -> Result<T, <T as TryFrom<U>>::Error>

Performs the conversion.
Source§

impl<T, U> TryInto<U> for T
where U: TryFrom<T>,

Source§

type Error = <U as TryFrom<T>>::Error

The type returned in the event of a conversion error.
Source§

fn try_into(self) -> Result<U, <U as TryFrom<T>>::Error>

Performs the conversion.
Source§

impl<V, T> VZip<V> for T
where V: MultiLane<T>,

Source§

fn vzip(self) -> V