Skip to main content

PyBook

Struct PyBook 

pub struct PyBook {
    pub(crate) inner: Book,
}
Expand description

A collection of trades valued together.

Fields§

§inner: Book

Implementations§

§

impl PyBook

pub(crate) fn new() -> Self

An empty book.

pub(crate) fn add( &self, id: &str, instrument: &PyInstrument, quantity: f64, ) -> PyResult<Self>

Books quantity of instrument under id. The new book carries this book’s market.

pub(crate) fn extend( &self, trades: Vec<(String, PyInstrument, f64)>, ) -> PyResult<Self>

Books every (id, instrument, quantity) of trades at once. The new book carries this book’s market.

The form for a book of many trades: add copies the book — every trade already booked and the attached market — per call, so booking thousands of trades one add at a time is quadratic. This copies it once. A non-finite quantity is refused naming its trade, and nothing is booked.

pub(crate) fn from_fpml( _cls: &Bound<'_, PyType>, documents: Vec<Bound<'_, PyAny>>, party: Option<String>, counterparties: Option<Vec<PyRef<'_, PyCounterparty>>>, credit: Option<HashMap<String, String>>, reporting: Option<&str>, strict: bool, ) -> PyResult<(Self, PyRecords)>

A book of every trade documents hold, with what was not booked.

Each document is its text, labelled by its one-based position, or a (label, text) pair. Every trade is read as party, its CSA from counterparties and its credit identities from credit, as fpml.read_all reads them; each component is booked under the trade’s identifier, or label#position where it states none. The book reports in reporting where given.

Returns (book, refusals), the refusals a Records with the columns source, position, trade, element, reason. With strict, the first refusal raises ValueError and nothing is booked.

pub(crate) fn reporting_in(&self, code: &str) -> PyResult<Self>

The book reporting in code: every trade’s value converted to that currency at the market’s spot. The new book carries this book’s market.

pub(crate) fn attach_market( &mut self, py: Python<'_>, market: Option<&PyMarket>, ) -> PyResult<()>

Attaches market to this book in place — it returns None — and fetches what the book needs for market’s date (today where it has none) from the market’s data source.

Unlike every with_* on Book, it changes its receiver and may do IO: the market is the book’s from here on, and every verb values against it. A market holding everything the book reads attaches without calling any source; an offline one (with_data_source(None)) never fetches. With no market, an undated MarketContext() carrying the default source is attached.

pub(crate) fn market_context(&self) -> Option<PyMarket>

The market this book carries, or None.

pub(crate) fn fetch_market_data( &mut self, py: Python<'_>, as_of: NaiveDate, ) -> PyResult<()>

Fetches what this book reads at as_of from its market’s data source and keeps it — the explicit form of the fetch every verb makes for a date it lacks, as the Rust book’s fetch_market_data. An undated market is attached first where none is. On a refusal it raises the verbs’ SnapshotError (or the source’s own exception) and leaves the market as it was; fetch_report() says what was asked either way.

pub(crate) fn fetch_report(&self) -> PyRecords

What the book’s last fetch asked for and got: family (strip, fixing, fx, unresolved), key and status (answered, missing, absent). Empty before any fetch.

pub(crate) fn recipe_ask( &self, py: Python<'_>, as_of: Option<NaiveDate>, ) -> PyResult<Option<PyRecipeAsk>>

The first half of a fetch: the RecipeAsk a source must answer before the demand at as_of can be stated, or None where nothing is to be asked. With demand_for and install, the halves an async caller drives: recipe_ask → await recipes → demand_for → await fetch → install.

pub(crate) fn demand_for( &mut self, py: Python<'_>, as_of: NaiveDate, recipes: Vec<PyRef<'_, PyRecipeSpec>>, ) -> PyResult<PyDemand>

The second half’s start: recipes (a source’s answer to recipe_ask, as curves.RecipeSpec values) kept as the source’s recipes for as_of, this book’s market moved to as_of, and that date’s Demand — empty where nothing is missing.

pub(crate) fn install( &mut self, py: Python<'_>, demand: &PyDemand, data: &PyMarketData, ) -> PyResult<()>

The last half: data (a source’s answer to demand) built into this book’s market at the demand’s date and kept, and fetch_report() written — on a refusal as well, which raises SnapshotError naming every gap and leaves the market as it was.

pub(crate) fn implied_vol( &mut self, py: Python<'_>, premium: Option<f64>, as_of: Option<NaiveDate>, ) -> PyResult<f64>

The single flat volatility under which every option in the book, priced at it, sums to premium — or, with none given, to the book’s own value: the quote a straddle or strangle trades at. The book must be one strategy: FX options on one pair, or surface-engine European swaptions in one currency.

pub(crate) fn under( &mut self, py: Python<'_>, scenario: &PyScenario, as_of: Option<NaiveDate>, ) -> PyResult<Self>

This book on its market under scenario, at as_of: a new book whose market is the shocked one. What the book lacks at as_of is fetched first, so the shock always reaches the fetched market.

pub(crate) fn credit_bumps( &mut self, py: Python<'_>, kind: &str, bump: f64, as_of: Option<NaiveDate>, ) -> PyResult<PyRecords>

A bumped sensitivity, one (key, value) row per credit index or entity: kind is correlation (each index’s base correlation, bumped in parallel), recovery (each entity’s market recovery, survival curve held) or recovery-quote-held (CDS quotes held), each the central-difference value change for a bump.

pub(crate) fn explain_pnl( &mut self, py: Python<'_>, as_of1: NaiveDate, as_of2: NaiveDate, order: Option<Vec<Named<RiskAxis>>>, ) -> PyResult<PyExplainReport>

The step-revaluation explain of this book from its market at as_of1 to as_of2, moving the axes in order (the core’s default where None). Within one day (as_of1 == as_of2) the snapshot held is the start and a fresh fetch of the same date — kept as the book’s — is the end. Across days the end is the book’s fetch at as_of2, and the legs open with cash, paid after as_of1 and up to as_of2, and carry, the book on as_of1’s quotes rebuilt at as_of2 less its value at as_of1.

pub(crate) fn predicted_pnl( &mut self, py: Python<'_>, as_of1: NaiveDate, as_of2: NaiveDate, ) -> PyResult<PyPredictedPnl>

The predicted explain within one day, on the terms of explain_pnl; across days it is refused.

pub(crate) fn reset_pnl( &mut self, py: Python<'_>, as_of1: NaiveDate, as_of2: NaiveDate, ) -> PyResult<PyResetPnl>

The reset P&L within one day, on the terms of explain_pnl; across days it is refused.

pub(crate) fn through(&self, lens: &PyLens) -> Self

The book restricted to the trades lens admits, carrying this book’s market.

pub(crate) fn __repr__(&self) -> String

The trades, as (id, instrument, quantity).

pub(crate) fn trades(&self) -> Vec<(String, PyInstrument, f64)>

The book’s trades as (id, instrument, quantity), in booking order.

pub(crate) fn report( &mut self, py: Python<'_>, measures: Vec<Bound<'_, PyAny>>, as_of: Option<NaiveDate>, ) -> PyResult<PyRecords>

measures from one risk pass at as_of, as (measure, label, value, scale, curve, date) rows in the order asked.

Each measure is a preset (hlx.risk.rates.PAR_LADDER), a risk.Measure value, or a spelling — "npv", "delta:<axis>[:<basis>[:<aggregation>]][:<scale>]", or a preset’s name. A preset asked for by name reports in its default scale unless the measure or the book states another; a spelling reports per unit unless the book states one.

measure is the preset’s name where the measure is one, and its spelling otherwise; scale is the unit value is in. The label carries which row of a measure this is: empty for a measure that produces one number, and the curve, the bucket or the ladder point otherwise.

pub(crate) fn scaled(&self, scales: &PyScales) -> Self

The book reporting each quantity kind in scales wherever a measure states no scale of its own. The new book carries this book’s market.

pub(crate) fn available_measures( &self, py: Python<'_>, as_of: Option<NaiveDate>, ) -> PyResult<PyRecords>

The catalogued measures this book’s trades can answer — where its market holds a snapshot at as_of, only those that snapshot can supply — as the catalogue’s records. Never fetches.

pub(crate) fn market_vega( &mut self, py: Python<'_>, fit: &PyHullWhiteFit, as_of: Option<NaiveDate>, ) -> PyResult<PyRecords>

MarketContext vega per quoted swaption: ((expiry, end), vega) rows, from one risk pass and the fit’s quote sensitivities.

The book’s market must hold the fit pinned — the pass needs the model’s σ as an exogenous input to have a σ row at all.

pub(crate) fn __len__(&self) -> usize

How many trades the book holds.

pub(crate) fn npv( &mut self, py: Python<'_>, as_of: Option<NaiveDate>, ) -> PyResult<f64>

The book’s present value at as_of — the attached market’s date where it has one, today otherwise — fetching first whatever the book lacks there from the market’s data source.

Instantiates the passive mode: nothing is recorded, and no tape exists for a caller to know about.

The interpreter lock is released for the valuation: every value the core reads is owned or reference-counted on the Rust side, so another Python thread may value its own book at the same time. One book is not shared between threads — a second thread calling it meanwhile raises RuntimeError; give each thread its own copy with book.through(Lens.all()). The error, if any, is mapped after the lock is back.

pub(crate) fn npv_by_trade( &mut self, py: Python<'_>, as_of: Option<NaiveDate>, ) -> PyResult<PyRecords>

Each trade’s value at as_of (the market’s date, else today): trade, npv_ccy, npv_local, pnl_ccy, npv_pnl — in the trade’s own currency, quantity applied, and converted at spot into the P&L currency, the book’s reporting one. npv_pnl sums to npv().

pub(crate) fn risk( &mut self, py: Python<'_>, as_of: Option<NaiveDate>, ) -> PyResult<PyRiskFrame>

One risk pass at as_of, held as a frame: its npv(), its raw risk() rows, and read on any axis, in the zero or par basis, at any aggregation — without another pass per reading.

Selects the reverse mode internally. The caller opens nothing, closes nothing, and never names a tape.

§

impl PyBook

pub(crate) fn default_date( &self, py: Python<'_>, as_of: Option<NaiveDate>, ) -> PyResult<NaiveDate>

The date a verb values at: as_of where given, else the attached market’s date, else today.

pub(crate) fn ensure( &mut self, py: Python<'_>, as_of: Option<NaiveDate>, ) -> PyResult<NaiveDate>

Makes sure the book’s market covers what the book reads at as_of: attaches an undated market where none is, and — where the market has a data source — fetches what is missing there, once, in place. A market with no source is left as it is, so a gap surfaces as the valuation’s own refusal naming the trade. Returns the date.

Trait Implementations§

§

impl Clone for PyBook

§

fn clone(&self) -> PyBook

Returns a duplicate of the value. Read more
1.0.0 (const: unstable) · Source§

fn clone_from(&mut self, source: &Self)

Performs copy-assignment from source. Read more
§

impl Default for PyBook

§

fn default() -> PyBook

Returns the “default value” for a type. Read more
§

impl DerefToPyAny for PyBook

§

impl IntoPy<Py<PyAny>> for PyBook

§

fn into_py(self, py: Python<'_>) -> PyObject

Performs the conversion.
§

impl PyClass for PyBook

§

type Frozen = False

Whether the pyclass is frozen. Read more
§

impl PyClassImpl for PyBook

§

const IS_BASETYPE: bool = false

#[pyclass(subclass)]
§

const IS_SUBCLASS: bool = false

#[pyclass(extends=…)]
§

const IS_MAPPING: bool = false

#[pyclass(mapping)]
§

const IS_SEQUENCE: bool = false

#[pyclass(sequence)]
§

type BaseType = PyAny

Base class
§

type ThreadChecker = SendablePyClass<PyBook>

This handles following two situations: Read more
§

type PyClassMutability = <<PyAny as PyClassBaseType>::PyClassMutability as PyClassMutability>::MutableChild

Immutable or mutable
§

type Dict = PyClassDummySlot

Specify this class has #[pyclass(dict)] or not.
§

type WeakRef = PyClassDummySlot

Specify this class has #[pyclass(weakref)] or not.
§

type BaseNativeType = PyAny

The closest native ancestor. This is PyAny by default, and when you declare #[pyclass(extends=PyDict)], it’s PyDict.
§

fn items_iter() -> PyClassItemsIter

§

fn doc(py: Python<'_>) -> PyResult<&'static CStr>

Rendered class doc
§

fn lazy_type_object() -> &'static LazyTypeObject<Self>

§

fn dict_offset() -> Option<isize>

§

fn weaklist_offset() -> Option<isize>

§

impl PyClassNewTextSignature<PyBook> for PyClassImplCollector<PyBook>

§

fn new_text_signature(self) -> Option<&'static str>

§

impl<'a, 'py> PyFunctionArgument<'a, 'py> for &'a PyBook

§

type Holder = Option<PyRef<'py, PyBook>>

§

fn extract( obj: &'a Bound<'py, PyAny>, holder: &'a mut Self::Holder, ) -> PyResult<Self>

§

impl<'a, 'py> PyFunctionArgument<'a, 'py> for &'a mut PyBook

§

type Holder = Option<PyRefMut<'py, PyBook>>

§

fn extract( obj: &'a Bound<'py, PyAny>, holder: &'a mut Self::Holder, ) -> PyResult<Self>

§

impl PyMethods<PyBook> for PyClassImplCollector<PyBook>

§

fn py_methods(self) -> &'static PyClassItems

§

impl PyTypeInfo for PyBook

§

const NAME: &'static str = "Book"

Class name.
§

const MODULE: Option<&'static str>

Module name, if any.
§

fn type_object_raw(py: Python<'_>) -> *mut PyTypeObject

Returns the PyTypeObject instance for this type.
§

fn type_object_bound(py: Python<'_>) -> Bound<'_, PyType>

Returns the safe abstraction over the type object.
§

fn is_type_of_bound(object: &Bound<'_, PyAny>) -> bool

Checks if object is an instance of this type or a subclass of this type.
§

fn is_exact_type_of_bound(object: &Bound<'_, PyAny>) -> bool

Checks if object is an instance of this type.

Auto Trait Implementations§

§

impl !Freeze for PyBook

§

impl !RefUnwindSafe for PyBook

§

impl !UnwindSafe for PyBook

§

impl Send for PyBook

§

impl Sync for PyBook

§

impl Unpin for PyBook

§

impl UnsafeUnpin for PyBook

Blanket Implementations§

Source§

impl<T> Any for T
where T: 'static + ?Sized,

Source§

fn type_id(&self) -> TypeId

Gets the TypeId of self. Read more
Source§

impl<T> Borrow<T> for T
where T: ?Sized,

Source§

fn borrow(&self) -> &T

Immutably borrows from an owned value. Read more
Source§

impl<T> BorrowMut<T> for T
where T: ?Sized,

Source§

fn borrow_mut(&mut self) -> &mut T

Mutably borrows from an owned value. Read more
Source§

impl<T> CloneToUninit for T
where T: Clone,

Source§

unsafe fn clone_to_uninit(&self, dest: *mut u8)

🔬This is a nightly-only experimental API. (clone_to_uninit)
Performs copy-assignment from self to dest. Read more
Source§

impl<T> From<T> for T

Source§

fn from(t: T) -> T

Returns the argument unchanged.

§

impl<T> FromPyObject<'_> for T
where T: PyClass + Clone,

§

fn extract_bound(obj: &Bound<'_, PyAny>) -> Result<T, PyErr>

Extracts Self from the bound smart pointer obj. Read more
§

impl<'py, T> FromPyObjectBound<'_, 'py> for T
where T: FromPyObject<'py>,

§

fn from_py_object_bound(ob: Borrowed<'_, 'py, PyAny>) -> Result<T, PyErr>

Extracts Self from the bound smart pointer obj. Read more
Source§

impl<T, U> Into<U> for T
where U: From<T>,

Source§

fn into(self) -> U

Calls U::from(self).

That is, this conversion is whatever the implementation of From<T> for U chooses to do.

§

impl<T> PyErrArguments for T
where T: IntoPy<Py<PyAny>> + Send + Sync,

§

fn arguments(self, py: Python<'_>) -> Py<PyAny>

Arguments for exception
§

impl<T> PyTypeCheck for T
where T: PyTypeInfo,

§

const NAME: &'static str = <T as PyTypeInfo>::NAME

Name of self. This is used in error messages, for example.
§

fn type_check(object: &Bound<'_, PyAny>) -> bool

Checks if object is an instance of Self, which may include a subtype. Read more
Source§

impl<T> ToOwned for T
where T: Clone,

Source§

type Owned = T

The resulting type after obtaining ownership.
Source§

fn to_owned(&self) -> T

Creates owned data from borrowed data, usually by cloning. Read more
Source§

fn clone_into(&self, target: &mut T)

Uses borrowed data to replace owned data, usually by cloning. Read more
Source§

impl<T, U> TryFrom<U> for T
where U: Into<T>,

Source§

type Error = Infallible

The type returned in the event of a conversion error.
Source§

fn try_from(value: U) -> Result<T, <T as TryFrom<U>>::Error>

Performs the conversion.
Source§

impl<T, U> TryInto<U> for T
where U: TryFrom<T>,

Source§

type Error = <U as TryFrom<T>>::Error

The type returned in the event of a conversion error.
Source§

fn try_into(self) -> Result<U, <U as TryFrom<T>>::Error>

Performs the conversion.
§

impl<T> Ungil for T
where T: Send,