pub struct Options {
pub option_type: OptionType,
pub side: Side,
pub underlying_symbol: String,
pub strike_price: Positive,
pub expiration_date: ExpirationDate,
pub implied_volatility: Positive,
pub quantity: Positive,
pub underlying_price: Positive,
pub risk_free_rate: Decimal,
pub option_style: OptionStyle,
pub dividend_yield: Positive,
pub exotic_params: Option<ExoticParams>,
}Expand description
Represents a financial option contract with its essential parameters and characteristics.
This structure contains all the necessary information to define an options contract, including its type (call/put), market position (long/short), pricing parameters, and contract specifications. It serves as the core data model for option pricing, risk analysis, and strategy development.
The Options struct supports both standard option types and exotic options through
the optional exotic_params field, making it versatile for various financial modeling
scenarios.
Fields§
§option_type: OptionTypeSpecifies whether this is a European or American option
side: SideIndicates whether the position is Long (purchased) or Short (sold/written), which determines the profit/loss direction and risk profile.
underlying_symbol: StringThe ticker symbol or identifier of the underlying asset (e.g., “AAPL” for Apple stock).
strike_price: PositiveThe price at which the option holder can exercise their right to buy (for calls) or sell (for puts) the underlying asset.
expiration_date: ExpirationDateWhen the option contract expires, either as days from now or as a specific date.
implied_volatility: PositiveThe market’s expectation for future volatility of the underlying asset, a key parameter for option pricing models.
quantity: PositiveThe number of contracts in this position.
underlying_price: PositiveThe current market price of the underlying asset.
risk_free_rate: DecimalThe current risk-free interest rate used in option pricing models, typically based on treasury yields of similar duration.
option_style: OptionStyleThe option is a Call or Put option, determining the fundamental right option can be exercised.
dividend_yield: PositiveThe annualized dividend yield of the underlying asset, affecting option pricing particularly for longer-dated contracts.
exotic_params: Option<ExoticParams>Additional parameters required for exotic option types like Asian or Lookback options. This field is None for standard (vanilla) options.
Implementations§
Source§impl Options
impl Options
Sourcepub fn new(
option_type: OptionType,
side: Side,
underlying_symbol: String,
strike_price: Positive,
expiration_date: ExpirationDate,
implied_volatility: Positive,
quantity: Positive,
underlying_price: Positive,
risk_free_rate: Decimal,
option_style: OptionStyle,
dividend_yield: Positive,
exotic_params: Option<ExoticParams>,
) -> Self
pub fn new( option_type: OptionType, side: Side, underlying_symbol: String, strike_price: Positive, expiration_date: ExpirationDate, implied_volatility: Positive, quantity: Positive, underlying_price: Positive, risk_free_rate: Decimal, option_style: OptionStyle, dividend_yield: Positive, exotic_params: Option<ExoticParams>, ) -> Self
Creates a new options contract with the specified parameters.
This constructor creates an instance of Options with all the required parameters
for defining and pricing an option contract. It supports both standard (vanilla)
options and exotic options through the optional exotic_params parameter.
§Parameters
option_type- Specifies whether this is a Call or Put option, determining the fundamental right the option contract provides.side- Indicates whether the position is Long (purchased) or Short (sold/written), which determines the profit/loss direction.underlying_symbol- The ticker symbol or identifier of the underlying asset (e.g., “AAPL”).strike_price- The price at which the option can be exercised, represented as aPositivevalue.expiration_date- When the option contract expires, either as days from now or as a specific date.implied_volatility- The market’s expectation for future volatility of the underlying asset, a key parameter for option pricing.quantity- The number of contracts in this position, represented as aPositivevalue.underlying_price- The current market price of the underlying asset.risk_free_rate- The current risk-free interest rate used in option pricing models.option_style- The option exercise style (European or American), determining when the option can be exercised.dividend_yield- The annualized dividend yield of the underlying asset, affecting option pricing.exotic_params- Additional parameters required for exotic option types. Set toNonefor standard (vanilla) options.
§Returns
A fully configured Options instance with all the specified parameters.
Sourcepub fn time_to_expiration(&self) -> OptionsResult<Positive>
pub fn time_to_expiration(&self) -> OptionsResult<Positive>
Calculates the time to expiration of the option in years.
This function computes the time remaining until the option’s expiration date, expressed as a positive decimal value representing years. This is a key parameter used in option pricing models.
§Returns
OptionsResult<Positive>- A result containing the time to expiration in years as a Positive value, or an error if the calculation failed.
Sourcepub fn is_long(&self) -> bool
pub fn is_long(&self) -> bool
Determines if the option position is long (purchased).
A long position indicates that the option has been bought, meaning the holder has the right to exercise the option according to its terms.
§Returns
bool- Returns true if the option is held as a long position, false otherwise.
Sourcepub fn is_short(&self) -> bool
pub fn is_short(&self) -> bool
Determines if the option position is short (written/sold).
A short position indicates that the option has been sold or written, meaning the holder has the obligation to fulfill the contract terms if the option is exercised.
§Returns
bool- Returns true if the option is held as a short position, false otherwise.
Sourcepub fn calculate_price_binomial(
&self,
no_steps: usize,
) -> OptionsResult<Decimal>
pub fn calculate_price_binomial( &self, no_steps: usize, ) -> OptionsResult<Decimal>
Calculates the price of an option using the binomial tree model.
This method implements the binomial option pricing model which constructs a discrete-time lattice (tree) of possible future underlying asset prices to determine the option’s value. The approach is particularly valuable for pricing American options and other early-exercise scenarios.
The calculation divides the time to expiration into a specified number of steps, creating a binomial tree that represents possible price paths of the underlying asset. The option’s value is then calculated by working backward from expiration to the present value.
§Parameters
no_steps- The number of steps to use in the binomial tree calculation. Higher values increase accuracy but also computational cost.
§Returns
OptionsResult<Decimal>- A result containing the calculated option price as a Decimal value, or an OptionsError if the calculation failed.
§Errors
Returns an OptionsError::OtherError if:
- The number of steps is zero
- The time to expiration calculation fails
- The binomial price calculation fails
Sourcepub fn calculate_price_binomial_tree(
&self,
no_steps: usize,
) -> OptionsResult<(Decimal, Vec<Vec<Decimal>>, Vec<Vec<Decimal>>)>
pub fn calculate_price_binomial_tree( &self, no_steps: usize, ) -> OptionsResult<(Decimal, Vec<Vec<Decimal>>, Vec<Vec<Decimal>>)>
Calculates option price using the binomial tree model.
This method implements a binomial tree (lattice) approach to option pricing, which discretizes the underlying asset’s price movement over time. The model builds a tree of possible future asset prices and works backwards to determine the current option value.
§Parameters
no_steps- The number of discrete time steps to use in the model. Higher values increase precision but also computational cost.
§Returns
PriceBinomialTree- A result containing:- The calculated option price
- The asset price tree (underlying price evolution)
- The option value tree (option price at each node)
This method is particularly valuable for pricing American options and other early-exercise scenarios that cannot be accurately priced using closed-form solutions.
Sourcepub fn calculate_price_black_scholes(&self) -> OptionsResult<Decimal>
pub fn calculate_price_black_scholes(&self) -> OptionsResult<Decimal>
Calculates option price using the Black-Scholes model.
This method implements the Black-Scholes option pricing formula, which provides a closed-form solution for European-style options. The model assumes lognormal distribution of underlying asset prices and constant volatility.
§Returns
OptionsResult<Decimal>- A result containing the calculated option price as a Decimal value, or an error if the calculation failed.
This method is computationally efficient but limited to European options without early exercise capabilities.
Sourcepub fn calculate_price_montecarlo(
&self,
prices: &[Positive],
) -> OptionsResult<Positive>
pub fn calculate_price_montecarlo( &self, prices: &[Positive], ) -> OptionsResult<Positive>
Calculates the price of an option using the Monte Carlo simulation method.
§Arguments
prices- A slice ofPositivevalues representing the prices used in the Monte Carlo simulation.
§Returns
OptionsResult<Positive>- The calculated price of the option wrapped in anOptionsResult. This will return a validPositivevalue if successful, or an error if the simulation fails.
§Errors
This function will return an error in the OptionsResult if the internal
Monte Carlo price computation fails during the execution of price_option_monte_carlo.
Sourcepub fn calculate_price_telegraph(
&self,
no_steps: usize,
) -> OptionsResult<Decimal>
pub fn calculate_price_telegraph( &self, no_steps: usize, ) -> OptionsResult<Decimal>
Calculates option price using the Telegraph equation approach.
This method implements a finite-difference method based on the Telegraph equation to price options. This approach can handle a variety of option styles and types, including path-dependent options.
§Parameters
no_steps- The number of discrete time steps to use in the model. Higher values increase precision but also computational cost.
§Returns
Result<Decimal, PricingError>- A result containing the calculated option price as a Decimal value, or a boxed error if the calculation failed.
Sourcepub fn payoff(&self) -> OptionsResult<Decimal>
pub fn payoff(&self) -> OptionsResult<Decimal>
Calculates the intrinsic value (payoff) of the option at the current underlying price.
The payoff represents what the option would be worth if exercised immediately, based on the current market conditions. For out-of-the-money options, the payoff will be zero.
§Returns
OptionsResult<Decimal>- A result containing the calculated payoff as a Decimal value, adjusted for the quantity of contracts held, or an error if the calculation failed.
This method is useful for determining the exercise value of an option and for analyzing whether an option has intrinsic value.
Sourcepub fn payoff_at_price(&self, price: &Positive) -> OptionsResult<Decimal>
pub fn payoff_at_price(&self, price: &Positive) -> OptionsResult<Decimal>
Calculates the financial payoff value of the option at a specific underlying price.
This method determines the option’s payoff based on its type, strike price, style, and side (long/short) at the given underlying price. The result represents the total profit or loss for the option position at that price, adjusted by the position quantity.
§Parameters
price- APositivevalue representing the hypothetical price of the underlying asset.
§Returns
OptionsResult<Decimal>- The calculated payoff value as aDecimal, wrapped in aResulttype. Returns anErrif the payoff calculation encounters an error.
Sourcepub fn intrinsic_value(
&self,
underlying_price: Positive,
) -> OptionsResult<Decimal>
pub fn intrinsic_value( &self, underlying_price: Positive, ) -> OptionsResult<Decimal>
Calculates the intrinsic value of the option.
The intrinsic value is the difference between the underlying asset’s price and the option’s strike price. For call options, the intrinsic value is the maximum of zero and the difference between the underlying price and the strike price. For put options, the intrinsic value is the maximum of zero and the difference between the strike price and the underlying price.
§Arguments
underlying_price- The current price of the underlying asset.
§Returns
OptionsResult<Decimal>- The intrinsic value of the option, or an error if the calculation fails.
Sourcepub fn is_in_the_money(&self) -> bool
pub fn is_in_the_money(&self) -> bool
Determines whether an option is “in-the-money” based on its current price relative to strike price.
An option is considered in-the-money when:
- For Call options: the underlying asset price is greater than or equal to the strike price
- For Put options: the underlying asset price is less than or equal to the strike price
This status is important for evaluating the option’s current value and potential profitability.
§Returns
true if the option is in-the-money, false otherwise
Sourcepub fn time_value(&self) -> OptionsResult<Decimal>
pub fn time_value(&self) -> OptionsResult<Decimal>
Calculates the time value component of an option’s price.
Time value represents the portion of an option’s premium that exceeds its intrinsic value. It reflects the market’s expectation that the option may become more valuable before expiration due to potential favorable movements in the underlying asset price.
The calculation uses the Black-Scholes model to determine the total option price, then subtracts the intrinsic value to find the time value component.
§Returns
Ok(Decimal)containing the time value (never negative, minimum value is zero)Errif the price calculation encounters an error
Sourcepub fn calculate_implied_volatility(
&self,
market_price: Decimal,
) -> Result<Positive, VolatilityError>
pub fn calculate_implied_volatility( &self, market_price: Decimal, ) -> Result<Positive, VolatilityError>
calculate_implied_volatility:
This function estimates the implied volatility of an option based on its market price using binary search. Implied volatility is a key metric in options trading that reflects the market’s view of the expected volatility of the underlying asset.
§Parameters:
market_price: The market price of the option as aDecimal. This represents the cost at which the option is traded in the market.
§Returns:
Ok(Positive): APositivevalue representing the calculated implied volatility as a percentage.Err(ImpliedVolatilityError): An error indicating the reason calculation failed, such as:- No convergence within the maximum number of iterations.
- Invalid option parameters.
§Implementation Details:
-
Binary Search: The function uses a binary search approach to iteratively find the implied volatility (
volatility) that narrows the difference between the calculated option price (via Black-Scholes) and the targetmarket_price. -
Short Options Adjustment: For short options, the market price is inverted (negated), and this adjustment ensures proper calculation of implied volatility.
-
Bounds and Iteration: The method starts with a maximum bound (
5.0, representing 500% volatility) and a lower bound (0.0). It adjusts these bounds based on whether the computed price is above or below the target and repeats until convergence or the maximum number of iterations is reached (MAX_ITERATIONS_IV). -
Convergence Tolerance: The function stops iterating when the computed price is within
IV_TOLERANCEof the target market price or when the difference between the high and low bounds is smaller than a threshold (0.0001).
§Error Cases:
- No Convergence: If the binary search exhausts the allowed number of iterations (
MAX_ITERATIONS_IV) without sufficiently narrowing down the implied volatility, the function returns anImpliedVolatilityError::NoConvergence. - Invalid Parameters: Bounds violations or invalid market inputs can potentially cause other errors during calculations.
§Example Usage:
use rust_decimal_macros::dec;
use rust_decimal::Decimal;
use tracing::{error, info};
use optionstratlib::{pos, ExpirationDate, OptionStyle, OptionType, Options, Side};
let options = Options::new(
OptionType::European,
Side::Short,
"TEST".to_string(),
pos!(6050.0), // strike
ExpirationDate::Days(pos!(60.0)),
pos!(0.1), // initial iv
pos!(1.0), // qty
pos!(6032.18), // underlying
dec!(0.0), // rate
OptionStyle::Call,
pos!(0.0), // div
None,
); // Configure your option parameters
let market_price = dec!(133.5);
match options.calculate_implied_volatility(market_price) {
Ok(volatility) => info!("Implied Volatility: {}", volatility.to_dec()),
Err(e) => error!("Failed to calculate implied volatility: {:?}", e),
}Trait Implementations§
Source§impl BasicAble for Options
impl BasicAble for Options
Source§fn get_title(&self) -> String
fn get_title(&self) -> String
Source§fn get_option_basic_type(&self) -> HashSet<OptionBasicType<'_>>
fn get_option_basic_type(&self) -> HashSet<OptionBasicType<'_>>
Source§fn get_symbol(&self) -> &str
fn get_symbol(&self) -> &str
get_symbol
method of the one_option object. Read moreSource§fn get_strike(&self) -> HashMap<OptionBasicType<'_>, &Positive>
fn get_strike(&self) -> HashMap<OptionBasicType<'_>, &Positive>
Source§fn get_type(&self) -> &OptionType
fn get_type(&self) -> &OptionType
Source§fn get_style(&self) -> HashMap<OptionBasicType<'_>, &OptionStyle>
fn get_style(&self) -> HashMap<OptionBasicType<'_>, &OptionStyle>
Source§fn get_expiration(&self) -> HashMap<OptionBasicType<'_>, &ExpirationDate>
fn get_expiration(&self) -> HashMap<OptionBasicType<'_>, &ExpirationDate>
Source§fn get_implied_volatility(&self) -> HashMap<OptionBasicType<'_>, &Positive>
fn get_implied_volatility(&self) -> HashMap<OptionBasicType<'_>, &Positive>
Source§fn get_quantity(&self) -> HashMap<OptionBasicType<'_>, &Positive>
fn get_quantity(&self) -> HashMap<OptionBasicType<'_>, &Positive>
Source§fn get_underlying_price(&self) -> &Positive
fn get_underlying_price(&self) -> &Positive
Source§fn get_risk_free_rate(&self) -> HashMap<OptionBasicType<'_>, &Decimal>
fn get_risk_free_rate(&self) -> HashMap<OptionBasicType<'_>, &Decimal>
Source§fn get_dividend_yield(&self) -> HashMap<OptionBasicType<'_>, &Positive>
fn get_dividend_yield(&self) -> HashMap<OptionBasicType<'_>, &Positive>
Source§fn one_option(&self) -> &Options
fn one_option(&self) -> &Options
one_option, is designed to retrieve a reference to an Options object.
However, in this implementation, the function is not currently functional, as it
explicitly triggers an unimplemented error when called. Read moreSource§fn one_option_mut(&mut self) -> &mut Options
fn one_option_mut(&mut self) -> &mut Options
Options instance. Read moreSource§fn set_implied_volatility(
&mut self,
volatility: &Positive,
) -> Result<(), StrategyError>
fn set_implied_volatility( &mut self, volatility: &Positive, ) -> Result<(), StrategyError>
Source§fn set_underlying_price(
&mut self,
price: &Positive,
) -> Result<(), StrategyError>
fn set_underlying_price( &mut self, price: &Positive, ) -> Result<(), StrategyError>
Source§fn set_expiration_date(
&mut self,
expiration_date: ExpirationDate,
) -> Result<(), StrategyError>
fn set_expiration_date( &mut self, expiration_date: ExpirationDate, ) -> Result<(), StrategyError>
Source§impl<'de> Deserialize<'de> for Options
impl<'de> Deserialize<'de> for Options
Source§fn deserialize<__D>(__deserializer: __D) -> Result<Self, __D::Error>where
__D: Deserializer<'de>,
fn deserialize<__D>(__deserializer: __D) -> Result<Self, __D::Error>where
__D: Deserializer<'de>,
Source§impl From<&OptionData> for Options
impl From<&OptionData> for Options
Source§fn from(option_data: &OptionData) -> Self
fn from(option_data: &OptionData) -> Self
Source§impl Graph for Options
impl Graph for Options
Source§fn graph_data(&self) -> GraphData
fn graph_data(&self) -> GraphData
Source§fn graph_config(&self) -> GraphConfig
fn graph_config(&self) -> GraphConfig
Source§impl Greeks for Options
impl Greeks for Options
Source§fn get_options(&self) -> Result<Vec<&Options>, GreeksError>
fn get_options(&self) -> Result<Vec<&Options>, GreeksError>
Source§fn greeks(&self) -> Result<Greek, GreeksError>
fn greeks(&self) -> Result<Greek, GreeksError>
Greek struct. Read moreSource§fn delta(&self) -> Result<Decimal, GreeksError>
fn delta(&self) -> Result<Decimal, GreeksError>
Source§fn gamma(&self) -> Result<Decimal, GreeksError>
fn gamma(&self) -> Result<Decimal, GreeksError>
Source§fn theta(&self) -> Result<Decimal, GreeksError>
fn theta(&self) -> Result<Decimal, GreeksError>
Source§fn vega(&self) -> Result<Decimal, GreeksError>
fn vega(&self) -> Result<Decimal, GreeksError>
Source§fn rho(&self) -> Result<Decimal, GreeksError>
fn rho(&self) -> Result<Decimal, GreeksError>
Source§fn rho_d(&self) -> Result<Decimal, GreeksError>
fn rho_d(&self) -> Result<Decimal, GreeksError>
Source§fn alpha(&self) -> Result<Decimal, GreeksError>
fn alpha(&self) -> Result<Decimal, GreeksError>
Source§fn vanna(&self) -> Result<Decimal, GreeksError>
fn vanna(&self) -> Result<Decimal, GreeksError>
Source§fn vomma(&self) -> Result<Decimal, GreeksError>
fn vomma(&self) -> Result<Decimal, GreeksError>
Source§fn veta(&self) -> Result<Decimal, GreeksError>
fn veta(&self) -> Result<Decimal, GreeksError>
Source§impl PnLCalculator for Options
impl PnLCalculator for Options
Source§fn calculate_pnl(
&self,
market_price: &Positive,
expiration_date: ExpirationDate,
implied_volatility: &Positive,
) -> Result<PnL, PricingError>
fn calculate_pnl( &self, market_price: &Positive, expiration_date: ExpirationDate, implied_volatility: &Positive, ) -> Result<PnL, PricingError>
Source§fn calculate_pnl_at_expiration(
&self,
underlying_price: &Positive,
) -> Result<PnL, PricingError>
fn calculate_pnl_at_expiration( &self, underlying_price: &Positive, ) -> Result<PnL, PricingError>
Source§fn adjustments_pnl(
&self,
_adjustments: &DeltaAdjustment,
) -> Result<PnL, PricingError>
fn adjustments_pnl( &self, _adjustments: &DeltaAdjustment, ) -> Result<PnL, PricingError>
Source§fn diff_position_pnl(&self, _position: &Position) -> Result<PnL, PricingError>
fn diff_position_pnl(&self, _position: &Position) -> Result<PnL, PricingError>
Source§impl Priceable for Options
Implementation of Priceable for Options.
impl Priceable for Options
Implementation of Priceable for Options.
This allows options to be priced using the unified pricing API.
Source§fn price(&self, engine: &PricingEngine) -> PricingResult<Positive>
fn price(&self, engine: &PricingEngine) -> PricingResult<Positive>
Source§impl Profit for Options
impl Profit for Options
Source§fn calculate_profit_at(&self, price: &Positive) -> Result<Decimal, PricingError>
fn calculate_profit_at(&self, price: &Positive) -> Result<Decimal, PricingError>
Source§fn get_point_at_price(
&self,
_price: &Positive,
) -> Result<(Decimal, Decimal), PricingError>
fn get_point_at_price( &self, _price: &Positive, ) -> Result<(Decimal, Decimal), PricingError>
impl StructuralPartialEq for Options
Auto Trait Implementations§
impl Freeze for Options
impl RefUnwindSafe for Options
impl Send for Options
impl Sync for Options
impl Unpin for Options
impl UnwindSafe for Options
Blanket Implementations§
§impl<T> BorrowMut<T> for Twhere
T: ?Sized,
impl<T> BorrowMut<T> for Twhere
T: ?Sized,
§fn borrow_mut(&mut self) -> &mut T
fn borrow_mut(&mut self) -> &mut T
§impl<T> CloneToUninit for Twhere
T: Clone,
impl<T> CloneToUninit for Twhere
T: Clone,
§unsafe fn clone_to_uninit(&self, dest: *mut u8)
unsafe fn clone_to_uninit(&self, dest: *mut u8)
clone_to_uninit)Source§impl<T> Instrument for T
impl<T> Instrument for T
Source§fn instrument(self, span: Span) -> Instrumented<Self>
fn instrument(self, span: Span) -> Instrumented<Self>
Source§fn in_current_span(self) -> Instrumented<Self>
fn in_current_span(self) -> Instrumented<Self>
Source§impl<T> IntoEither for T
impl<T> IntoEither for T
Source§fn into_either(self, into_left: bool) -> Either<Self, Self>
fn into_either(self, into_left: bool) -> Either<Self, Self>
self into a Left variant of Either<Self, Self>
if into_left is true.
Converts self into a Right variant of Either<Self, Self>
otherwise. Read moreSource§fn into_either_with<F>(self, into_left: F) -> Either<Self, Self>
fn into_either_with<F>(self, into_left: F) -> Either<Self, Self>
self into a Left variant of Either<Self, Self>
if into_left(&self) returns true.
Converts self into a Right variant of Either<Self, Self>
otherwise. Read moreSource§impl<T> PartialSchema for Twhere
T: ComposeSchema + ?Sized,
impl<T> PartialSchema for Twhere
T: ComposeSchema + ?Sized,
Source§impl<T> Pointable for T
impl<T> Pointable for T
Source§impl<SS, SP> SupersetOf<SS> for SPwhere
SS: SubsetOf<SP>,
impl<SS, SP> SupersetOf<SS> for SPwhere
SS: SubsetOf<SP>,
Source§fn to_subset(&self) -> Option<SS>
fn to_subset(&self) -> Option<SS>
self from the equivalent element of its
superset. Read moreSource§fn is_in_subset(&self) -> bool
fn is_in_subset(&self) -> bool
self is actually part of its subset T (and can be converted to it).Source§fn to_subset_unchecked(&self) -> SS
fn to_subset_unchecked(&self) -> SS
self.to_subset but without any property checks. Always succeeds.Source§fn from_subset(element: &SS) -> SP
fn from_subset(element: &SS) -> SP
self to the equivalent element of its superset.