Expand description
Prices derivatives under Black-Scholes-Merton, local-volatility, and Heston models.
Construct a contract and a PricingContext, then choose an engine that
supports the contract and model. Use PricingEngine::price for a price
and PricingEngine::price_with_greeks for selected sensitivities. Import
PricingEngine to call its methods. Each engine documents its supported
combinations and numerical controls.
Use numerical_greeks to select scalar BSM differences explicitly.
implied_volatility, implied_snowball_coupon and
implied_phoenix_coupon solve for inputs that reproduce a quoted price.
Monte Carlo engines can also report the sampling seed and, for supported
contracts, sampling statistics.
Find algorithm-specific controls and results in engines and contract
presets and extension types in instruments.
For batches, choose the operation by the input that varies. Engines with
price_many accept existing contracts. Use price_strikes to vary the
strike, or engines::VanillaBatchEngine::price_surface to vary strike and expiry.
Use engines::FiniteDifferenceEngine::solve to reuse a solution across spot prices.
§Conventions
Annual rates and annualized volatility use decimal units. Rates are continuously
compounded and accrue on Actual/365 Fixed by default. Use
RateTermStructure::bounded_flat_with_calendar for calendar-based accrual.
VarianceTimeConvention defines volatility units and variance accumulation.
BSM and local-volatility PDE models support business time over a calendar’s
fixed basis, with no variance accumulation on closed dates. Rate curves govern
carry and discounting independently of variance and contractual dates. Other engines
reject business time with Error::UnsupportedOperation. Heston variance
parameters use Actual/365 Fixed. Greek defines sensitivity units.
BSM volatility may be zero, selecting deterministic pricing. Check numerical
convergence separately from Monte Carlo sampling uncertainty and solver tolerances.
Contract and market times use Timestamp in a caller-selected time basis.
Contract boundaries are inclusive. Calendars classify Date values without
moving those boundaries. Constructors validate terms and observation calendars;
pricing validates valuation times, model coverage, and required history.
Barrier and touch terms select continuous monitoring with observation_schedule: None
or scheduled monitoring with a nonempty schedule. Terms inherit the schedule’s
calendar unless they specify an override. Borrow the schedule with the
contract’s observation_schedule() method, which returns None for continuous
monitoring. Clone the schedule to pass it to another constructor or replacement.
An Accumulator’s explicit knock-out schedule
may be empty to disable early knock-out. With None, knock-out follows the
daily accumulation schedule.
European vanilla and digital options permit pre-effective valuation; other
contracts require valuation within their life.
Values own their data, and accessors may borrow it. Replacement reads an
existing value and returns a separate validated value. See each contract’s
replace method for its history rules.
§Caller-supplied history
Supplied history describes events strictly before PricingContext::valuation_time.
Observations exactly at valuation use the current spot and are processed once.
Callers maintain lifecycle events, historical market data and settlement status,
keeping supplied state consistent with valuation time and contract terms.
Kiyosi does not check state age, reconstruct historical paths or advance supplied
state. Callers must prevent stale or future state from being supplied.
Absent history is unknown; explicit zero, false, untouched, and no-event states
are known history where supported. AutocallableBarrierState::KnockedIn
means prior knock-in on an outstanding note without prior knock-out;
AutocallableBarrierState::NoEvent means neither occurred.
AutocallableBarrierState::KnockedOut denotes a settled contract.
Missing required history returns Error::MissingHistory; intrinsically invalid
inputs and impossible states return Error::InvalidInput. Constructors and
replacement validate constraints known from their inputs; pricing validates
constraints relative to valuation, including whether prior events are possible.
replace validates terms and history together. Omitted fields, including
history, default to their values on the source contract. Numerical time
sensitivities hold supplied history fixed. Observation boundaries determine
whether a time stencil is available.
use kiyosi::*;
let start = Date::new(2025, 1, 2)?.start_of_day();
let at = Date::new(2025, 1, 6)?.at_time(TimeOfDay::new(12, 0, 0, 0)?);
let end = Date::new(2025, 1, 10)?.start_of_day();
let mut terms = RangeAccrualTerms::new(100.0, 0.1, 90.0, 110.0,
start, end, TimeOfDay::new(15, 0, 0, 0)?);
terms.realized_hit_count = Some(1);
let option = RangeAccrualOption::new(terms)?;
let context = PricingContext::new(BlackScholesMertonParameters::new(0.0, 0.0, 0.0)?, 100.0, at)?;
let price = AnalyticRangeAccrualEngine.price(&option, &context)?;
let later = context.replace(PricingContextChanges {
valuation_time: Some(at.add_days(1)?), ..Default::default()
})?;
assert!(AnalyticRangeAccrualEngine.price(&option, &later)? < price);
let refreshed = option.replace(RangeAccrualOptionChanges {
realized_hit_count: Some(Some(2)),
..Default::default()
})?;
assert_eq!(AnalyticRangeAccrualEngine.price(&refreshed, &later)?, price);§Concurrency and errors
Built-in contracts, market data, engines, and results are Send + Sync.
Distinct and shared instances support concurrent reads and pricing. Mutation
requires exclusive Rust access. Parallel Monte Carlo calls share a library-owned
Rayon pool with per-call buffers and worker caps; serial calls use the calling
thread. engines::configure_monte_carlo_pool caps created workers before initialization.
Kiyosi’s Monte Carlo pool is independent of the application’s global Rayon pool.
engines::FiniteDifferenceSolution owns immutable query state; clones and shared
instances permit concurrent spot queries after the source inputs are dropped.
Its queries do not perform rollback or mutate the saved numerical solution.
Custom calendar predicates must return stable answers throughout the calendar’s
lifetime, including clones. See PricingEngine for custom engine contracts.
Domain rejections return Result<T>. Operational failures retain native I/O
details through Error::Io. Calls are synchronous; CancellationToken::run
enables cooperative cancellation from another thread. Built-in loops check between
work units and return std::io::ErrorKind::Interrupted without a partial result.
Custom engines must check their token. Allocation and callbacks may delay checks.
Panics, including user callback panics, unwind or abort according to the build’s
panic strategy. Allocation exhaustion normally aborts. Python signal handling
and exception mappings belong to the bindings.
§Examples
use kiyosi::{AnalyticEuropeanEngine, BlackScholesMertonParameters, Date,
EuropeanOption, OptionType, PricingContext, PricingEngine};
let start = Date::new(2025, 1, 1)?.start_of_day();
let expiry = Date::new(2026, 1, 1)?.start_of_day();
let option = EuropeanOption::new(OptionType::Call, 100.0, start, expiry)?;
let model = BlackScholesMertonParameters::new(0.05, 0.02, 0.2)?;
let context = PricingContext::new(model, 100.0, start.into())?;
assert!((AnalyticEuropeanEngine.price(&option, &context)? - 9.227005508154036).abs() < 1e-12);
let result = AnalyticEuropeanEngine.price_with_greeks(&option, &context,
kiyosi::GreeksRequest::all())?;
assert!(result.require(kiyosi::Greek::Delta)? > 0.0);
let sigma = kiyosi::implied_volatility(&AnalyticEuropeanEngine, &option,
&context, result.price(), kiyosi::ImpliedVolatilitySettings::new(0.0, 4.0))?;
assert!((sigma - 0.2).abs() < 1e-8);Modules§
- engines
- Algorithm-specific engine settings, batch traits, and pricing results.
- instruments
- Contract presets and traits for working with contracts generically.
Structs§
- Accumulator
- Owns daily accumulations settled together at knock-out or expiry.
- Accumulator
Changes - Selects replacements for
Accumulator::replace. Absent fields default to the source values. - Accumulator
Terms - Supplies accumulator terms; see
Accumulator::newfor validation and usage. - American
Option - Owns vanilla terms exercisable at any time during the inclusive contract life.
- Analytic
Barrier Engine - Prices single-barrier vanilla options analytically with flat rates.
- Analytic
Binary Barrier Engine - Prices binary barriers and single-touch contracts analytically with flat rates.
- Analytic
Digital Engine - Prices European cash-or-nothing and asset-or-nothing contracts under BSM.
- Analytic
Double Barrier Engine - Prices continuous double-barrier options analytically with flat rates.
- Analytic
Double Touch Engine - Prices continuous cash double-touch and double-no-touch contracts with flat rates.
- Analytic
European Engine - Prices European vanilla options analytically under the BSM model.
- Analytic
Geometric Average Price Engine - Prices continuously monitored geometric average-price Asian options under BSM.
- Analytic
Heston European Engine - Prices European calls and puts under Heston using adaptive Fourier integration.
- Analytic
Range Accrual Engine - Prices range coupons by summing exact BSM marginal probabilities with deterministic curves.
- Arithmetic
Average Price Option - Defines an arithmetic average-price Asian option.
- Average
Price Option Changes - Selects replacements for continuous average-price Asian options.
- Barrier
Option - Owns validated single-barrier vanilla terms and strictly prior history.
- Barrier
Option Changes - Selects replacements for
BarrierOption::replace. Absent fields default to the source values. - Barrier
Option Terms - Input terms, validated by
BarrierOption::new. See its example. - Binary
Barrier Option - Owns a validated strike-based binary barrier paying cash or the asset at expiry.
- Binary
Barrier Option Changes - Selects replacements for
BinaryBarrierOption::replace. Absent fields default to the source values. SeeBinaryBarrierOption::cashfor a touch history example. - Binary
Barrier Terms - Supplies binary strike and monitoring inputs.
- Binary
Snowball Option Changes - Selects replacements for
BinarySnowballOption::replace. Absent fields default to the source values. SeeBinarySnowballOption::newfor a principal replacement example. - Binary
Snowball Terms - Supplies binary snowball terms; see
Self::newandBinarySnowballOption::new. - Bjerksund
Stensland Vanilla Engine - Prices American vanilla options using the Bjerksund-Stensland 2002 approximation.
- Black
Scholes Merton Parameter Changes - Selects model replacements. Absent fields default to the source values.
See
BlackScholesMertonParameters::newfor a volatility replacement example. - Black
Scholes Merton Parameters - Owns Black-Scholes-Merton (BSM) rate curves and annualized log-return volatility.
- Cancellation
Token - Requests cooperative cancellation of a numerical calculation.
- Coupon
Observation - Owns one exact Phoenix observation time and its nonnegative inclusive coupon threshold.
- CoxRoss
Rubinstein Barrier Engine - Prices single-barrier vanilla contracts with a flat-rate CRR tree.
- CoxRoss
Rubinstein Digital Engine - Prices European cash-or-nothing and asset-or-nothing contracts with a CRR tree.
- CoxRoss
Rubinstein Vanilla Engine - Prices European and American vanilla contracts with a flat-rate CRR tree.
- Date
- Represents a proleptic Gregorian date in years -32767 through 32767.
- Digital
Option - Owns a validated European cash-or-nothing or asset-or-nothing contract.
- Digital
Option Changes - Selects digital contract replacements. Absent fields default to the source values.
- Double
Barrier Option - Owns two ordered boundaries sharing monitoring and strictly prior history.
- Double
Barrier Option Changes - Selects replacements for
DoubleBarrierOption::replace. Absent fields default to the source values. SeeDoubleBarrierOption::newfor a barrier replacement example. - Double
Barrier Option Terms - Input terms validated by
DoubleBarrierOption::new; see its example. - Double
Touch Option - Owns a cash payment activated by either inclusive boundary, or by neither being touched.
- Double
Touch Option Changes - Selects replacements for
DoubleTouchOption::replace. Absent fields default to the source values. SeeDoubleTouchOption::cashfor a touch history example. - Double
Touch Option Terms - Cash double-touch inputs; see
DoubleTouchOption::cashfor validation and usage. - European
Option - Owns a validated European vanilla contract.
- Finite
Difference Accumulator Engine - Prices trading-date accumulators using affine quantity layers and projected events.
- Finite
Difference Autocallable Engine - Prices snowball variants and Phoenix notes with event-projected finite differences; defaults to 800 asset and 400 time steps.
- Finite
Difference Barrier Engine - Prices single-barrier contracts with exact continuous edges and scheduled event projection.
- Finite
Difference Binary Barrier Engine - Prices binary barriers and single touch/no-touch contracts with finite differences.
- Finite
Difference Digital Engine - Prices European cash-or-nothing and asset-or-nothing contracts with finite differences.
- Finite
Difference Double Barrier Engine - Prices double-barrier contracts with exact continuous edges and simultaneous scheduled events.
- Finite
Difference Double Touch Engine - Prices cash double-touch and double-no-touch contracts with finite differences.
- Finite
Difference Heston Vanilla Engine - Prices European and American vanilla options under the Heston model.
- Finite
Difference Vanilla Engine - Prices European and American vanilla contracts with uniform or concentrated finite-difference grids.
- Geometric
Average Price Option - Defines a geometric average-price Asian option.
- Greeks
Request - Selects price sensitivities, ignoring duplicates.
- Heston
Parameter Changes - Selects Heston replacements. Absent fields default to the source values.
- Heston
Parameter Inputs - Supplies named inputs validated by
HestonParameters::new. - Heston
Parameters - Owns constant Heston stochastic-volatility parameters under the risk-neutral measure.
- Implied
Coupon Settings - Sets finite signed coupon bounds and convergence controls in the contract’s units.
- Implied
Volatility Settings - Configures a nonnegative volatility bracket and convergence tolerances.
- Knock
OutObservation - Owns one exact Phoenix observation time and its positive inclusive knock-out threshold.
- Local
Volatility Parameter Changes - Selects local-volatility replacements. Absent fields default to the source values.
See
LocalVolatilityParameters::newfor a rate replacement example. - Local
Volatility Parameters - Owns rate curves and a validated local-volatility surface.
- Local
Volatility Surface - Owns a local-volatility table in absolute time and spot coordinates.
- Monte
Carlo Accumulator Engine - Prices accumulators with exact lognormal transitions between trading dates.
- Monte
Carlo Asian Engine - Prices geometric and arithmetic continuous averages using CPU Monte Carlo.
- Monte
Carlo Autocallable Engine - Prices snowball variants and Phoenix notes with trading-day CPU Monte Carlo.
- Monte
Carlo Barrier Engine - Prices single- and double-barrier contracts with conditional-survival CPU Monte Carlo.
- Monte
Carlo Digital Engine - Prices European cash-or-nothing and asset-or-nothing contracts by terminal sampling.
- Monte
Carlo Vanilla Engine - Prices European and American vanilla contracts with flat-rate CPU sampling.
- Numerical
Shift Settings - Configures absolute finite-difference bumps.
- Observation
Schedule - Owns strictly ordered observation times and their validation calendar.
- Phoenix
Option Changes - Selects replacements for
PhoenixOption::replace. Absent fields default to the source values. SeePhoenixOption::newfor a history replacement example. - Phoenix
Terms - Supplies Phoenix terms; see
Self::newandPhoenixOption::new. - Pricing
Context - Owns a validated valuation snapshot.
- Pricing
Context Changes - Selects context replacements. Absent fields default to the source values.
See
PricingContext::newfor a spot replacement example. - Pricing
Result - Owns a finite price and optional finite Greeks.
- Quadrature
Accumulator Engine - Prices accumulators and decumulators using affine layers and Gaussian integration.
- Quadrature
Autocallable Engine - Prices snowball variants and Phoenix notes by quadrature between event dates.
- Quadrature
Barrier Engine - Prices single-barrier contracts by flat-rate quadrature with exact observation dates.
- Quadrature
Digital Engine - Prices European cash-or-nothing and asset-or-nothing options by BSM quadrature.
- Quadrature
Vanilla Engine - Prices European and American vanilla options by flat-rate BSM quadrature.
- Range
Accrual Option - Owns a validated range coupon with no principal payment or early termination.
- Range
Accrual Option Changes - Selects replacements for
RangeAccrualOption::replace. Absent fields default to the source values. - Range
Accrual Terms - Supplies equally weighted range-coupon terms; see
RangeAccrualOption::new. - Rate
Term Structure - Owns a term structure of continuously compounded rates.
- Snowball
Coupon Quote - Owns an annual snowball coupon quote and its maturity convention.
- Snowball
Observation - Associates one snowball autocall time with its knock-out and annual coupon terms.
- Snowball
Observation Changes - Selects observation replacements. Absent fields default to the source values.
- Snowball
Option Changes - Selects replacements for
SnowballOption::replace. Absent fields default to the source values. SeeSnowballPresetTerms::expandfor a history replacement example. - Snowball
Terms - Supplies basic snowball terms; see
Self::newandSnowballOption::new. - Ternary
Snowball Option Changes - Selects replacements for
TernarySnowballOption::replace. Absent fields default to the source values. SeeTernarySnowballOption::newfor a calendar replacement example. - Ternary
Snowball Terms - Supplies ternary snowball terms; see
Self::newandTernarySnowballOption::new. - Time
OfDay - Represents a timezone-free clock time with microsecond precision.
- Timestamp
- Represents a date and time with microsecond resolution.
- Touch
Option - Owns a validated cash/asset one-touch or no-touch contract, with no strike.
- Touch
Option Changes - Selects replacements for
TouchOption::replace. Absent fields default to the source values. SeeTouchOption::cashfor a settlement timing example. - Touch
Option Terms - Strike-free touch inputs; validated by
TouchOption::cashorTouchOption::asset. - Trading
Calendar - Owns a trading-day predicate and positive annualization basis.
- Turnbull
Wakeman Arithmetic Average Price Engine - Approximates continuously monitored arithmetic average-price Asian option prices.
- Vanilla
Option Changes - Selects European or American vanilla contract replacements. Absent fields default to the source values.
Enums§
- Autocallable
Barrier State - Records events strictly before valuation; see
PhoenixOption::newfor an example. - Barrier
Touch State - Caller-supplied observations strictly before valuation; see
BarrierOption::replace. - Barrier
Type - Direction and activation behavior; see
BarrierOption::new. - Binary
Payoff - Selects explicit cash or asset settlement for binary and touch replacements.
- Business
DayConvention - Selects the direction of inclusive business-day adjustment.
- Coupon
Quote Convention - Selects how a snowball maturity coupon follows its quoted observation coupon.
- Double
Barrier Type - Activation by either boundary; see
DoubleBarrierOption::new. - Error
- Describes an input rejection, computation failure or native I/O failure.
- Greek
- Selects an unscaled partial derivative of the price.
- Greek
Method - Describes how an engine estimates Greeks and which shift controls it may use.
- Greek
Status - Describes whether a sensitivity was requested and could be calculated.
- Knock
InObservation - Specifies when an autocallable’s strict downside barrier is observed.
- Model
Parameters - Selects a concrete pricing model at the valuation boundary.
- Option
Type - Selects the call or put payoff direction.
- Rate
- Supplies a continuously compounded flat rate or an owned term structure.
- Rebate
Timing - Cash rebate payment timing; see
BarrierOption::new. - Settlement
Timing - Payment timing for a touch contract; see
TouchOption::cash. - Variance
Time Convention - Defines volatility’s annualization unit and the clock accumulating variance.
Constants§
- VERSION
- Reports the package version shared with the Python bindings.
Traits§
- Pricing
Engine - Prices a contract and provides sensitivities for the supported model.
Functions§
- implied_
phoenix_ coupon - Solves a Phoenix price curve in its conditional periodic coupon rate.
- implied_
snowball_ coupon - Solves a snowball family’s price curve in its first observation coupon.
- implied_
volatility - Solves implied volatility with safeguarded Brent iteration, retaining the caller’s bracket.
- numerical_
greeks - Computes BSM numerical price sensitivities for scalar engines.
Type Aliases§
- Binary
Snowball Option - Owns a binary snowball with no knock-in monitoring or downside participation.
- Phoenix
Option - Owns validated Phoenix terms; see
Self::new. - Result
- Represents a value, a domain rejection or a reported operational failure.
- Snowball
Option - Owns validated basic snowball terms; see
Self::new. - Ternary
Snowball Option - Owns a ternary snowball with separate maturity coupon rates before and after knock-in.