ExpirationDate

Enum ExpirationDate 

Source
pub enum ExpirationDate {
    Days(Positive),
    DateTime(DateTime<Utc>),
}
Expand description

Represents the expiration of an option contract or financial instrument.

This enum allows for two different ways to specify when something expires:

  • As a number of days from the current date
  • As a specific date and time

ExpirationDate is used throughout the options modeling system to handle time-based calculations such as time decay (theta) and option valuation.

Variants§

§

Days(Positive)

Represents expiration as a positive number of days from the current date. This is typically used for relative time specifications. when converting between Days and DateTime variants.

§

DateTime(DateTime<Utc>)

Represents expiration as an absolute point in time using UTC datetime. This is used when a precise expiration moment is known.

Implementations§

Source§

impl ExpirationDate

Source

pub fn get_years(&self) -> Result<Positive, DecimalError>

Calculates the time to expiration in years.

Returns a Result<Positive, ChainError>.

§Arguments
  • &self - The ExpirationDate instance.
§Errors

Returns an error if the DateTime variant results in a negative duration indicating the expiration date is in the past.

§Examples
use chrono::{Duration, Utc};
use rust_decimal_macros::dec;
use optionstratlib::{assert_pos_relative_eq, pos, ExpirationDate};

let days = pos!(365.0);
let expiration_date_days = ExpirationDate::Days(days);
let years = expiration_date_days.get_years().unwrap();
assert_pos_relative_eq!(years, pos!(1.0), pos!(0.001));

let datetime = Utc::now() + Duration::days(365);
let expiration_date_datetime = ExpirationDate::DateTime(datetime);
let years = expiration_date_datetime.get_years().unwrap();
assert_pos_relative_eq!(years, pos!(1.0), pos!(0.001));
Source

pub fn get_days(&self) -> Result<Positive, DecimalError>

Calculates the number of days until expiration for this ExpirationDate instance.

This method converts both variants of ExpirationDate to a common representation: the number of days until expiration. This is useful for calculations that need time-to-expiry in a standardized format.

§Returns
  • Result<Positive, DecimalError> - A Positive value representing the number of days until expiration, or an error if the calculation fails.
§Details
  • For ExpirationDate::Days variant: Returns the stored days value directly.
  • For ExpirationDate::DateTime variant: Calculates the difference between the stored datetime and the current time, converting it to days.

If the calculation results in zero or negative days (meaning the expiration date is in the past), the method returns Positive::ZERO to indicate immediate expiration.

Source

pub fn get_date(&self) -> Result<DateTime<Utc>, DecimalError>

Returns the expiration date as a DateTime<Utc>.

For the Days variant, it calculates the date by adding the specified number of days to the current date and time. For the DateTime variant, it returns the stored DateTime<Utc>.

§Examples
use chrono::{Duration, Utc};
use rust_decimal_macros::dec;
use optionstratlib::{pos, ExpirationDate};

let days = pos!(30.0);
let expiration_date_days = ExpirationDate::Days(days);
let future_date = Utc::now() + Duration::days(30);
let calculated_date = expiration_date_days.get_date().unwrap();
// Check if dates are within a small tolerance (due to potential time differences during test)
assert_eq!(calculated_date.date_naive(), future_date.date_naive());

let datetime = Utc::now() + Duration::days(365);
let expiration_date_datetime = ExpirationDate::DateTime(datetime);
let stored_date = expiration_date_datetime.get_date().unwrap();
assert_eq!(stored_date, datetime);
Source

pub fn get_date_with_options( &self, use_fixed_time: bool, ) -> Result<DateTime<Utc>, DecimalError>

Calculates and returns a DateTime<Utc> based on the specified options and expiration criteria.

§Parameters
  • use_fixed_time:
    • If true, a fixed daily time of 18:30 UTC is used as the base time for calculations.
    • If false, the base time for calculations depends on a reference datetime if available. If no reference datetime exists, the calculation will use the current time.
§Returns
  • Ok(DateTime<Utc>):
    • If the expiration date can be successfully calculated based on the provided options and stored expiration criteria (Days or DateTime).
  • Err(ChainError):
    • If there is an invalid time conversion or inconsistency in the configuration.
§Behavior

This function handles two expiration types:

  1. ExpirationDate::Days:
    • If use_fixed_time is true:
      • Takes today’s date and sets the time to 18:30 UTC as the base datetime.
      • Adds the specified number of days from the Days variant to this fixed datetime.
    • If use_fixed_time is false:
      • Uses a stored reference datetime (get_reference_datetime, if available) as the base datetime, and adds the number of days from the Days variant.
      • If no reference datetime is found, uses the current time as the base datetime.
  2. ExpirationDate::DateTime:
    • Directly returns the pre-stored datetime associated with this variant.
§Errors
  • Returns an error if a fixed time (18:30 UTC) cannot be correctly configured.
  • Returns an error if any internal inconsistency occurs (e.g., invalid conversions).
Source

pub fn get_date_string(&self) -> Result<String, ChainError>

Returns the expiration date as a formatted string in YYYY-MM-DD format.

This method calls get_date() to retrieve the DateTime<Utc> and then formats it into the specified string format.

§Examples
use chrono::{Duration, Utc};
use rust_decimal_macros::dec;
use optionstratlib::{pos, ExpirationDate};

let days = pos!(30.0);
let expiration_date = ExpirationDate::Days(days);
let date_string = expiration_date.get_date_string().unwrap();
assert!(date_string.len() == 10); // YYYY-MM-DD format
Source

pub fn from_string(s: &str) -> Result<Self, ChainError>

Creates an ExpirationDate from a string.

This function attempts to parse the input string s into an ExpirationDate. It supports various formats, including:

  1. Positive number of days: Parses the string as a Positive number, representing days from now.
  2. RFC3339 DateTime: Parses the string as an RFC3339 compliant date and time string.
  3. Numeric Date (YYYYMMDD): Parses an 8-digit numeric string as year, month, and day. Sets the time to 23:59:59.
  4. Common Date formats: Parses various common date formats (e.g., DD-MM-YYYY, DD MMM YYYY, etc.). Sets the time to 23:59:59.

If none of the above formats can be parsed successfully, an error is returned.

§Arguments
  • s - The input string to parse.
§Examples
use chrono::{DateTime, Utc};
use rust_decimal_macros::dec;
use tracing::info;
use optionstratlib::{pos, ExpirationDate};

let expiration_date_days = ExpirationDate::from_string("365").unwrap();
assert_eq!(expiration_date_days, ExpirationDate::Days(pos!(365.0)));

let rfc3339_string = "2025-01-01T12:00:00Z";
let expiration_date_rfc3339 = ExpirationDate::from_string(rfc3339_string).unwrap();
let datetime = DateTime::parse_from_rfc3339(rfc3339_string).unwrap();
assert_eq!(expiration_date_rfc3339, ExpirationDate::DateTime(DateTime::from(datetime)));

let numeric_date_string = "20250101";
let expiration_date_numeric = ExpirationDate::from_string(numeric_date_string).unwrap();
if let ExpirationDate::DateTime(dt) = expiration_date_numeric {
    assert_eq!(dt.format("%Y%m%d").to_string(), numeric_date_string);
} else {
    info!("Expected ExpirationDate::DateTime");
}


let common_date_string = "01-01-2025";
let expiration_date_common = ExpirationDate::from_string(common_date_string).unwrap();
if let ExpirationDate::DateTime(dt) = expiration_date_common {
    assert_eq!(dt.format("%d-%m-%Y").to_string(), common_date_string);
} else {
    info!("Expected ExpirationDate::DateTime");
}
Source

pub fn from_string_to_days(s: &str) -> Result<Self, ChainError>

Converts a string representation of an expiration date into a Days variant of ExpirationDate.

§Arguments
  • s - A string slice representing the expiration date. The string should adhere to a format that ExpirationDate::from_string can parse.
§Returns
  • Ok(Self) - If the string is successfully parsed and converted into days. The result is an ExpirationDate::Days variant containing the floored number of days.
  • Err(ChainError) - If parsing or conversion fails, an error wrapped in a ChainError is returned.
§Errors

This function may return an error in the following cases:

  • The provided string s is not in a valid or expected format.
  • The computed number of days could not be retrieved from the parsed expiration date.
§Note

The function assumes that floor() truncates any remaining fractional days.

Trait Implementations§

Source§

impl Clone for ExpirationDate

Source§

fn clone(&self) -> ExpirationDate

Returns a duplicate of the value. Read more
1.0.0§

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

Performs copy-assignment from source. Read more
Source§

impl ComposeSchema for ExpirationDate

Source§

impl Debug for ExpirationDate

Source§

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

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

impl Default for ExpirationDate

Source§

fn default() -> Self

Returns the “default value” for a type. Read more
Source§

impl<'de> Deserialize<'de> for ExpirationDate

Source§

fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
where D: Deserializer<'de>,

Deserialize this value from the given Serde deserializer. Read more
Source§

impl Display for ExpirationDate

Source§

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

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

impl Hash for ExpirationDate

Source§

fn hash<H: Hasher>(&self, state: &mut H)

Feeds this value into the given Hasher. Read more
1.3.0§

fn hash_slice<H>(data: &[Self], state: &mut H)
where H: Hasher, Self: Sized,

Feeds a slice of this type into the given Hasher. Read more
Source§

impl Ord for ExpirationDate

Source§

fn cmp(&self, other: &Self) -> Ordering

This method returns an Ordering between self and other. Read more
1.21.0§

fn max(self, other: Self) -> Self
where Self: Sized,

Compares and returns the maximum of two values. Read more
1.21.0§

fn min(self, other: Self) -> Self
where Self: Sized,

Compares and returns the minimum of two values. Read more
1.50.0§

fn clamp(self, min: Self, max: Self) -> Self
where Self: Sized,

Restrict a value to a certain interval. Read more
Source§

impl PartialEq for ExpirationDate

Source§

fn eq(&self, other: &Self) -> bool

Tests for self and other values to be equal, and is used by ==.
1.0.0§

fn ne(&self, other: &Rhs) -> bool

Tests for !=. The default implementation is almost always sufficient, and should not be overridden without very good reason.
Source§

impl PartialOrd for ExpirationDate

Source§

fn partial_cmp(&self, other: &Self) -> Option<Ordering>

This method returns an ordering between self and other values if one exists. Read more
1.0.0§

fn lt(&self, other: &Rhs) -> bool

Tests less than (for self and other) and is used by the < operator. Read more
1.0.0§

fn le(&self, other: &Rhs) -> bool

Tests less than or equal to (for self and other) and is used by the <= operator. Read more
1.0.0§

fn gt(&self, other: &Rhs) -> bool

Tests greater than (for self and other) and is used by the > operator. Read more
1.0.0§

fn ge(&self, other: &Rhs) -> bool

Tests greater than or equal to (for self and other) and is used by the >= operator. Read more
Source§

impl Serialize for ExpirationDate

Source§

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

Serialize this value into the given Serde serializer. Read more
Source§

impl ToSchema for ExpirationDate

Source§

fn name() -> Cow<'static, str>

Return name of the schema. Read more
Source§

fn schemas(schemas: &mut Vec<(String, RefOr<Schema>)>)

Implement reference utoipa::openapi::schema::Schemas for this type. Read more
Source§

impl Copy for ExpirationDate

Source§

impl Eq for ExpirationDate

Auto Trait Implementations§

Blanket Implementations§

§

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

§

fn type_id(&self) -> TypeId

Gets the TypeId of self. Read more
§

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

§

fn borrow(&self) -> &T

Immutably borrows from an owned value. Read more
§

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

§

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

Mutably borrows from an owned value. Read more
§

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

§

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

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

impl<Q, K> Comparable<K> for Q
where Q: Ord + ?Sized, K: Borrow<Q> + ?Sized,

Source§

fn compare(&self, key: &K) -> Ordering

Compare self to key and return their ordering.
Source§

impl<Q, K> Equivalent<K> for Q
where Q: Eq + ?Sized, K: Borrow<Q> + ?Sized,

Source§

fn equivalent(&self, key: &K) -> bool

Checks if this value is equivalent to the given key. Read more
Source§

impl<Q, K> Equivalent<K> for Q
where Q: Eq + ?Sized, K: Borrow<Q> + ?Sized,

Source§

fn equivalent(&self, key: &K) -> bool

Compare self to key and return true if they are equal.
§

impl<T> From<T> for T

§

fn from(t: T) -> T

Returns the argument unchanged.

Source§

impl<T> Instrument for T

Source§

fn instrument(self, span: Span) -> Instrumented<Self>

Instruments this type with the provided Span, returning an Instrumented wrapper. Read more
Source§

fn in_current_span(self) -> Instrumented<Self>

Instruments this type with the current Span, returning an Instrumented wrapper. Read more
§

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

§

fn into(self) -> U

Calls U::from(self).

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

Source§

impl<T> IntoEither for T

Source§

fn into_either(self, into_left: bool) -> Either<Self, Self>

Converts 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 more
Source§

fn into_either_with<F>(self, into_left: F) -> Either<Self, Self>
where F: FnOnce(&Self) -> bool,

Converts 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 more
Source§

impl<T> PartialSchema for T
where T: ComposeSchema + ?Sized,

Source§

fn schema() -> RefOr<Schema>

Return ref or schema of implementing type that can then be used to construct combined schemas.
Source§

impl<T> Pointable for T

Source§

const ALIGN: usize

The alignment of pointer.
Source§

type Init = T

The type for initializers.
Source§

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

Initializes a with the given initializer. Read more
Source§

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

Dereferences the given pointer. Read more
Source§

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

Mutably dereferences the given pointer. Read more
Source§

unsafe fn drop(ptr: usize)

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

impl<T> Same for T

Source§

type Output = T

Should always be Self
Source§

impl<SS, SP> SupersetOf<SS> for SP
where SS: SubsetOf<SP>,

Source§

fn to_subset(&self) -> Option<SS>

The inverse inclusion map: attempts to construct self from the equivalent element of its superset. Read more
Source§

fn is_in_subset(&self) -> bool

Checks if self is actually part of its subset T (and can be converted to it).
Source§

fn to_subset_unchecked(&self) -> SS

Use with care! Same as self.to_subset but without any property checks. Always succeeds.
Source§

fn from_subset(element: &SS) -> SP

The inclusion map: converts self to the equivalent element of its superset.
§

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

§

type Owned = T

The resulting type after obtaining ownership.
§

fn to_owned(&self) -> T

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

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

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

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

§

fn to_string(&self) -> String

Converts the given value to a String. Read more
§

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

§

type Error = Infallible

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

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

Performs the conversion.
§

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

§

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

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

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

Performs the conversion.
Source§

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

Source§

fn vzip(self) -> V

Source§

impl<T> WithSubscriber for T

Source§

fn with_subscriber<S>(self, subscriber: S) -> WithDispatch<Self>
where S: Into<Dispatch>,

Attaches the provided Subscriber to this type, returning a WithDispatch wrapper. Read more
Source§

fn with_current_subscriber(self) -> WithDispatch<Self>

Attaches the current default Subscriber to this type, returning a WithDispatch wrapper. Read more
Source§

impl<T> DeserializeOwned for T
where T: for<'de> Deserialize<'de>,

Source§

impl<T> Scalar for T
where T: 'static + Clone + PartialEq + Debug,