quantlib_rs 0.1.0

A ground-up, idiomatic Rust quantitative finance library inspired by QuantLib.
Documentation
//! Discounting engine for bond valuation.

use crate::instruments::bonds::fixed_rate_bond::{BondError, FixedRateBond};
use crate::termstructures::yield_term_structure::YieldTermStructure;
use crate::time::date::Date;
use std::sync::Arc;

/// Discounting pricing engine for bonds.
///
/// Computes Net Present Value (NPV), clean price, and dirty price of bonds
/// given a yield term structure.
///
/// # Examples
/// ```
/// use std::sync::Arc;
/// use quantlib_rs::engines::bond_engine::DiscountingBondEngine;
/// use quantlib_rs::instruments::bonds::fixed_rate_bond::FixedRateBond;
/// use quantlib_rs::termstructures::yield_term_structure::FlatForward;
/// use quantlib_rs::time::calendar::BusinessDayConvention;
/// use quantlib_rs::time::calendars::weekends_only::WeekendsOnly;
/// use quantlib_rs::time::date::{Date, Month, Period};
/// use quantlib_rs::time::day_counters::actual_actual::ActualActual;
/// use quantlib_rs::time::schedule::{DateGenerationRule, Schedule};
///
/// let cal = Arc::new(WeekendsOnly);
/// let dc = Arc::new(ActualActual::default());
/// let issue = Date::from_ymd(2024, Month::January, 15).unwrap();
/// let maturity = Date::from_ymd(2029, Month::January, 15).unwrap();
///
/// let schedule = Schedule::new(
///     issue,
///     maturity,
///     Period::Months(6),
///     cal.as_ref(),
///     BusinessDayConvention::Following,
///     BusinessDayConvention::Following,
///     DateGenerationRule::Backward,
///     false,
/// ).unwrap();
///
/// let bond = FixedRateBond::new(1, 100.0, schedule, 0.04, dc, cal, issue, 100.0);
/// let today = Date::from_ymd(2024, Month::January, 15).unwrap();
/// let curve = Arc::new(FlatForward::new(0.04, today));
/// let engine = DiscountingBondEngine::new(curve);
/// let clean = engine.calculate_clean(&bond, today).unwrap();
/// assert!((clean - 100.0).abs() < 1.0);
/// ```
#[derive(Clone)]
pub struct DiscountingBondEngine {
    discount_curve: Arc<dyn YieldTermStructure>,
}

impl DiscountingBondEngine {
    /// Create a new discounting bond engine.
    pub fn new(discount_curve: Arc<dyn YieldTermStructure>) -> Self {
        Self { discount_curve }
    }

    /// Return a reference to the underlying discount curve.
    pub fn discount_curve(&self) -> &dyn YieldTermStructure {
        self.discount_curve.as_ref()
    }

    /// Calculate the full (dirty) price of the bond on valuation date `as_of`.
    pub fn calculate_dirty(&self, bond: &FixedRateBond, as_of: Date) -> Result<f64, BondError> {
        bond.dirty_price(self.discount_curve.as_ref(), as_of)
    }

    /// Calculate the clean price of the bond on valuation date `as_of`.
    pub fn calculate_clean(&self, bond: &FixedRateBond, as_of: Date) -> Result<f64, BondError> {
        bond.clean_price(self.discount_curve.as_ref(), as_of)
    }
}