Skip to content

Commit

Permalink
Update interpolation method and handle insufficient points error
Browse files Browse the repository at this point in the history
The interpolation method used in qlab-math has been updated to handle cases where there are insufficient points for interpolation, returning an error. Also, the interpolation method used in yield curve calculation within the calculate_bond test has been changed from Linear to Natural Cubic. These changes enhance the accuracy and reliability of the calculations.
  • Loading branch information
nakashima-hikaru committed Jun 15, 2024
1 parent 7a63090 commit 747629b
Show file tree
Hide file tree
Showing 2 changed files with 10 additions and 4 deletions.
8 changes: 7 additions & 1 deletion crates/qlab-math/src/interpolation.rs
Original file line number Diff line number Diff line change
Expand Up @@ -76,11 +76,17 @@ fn find_index_at_left_boundary<V: PartialOrd>(
points: &[impl X<V>],
x: V,
) -> Result<usize, InterpolationError<V>> {
if points.is_empty() {
return Err(InterpolationError::InsufficientPointsError(points.len()));
}
let pos = points.partition_point(|point| *point.x() < x);
if pos.is_zero() && *points.iter().next().unwrap().x() <= x {
return Ok(0);
}
if pos.is_zero() {
return Err(InterpolationError::OutOfLowerBound(x));
}
if pos > points.len() {
if pos == points.len() {
return Err(InterpolationError::OutOfUpperBound(x));
}
Ok(pos - 1)
Expand Down
6 changes: 3 additions & 3 deletions crates/qlab/tests/calculate_bond.rs
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
use qlab_instrument::bond::Bond;
use qlab_math::interpolation::linear::Linear;
use qlab_math::interpolation::spline::natural_cubic::NaturalCubic;
use qlab_termstructure::yield_curve::YieldCurve;
use qlab_time::date::Date;
use qlab_time::day_count::act_365::Act365;
Expand Down Expand Up @@ -44,11 +44,11 @@ fn main() {
let spot_yields: Vec<f64> = vec![
0.02, 0.0219, 0.0237, 0.0267, 0.0312, 0.0343, 0.0378, 0.0393, 0.04, 0.0401, 0.0401, 0.04,
];
let yield_curve: YieldCurve<Act365, _, Linear<f64>> =
let yield_curve: YieldCurve<Act365, _, NaturalCubic<f64>> =
YieldCurve::new(spot_settle_date, &maturities, &spot_yields).unwrap();
let val = bond_20_yr
.discounted_value(spot_settle_date, &yield_curve)
.unwrap();
println!("{}", bond_20_yr.bond_id());
println!("{val}"); // 1314.934419206669
println!("{val}"); // 1314.5664389486494
}

0 comments on commit 747629b

Please sign in to comment.