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
impl ExpirationDate
Sourcepub fn get_years(&self) -> Result<Positive, DecimalError>
pub fn get_years(&self) -> Result<Positive, DecimalError>
Calculates the time to expiration in years.
Returns a Result<Positive, ChainError>.
§Arguments
&self- TheExpirationDateinstance.
§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));Sourcepub fn get_days(&self) -> Result<Positive, DecimalError>
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>- APositivevalue representing the number of days until expiration, or an error if the calculation fails.
§Details
- For
ExpirationDate::Daysvariant: Returns the stored days value directly. - For
ExpirationDate::DateTimevariant: 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.
Sourcepub fn get_date(&self) -> Result<DateTime<Utc>, DecimalError>
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);Sourcepub fn get_date_with_options(
&self,
use_fixed_time: bool,
) -> Result<DateTime<Utc>, DecimalError>
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.
- If
§Returns
Ok(DateTime<Utc>):- If the expiration date can be successfully calculated based on the provided options and
stored expiration criteria (
DaysorDateTime).
- If the expiration date can be successfully calculated based on the provided options and
stored expiration criteria (
Err(ChainError):- If there is an invalid time conversion or inconsistency in the configuration.
§Behavior
This function handles two expiration types:
ExpirationDate::Days:- If
use_fixed_timeistrue:- Takes today’s date and sets the time to 18:30 UTC as the base datetime.
- Adds the specified number of days from the
Daysvariant to this fixed datetime.
- If
use_fixed_timeisfalse:- Uses a stored reference datetime (
get_reference_datetime, if available) as the base datetime, and adds the number of days from theDaysvariant. - If no reference datetime is found, uses the current time as the base datetime.
- Uses a stored reference datetime (
- If
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).
Sourcepub fn get_date_string(&self) -> Result<String, ChainError>
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 formatSourcepub fn from_string(s: &str) -> Result<Self, ChainError>
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:
- Positive number of days: Parses the string as a
Positivenumber, representing days from now. - RFC3339 DateTime: Parses the string as an RFC3339 compliant date and time string.
- Numeric Date (YYYYMMDD): Parses an 8-digit numeric string as year, month, and day. Sets the time to 23:59:59.
- 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");
}Sourcepub fn from_string_to_days(s: &str) -> Result<Self, ChainError>
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 thatExpirationDate::from_stringcan parse.
§Returns
Ok(Self)- If the string is successfully parsed and converted into days. The result is anExpirationDate::Daysvariant containing the floored number of days.Err(ChainError)- If parsing or conversion fails, an error wrapped in aChainErroris returned.
§Errors
This function may return an error in the following cases:
- The provided string
sis 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
impl Clone for ExpirationDate
Source§fn clone(&self) -> ExpirationDate
fn clone(&self) -> ExpirationDate
1.0.0§fn clone_from(&mut self, source: &Self)
fn clone_from(&mut self, source: &Self)
source. Read moreSource§impl ComposeSchema for ExpirationDate
impl ComposeSchema for ExpirationDate
Source§impl Debug for ExpirationDate
impl Debug for ExpirationDate
Source§impl Default for ExpirationDate
impl Default for ExpirationDate
Source§impl<'de> Deserialize<'de> for ExpirationDate
impl<'de> Deserialize<'de> for ExpirationDate
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 Display for ExpirationDate
impl Display for ExpirationDate
Source§impl Hash for ExpirationDate
impl Hash for ExpirationDate
Source§impl Ord for ExpirationDate
impl Ord for ExpirationDate
Source§impl PartialEq for ExpirationDate
impl PartialEq for ExpirationDate
Source§impl PartialOrd for ExpirationDate
impl PartialOrd for ExpirationDate
Source§impl Serialize for ExpirationDate
impl Serialize for ExpirationDate
Source§impl ToSchema for ExpirationDate
impl ToSchema for ExpirationDate
impl Copy for ExpirationDate
impl Eq for ExpirationDate
Auto Trait Implementations§
impl Freeze for ExpirationDate
impl RefUnwindSafe for ExpirationDate
impl Send for ExpirationDate
impl Sync for ExpirationDate
impl Unpin for ExpirationDate
impl UnwindSafe for ExpirationDate
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<Q, K> Comparable<K> for Q
impl<Q, K> Comparable<K> for Q
Source§impl<Q, K> Equivalent<K> for Q
impl<Q, K> Equivalent<K> for Q
Source§impl<Q, K> Equivalent<K> for Q
impl<Q, K> Equivalent<K> for Q
Source§fn equivalent(&self, key: &K) -> bool
fn equivalent(&self, key: &K) -> bool
key and return true if they are equal.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.