feat: derivatives basis & calendar-spread indicators (part 3 of 3) (#128)

* feat(derivatives): TermStructureBasis indicator (core)

* feat(derivatives): CalendarSpread indicator (core)

* feat(derivatives): Python, Node and WASM bindings for basis & calendar-spread indicators

* test(derivatives): Python and Node tests for basis & calendar-spread indicators

* docs(derivatives): README row + counter 242->244, CHANGELOG part 3; fuzz basis indicators
This commit is contained in:
kingchenc
2026-06-01 22:07:35 +02:00
committed by GitHub
parent 8e5bfd07ce
commit 2d140419bb
17 changed files with 830 additions and 12 deletions
@@ -268,6 +268,8 @@ from ._wickra import (
LongShortRatio,
TakerBuySellRatio,
LiquidationFeatures,
TermStructureBasis,
CalendarSpread,
# Risk / Performance
SharpeRatio,
SortinoRatio,
@@ -533,6 +535,8 @@ __all__ = [
"LongShortRatio",
"TakerBuySellRatio",
"LiquidationFeatures",
"TermStructureBasis",
"CalendarSpread",
# Risk / Performance
"SharpeRatio",
"SortinoRatio",
+157
View File
@@ -12308,6 +12308,42 @@ fn deriv_liquidation(
.map_err(map_err)
}
fn deriv_futures_index(futures_price: f64, index_price: f64) -> PyResult<wc::DerivativesTick> {
wc::DerivativesTick::new(
0.0,
1.0,
index_price,
futures_price,
0.0,
0.0,
0.0,
0.0,
0.0,
0.0,
0.0,
0,
)
.map_err(map_err)
}
fn deriv_futures_mark(futures_price: f64, mark_price: f64) -> PyResult<wc::DerivativesTick> {
wc::DerivativesTick::new(
0.0,
mark_price,
1.0,
futures_price,
0.0,
0.0,
0.0,
0.0,
0.0,
0.0,
0.0,
0,
)
.map_err(map_err)
}
// FundingRate takes no parameters; streaming `update(funding_rate)`, `batch`
// over one funding-rate array.
#[pyclass(name = "FundingRate", module = "wickra._wickra", skip_from_py_object)]
@@ -12852,6 +12888,125 @@ impl PyLiquidationFeatures {
}
}
// TermStructureBasis takes no parameters; streaming
// `update(futures_price, index_price)`.
#[pyclass(
name = "TermStructureBasis",
module = "wickra._wickra",
skip_from_py_object
)]
#[derive(Clone)]
struct PyTermStructureBasis {
inner: wc::TermStructureBasis,
}
#[pymethods]
impl PyTermStructureBasis {
#[new]
fn new() -> Self {
Self {
inner: wc::TermStructureBasis::new(),
}
}
fn update(&mut self, futures_price: f64, index_price: f64) -> PyResult<Option<f64>> {
Ok(self
.inner
.update(deriv_futures_index(futures_price, index_price)?))
}
fn batch<'py>(
&mut self,
py: Python<'py>,
futures_price: Vec<f64>,
index_price: Vec<f64>,
) -> PyResult<Bound<'py, PyArray1<f64>>> {
if futures_price.len() != index_price.len() {
return Err(PyValueError::new_err(
"futures_price and index_price must be equal length",
));
}
let mut out = Vec::with_capacity(futures_price.len());
for i in 0..futures_price.len() {
out.push(
self.inner
.update(deriv_futures_index(futures_price[i], index_price[i])?)
.unwrap_or(f64::NAN),
);
}
Ok(out.into_pyarray(py))
}
fn reset(&mut self) {
self.inner.reset();
}
fn is_ready(&self) -> bool {
self.inner.is_ready()
}
fn warmup_period(&self) -> usize {
self.inner.warmup_period()
}
fn __repr__(&self) -> String {
"TermStructureBasis()".to_string()
}
}
// CalendarSpread takes no parameters; streaming `update(futures_price, mark_price)`.
#[pyclass(
name = "CalendarSpread",
module = "wickra._wickra",
skip_from_py_object
)]
#[derive(Clone)]
struct PyCalendarSpread {
inner: wc::CalendarSpread,
}
#[pymethods]
impl PyCalendarSpread {
#[new]
fn new() -> Self {
Self {
inner: wc::CalendarSpread::new(),
}
}
fn update(&mut self, futures_price: f64, mark_price: f64) -> PyResult<Option<f64>> {
Ok(self
.inner
.update(deriv_futures_mark(futures_price, mark_price)?))
}
fn batch<'py>(
&mut self,
py: Python<'py>,
futures_price: Vec<f64>,
mark_price: Vec<f64>,
) -> PyResult<Bound<'py, PyArray1<f64>>> {
if futures_price.len() != mark_price.len() {
return Err(PyValueError::new_err(
"futures_price and mark_price must be equal length",
));
}
let mut out = Vec::with_capacity(futures_price.len());
for i in 0..futures_price.len() {
out.push(
self.inner
.update(deriv_futures_mark(futures_price[i], mark_price[i])?)
.unwrap_or(f64::NAN),
);
}
Ok(out.into_pyarray(py))
}
fn reset(&mut self) {
self.inner.reset();
}
fn is_ready(&self) -> bool {
self.inner.is_ready()
}
fn warmup_period(&self) -> usize {
self.inner.warmup_period()
}
fn __repr__(&self) -> String {
"CalendarSpread()".to_string()
}
}
// ============================== Family 15: Risk / Performance ==============================
#[pyclass(name = "SharpeRatio", module = "wickra._wickra", skip_from_py_object)]
@@ -13985,6 +14140,8 @@ fn _wickra(_py: Python<'_>, m: &Bound<'_, PyModule>) -> PyResult<()> {
m.add_class::<PyLongShortRatio>()?;
m.add_class::<PyTakerBuySellRatio>()?;
m.add_class::<PyLiquidationFeatures>()?;
m.add_class::<PyTermStructureBasis>()?;
m.add_class::<PyCalendarSpread>()?;
// Family 15: Risk / Performance metrics.
m.add_class::<PySharpeRatio>()?;
m.add_class::<PySortinoRatio>()?;
@@ -268,3 +268,13 @@ def test_oi_price_divergence_zero_window_raises():
def test_oi_weighted_non_positive_mark_raises():
with pytest.raises(ValueError):
ta.OIWeighted().update(0.0, 100.0)
def test_term_structure_basis_non_positive_index_raises():
with pytest.raises(ValueError):
ta.TermStructureBasis().update(100.0, 0.0)
def test_calendar_spread_non_positive_mark_raises():
with pytest.raises(ValueError):
ta.CalendarSpread().update(100.0, 0.0)
@@ -1013,3 +1013,16 @@ def test_liquidation_features_reference_value():
# 30 long vs 10 short: (long, short, net, total, imbalance).
out = ta.LiquidationFeatures().update(30.0, 10.0)
assert out == pytest.approx((30.0, 10.0, 20.0, 40.0, 0.5))
def test_term_structure_basis_reference_value():
# futures 102 vs index 100 -> 0.02 (contango).
assert ta.TermStructureBasis().update(102.0, 100.0) == pytest.approx(0.02)
# Backwardation reads negative.
assert ta.TermStructureBasis().update(98.0, 100.0) == pytest.approx(-0.02)
def test_calendar_spread_reference_value():
# futures 101 vs perpetual mark 100 -> 0.01.
assert ta.CalendarSpread().update(101.0, 100.0) == pytest.approx(0.01)
assert ta.CalendarSpread().update(99.0, 100.0) == pytest.approx(-0.01)
@@ -2047,3 +2047,29 @@ def test_liquidation_features_streaming_equals_batch():
for i in range(n):
row = streamer.update(long_liq[i], short_liq[i])
assert tuple(batch[i]) == pytest.approx(row)
def test_basis_indicators_streaming_equals_batch():
n = 40
index = np.array([100.0 + math.sin(i * 0.2) for i in range(n)], dtype=np.float64)
mark = np.array([index[i] + 0.05 * math.cos(i * 0.3) for i in range(n)], dtype=np.float64)
futures = np.array(
[index[i] + 0.5 + 0.1 * math.sin(i * 0.25) for i in range(n)], dtype=np.float64
)
# TermStructureBasis; update(futures_price, index_price).
batch = ta.TermStructureBasis().batch(futures, index)
streamer = ta.TermStructureBasis()
streamed = np.array(
[streamer.update(futures[i], index[i]) for i in range(n)], dtype=np.float64
)
assert batch.shape == (n,)
assert _eq_nan(batch, streamed)
# CalendarSpread; update(futures_price, mark_price).
batch = ta.CalendarSpread().batch(futures, mark)
streamer = ta.CalendarSpread()
streamed = np.array(
[streamer.update(futures[i], mark[i]) for i in range(n)], dtype=np.float64
)
assert _eq_nan(batch, streamed)