Skip to main content

Crate kiyosi

Crate kiyosi 

Source
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.
AccumulatorChanges
Selects replacements for Accumulator::replace. Absent fields default to the source values.
AccumulatorTerms
Supplies accumulator terms; see Accumulator::new for validation and usage.
AmericanOption
Owns vanilla terms exercisable at any time during the inclusive contract life.
AnalyticBarrierEngine
Prices single-barrier vanilla options analytically with flat rates.
AnalyticBinaryBarrierEngine
Prices binary barriers and single-touch contracts analytically with flat rates.
AnalyticDigitalEngine
Prices European cash-or-nothing and asset-or-nothing contracts under BSM.
AnalyticDoubleBarrierEngine
Prices continuous double-barrier options analytically with flat rates.
AnalyticDoubleTouchEngine
Prices continuous cash double-touch and double-no-touch contracts with flat rates.
AnalyticEuropeanEngine
Prices European vanilla options analytically under the BSM model.
AnalyticGeometricAveragePriceEngine
Prices continuously monitored geometric average-price Asian options under BSM.
AnalyticHestonEuropeanEngine
Prices European calls and puts under Heston using adaptive Fourier integration.
AnalyticRangeAccrualEngine
Prices range coupons by summing exact BSM marginal probabilities with deterministic curves.
ArithmeticAveragePriceOption
Defines an arithmetic average-price Asian option.
AveragePriceOptionChanges
Selects replacements for continuous average-price Asian options.
BarrierOption
Owns validated single-barrier vanilla terms and strictly prior history.
BarrierOptionChanges
Selects replacements for BarrierOption::replace. Absent fields default to the source values.
BarrierOptionTerms
Input terms, validated by BarrierOption::new. See its example.
BinaryBarrierOption
Owns a validated strike-based binary barrier paying cash or the asset at expiry.
BinaryBarrierOptionChanges
Selects replacements for BinaryBarrierOption::replace. Absent fields default to the source values. See BinaryBarrierOption::cash for a touch history example.
BinaryBarrierTerms
Supplies binary strike and monitoring inputs.
BinarySnowballOptionChanges
Selects replacements for BinarySnowballOption::replace. Absent fields default to the source values. See BinarySnowballOption::new for a principal replacement example.
BinarySnowballTerms
Supplies binary snowball terms; see Self::new and BinarySnowballOption::new.
BjerksundStenslandVanillaEngine
Prices American vanilla options using the Bjerksund-Stensland 2002 approximation.
BlackScholesMertonParameterChanges
Selects model replacements. Absent fields default to the source values. See BlackScholesMertonParameters::new for a volatility replacement example.
BlackScholesMertonParameters
Owns Black-Scholes-Merton (BSM) rate curves and annualized log-return volatility.
CancellationToken
Requests cooperative cancellation of a numerical calculation.
CouponObservation
Owns one exact Phoenix observation time and its nonnegative inclusive coupon threshold.
CoxRossRubinsteinBarrierEngine
Prices single-barrier vanilla contracts with a flat-rate CRR tree.
CoxRossRubinsteinDigitalEngine
Prices European cash-or-nothing and asset-or-nothing contracts with a CRR tree.
CoxRossRubinsteinVanillaEngine
Prices European and American vanilla contracts with a flat-rate CRR tree.
Date
Represents a proleptic Gregorian date in years -32767 through 32767.
DigitalOption
Owns a validated European cash-or-nothing or asset-or-nothing contract.
DigitalOptionChanges
Selects digital contract replacements. Absent fields default to the source values.
DoubleBarrierOption
Owns two ordered boundaries sharing monitoring and strictly prior history.
DoubleBarrierOptionChanges
Selects replacements for DoubleBarrierOption::replace. Absent fields default to the source values. See DoubleBarrierOption::new for a barrier replacement example.
DoubleBarrierOptionTerms
Input terms validated by DoubleBarrierOption::new; see its example.
DoubleTouchOption
Owns a cash payment activated by either inclusive boundary, or by neither being touched.
DoubleTouchOptionChanges
Selects replacements for DoubleTouchOption::replace. Absent fields default to the source values. See DoubleTouchOption::cash for a touch history example.
DoubleTouchOptionTerms
Cash double-touch inputs; see DoubleTouchOption::cash for validation and usage.
EuropeanOption
Owns a validated European vanilla contract.
FiniteDifferenceAccumulatorEngine
Prices trading-date accumulators using affine quantity layers and projected events.
FiniteDifferenceAutocallableEngine
Prices snowball variants and Phoenix notes with event-projected finite differences; defaults to 800 asset and 400 time steps.
FiniteDifferenceBarrierEngine
Prices single-barrier contracts with exact continuous edges and scheduled event projection.
FiniteDifferenceBinaryBarrierEngine
Prices binary barriers and single touch/no-touch contracts with finite differences.
FiniteDifferenceDigitalEngine
Prices European cash-or-nothing and asset-or-nothing contracts with finite differences.
FiniteDifferenceDoubleBarrierEngine
Prices double-barrier contracts with exact continuous edges and simultaneous scheduled events.
FiniteDifferenceDoubleTouchEngine
Prices cash double-touch and double-no-touch contracts with finite differences.
FiniteDifferenceHestonVanillaEngine
Prices European and American vanilla options under the Heston model.
FiniteDifferenceVanillaEngine
Prices European and American vanilla contracts with uniform or concentrated finite-difference grids.
GeometricAveragePriceOption
Defines a geometric average-price Asian option.
GreeksRequest
Selects price sensitivities, ignoring duplicates.
HestonParameterChanges
Selects Heston replacements. Absent fields default to the source values.
HestonParameterInputs
Supplies named inputs validated by HestonParameters::new.
HestonParameters
Owns constant Heston stochastic-volatility parameters under the risk-neutral measure.
ImpliedCouponSettings
Sets finite signed coupon bounds and convergence controls in the contract’s units.
ImpliedVolatilitySettings
Configures a nonnegative volatility bracket and convergence tolerances.
KnockOutObservation
Owns one exact Phoenix observation time and its positive inclusive knock-out threshold.
LocalVolatilityParameterChanges
Selects local-volatility replacements. Absent fields default to the source values. See LocalVolatilityParameters::new for a rate replacement example.
LocalVolatilityParameters
Owns rate curves and a validated local-volatility surface.
LocalVolatilitySurface
Owns a local-volatility table in absolute time and spot coordinates.
MonteCarloAccumulatorEngine
Prices accumulators with exact lognormal transitions between trading dates.
MonteCarloAsianEngine
Prices geometric and arithmetic continuous averages using CPU Monte Carlo.
MonteCarloAutocallableEngine
Prices snowball variants and Phoenix notes with trading-day CPU Monte Carlo.
MonteCarloBarrierEngine
Prices single- and double-barrier contracts with conditional-survival CPU Monte Carlo.
MonteCarloDigitalEngine
Prices European cash-or-nothing and asset-or-nothing contracts by terminal sampling.
MonteCarloVanillaEngine
Prices European and American vanilla contracts with flat-rate CPU sampling.
NumericalShiftSettings
Configures absolute finite-difference bumps.
ObservationSchedule
Owns strictly ordered observation times and their validation calendar.
PhoenixOptionChanges
Selects replacements for PhoenixOption::replace. Absent fields default to the source values. See PhoenixOption::new for a history replacement example.
PhoenixTerms
Supplies Phoenix terms; see Self::new and PhoenixOption::new.
PricingContext
Owns a validated valuation snapshot.
PricingContextChanges
Selects context replacements. Absent fields default to the source values. See PricingContext::new for a spot replacement example.
PricingResult
Owns a finite price and optional finite Greeks.
QuadratureAccumulatorEngine
Prices accumulators and decumulators using affine layers and Gaussian integration.
QuadratureAutocallableEngine
Prices snowball variants and Phoenix notes by quadrature between event dates.
QuadratureBarrierEngine
Prices single-barrier contracts by flat-rate quadrature with exact observation dates.
QuadratureDigitalEngine
Prices European cash-or-nothing and asset-or-nothing options by BSM quadrature.
QuadratureVanillaEngine
Prices European and American vanilla options by flat-rate BSM quadrature.
RangeAccrualOption
Owns a validated range coupon with no principal payment or early termination.
RangeAccrualOptionChanges
Selects replacements for RangeAccrualOption::replace. Absent fields default to the source values.
RangeAccrualTerms
Supplies equally weighted range-coupon terms; see RangeAccrualOption::new.
RateTermStructure
Owns a term structure of continuously compounded rates.
SnowballCouponQuote
Owns an annual snowball coupon quote and its maturity convention.
SnowballObservation
Associates one snowball autocall time with its knock-out and annual coupon terms.
SnowballObservationChanges
Selects observation replacements. Absent fields default to the source values.
SnowballOptionChanges
Selects replacements for SnowballOption::replace. Absent fields default to the source values. See SnowballPresetTerms::expand for a history replacement example.
SnowballTerms
Supplies basic snowball terms; see Self::new and SnowballOption::new.
TernarySnowballOptionChanges
Selects replacements for TernarySnowballOption::replace. Absent fields default to the source values. See TernarySnowballOption::new for a calendar replacement example.
TernarySnowballTerms
Supplies ternary snowball terms; see Self::new and TernarySnowballOption::new.
TimeOfDay
Represents a timezone-free clock time with microsecond precision.
Timestamp
Represents a date and time with microsecond resolution.
TouchOption
Owns a validated cash/asset one-touch or no-touch contract, with no strike.
TouchOptionChanges
Selects replacements for TouchOption::replace. Absent fields default to the source values. See TouchOption::cash for a settlement timing example.
TouchOptionTerms
Strike-free touch inputs; validated by TouchOption::cash or TouchOption::asset.
TradingCalendar
Owns a trading-day predicate and positive annualization basis.
TurnbullWakemanArithmeticAveragePriceEngine
Approximates continuously monitored arithmetic average-price Asian option prices.
VanillaOptionChanges
Selects European or American vanilla contract replacements. Absent fields default to the source values.

Enums§

AutocallableBarrierState
Records events strictly before valuation; see PhoenixOption::new for an example.
BarrierTouchState
Caller-supplied observations strictly before valuation; see BarrierOption::replace.
BarrierType
Direction and activation behavior; see BarrierOption::new.
BinaryPayoff
Selects explicit cash or asset settlement for binary and touch replacements.
BusinessDayConvention
Selects the direction of inclusive business-day adjustment.
CouponQuoteConvention
Selects how a snowball maturity coupon follows its quoted observation coupon.
DoubleBarrierType
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.
GreekMethod
Describes how an engine estimates Greeks and which shift controls it may use.
GreekStatus
Describes whether a sensitivity was requested and could be calculated.
KnockInObservation
Specifies when an autocallable’s strict downside barrier is observed.
ModelParameters
Selects a concrete pricing model at the valuation boundary.
OptionType
Selects the call or put payoff direction.
Rate
Supplies a continuously compounded flat rate or an owned term structure.
RebateTiming
Cash rebate payment timing; see BarrierOption::new.
SettlementTiming
Payment timing for a touch contract; see TouchOption::cash.
VarianceTimeConvention
Defines volatility’s annualization unit and the clock accumulating variance.

Constants§

VERSION
Reports the package version shared with the Python bindings.

Traits§

PricingEngine
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§

BinarySnowballOption
Owns a binary snowball with no knock-in monitoring or downside participation.
PhoenixOption
Owns validated Phoenix terms; see Self::new.
Result
Represents a value, a domain rejection or a reported operational failure.
SnowballOption
Owns validated basic snowball terms; see Self::new.
TernarySnowballOption
Owns a ternary snowball with separate maturity coupon rates before and after knock-in.