Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

BUG: FxRates Python pickling #393

Merged
merged 3 commits into from
Sep 16, 2024
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
4 changes: 4 additions & 0 deletions docs/source/i_whatsnew.rst
Original file line number Diff line number Diff line change
Expand Up @@ -50,6 +50,10 @@ email contact through **[email protected]**.
- Improve the speed of bond :meth:`~rateslib.instruments.FixedRateBond.ytm` calculations from about 750us to
500us on average.
`(380) <https://github.com/attack68/rateslib/pull/380>`_
* - Bug
- :class:`~rateslib.fx.FXRates` fix support for pickling which allows multithreading across CPU pools or
external serialization.
`(393) <https://github.com/attack68/rateslib/pull/393>`_
* - Bug
- The ``eom`` parameter for spec *"us_gb"* and *"us_gb_tsy"* and associated aliases is corrected to *True*.
`(368) <https://github.com/attack68/rateslib/pull/368>`_
Expand Down
8 changes: 8 additions & 0 deletions python/tests/test_fx.py
Original file line number Diff line number Diff line change
Expand Up @@ -46,6 +46,14 @@ def test_rates() -> None:
assert fxr.rate("eurgbp") == Dual(1.25, ["fx_usdeur", "fx_usdgbp"], [-0.625, 0.50])


def test_fxrates_pickle():
fxr = FXRates({"usdeur": 2.0, "usdgbp": 2.5}, settlement=dt(2002, 1, 1))
import pickle
pickled = pickle.dumps(fxr)
result = pickle.loads(pickled)
assert result == fxr


def test_rates_repr():
fxr = FXRates({"usdeur": 2.0, "usdgbp": 2.5})
result = fxr.__repr__()
Expand Down
46 changes: 43 additions & 3 deletions rust/fx/rates_py.rs
Original file line number Diff line number Diff line change
Expand Up @@ -2,15 +2,16 @@

use crate::dual::{ADOrder, Number, NumberArray2};
use crate::fx::rates::{Ccy, FXRate, FXRates};
use bincode::{deserialize, serialize};
use chrono::prelude::*;
use ndarray::Axis;
use pyo3::prelude::*;
// use std::collections::HashMap;
use pyo3::exceptions::PyValueError;
// use pyo3::exceptions::PyValueError;
// use pyo3::types::PyFloat;
use crate::json::json_py::DeserializedObj;
use crate::json::JSON;
use pyo3::types::PyBytes;

#[pymethods]
impl Ccy {
Expand All @@ -32,6 +33,18 @@ impl Ccy {
fn __eq__(&self, other: &Self) -> bool {
self.name == other.name
}

// Pickling
pub fn __setstate__(&mut self, state: Bound<'_, PyBytes>) -> PyResult<()> {
*self = deserialize(state.as_bytes()).unwrap();
Ok(())
}
pub fn __getstate__<'py>(&self, py: Python<'py>) -> PyResult<Bound<'py, PyBytes>> {
Ok(PyBytes::new_bound(py, &serialize(&self).unwrap()))
}
pub fn __getnewargs__<'py>(&self) -> PyResult<(String,)> {
Ok(((*(self.name)).clone(),))
}
}

#[pymethods]
Expand Down Expand Up @@ -93,6 +106,23 @@ impl FXRate {
fn __eq__(&self, other: &Self) -> bool {
self == other
}

// Pickling
pub fn __setstate__(&mut self, state: Bound<'_, PyBytes>) -> PyResult<()> {
*self = deserialize(state.as_bytes()).unwrap();
Ok(())
}
pub fn __getstate__<'py>(&self, py: Python<'py>) -> PyResult<Bound<'py, PyBytes>> {
Ok(PyBytes::new_bound(py, &serialize(&self).unwrap()))
}
pub fn __getnewargs__<'py>(&self) -> PyResult<(String, String, Number, Option<NaiveDateTime>)> {
Ok((
(*(self.pair.0.name)).clone(),
(*(self.pair.1.name)).clone(),
self.rate.clone(),
self.settlement,
))
}
}

#[pymethods]
Expand Down Expand Up @@ -216,10 +246,20 @@ impl FXRates {
}
}

// Pickling
pub fn __setstate__(&mut self, state: Bound<'_, PyBytes>) -> PyResult<()> {
*self = deserialize(state.as_bytes()).unwrap();
Ok(())
}
pub fn __getstate__<'py>(&self, py: Python<'py>) -> PyResult<Bound<'py, PyBytes>> {
Ok(PyBytes::new_bound(py, &serialize(&self).unwrap()))
}
pub fn __getnewargs__<'py>(&self) -> PyResult<(Vec<FXRate>, Option<Ccy>)> {
Ok((self.fx_rates.clone(), Some(self.currencies[0])))
}

// Equality
fn __eq__(&self, other: FXRates) -> bool {
println!("{:?}", self);
println!("{:?}", other);
self.eq(&other)
}

Expand Down
Loading