feat: derivatives funding & open-interest indicators (part 1 of 3) (#126)
* feat(derivatives): DerivativesTick input type + InvalidDerivatives error * feat(derivatives): FundingRate indicator (core) * feat(derivatives): FundingRateMean indicator (core) * feat(derivatives): FundingRateZScore indicator (core) * feat(derivatives): FundingBasis indicator (core) * feat(derivatives): OpenInterestDelta indicator (core) * feat(derivatives): Python, Node and WASM bindings for funding & OI-delta indicators * test(derivatives): Python and Node tests for funding & OI-delta indicators * bench(derivatives): synthetic-tick bench + derivatives fuzz target * docs(derivatives): README family row + counter 232->237, CHANGELOG entry
This commit is contained in:
@@ -257,6 +257,12 @@ from ._wickra import (
|
||||
KylesLambda,
|
||||
# Microstructure: footprint
|
||||
Footprint,
|
||||
# Derivatives
|
||||
FundingRate,
|
||||
FundingRateMean,
|
||||
FundingRateZScore,
|
||||
FundingBasis,
|
||||
OpenInterestDelta,
|
||||
# Risk / Performance
|
||||
SharpeRatio,
|
||||
SortinoRatio,
|
||||
@@ -511,6 +517,12 @@ __all__ = [
|
||||
"KylesLambda",
|
||||
# Microstructure: footprint
|
||||
"Footprint",
|
||||
# Derivatives
|
||||
"FundingRate",
|
||||
"FundingRateMean",
|
||||
"FundingRateZScore",
|
||||
"FundingBasis",
|
||||
"OpenInterestDelta",
|
||||
# Risk / Performance
|
||||
"SharpeRatio",
|
||||
"SortinoRatio",
|
||||
|
||||
+307
-1
@@ -28,7 +28,8 @@ fn map_err(e: wc::Error) -> PyErr {
|
||||
| wc::Error::InvalidCandle { .. }
|
||||
| wc::Error::InvalidTick { .. }
|
||||
| wc::Error::InvalidOrderBook { .. }
|
||||
| wc::Error::InvalidTrade { .. } => PyValueError::new_err(e.to_string()),
|
||||
| wc::Error::InvalidTrade { .. }
|
||||
| wc::Error::InvalidDerivatives { .. } => PyValueError::new_err(e.to_string()),
|
||||
}
|
||||
}
|
||||
|
||||
@@ -12182,6 +12183,305 @@ impl PyFootprint {
|
||||
}
|
||||
}
|
||||
|
||||
// ============================== Derivatives ==============================
|
||||
//
|
||||
// Derivatives indicators consume a perpetual / futures tick rather than OHLCV.
|
||||
// Each wrapper exposes only the tick fields its indicator reads; the helpers
|
||||
// below build a fully-valid `DerivativesTick`, filling the unused fields with
|
||||
// neutral defaults (prices `1.0`, sizes / rates `0.0`).
|
||||
|
||||
fn deriv_funding(funding_rate: f64) -> PyResult<wc::DerivativesTick> {
|
||||
wc::DerivativesTick::new(
|
||||
funding_rate,
|
||||
1.0,
|
||||
1.0,
|
||||
1.0,
|
||||
0.0,
|
||||
0.0,
|
||||
0.0,
|
||||
0.0,
|
||||
0.0,
|
||||
0.0,
|
||||
0.0,
|
||||
0,
|
||||
)
|
||||
.map_err(map_err)
|
||||
}
|
||||
|
||||
fn deriv_basis(mark_price: f64, index_price: f64) -> PyResult<wc::DerivativesTick> {
|
||||
wc::DerivativesTick::new(
|
||||
0.0,
|
||||
mark_price,
|
||||
index_price,
|
||||
1.0,
|
||||
0.0,
|
||||
0.0,
|
||||
0.0,
|
||||
0.0,
|
||||
0.0,
|
||||
0.0,
|
||||
0.0,
|
||||
0,
|
||||
)
|
||||
.map_err(map_err)
|
||||
}
|
||||
|
||||
fn deriv_oi(open_interest: f64) -> PyResult<wc::DerivativesTick> {
|
||||
wc::DerivativesTick::new(
|
||||
0.0,
|
||||
1.0,
|
||||
1.0,
|
||||
1.0,
|
||||
open_interest,
|
||||
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)]
|
||||
#[derive(Clone)]
|
||||
struct PyFundingRate {
|
||||
inner: wc::FundingRate,
|
||||
}
|
||||
|
||||
#[pymethods]
|
||||
impl PyFundingRate {
|
||||
#[new]
|
||||
fn new() -> Self {
|
||||
Self {
|
||||
inner: wc::FundingRate::new(),
|
||||
}
|
||||
}
|
||||
fn update(&mut self, funding_rate: f64) -> PyResult<Option<f64>> {
|
||||
Ok(self.inner.update(deriv_funding(funding_rate)?))
|
||||
}
|
||||
fn batch<'py>(
|
||||
&mut self,
|
||||
py: Python<'py>,
|
||||
funding_rate: Vec<f64>,
|
||||
) -> PyResult<Bound<'py, PyArray1<f64>>> {
|
||||
let mut out = Vec::with_capacity(funding_rate.len());
|
||||
for rate in funding_rate {
|
||||
out.push(self.inner.update(deriv_funding(rate)?).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 {
|
||||
"FundingRate()".to_string()
|
||||
}
|
||||
}
|
||||
|
||||
// FundingRateMean carries a `window` parameter.
|
||||
#[pyclass(
|
||||
name = "FundingRateMean",
|
||||
module = "wickra._wickra",
|
||||
skip_from_py_object
|
||||
)]
|
||||
#[derive(Clone)]
|
||||
struct PyFundingRateMean {
|
||||
inner: wc::FundingRateMean,
|
||||
}
|
||||
|
||||
#[pymethods]
|
||||
impl PyFundingRateMean {
|
||||
#[new]
|
||||
fn new(window: usize) -> PyResult<Self> {
|
||||
Ok(Self {
|
||||
inner: wc::FundingRateMean::new(window).map_err(map_err)?,
|
||||
})
|
||||
}
|
||||
fn update(&mut self, funding_rate: f64) -> PyResult<Option<f64>> {
|
||||
Ok(self.inner.update(deriv_funding(funding_rate)?))
|
||||
}
|
||||
fn batch<'py>(
|
||||
&mut self,
|
||||
py: Python<'py>,
|
||||
funding_rate: Vec<f64>,
|
||||
) -> PyResult<Bound<'py, PyArray1<f64>>> {
|
||||
let mut out = Vec::with_capacity(funding_rate.len());
|
||||
for rate in funding_rate {
|
||||
out.push(self.inner.update(deriv_funding(rate)?).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 {
|
||||
format!("FundingRateMean(window={})", self.inner.window())
|
||||
}
|
||||
}
|
||||
|
||||
// FundingRateZScore carries a `window` parameter.
|
||||
#[pyclass(
|
||||
name = "FundingRateZScore",
|
||||
module = "wickra._wickra",
|
||||
skip_from_py_object
|
||||
)]
|
||||
#[derive(Clone)]
|
||||
struct PyFundingRateZScore {
|
||||
inner: wc::FundingRateZScore,
|
||||
}
|
||||
|
||||
#[pymethods]
|
||||
impl PyFundingRateZScore {
|
||||
#[new]
|
||||
fn new(window: usize) -> PyResult<Self> {
|
||||
Ok(Self {
|
||||
inner: wc::FundingRateZScore::new(window).map_err(map_err)?,
|
||||
})
|
||||
}
|
||||
fn update(&mut self, funding_rate: f64) -> PyResult<Option<f64>> {
|
||||
Ok(self.inner.update(deriv_funding(funding_rate)?))
|
||||
}
|
||||
fn batch<'py>(
|
||||
&mut self,
|
||||
py: Python<'py>,
|
||||
funding_rate: Vec<f64>,
|
||||
) -> PyResult<Bound<'py, PyArray1<f64>>> {
|
||||
let mut out = Vec::with_capacity(funding_rate.len());
|
||||
for rate in funding_rate {
|
||||
out.push(self.inner.update(deriv_funding(rate)?).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 {
|
||||
format!("FundingRateZScore(window={})", self.inner.window())
|
||||
}
|
||||
}
|
||||
|
||||
// FundingBasis takes no parameters; streaming `update(mark_price, index_price)`.
|
||||
#[pyclass(name = "FundingBasis", module = "wickra._wickra", skip_from_py_object)]
|
||||
#[derive(Clone)]
|
||||
struct PyFundingBasis {
|
||||
inner: wc::FundingBasis,
|
||||
}
|
||||
|
||||
#[pymethods]
|
||||
impl PyFundingBasis {
|
||||
#[new]
|
||||
fn new() -> Self {
|
||||
Self {
|
||||
inner: wc::FundingBasis::new(),
|
||||
}
|
||||
}
|
||||
fn update(&mut self, mark_price: f64, index_price: f64) -> PyResult<Option<f64>> {
|
||||
Ok(self.inner.update(deriv_basis(mark_price, index_price)?))
|
||||
}
|
||||
fn batch<'py>(
|
||||
&mut self,
|
||||
py: Python<'py>,
|
||||
mark_price: Vec<f64>,
|
||||
index_price: Vec<f64>,
|
||||
) -> PyResult<Bound<'py, PyArray1<f64>>> {
|
||||
if mark_price.len() != index_price.len() {
|
||||
return Err(PyValueError::new_err(
|
||||
"mark_price and index_price must be equal length",
|
||||
));
|
||||
}
|
||||
let mut out = Vec::with_capacity(mark_price.len());
|
||||
for i in 0..mark_price.len() {
|
||||
out.push(
|
||||
self.inner
|
||||
.update(deriv_basis(mark_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 {
|
||||
"FundingBasis()".to_string()
|
||||
}
|
||||
}
|
||||
|
||||
// OpenInterestDelta takes no parameters; streaming `update(open_interest)`.
|
||||
#[pyclass(
|
||||
name = "OpenInterestDelta",
|
||||
module = "wickra._wickra",
|
||||
skip_from_py_object
|
||||
)]
|
||||
#[derive(Clone)]
|
||||
struct PyOpenInterestDelta {
|
||||
inner: wc::OpenInterestDelta,
|
||||
}
|
||||
|
||||
#[pymethods]
|
||||
impl PyOpenInterestDelta {
|
||||
#[new]
|
||||
fn new() -> Self {
|
||||
Self {
|
||||
inner: wc::OpenInterestDelta::new(),
|
||||
}
|
||||
}
|
||||
fn update(&mut self, open_interest: f64) -> PyResult<Option<f64>> {
|
||||
Ok(self.inner.update(deriv_oi(open_interest)?))
|
||||
}
|
||||
fn batch<'py>(
|
||||
&mut self,
|
||||
py: Python<'py>,
|
||||
open_interest: Vec<f64>,
|
||||
) -> PyResult<Bound<'py, PyArray1<f64>>> {
|
||||
let mut out = Vec::with_capacity(open_interest.len());
|
||||
for oi in open_interest {
|
||||
out.push(self.inner.update(deriv_oi(oi)?).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 {
|
||||
"OpenInterestDelta()".to_string()
|
||||
}
|
||||
}
|
||||
|
||||
// ============================== Family 15: Risk / Performance ==============================
|
||||
|
||||
#[pyclass(name = "SharpeRatio", module = "wickra._wickra", skip_from_py_object)]
|
||||
@@ -13304,6 +13604,12 @@ fn _wickra(_py: Python<'_>, m: &Bound<'_, PyModule>) -> PyResult<()> {
|
||||
m.add_class::<PyKylesLambda>()?;
|
||||
// Microstructure: footprint.
|
||||
m.add_class::<PyFootprint>()?;
|
||||
// Derivatives.
|
||||
m.add_class::<PyFundingRate>()?;
|
||||
m.add_class::<PyFundingRateMean>()?;
|
||||
m.add_class::<PyFundingRateZScore>()?;
|
||||
m.add_class::<PyFundingBasis>()?;
|
||||
m.add_class::<PyOpenInterestDelta>()?;
|
||||
// Family 15: Risk / Performance metrics.
|
||||
m.add_class::<PySharpeRatio>()?;
|
||||
m.add_class::<PySortinoRatio>()?;
|
||||
|
||||
@@ -238,3 +238,23 @@ def test_footprint_non_positive_tick_raises():
|
||||
ta.Footprint(0.0)
|
||||
with pytest.raises(ValueError):
|
||||
ta.Footprint(-1.0)
|
||||
|
||||
|
||||
def test_funding_rate_mean_zero_window_raises():
|
||||
with pytest.raises(ValueError):
|
||||
ta.FundingRateMean(0)
|
||||
|
||||
|
||||
def test_funding_rate_zscore_zero_window_raises():
|
||||
with pytest.raises(ValueError):
|
||||
ta.FundingRateZScore(0)
|
||||
|
||||
|
||||
def test_funding_basis_non_positive_index_raises():
|
||||
with pytest.raises(ValueError):
|
||||
ta.FundingBasis().update(100.0, 0.0)
|
||||
|
||||
|
||||
def test_funding_rate_non_finite_raises():
|
||||
with pytest.raises(ValueError):
|
||||
ta.FundingRate().update(float("nan"))
|
||||
|
||||
@@ -946,3 +946,36 @@ def test_kyles_lambda_recovers_constant_impact():
|
||||
mids.append(mid)
|
||||
out = ta.KylesLambda(6).batch(price, size, is_buy, mids)
|
||||
assert out[-1] == pytest.approx(0.5, abs=1e-9)
|
||||
|
||||
|
||||
def test_funding_rate_reference_values():
|
||||
assert ta.FundingRate().update(0.0001) == pytest.approx(0.0001)
|
||||
assert ta.FundingRate().update(-0.0003) == pytest.approx(-0.0003)
|
||||
|
||||
|
||||
def test_funding_rate_mean_reference_value():
|
||||
frm = ta.FundingRateMean(2)
|
||||
assert frm.update(0.001) is None # warming up
|
||||
# Window [0.001, 0.003] -> mean 0.002.
|
||||
assert frm.update(0.003) == pytest.approx(0.002)
|
||||
|
||||
|
||||
def test_funding_rate_zscore_reference_value():
|
||||
z = ta.FundingRateZScore(2)
|
||||
assert z.update(0.001) is None # warming up
|
||||
# Window [0.001, 0.003]: mean 0.002, population stddev 0.001 -> +1.
|
||||
assert z.update(0.003) == pytest.approx(1.0, abs=1e-9)
|
||||
|
||||
|
||||
def test_funding_basis_reference_value():
|
||||
# mark 100.5 vs index 100.0 -> (100.5 - 100.0) / 100.0 = 0.005.
|
||||
assert ta.FundingBasis().update(100.5, 100.0) == pytest.approx(0.005)
|
||||
# A discount reads negative.
|
||||
assert ta.FundingBasis().update(99.5, 100.0) == pytest.approx(-0.005)
|
||||
|
||||
|
||||
def test_open_interest_delta_reference_value():
|
||||
oid = ta.OpenInterestDelta()
|
||||
assert oid.update(1000.0) is None # seeds the previous OI
|
||||
assert oid.update(1250.0) == pytest.approx(250.0)
|
||||
assert oid.update(1100.0) == pytest.approx(-150.0)
|
||||
|
||||
@@ -1952,3 +1952,45 @@ def test_footprint_streaming_equals_batch():
|
||||
for i in range(n):
|
||||
streamed = streamer.update(price[i], size[i], is_buy[i])
|
||||
assert np.array_equal(streamed, batch[i])
|
||||
|
||||
|
||||
def test_funding_indicators_streaming_equals_batch():
|
||||
n = 40
|
||||
rate = np.array([0.0001 * math.sin(i * 0.3) for i in range(n)], dtype=np.float64)
|
||||
for make in (
|
||||
ta.FundingRate,
|
||||
lambda: ta.FundingRateMean(5),
|
||||
lambda: ta.FundingRateZScore(5),
|
||||
):
|
||||
batch = make().batch(rate)
|
||||
streamer = make()
|
||||
streamed = np.array(
|
||||
[streamer.update(rate[i]) for i in range(n)], dtype=np.float64
|
||||
)
|
||||
assert batch.shape == (n,)
|
||||
assert _eq_nan(batch, streamed)
|
||||
|
||||
|
||||
def test_funding_basis_streaming_equals_batch():
|
||||
n = 40
|
||||
index = np.array([100.0 + 0.5 * math.sin(i * 0.2) for i in range(n)], dtype=np.float64)
|
||||
mark = np.array(
|
||||
[index[i] + 0.1 * math.cos(i * 0.3) for i in range(n)], dtype=np.float64
|
||||
)
|
||||
batch = ta.FundingBasis().batch(mark, index)
|
||||
streamer = ta.FundingBasis()
|
||||
streamed = np.array(
|
||||
[streamer.update(mark[i], index[i]) for i in range(n)], dtype=np.float64
|
||||
)
|
||||
assert batch.shape == (n,)
|
||||
assert _eq_nan(batch, streamed)
|
||||
|
||||
|
||||
def test_open_interest_delta_streaming_equals_batch():
|
||||
n = 40
|
||||
oi = np.array([1000.0 + 50.0 * math.sin(i * 0.25) for i in range(n)], dtype=np.float64)
|
||||
batch = ta.OpenInterestDelta().batch(oi)
|
||||
streamer = ta.OpenInterestDelta()
|
||||
streamed = np.array([streamer.update(oi[i]) for i in range(n)], dtype=np.float64)
|
||||
assert batch.shape == (n,)
|
||||
assert _eq_nan(batch, streamed)
|
||||
|
||||
Reference in New Issue
Block a user