### Test helper functions for market setup Source: https://docs.rs/RustyQLib/latest/src/rustyqlib/core/market.rs.html?search= Provides helper functions to create a sample market with a flat yield curve, volatility surface, and spot quotes. Used across tests for consistent setup. ```rust fn date() -> NaiveDate { NaiveDate::from_ymd_opt(2026, 1, 5).unwrap() } ``` ```rust fn shock(factor: RiskFactor, mode: BumpMode, size: f64) -> Shock { Shock { factor, mode, size, underlying: None, tenors: None, shifts: None } } ``` ```rust fn sample_market() -> Market { let curve = YieldCurve::flat(0.03, date(), DayCountConvention::Act365, Compounding::Continuous) .expect("curve must build"); let surf = VolSurface::flat(0.25, date(), DayCountConvention::Act365).expect("surface"); Market::new(date()) .with(Spot("ACME".into()), Quote::new(100.0)) .with(Spot("ZENO".into()), Quote::new(50.0)) .with(Vol("ACME".into()), Arc::new(surf)) .with(Discount("USD".into()), Arc::new(curve)) } ``` -------------------------------- ### Search Examples Source: https://docs.rs/RustyQLib/latest/src/rustyqlib/core/results.rs.html?search= Example searches for the search functionality. ```text std::vec ``` ```text u32 -> bool ``` ```text Option, (T -> U) -> Option ``` -------------------------------- ### into_ok example Source: https://docs.rs/RustyQLib/latest/rustyqlib/core/errors/type.Result.html?search=std%3A%3Avec Shows how into_ok returns the contained Ok value without panicking, for Result types where the error type is !. The example defines a function that returns Result and uses into_ok to get the string. ```rust fn only_good_news() -> Result { Ok("this is fine".into()) } let s: String = only_good_news().into_ok(); println!("{s}"); ``` -------------------------------- ### Construct EquityOption with EquityOptionBuilder Source: https://docs.rs/RustyQLib/latest/rustyqlib/equity/builder/index.html Builds an `EquityOption` using the builder pattern with spot, strike, volatility, rate, maturity, option type, and engine. The example prints the net present value (NPV) of the option. Requires the `rustyqlib` crate and the listed imports. ```rust use rustyqlib::equity::builder::EquityOptionBuilder; use rustyqlib::equity::utils::Engine; use rustyqlib::core::trade::PutOrCall; use rustyqlib::Instrument; let option = EquityOptionBuilder::new() .spot(100.0) .strike(100.0) .flat_vol(0.30) .flat_rate(0.05) .years_to_maturity(1.0) .vanilla(PutOrCall::Call) .engine(Engine::BlackScholes) .build().expect("option must build"); println!("{}", option.npv()); ``` -------------------------------- ### into_err example Source: https://docs.rs/RustyQLib/latest/rustyqlib/core/errors/type.Result.html?search=std%3A%3Avec Shows how into_err returns the contained Err value without panicking, for Result types where the Ok type is !. The example defines a function that returns Result and uses into_err to get the error string. ```rust fn only_bad_news() -> Result { Err("Oops, it failed".into()) } let error: String = only_bad_news().into_err(); println!("{error}"); ``` -------------------------------- ### PricingEngine::from_kind Source: https://docs.rs/RustyQLib/latest/rustyqlib/equity/utils/enum.PricingEngine.html?search=Option%3CT%3E%2C+%28T+-%3E+U%29+-%3E+Option%3CU%3E Builds a PricingEngine from a selector with default per-engine configuration. ```APIDOC ## PricingEngine::from_kind ### Description Builds a PricingEngine from a selector with default per-engine configuration. ### Method `pub fn from_kind(kind: Engine) -> PricingEngine` ### Parameters - `kind` (Engine) - The engine selector. ### Returns - `PricingEngine` - The constructed PricingEngine with default configuration. ``` -------------------------------- ### Tape::new Source: https://docs.rs/RustyQLib/latest/rustyqlib/core/aad/tape/struct.Tape.html?search=std%3A%3Avec Creates a new Tape instance. ```APIDOC ## Tape::new ### Description Creates a new `Tape` instance for recording a differentiated computation. ### Method `pub fn new() -> Tape` ### Parameters None ### Returns - `Tape` - A new empty tape. ### Example ```rust let tape = Tape::new(); ``` ``` -------------------------------- ### unwrap basic usage Source: https://docs.rs/RustyQLib/latest/rustyqlib/core/errors/type.Result.html?search=std%3A%3Avec Shows how to use unwrap on an Ok value to get the contained value. The example asserts that unwrap returns 2. ```rust let x: Result = Ok(2); assert_eq!(x.unwrap(), 2); ``` -------------------------------- ### Tape::new Source: https://docs.rs/RustyQLib/latest/rustyqlib/core/aad/tape/struct.Tape.html?search=u32+-%3E+bool Creates a new Tape instance. ```APIDOC ## Tape::new ### Description Creates a new Tape instance. ### Method new ### Signature pub fn new() -> Tape ### Parameters None ### Returns - **Tape** - A new Tape instance. ### Example ```rust let tape = Tape::new(); ``` ``` -------------------------------- ### iter example: iterating over Ok value Source: https://docs.rs/RustyQLib/latest/rustyqlib/core/errors/type.Result.html?search=std%3A%3Avec Shows how to use iter to get an iterator over the possibly contained value. Yields one value if Ok, otherwise none. ```rust let x: Result = Ok(7); assert_eq!(x.iter().next(), Some(&7)); let x: Result = Err("nothing!"); assert_eq!(x.iter().next(), None); ``` -------------------------------- ### iter_mut example: mutably iterating over Ok value Source: https://docs.rs/RustyQLib/latest/rustyqlib/core/errors/type.Result.html?search=std%3A%3Avec Shows how to use iter_mut to get a mutable iterator over the possibly contained value. Yields one value if Ok, otherwise none. ```rust let mut x: Result = Ok(7); match x.iter_mut().next() { Some(v) => *v = 40, None => {}, } assert_eq!(x, Ok(40)); let mut x: Result = Err("nothing!"); assert_eq!(x.iter_mut().next(), None); ``` -------------------------------- ### with Source: https://docs.rs/RustyQLib/latest/rustyqlib/core/market/struct.Market.html?search=u32+-%3E+bool Chainable insert, for building markets by hand. ```APIDOC ## with ### Description Chainable insert, for building markets by hand. ### Method Builder method ### Parameters - **key** (K) - Required - The key under which to store the value. - **value** (K::Value) - Required - The value to store. ### Returns - **Market** - The updated Market. ``` -------------------------------- ### pub fn from_data(data: &EquityOptionData) -> Self Source: https://docs.rs/RustyQLib/latest/rustyqlib/equity/finite_difference/struct.FdConfig.html?search=u32+-%3E+bool Constructs an FdConfig instance from equity option data. This is a direct method users can call to initialize configuration based on market data. ```APIDOC ## from_data(data: &EquityOptionData) -> Self ### Description Constructs an FdConfig from the provided EquityOptionData. This is a direct method users can call. ### Method from_data ### Signature pub fn from_data(data: &EquityOptionData) -> Self ### Parameters - **data** (&EquityOptionData) - Required - The equity option data used to initialize the configuration. ### Returns - **Self** - A new FdConfig instance. ### Example ```rust let config = FdConfig::from_data(&data); ``` ``` -------------------------------- ### Direct Newton-Raphson call on Solver1d Source: https://docs.rs/RustyQLib/latest/rustyqlib/core/solvers/index.html Use this when the method is fixed at the call site. `Solver1d` carries convergence settings and each method is a call on it. The example solves `x^2 - 2 = 0` starting from 1.0 and asserts convergence and accuracy to 1e-12. ```rust use rustyqlib::core::solvers::Solver1d; let root = Solver1d::default() .newton_raphson(|x| x * x - 2.0, |x| 2.0 * x, 1.0); assert!(root.converged && (root.x - 2.0_f64.sqrt()).abs() < 1e-12); ``` -------------------------------- ### as_mut: Mutate Result contents in place Source: https://docs.rs/RustyQLib/latest/rustyqlib/core/errors/type.Result.html?search=std%3A%3Avec Demonstrates `Result::as_mut` to get mutable references to the contained `Ok` or `Err` value, allowing in-place mutation. The example defines a helper function that modifies the value based on the variant. ```rust fn mutate(r: &mut Result) { match r.as_mut() { Ok(v) => *v = 42, Err(e) => *e = 0, } } let mut x: Result = Ok(2); mutate(&mut x); assert_eq!(x.unwrap(), 42); let mut x: Result = Err(13); mutate(&mut x); assert_eq!(x.unwrap_err(), 0); ``` -------------------------------- ### EquityOptionBuilder::new().spot().strike().flat_vol().flat_rate().years_to_maturity().vanilla().engine().build() Source: https://docs.rs/RustyQLib/latest/rustyqlib/equity/builder/index.html?search=std%3A%3Avec Constructs an EquityOption using the builder pattern. Users can chain methods to set spot price, strike price, flat volatility, flat rate, years to maturity, option type (PutOrCall), and pricing engine (Engine), then call build() to create the option. ```APIDOC ## EquityOptionBuilder ### Description Ergonomic construction of `EquityOption` from Rust code. The builder is the equivalent for library users of the JSON path interface used by the CLI. ### Usage Example ```rust use rustyqlib::equity::builder::EquityOptionBuilder; use rustyqlib::equity::utils::Engine; use rustyqlib::core::trade::PutOrCall; use rustyqlib::Instrument; let option = EquityOptionBuilder::new() .spot(100.0) .strike(100.0) .flat_vol(0.30) .flat_rate(0.05) .years_to_maturity(1.0) .vanilla(PutOrCall::Call) .engine(Engine::BlackScholes) .build().expect("option must build"); println!("{}", option.npv()); ``` ### Methods #### new() Creates a new builder instance. #### spot(value: f64) Sets the spot price of the underlying asset. #### strike(value: f64) Sets the strike price of the option. #### flat_vol(value: f64) Sets a flat volatility value. #### flat_rate(value: f64) Sets a flat risk-free interest rate. #### years_to_maturity(value: f64) Sets the time to maturity in years. #### vanilla(put_or_call: PutOrCall) Sets the option type (call or put). #### engine(engine: Engine) Sets the pricing engine (e.g., BlackScholes). #### build() -> Result Builds the `EquityOption` instance. Returns an error if the option cannot be built. ``` -------------------------------- ### pub fn from_data(data: &EquityOptionData) -> Self Source: https://docs.rs/RustyQLib/latest/rustyqlib/equity/finite_difference/struct.FdConfig.html Constructs an FdConfig from an EquityOptionData reference. ```APIDOC ## pub fn from_data(data: &EquityOptionData) -> Self ### Description Constructs an FdConfig from an EquityOptionData reference. ### Method from_data ### Parameters - **data** (&EquityOptionData) - Required - The equity option data used to construct the configuration. ### Returns - **Self** - A new FdConfig instance. ``` -------------------------------- ### pub fn from_data(data: &EquityOptionData) -> Self Source: https://docs.rs/RustyQLib/latest/rustyqlib/equity/finite_difference/struct.FdConfig.html?search=Option%3CT%3E%2C+%28T+-%3E+U%29+-%3E+Option%3CU%3E Constructs an FdConfig from an EquityOptionData reference. ```APIDOC ## Method: from_data ### Description Creates a new `FdConfig` instance based on the provided `EquityOptionData`. This method is used to derive grid configuration parameters from option data. ### Signature ```rust pub fn from_data(data: &EquityOptionData) -> Self ``` ### Parameters - **data** (`&EquityOptionData`) - A reference to the equity option data used to construct the configuration. ### Returns - **Self** - A new `FdConfig` instance. ### Example ```rust let config = FdConfig::from_data(&option_data); ``` ``` -------------------------------- ### pub fn year_fraction(&self, start: NaiveDate, end: NaiveDate) -> f64 Source: https://docs.rs/RustyQLib/latest/rustyqlib/core/daycount/enum.DayCountConvention.html?search=std%3A%3Avec Computes the year fraction from start to end under the given day count convention. Returns a negative value if end is before start. ```APIDOC ## pub fn year_fraction(&self, start: NaiveDate, end: NaiveDate) -> f64 ### Description Computes the year fraction from `start` to `end` under this convention. Negative if `end` is before `start`. ### Method `year_fraction` ### Parameters - **start** (`NaiveDate`) - Required - The start date. - **end** (`NaiveDate`) - Required - The end date. ### Returns - **f64** - The year fraction between the two dates. ``` -------------------------------- ### is_err() example Source: https://docs.rs/RustyQLib/latest/rustyqlib/core/errors/type.Result.html?search=std%3A%3Avec Example for the is_err method. It returns true if the result is Err, false otherwise. ```rust let x: Result = Ok(-3); assert_eq!(x.is_err(), false); let x: Result = Err("Some error message"); assert_eq!(x.is_err(), true); ``` -------------------------------- ### pub fn from_kind(kind: Engine) -> PricingEngine Source: https://docs.rs/RustyQLib/latest/rustyqlib/equity/utils/enum.PricingEngine.html?search= Builds a PricingEngine from an Engine selector, using default per-engine configuration. This is a convenient way to create a pricing engine when you only have the engine kind. ```APIDOC ## pub fn from_kind(kind: Engine) -> PricingEngine ### Description Builds a PricingEngine from an Engine selector, using default per-engine configuration. ### Method from_kind ### Parameters - **kind** (Engine) - The engine selector. ### Returns - **PricingEngine** - A PricingEngine with default configuration for the given kind. ### Example ```rust let engine = PricingEngine::from_kind(Engine::BlackScholes); ``` ``` -------------------------------- ### is_ok() example Source: https://docs.rs/RustyQLib/latest/rustyqlib/core/errors/type.Result.html?search=std%3A%3Avec Example for the is_ok method. It returns true if the result is Ok, false otherwise. ```rust let x: Result = Ok(-3); assert_eq!(x.is_ok(), true); let x: Result = Err("Some error message"); assert_eq!(x.is_ok(), false); ``` -------------------------------- ### Test module setup with constants Source: https://docs.rs/RustyQLib/latest/src/rustyqlib/equity/lookback.rs.html?search=std%3A%3Avec This snippet sets up the test module, importing super::* and blackscholes::bs_price, and defines option pricing constants: S, R, Q, SIG, T. These constants are used throughout the subsequent tests. ```Rust #[cfg(test)] mod tests { use super::*; use crate::equity::blackscholes::bs_price; const S: f64 = 100.0; const R: f64 = 0.05; const Q: f64 = 0.02; const SIG: f64 = 0.3; const T: f64 = 1.0; ``` -------------------------------- ### DayCountConvention::year_fraction Source: https://docs.rs/RustyQLib/latest/rustyqlib/core/daycount/enum.DayCountConvention.html?search=u32+-%3E+bool Computes the year fraction from start to end under this convention. Returns a negative value if end is before start. ```APIDOC ## DayCountConvention::year_fraction ### Description Computes the year fraction from `start` to `end` under this convention. Negative if `end` is before `start`. ### Method `pub fn year_fraction(&self, start: NaiveDate, end: NaiveDate) -> f64` ### Parameters - **start** (NaiveDate) - Required - The start date. - **end** (NaiveDate) - Required - The end date. ### Return Value - **f64** - The year fraction between the two dates under the convention. Negative if `end` is before `start`. ### Example ```rust use rustyqlib::core::daycount::DayCountConvention; use chrono::NaiveDate; let start = NaiveDate::from_ymd(2023, 1, 1); let end = NaiveDate::from_ymd(2023, 1, 2); let convention = DayCountConvention::Act365; let fraction = convention.year_fraction(start, end); ``` ``` -------------------------------- ### PricingEngine::from_kind Source: https://docs.rs/RustyQLib/latest/rustyqlib/equity/utils/enum.PricingEngine.html?search=u32+-%3E+bool Builds a PricingEngine from an Engine selector with default per-engine configuration. This allows users to create an engine instance by specifying only the engine type and automatically receive the appropriate default configuration. ```APIDOC ## from_kind ### Description Builds a PricingEngine from an Engine selector with default per-engine configuration. ### Function Signature pub fn from_kind(kind: Engine) -> PricingEngine ### Parameters - **kind** (Engine) - Required - The engine selector specifying the type of pricing engine. ### Returns - **PricingEngine** - A PricingEngine instance with the given engine type and its default configuration. ### Example ```rust let engine = PricingEngine::from_kind(Engine::Binomial); ``` ``` -------------------------------- ### DayCountConvention::year_fraction Source: https://docs.rs/RustyQLib/latest/rustyqlib/core/daycount/enum.DayCountConvention.html?search=Option%3CT%3E%2C+%28T+-%3E+U%29+-%3E+Option%3CU%3E Computes the year fraction from a start date to an end date under this convention. Returns a negative value if the end date is before the start date. ```APIDOC ## DayCountConvention::year_fraction ### Description Computes the year fraction from `start` to `end` under this convention. Returns a negative value if `end` is before `start`. ### Method `pub fn year_fraction(&self, start: NaiveDate, end: NaiveDate) -> f64` ### Parameters - `start` (NaiveDate) - Start date. - `end` (NaiveDate) - End date. ### Return Value - `f64` - Year fraction between the two dates. Negative if `end` is before `start`. ### Example Usage ```rust use rustyqlib::core::daycount::DayCountConvention; use chrono::NaiveDate; let convention = DayCountConvention::Act365; let start = NaiveDate::from_ymd(2023, 1, 1); let end = NaiveDate::from_ymd(2023, 1, 2); let frac = convention.year_fraction(start, end); ``` ``` -------------------------------- ### unwrap_or_default example Source: https://docs.rs/RustyQLib/latest/rustyqlib/core/errors/type.Result.html?search=std%3A%3Avec Shows how unwrap_or_default returns the contained Ok value or a default value for the type. The example parses strings to integers, turning poorly-formed strings into 0. ```rust let good_year_from_input = "1909"; let bad_year_from_input = "190blarg"; let good_year = good_year_from_input.parse().unwrap_or_default(); let bad_year = bad_year_from_input.parse().unwrap_or_default(); assert_eq!(1909, good_year); assert_eq!(0, bad_year); ``` -------------------------------- ### Forward-start option helper and Monte Carlo test Source: https://docs.rs/RustyQLib/latest/src/rustyqlib/equity/blackscholes.rs.html?search= Defines a helper to build a forward-start option and a test that compares the analytic NPV to a Monte Carlo simulation with 50,000 paths. ```rust fn forward_start_option(pc: PutOrCall) -> EquityOption { test_option_with( Box::new(crate::equity::forward_start_option::ForwardStartPayoff { put_or_call: pc, exercise_style: ContractStyle::European, strike_fraction: 1.0, start_fraction: 0.5, }), flat_5pct(), ) } ``` ```rust #[test] fn forward_start_analytic_matches_monte_carlo() { let analytic = forward_start_option(PutOrCall::Call).npv(); let mut mc = forward_start_option(PutOrCall::Call); mc.engine = crate::equity::utils::PricingEngine::from_kind(Engine::MonteCarlo); mc.mc_cfg_mut().paths = 50_000; } ``` -------------------------------- ### ForwardStartPayoff struct Source: https://docs.rs/RustyQLib/latest/rustyqlib/equity/forward_start_option/struct.ForwardStartPayoff.html?search=Option%3CT%3E%2C+%28T+-%3E+U%29+-%3E+Option%3CU%3E The ForwardStartPayoff struct represents the payoff of a forward start option. It contains fields for put/call type, exercise style, strike fraction, and start fraction. ```APIDOC ## Struct ForwardStartPayoff ### Description Represents the payoff of a forward start option. ### Fields - `put_or_call: PutOrCall` - The option type (put or call). - `exercise_style: ContractStyle` - The exercise style (e.g., European, American). - `strike_fraction: f64` - Strike as a fraction of the spot on the fixing date (1.0 = at the money). - `start_fraction: f64` - Fixing time as a fraction of the option life, in (0, 1). ### Trait Implementations #### `impl Clone for ForwardStartPayoff` - `fn clone(&self) -> ForwardStartPayoff` - Returns a duplicate of the value. - `fn clone_from(&mut self, source: &Self)` - Performs copy-assignment from `source`. #### `impl Debug for ForwardStartPayoff` - `fn fmt(&self, f: &mut Formatter<'_>) -> Result` - Formats the value using the given formatter. #### `impl Payoff for ForwardStartPayoff` - `fn payoff(&self, _spot: f64, _strike: f64) -> f64` - Degenerate single-point value (strike not yet fixed): zero. - `fn path_payoff(&self, path: &[f64], _strike: f64) -> f64` - Payoff for a full simulated path (used by Monte Carlo). Terminal payoffs default to the last point; Asian/Barrier override this. The path excludes the initial spot (it starts at the first step). - `fn path_payoff_var<'t>(&self, path: &[Var<'t>], _strike: f64) -> Option>` - Path payoff in AAD arithmetic — the mirror of `path_payoff` over tape variables, used by the adjoint Monte Carlo Greeks (`montecarlo::aad_greeks`). `None` (the default) opts a payoff out: **discontinuous payoffs (barrier, binary, autocallable) must stay out** , because the almost-everywhere derivative of an indicator is zero — their Greeks come from the bump stencils instead. - `fn is_path_dependent(&self) -> bool` - True when the payoff depends on the whole path (Asian, Barrier), so engines must simulate paths rather than terminal values. - `fn payoff_kind(&self) -> PayoffType` - Returns the type of payoff. - `fn put_or_call(&self) -> &PutOrCall` - Returns a reference to the put/call type. - `fn exercise_style(&self) -> &ContractStyle` - Returns a reference to the exercise style. - `fn as_any(&self) -> &dyn Any` - Downcast hook so pricers that need payoff-specific details (e.g. the analytic pricer distinguishing cash- from asset-or-nothing binaries) can recover the concrete payoff type. - `fn clone_box(&self) -> Box` - Clone through the trait object, so instruments holding a `Box` are cloneable (repricing a contract under another market clones the instrument). Implementors write `Box::new(self.clone())`. - `fn payoff_amount(&self, spot: f64, strike: f64) -> f64` - Intrinsic value at the given spot (the option’s current market spot at its contract strike). ``` -------------------------------- ### Build a forward-start option Source: https://docs.rs/RustyQLib/latest/src/rustyqlib/equity/blackscholes.rs.html Helper function that constructs a forward-start option with a strike fraction of 1.0 and start fraction of 0.5, using the flat 5% rate environment. ```rust fn forward_start_option(pc: PutOrCall) -> EquityOption { test_option_with( Box::new(crate::equity::forward_start_option::ForwardStartPayoff { put_or_call: pc, exercise_style: ContractStyle::European, strike_fraction: 1.0, start_fraction: 0.5, }), flat_5pct(), ) } ``` -------------------------------- ### Forward-start option pricing and Greeks with Rubinstein closed form Source: https://docs.rs/RustyQLib/latest/src/rustyqlib/equity/blackscholes.rs.html Implements forward-start option pricing and Greeks using the Rubinstein closed form under GBM. The helper forward_start_price_with applies finite-difference perturbations to spot, volatility, rate, and time-to-maturity; npv_forward_start calls it with zero shifts, while delta, gamma, vega, theta, and rho use central differences with the specified step sizes. ```rust fn forward_start_price_with( bsd_option: &EquityOption, ds: f64, dsigma: f64, dr: f64, dt_shift: f64, ) -> f64 { let payoff = bsd_option .payoff .as_any() .downcast_ref::() .expect("payoff of kind ForwardStart must be a ForwardStartPayoff"); let t = bsd_option.time_to_maturity() + dt_shift; crate::equity::forward_start_option::forward_start_price( bsd_option.effective_spot() + ds, payoff.strike_fraction, bsd_option.risk_free_rate() + dr, bsd_option.carry_yield(), bsd_option.volatility() + dsigma, payoff.start_fraction * t, t, *bsd_option.payoff.put_or_call(), ) } ``` ```rust fn npv_forward_start(&self, bsd_option: &EquityOption) -> f64 { Self::forward_start_price_with(bsd_option, 0.0, 0.0, 0.0, 0.0) } ``` ```rust fn delta_forward_start(&self, bsd_option: &EquityOption) -> f64 { let h = bsd_option.market.spot.value() * 1e-4; (Self::forward_start_price_with(bsd_option, h, 0.0, 0.0, 0.0) - Self::forward_start_price_with(bsd_option, -h, 0.0, 0.0, 0.0)) / (2.0 * h) } ``` ```rust fn gamma_forward_start(&self, bsd_option: &EquityOption) -> f64 { let h = bsd_option.market.spot.value() * 1e-3; (Self::forward_start_price_with(bsd_option, h, 0.0, 0.0, 0.0) - 2.0 * Self::forward_start_price_with(bsd_option, 0.0, 0.0, 0.0, 0.0) + Self::forward_start_price_with(bsd_option, -h, 0.0, 0.0, 0.0)) / (h * h) } ``` ```rust fn vega_forward_start(&self, bsd_option: &EquityOption) -> f64 { let h = 1e-4; (Self::forward_start_price_with(bsd_option, 0.0, h, 0.0, 0.0) - Self::forward_start_price_with(bsd_option, 0.0, -h, 0.0, 0.0)) / (2.0 * h) } ``` ```rust fn theta_forward_start(&self, bsd_option: &EquityOption) -> f64 { let h = (1.0 / 365.0_f64).min(0.25 * bsd_option.time_to_maturity()); -(Self::forward_start_price_with(bsd_option, 0.0, 0.0, 0.0, h) - Self::forward_start_price_with(bsd_option, 0.0, 0.0, 0.0, -h)) / (2.0 * h) } ``` ```rust fn rho_forward_start(&self, bsd_option: &EquityOption) -> f64 { let h = 1e-5; (Self::forward_start_price_with(bsd_option, 0.0, 0.0, h, 0.0) - Self::forward_start_price_with(bsd_option, 0.0, 0.0, -h, 0.0)) / (2.0 * h) } ``` -------------------------------- ### and method examples Source: https://docs.rs/RustyQLib/latest/rustyqlib/core/errors/type.Result.html?search=std%3A%3Avec Shows how the and method returns res if the result is Ok, otherwise returns the Err value of self. The examples cover various combinations of Ok and Err values. ```rust let x: Result = Ok(2); let y: Result<&str, &str> = Err("late error"); assert_eq!(x.and(y), Err("late error")); let x: Result = Err("early error"); let y: Result<&str, &str> = Ok("foo"); assert_eq!(x.and(y), Err("early error")); let x: Result = Err("not a 2"); let y: Result<&str, &str> = Err("late error"); assert_eq!(x.and(y), Err("not a 2")); let x: Result = Ok(2); let y: Result<&str, &str> = Ok("different result type"); assert_eq!(x.and(y), Ok("different result type")); ``` -------------------------------- ### is_ok_and() example Source: https://docs.rs/RustyQLib/latest/rustyqlib/core/errors/type.Result.html?search=std%3A%3Avec Example for the is_ok_and method. It returns true if the result is Ok and the value matches a predicate. The last part shows using as_ref() to avoid moving the value. ```rust let x: Result = Ok(2); assert_eq!(x.is_ok_and(|x| x > 1), true); let x: Result = Ok(0); assert_eq!(x.is_ok_and(|x| x > 1), false); let x: Result = Err("hey"); assert_eq!(x.is_ok_and(|x| x > 1), false); let x: Result = Ok("ownership".to_string()); assert_eq!(x.as_ref().is_ok_and(|x| x.len() > 1), true); println!("still alive {:?}", x); ``` -------------------------------- ### PricingEngine::from_kind Source: https://docs.rs/RustyQLib/latest/rustyqlib/equity/utils/enum.PricingEngine.html Builds a PricingEngine from a selector with default per-engine configuration. This is useful for creating an engine instance from a simple enum value. ```APIDOC ## PricingEngine::from_kind ### Description Builds a PricingEngine from a selector with default per-engine configuration. ### Method `pub fn from_kind(kind: Engine) -> PricingEngine` ### Parameters - `kind` (Engine) - Required - The engine selector. ### Returns - `PricingEngine` - A PricingEngine instance with default configuration for the given kind. ``` -------------------------------- ### cloned() on Result<&T, E> example Source: https://docs.rs/RustyQLib/latest/rustyqlib/core/errors/type.Result.html?search=std%3A%3Avec Example for the cloned method on Result<&T, E>. It clones the contents of the Ok part, converting a Result<&i32, i32> to a Result. ```rust let val = 12; let x: Result<&i32, i32> = Ok(&val); assert_eq!(x, Ok(&12)); let cloned = x.cloned(); assert_eq!(cloned, Ok(12)); ``` -------------------------------- ### SpotKernel::new boundary solver Source: https://docs.rs/RustyQLib/latest/src/rustyqlib/equity/baw.rs.html Constructs a SpotKernel by solving the early-exercise boundary under volatility, rate, and maturity shifts. Returns None premium for European or non-positive volatility, and for calls when b >= r. ```rust impl SpotKernel { /// Solve the boundary for this option under (vol, rate, maturity) /// shifts; `d_maturity` extends the maturity (the same convention as /// [`reprice`]). pub(crate) fn new(option: &EquityOption, d_vol: f64, d_rate: f64, d_maturity: f64) -> Self { let k = option.base.strike_price; let r = option.risk_free_rate() + d_rate; let q = option.carry_yield(); let sigma = option.volatility() + d_vol; let t = (option.time_to_maturity() + d_maturity).max(1e-8); let pc = *option.payoff.put_or_call(); let american = matches!(option.payoff.exercise_style(), ContractStyle::American); let b = r - q; let premium = if !american || sigma <= 0.0 { None } else { match pc { // never optimal to exercise a call early when b >= r PutOrCall::Call if b >= r => None, PutOrCall::Call => { let s_star = critical_call(k, r, b, sigma, t); let q2 = quadratic_root(r, b, sigma, t, true); let d1 = d1_of(s_star, k, b, sigma, t); let a2 = (s_star / q2) * (1.0 - ((b - r) * t).exp() * norm_cdf(d1)); Some((s_star, q2, a2)) } PutOrCall::Put => { let s_star = critical_put(k, r, b, sigma, t); let q1 = quadratic_root(r, b, sigma, t, false); let d1 = d1_of(s_star, k, b, sigma, t); let a1 = -(s_star / q1) * (1.0 - ((b - r) * t).exp() * norm_cdf(-d1)); Some((s_star, q1, a1)) } } }; SpotKernel { k, r, q, sigma, t, pc, american, premium } } ``` -------------------------------- ### Market::with(self, key: K, value: K::Value) -> Self Source: https://docs.rs/RustyQLib/latest/rustyqlib/core/market/struct.Market.html Chainable version of insert for building markets by hand. ```APIDOC ## Market::with(self, key: K, value: K::Value) -> Self ### Description Chainable version of insert for building markets by hand. ### Method with ### Parameters - **self** (Self) - Required - The market instance. - **key** (K) - Required - The key identifying the datum. - **value** (K::Value) - Required - The value to store. ### Returns - **Self** - The market with the inserted datum. ``` -------------------------------- ### copied() on Result<&T, E> example Source: https://docs.rs/RustyQLib/latest/rustyqlib/core/errors/type.Result.html?search=std%3A%3Avec Example for the copied method on Result<&T, E>. It copies the contents of the Ok part, converting a Result<&i32, i32> to a Result. ```rust let val = 12; let x: Result<&i32, i32> = Ok(&val); assert_eq!(x, Ok(&12)); let copied = x.copied(); assert_eq!(copied, Ok(12)); ``` -------------------------------- ### DayCountConvention::year_fraction Source: https://docs.rs/RustyQLib/latest/rustyqlib/core/daycount/enum.DayCountConvention.html?search= Computes the year fraction from a start date to an end date under the given day count convention. Returns a negative value if the end date is before the start date. ```APIDOC ## DayCountConvention::year_fraction ### Description Computes the year fraction from `start` to `end` under this convention. Negative if `end` is before `start`. ### Method `pub fn year_fraction(&self, start: NaiveDate, end: NaiveDate) -> f64` ### Parameters - **start** (NaiveDate) - Required - The start date. - **end** (NaiveDate) - Required - The end date. ### Returns - **f64** - The year fraction between the two dates under the convention. Negative if `end` is before `start`. ### Example ```rust use rustyqlib::core::daycount::DayCountConvention; use chrono::NaiveDate; let convention = DayCountConvention::Act365; let start = NaiveDate::from_ymd(2023, 1, 1); let end = NaiveDate::from_ymd(2023, 12, 31); let fraction = convention.year_fraction(start, end); ``` ``` -------------------------------- ### build(self) -> Result Source: https://docs.rs/RustyQLib/latest/rustyqlib/equity/builder/struct.EquityOptionBuilder.html?search=Option%3CT%3E%2C+%28T+-%3E+U%29+-%3E+Option%3CU%3E Validates every input and constructs the option. After a successful build, the option prices without InvalidInput or UnsupportedEngine errors. ```APIDOC ## build(self) -> Result ### Description Validates every input and constructs the option. After a successful build, the option prices without InvalidInput or UnsupportedEngine errors. ### Method Builder method ### Parameters None ### Returns - **Result** - The constructed option or an error if validation fails. ``` -------------------------------- ### DayCountConvention::year_fraction Source: https://docs.rs/RustyQLib/latest/rustyqlib/core/daycount/enum.DayCountConvention.html Computes the year fraction from a start date to an end date under the given day count convention. Returns a negative value if the end date is before the start date. ```APIDOC ## DayCountConvention::year_fraction ### Description Computes the year fraction from `start` to `end` under this convention. Negative if `end` is before `start`. ### Method `pub fn year_fraction(&self, start: NaiveDate, end: NaiveDate) -> f64` ### Parameters - `start` (NaiveDate) - Required - The start date. - `end` (NaiveDate) - Required - The end date. ### Returns - `f64` - The year fraction between the two dates under the convention. ### Example rust let convention = DayCountConvention::Act365; let start = NaiveDate::from_ymd(2023, 1, 1); let end = NaiveDate::from_ymd(2023, 1, 2); let fraction = convention.year_fraction(start, end); ``` -------------------------------- ### EquityOptionBuilder::new Source: https://docs.rs/RustyQLib/latest/rustyqlib/equity/builder/struct.EquityOptionBuilder.html?search=std%3A%3Avec Creates a new EquityOptionBuilder instance with default settings. ```APIDOC ## EquityOptionBuilder::new ### Description Creates a new builder for constructing an equity option. ### Method `pub fn new() -> Self` ### Parameters None. ### Returns A new `EquityOptionBuilder` instance. ``` -------------------------------- ### EquityOptionBuilder::new Source: https://docs.rs/RustyQLib/latest/rustyqlib/equity/builder/struct.EquityOptionBuilder.html Creates a new EquityOptionBuilder instance with default settings. ```APIDOC ## EquityOptionBuilder::new ### Description Creates a new EquityOptionBuilder instance with default settings. ### Method new ### Signature `pub fn new() -> Self` ### Parameters None ### Returns - **Self** - A new builder instance. ``` -------------------------------- ### and_then example Source: https://docs.rs/RustyQLib/latest/rustyqlib/core/errors/type.Result.html?search=std%3A%3Avec Shows how and_then calls op if the result is Ok, otherwise returns the Err value of self. The example defines a function sq_then_to_string that uses checked_mul and ok_or to return a Result. ```rust fn sq_then_to_string(x: u32) -> Result { x.checked_mul(x).map(|sq| sq.to_string()).ok_or("overflowed") } ``` -------------------------------- ### flatten() on Result, E> example Source: https://docs.rs/RustyQLib/latest/rustyqlib/core/errors/type.Result.html?search=std%3A%3Avec Example for the flatten method on Result, E>. It converts a nested Result into a single Result, removing one level of nesting. ```rust let x: Result, u32> = Ok(Ok("hello")); assert_eq!(Ok("hello"), x.flatten()); let x: Result, u32> = Ok(Err(6)); assert_eq!(Err(6), x.flatten()); let x: Result, u32> = Err(6); assert_eq!(Err(6), x.flatten()); ``` -------------------------------- ### SLV test setup: imports, constants, and helper functions Source: https://docs.rs/RustyQLib/latest/src/rustyqlib/equity/slv.rs.html Imports the necessary modules and defines constants S0 and R, a reference date, a flat yield curve, and a mixing Heston parameter set with normalized variance (v0 = theta = 1). ```rust use crate::core::curves::YieldCurve; use crate::core::curves::Compounding; use crate::core::daycount::DayCountConvention; use crate::core::vols::VolSurface; use crate::equity::blackscholes::{bs_price, implied_vol_from_price}; use chrono::NaiveDate; const S0: f64 = 100.0; const R: f64 = 0.02; fn reference() -> NaiveDate { NaiveDate::from_ymd_opt(2026, 1, 1).unwrap() } fn curve() -> YieldCurve { YieldCurve::flat(R, reference(), DayCountConvention::Act365, Compounding::Continuous) .unwrap() } fn mixing_heston() -> HestonParams { // normalized variance process (v0 = theta = 1) supplying the // stochasticity the leverage must neutralize for vanillas HestonParams { v0: 1.0, kappa: 2.0, theta: 1.0, vol_of_vol: 0.8, rho: -0.6 } } ``` -------------------------------- ### transpose() on Result, E> example Source: https://docs.rs/RustyQLib/latest/rustyqlib/core/errors/type.Result.html?search=std%3A%3Avec Example for the transpose method on Result, E>. It converts a Result of an Option into an Option of a Result, mapping Ok(None) to None and Ok(Some(_)) to Some(Ok(_)). ```rust #[derive(Debug, Eq, PartialEq)] struct SomeErr; let x: Result, SomeErr> = Ok(Some(5)); let y: Option> = Some(Ok(5)); assert_eq!(x.transpose(), y); ``` -------------------------------- ### EquityOptionBuilder::new Source: https://docs.rs/RustyQLib/latest/rustyqlib/equity/builder/struct.EquityOptionBuilder.html?search=Option%3CT%3E%2C+%28T+-%3E+U%29+-%3E+Option%3CU%3E Creates a new EquityOptionBuilder instance with default settings. ```APIDOC ## EquityOptionBuilder::new ### Description Creates a new builder instance for constructing an equity option. ### Method new ### Signature `pub fn new() -> Self` ### Parameters None. ### Returns A new `EquityOptionBuilder`. ``` -------------------------------- ### EquityOptionBuilder::new Source: https://docs.rs/RustyQLib/latest/rustyqlib/equity/builder/index.html?search=Option%3CT%3E%2C+%28T+-%3E+U%29+-%3E+Option%3CU%3E Creates a new `EquityOptionBuilder` instance for constructing an `EquityOption`. This is the entry point for the builder pattern. ```APIDOC ## EquityOptionBuilder::new ### Description Creates a new `EquityOptionBuilder` instance for constructing an `EquityOption`. This is the entry point for the builder pattern. ### Method `new` ### Parameters None ### Returns - **EquityOptionBuilder** - A new builder instance. ### Example ```rust let builder = EquityOptionBuilder::new(); ``` ``` -------------------------------- ### Module documentation and example: minimize with Method::Bfgs Source: https://docs.rs/RustyQLib/latest/src/rustyqlib/core/optimization/mod.rs.html?search= Module-level doc comment listing optimization algorithms and an example showing how to fit a scalar problem using minimize with the Bfgs method and default config. ```Rust //! Multi-dimensional optimization for model calibration, one algorithm //! per file. This is the fitting layer for every parametric model — //! Heston today ([`equity::heston::calibrate`](crate::equity::heston)), //! SABR / Nelson-Siegel or any other least-squares fit tomorrow — so the //! machinery lives in one place, like [`solvers`](crate::core::solvers) //! does for 1-D root finding. //! //! **Gradient-based** (analytic gradient optional — central finite //! differences fill in when absent): //! //! - [`steepest_descent`]: robust baseline, linear convergence; //! - [`conjugate_gradient`]: nonlinear CG (Polak-Ribiere with restarts); //! - [`bfgs`]: quasi-Newton with the inverse-Hessian update — the //! default choice for smooth unconstrained problems; //! - [`levenberg_marquardt`]: for least squares `min sum r_i(x)^2` //! specifically — the standard calibration workhorse. //! //! **Gradient-free**: //! //! - [`nelder_mead`]: the simplex method, for noisy or non-smooth //! objectives; //! - [`differential_evolution`]: seeded, bounded global search for //! multimodal landscapes (e.g. a cold-start calibration before a //! gradient polish). //! //! Every algorithm can be called directly, or through the pluggable //! [`minimize`] with a [`Method`] enum and a [`Problem`] description: //! //! ``` //! use rustyqlib::core::optimization::{minimize, Method, OptimConfig, Problem}; //! let rosenbrock = |x: &[f64]| { //! (1.0 - x[0]).powi(2) + 100.0 * (x[1] - x[0] * x[0]).powi(2) //! }; //! let problem = Problem::scalar(&rosenbrock, vec![-1.2, 1.0]); //! let fit = minimize(&OptimConfig::default(), Method::Bfgs, &problem).unwrap(); //! assert!((fit.x[0] - 1.0).abs() < 1e-5 && (fit.x[1] - 1.0).abs() < 1e-5); //! ``` ``` -------------------------------- ### EquityOptionBuilder::new() Source: https://docs.rs/RustyQLib/latest/rustyqlib/equity/builder/index.html?search= Creates a new `EquityOptionBuilder` instance for constructing an `EquityOption`. This is the entry point for the builder pattern. ```APIDOC ## EquityOptionBuilder::new() ### Description Creates a new `EquityOptionBuilder` instance for constructing an `EquityOption`. This is the entry point for the builder pattern. ### Method Constructor ### Endpoint `EquityOptionBuilder::new()` ### Parameters None ### Request Example ```rust use rustyqlib::equity::builder::EquityOptionBuilder; let builder = EquityOptionBuilder::new(); ``` ### Response #### Success Response Returns a new `EquityOptionBuilder` instance. #### Response Example ```rust let builder = EquityOptionBuilder::new(); ``` ```