Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
66 changes: 61 additions & 5 deletions python/rateslib/curves/rs.py
Original file line number Diff line number Diff line change
@@ -1,28 +1,84 @@
from __future__ import annotations

from datetime import datetime as dt
from uuid import uuid4

from rateslib import defaults
from rateslib.default import NoInput, _drb
from rateslib.dual import _get_adorder
from rateslib.dual import ADOrder, _get_adorder
from rateslib.rs import Curve as CurveObj # noqa: F401
from rateslib.rs import (
FlatBackwardInterpolator,
FlatForwardInterpolator,
LinearInterpolator,
LinearZeroRateInterpolator,
LogLinearInterpolator,
NullInterpolator,
)


class CurveRs:
def __init__(self, nodes, interpolation, id, ad, index_base=NoInput(0)):
interpolation = _get_interpolator(interpolation)
self.obj = CurveObj(nodes, interpolation, _get_adorder(ad), id, _drb(None, index_base))
def __init__(
self,
nodes: dict,
*,
interpolation: str | callable | NoInput = NoInput(0),
id: str | NoInput = NoInput(0),
ad: int = 0,
index_base: float | NoInput = NoInput(0),
):
self._py_interpolator = interpolation if callable(interpolation) else None

self.obj = CurveObj(
nodes=nodes,
interpolator=self._validate_interpolator(interpolation),
ad=_get_adorder(ad),
id=_drb(uuid4().hex[:5] + "_", id), # 1 in a million clash
index_base=_drb(None, index_base),
)

@property
def id(self):
return self.obj.id

@property
def interpolation(self):
return self.obj.interpolation

@property
def nodes(self):
return self.obj.nodes

@property
def ad(self):
_ = self.obj.ad
if _ is ADOrder.One:
return 1
elif _ is ADOrder.Two:
return 2
return 0

@staticmethod
def _validate_interpolator(interpolation: str | callable | NoInput):
if interpolation is NoInput.blank:
return _get_interpolator(defaults.interpolation["Curve"])
elif isinstance(interpolation, str):
return _get_interpolator(interpolation)
else:
return NullInterpolator()

def to_json(self):
return '{"Py":' + self.obj.to_json() + "}"

@classmethod
def __init_from_obj__(cls, obj):
new = cls({dt(2000, 1, 1): 1.0}, "linear", "_", 0)
new = cls(
nodes={dt(2000, 1, 1): 1.0},
interpolation="linear",
id="_",
ad=0,
index_base=NoInput(0),
)
new.obj = obj
return new

Expand Down
7 changes: 5 additions & 2 deletions src/curves/curve_py.rs
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@
use crate::curves::nodes::{Nodes, NodesTimestamp};
use crate::curves::{
CurveDF, CurveInterpolation, FlatBackwardInterpolator, FlatForwardInterpolator,
LinearInterpolator, LinearZeroRateInterpolator, LogLinearInterpolator,
LinearInterpolator, LinearZeroRateInterpolator, LogLinearInterpolator, NullInterpolator,
};
use crate::dual::{get_variable_tags, set_order, ADOrder, Dual, Dual2, DualsOrF64};
use crate::json::json_py::DeserializedObj;
Expand All @@ -20,8 +20,9 @@ pub(crate) enum CurveInterpolator {
LogLinear(LogLinearInterpolator),
Linear(LinearInterpolator),
LinearZeroRate(LinearZeroRateInterpolator),
FlatForward(FlatForwardInterpolator), // LinearIndex,
FlatForward(FlatForwardInterpolator),
FlatBackward(FlatBackwardInterpolator),
Null(NullInterpolator),
}

impl CurveInterpolation for CurveInterpolator {
Expand All @@ -32,6 +33,7 @@ impl CurveInterpolation for CurveInterpolator {
CurveInterpolator::LinearZeroRate(i) => i.interpolated_value(nodes, date),
CurveInterpolator::FlatBackward(i) => i.interpolated_value(nodes, date),
CurveInterpolator::FlatForward(i) => i.interpolated_value(nodes, date),
CurveInterpolator::Null(i) => i.interpolated_value(nodes, date),
}
}
}
Expand Down Expand Up @@ -91,6 +93,7 @@ impl Curve {
CurveInterpolator::LinearZeroRate(_) => "linear_zero_rate".to_string(),
CurveInterpolator::FlatForward(_) => "flat_forward".to_string(),
CurveInterpolator::FlatBackward(_) => "flat_backward".to_string(),
CurveInterpolator::Null(_) => "null".to_string(),
}
}

Expand Down
55 changes: 55 additions & 0 deletions src/curves/interpolation/intp_null.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,55 @@
use crate::curves::nodes::NodesTimestamp;
use crate::curves::CurveInterpolation;
use crate::dual::DualsOrF64;
use chrono::NaiveDateTime;
use pyo3::{pyclass, pymethods};
use serde::{Deserialize, Serialize};
use std::cmp::PartialEq;

/// Define a null interpolation object.
///
/// This is used by PyO3 binding to indicate interpolation occurs in Python.
#[pyclass(module = "rateslib.rs")]
#[derive(Clone, Debug, PartialEq, Deserialize, Serialize)]
pub struct NullInterpolator {}

#[pymethods]
impl NullInterpolator {
#[new]
pub fn new() -> Self {
NullInterpolator {}
}
}

impl CurveInterpolation for NullInterpolator {
fn interpolated_value(&self, _nodes: &NodesTimestamp, _date: &NaiveDateTime) -> DualsOrF64 {
panic!("NullInterpolator cannot be used to obtain interpolated values.");
#[allow(unreachable_code)]
DualsOrF64::F64(0.0)
}
}

#[cfg(test)]
mod tests {
use super::*;
use crate::calendars::ndt;
use crate::curves::nodes::Nodes;
use indexmap::IndexMap;

fn nodes_timestamp_fixture() -> NodesTimestamp {
let nodes = Nodes::F64(IndexMap::from_iter(vec![
(ndt(2000, 1, 1), 1.0_f64),
(ndt(2001, 1, 1), 0.99_f64),
(ndt(2002, 1, 1), 0.98_f64),
]));
NodesTimestamp::from(nodes)
}

#[test]
#[should_panic]
fn test_null_interpolation() {
let nts = nodes_timestamp_fixture();
let li = NullInterpolator::new();
li.interpolated_value(&nts, &ndt(2000, 7, 1));
}
}
1 change: 1 addition & 0 deletions src/curves/interpolation/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -5,5 +5,6 @@ pub(crate) mod intp_flat_forward;
pub(crate) mod intp_linear;
pub(crate) mod intp_linear_zero_rate;
pub(crate) mod intp_log_linear;
pub(crate) mod intp_null;

pub(crate) mod utils;
1 change: 1 addition & 0 deletions src/curves/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,7 @@ pub use crate::curves::interpolation::intp_flat_forward::FlatForwardInterpolator
pub use crate::curves::interpolation::intp_linear::LinearInterpolator;
pub use crate::curves::interpolation::intp_linear_zero_rate::LinearZeroRateInterpolator;
pub use crate::curves::interpolation::intp_log_linear::LogLinearInterpolator;
pub use crate::curves::interpolation::intp_null::NullInterpolator;

pub(crate) mod curve;
pub use crate::curves::curve::{CurveDF, CurveInterpolation};
Expand Down
3 changes: 2 additions & 1 deletion src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -28,7 +28,7 @@ use curves::curve_py::Curve;
use curves::interpolation::interpolation_py::index_left_f64;
use curves::{
FlatBackwardInterpolator, FlatForwardInterpolator, LinearInterpolator,
LinearZeroRateInterpolator, LogLinearInterpolator,
LinearZeroRateInterpolator, LogLinearInterpolator, NullInterpolator,
};

pub mod calendars;
Expand Down Expand Up @@ -68,6 +68,7 @@ fn rs(m: &Bound<'_, PyModule>) -> PyResult<()> {
m.add_class::<LinearInterpolator>()?;
m.add_class::<LogLinearInterpolator>()?;
m.add_class::<LinearZeroRateInterpolator>()?;
m.add_class::<NullInterpolator>()?;

// Calendars
m.add_class::<Cal>()?;
Expand Down