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:
@@ -1175,3 +1175,28 @@ test('OI flow rejects bad input', () => {
|
||||
assert.throws(() => new wickra.OIPriceDivergence(0));
|
||||
assert.throws(() => new wickra.OIWeighted().update(0, 100));
|
||||
});
|
||||
|
||||
test('basis & calendar-spread reference values', () => {
|
||||
// futures 102 vs index 100 -> 0.02 contango.
|
||||
assert.ok(Math.abs(new wickra.TermStructureBasis().update(102, 100) - 0.02) < 1e-12);
|
||||
assert.ok(Math.abs(new wickra.TermStructureBasis().update(98, 100) + 0.02) < 1e-12);
|
||||
// futures 101 vs perpetual mark 100 -> 0.01.
|
||||
assert.ok(Math.abs(new wickra.CalendarSpread().update(101, 100) - 0.01) < 1e-12);
|
||||
});
|
||||
|
||||
test('basis streaming update matches batch', () => {
|
||||
const n = 20;
|
||||
const index = Array.from({ length: n }, (_, i) => 100 + Math.sin(i * 0.2));
|
||||
const futures = Array.from({ length: n }, (_, i) => index[i] + 0.5);
|
||||
const batch = new wickra.TermStructureBasis().batch(futures, index);
|
||||
const streamer = new wickra.TermStructureBasis();
|
||||
assert.equal(batch.length, n);
|
||||
for (let i = 0; i < n; i++) {
|
||||
assert.ok(Math.abs(streamer.update(futures[i], index[i]) - batch[i]) < 1e-12);
|
||||
}
|
||||
});
|
||||
|
||||
test('basis rejects bad input', () => {
|
||||
assert.throws(() => new wickra.TermStructureBasis().update(100, 0));
|
||||
assert.throws(() => new wickra.CalendarSpread().update(100, 0));
|
||||
});
|
||||
|
||||
Vendored
+18
@@ -2417,6 +2417,24 @@ export declare class LiquidationFeatures {
|
||||
isReady(): boolean
|
||||
warmupPeriod(): number
|
||||
}
|
||||
export type TermStructureBasisNode = TermStructureBasis
|
||||
export declare class TermStructureBasis {
|
||||
constructor()
|
||||
update(futuresPrice: number, indexPrice: number): number | null
|
||||
batch(futuresPrice: Array<number>, indexPrice: Array<number>): Array<number>
|
||||
reset(): void
|
||||
isReady(): boolean
|
||||
warmupPeriod(): number
|
||||
}
|
||||
export type CalendarSpreadNode = CalendarSpread
|
||||
export declare class CalendarSpread {
|
||||
constructor()
|
||||
update(futuresPrice: number, markPrice: number): number | null
|
||||
batch(futuresPrice: Array<number>, markPrice: Array<number>): Array<number>
|
||||
reset(): void
|
||||
isReady(): boolean
|
||||
warmupPeriod(): number
|
||||
}
|
||||
export type SharpeRatioNode = SharpeRatio
|
||||
export declare class SharpeRatio {
|
||||
constructor(period: number, riskFree: number)
|
||||
|
||||
@@ -310,7 +310,7 @@ if (!nativeBinding) {
|
||||
throw new Error(`Failed to load native binding`)
|
||||
}
|
||||
|
||||
const { version, SMA, EMA, WMA, RSI, DEMA, TEMA, HMA, ROC, TRIX, SMMA, TRIMA, ZLEMA, MOM, CMO, DPO, StdDev, UlcerIndex, VerticalHorizontalFilter, ZScore, McGinleyDynamic, FRAMA, SuperSmoother, FisherTransform, Decycler, CenterOfGravity, CyberneticCycle, InstantaneousTrendline, EhlersStochastic, RVIVolatility, Variance, CoefficientOfVariation, Skewness, Kurtosis, StandardError, DetrendedStdDev, RSquared, MedianAbsoluteDeviation, Autocorrelation, HurstExponent, PearsonCorrelation, Beta, PairwiseBeta, SpearmanCorrelation, PairSpreadZScore, LeadLagCrossCorrelation, Cointegration, RelativeStrengthAB, MACD, BollingerBands, ATR, Stochastic, OBV, ADX, ADXR, CCI, WilliamsR, MFI, PSAR, Keltner, Donchian, VWAP, RollingVWAP, AwesomeOscillator, Aroon, Inertia, ConnorsRSI, LaguerreRSI, SMI, KST, PGO, RVI, AwesomeOscillatorHistogram, STC, ElderImpulse, ZeroLagMACD, CFO, APO, KAMA, EVWMA, Alligator, JMA, VIDYA, ALMA, T3, TSI, PMO, TII, ADL, VolumePriceTrend, ChaikinMoneyFlow, ChaikinOscillator, ForceIndex, NVI, PVI, VolumeOscillator, KVO, WilliamsAD, AnchoredVWAP, DemandIndex, TSV, VZO, MarketFacilitationIndex, EaseOfMovement, SuperTrend, ChandelierExit, ChandeKrollStop, AtrTrailingStop, HiLoActivator, VoltyStop, YoyoExit, DonchianStop, PercentageTrailingStop, StepTrailingStop, RenkoTrailingStop, TypicalPrice, MedianPrice, WeightedClose, LinearRegression, LinRegSlope, AcceleratorOscillator, BalanceOfPower, ChoppinessIndex, TrueRange, ChaikinVolatility, YangZhangVolatility, RogersSatchellVolatility, GarmanKlassVolatility, ParkinsonVolatility, LinRegAngle, BollingerBandwidth, PercentB, NATR, HistoricalVolatility, AroonOscillator, WaveTrend, RWI, Vortex, MassIndex, StochRSI, UltimateOscillator, PPO, Coppock, VWMA, MaEnvelope, AccelerationBands, StarcBands, AtrBands, HurstChannel, LinRegChannel, StandardErrorBands, DoubleBollinger, TtmSqueeze, FractalChaosBands, VwapStdDevBands, ClassicPivots, FibonacciPivots, Camarilla, WoodiePivots, DemarkPivots, WilliamsFractals, ZigZag, TDSetup, TDSequential, TDDeMarker, TDREI, TDPressure, TDCombo, TDCountdown, TDLines, TDRangeProjection, TDDifferential, TDOpen, TDRiskLevel, InverseFisherTransform, DecyclerOscillator, RoofingFilter, EmpiricalModeDecomposition, HilbertDominantCycle, AdaptiveCycle, SineWave, MAMA, FAMA, Ichimoku, HeikinAshi, ValueArea, InitialBalance, OpeningRange, Doji, Hammer, InvertedHammer, HangingMan, ShootingStar, Engulfing, Harami, MorningEveningStar, ThreeSoldiersOrCrows, PiercingDarkCloud, Marubozu, Tweezer, SpinningTop, ThreeInside, ThreeOutside, OrderBookImbalanceTop1, OrderBookImbalanceFull, Microprice, QuotedSpread, DepthSlope, OrderBookImbalanceTopN, SignedVolume, CumulativeVolumeDelta, TradeImbalance, EffectiveSpread, RealizedSpread, KylesLambda, Footprint, FundingRate, FundingRateMean, FundingRateZScore, FundingBasis, OpenInterestDelta, OIPriceDivergence, OIWeighted, LongShortRatio, TakerBuySellRatio, LiquidationFeatures, SharpeRatio, SortinoRatio, CalmarRatio, OmegaRatio, MaxDrawdown, AverageDrawdown, DrawdownDuration, PainIndex, ValueAtRisk, ConditionalValueAtRisk, ProfitFactor, GainLossRatio, RecoveryFactor, KellyCriterion, TreynorRatio, InformationRatio, Alpha } = nativeBinding
|
||||
const { version, SMA, EMA, WMA, RSI, DEMA, TEMA, HMA, ROC, TRIX, SMMA, TRIMA, ZLEMA, MOM, CMO, DPO, StdDev, UlcerIndex, VerticalHorizontalFilter, ZScore, McGinleyDynamic, FRAMA, SuperSmoother, FisherTransform, Decycler, CenterOfGravity, CyberneticCycle, InstantaneousTrendline, EhlersStochastic, RVIVolatility, Variance, CoefficientOfVariation, Skewness, Kurtosis, StandardError, DetrendedStdDev, RSquared, MedianAbsoluteDeviation, Autocorrelation, HurstExponent, PearsonCorrelation, Beta, PairwiseBeta, SpearmanCorrelation, PairSpreadZScore, LeadLagCrossCorrelation, Cointegration, RelativeStrengthAB, MACD, BollingerBands, ATR, Stochastic, OBV, ADX, ADXR, CCI, WilliamsR, MFI, PSAR, Keltner, Donchian, VWAP, RollingVWAP, AwesomeOscillator, Aroon, Inertia, ConnorsRSI, LaguerreRSI, SMI, KST, PGO, RVI, AwesomeOscillatorHistogram, STC, ElderImpulse, ZeroLagMACD, CFO, APO, KAMA, EVWMA, Alligator, JMA, VIDYA, ALMA, T3, TSI, PMO, TII, ADL, VolumePriceTrend, ChaikinMoneyFlow, ChaikinOscillator, ForceIndex, NVI, PVI, VolumeOscillator, KVO, WilliamsAD, AnchoredVWAP, DemandIndex, TSV, VZO, MarketFacilitationIndex, EaseOfMovement, SuperTrend, ChandelierExit, ChandeKrollStop, AtrTrailingStop, HiLoActivator, VoltyStop, YoyoExit, DonchianStop, PercentageTrailingStop, StepTrailingStop, RenkoTrailingStop, TypicalPrice, MedianPrice, WeightedClose, LinearRegression, LinRegSlope, AcceleratorOscillator, BalanceOfPower, ChoppinessIndex, TrueRange, ChaikinVolatility, YangZhangVolatility, RogersSatchellVolatility, GarmanKlassVolatility, ParkinsonVolatility, LinRegAngle, BollingerBandwidth, PercentB, NATR, HistoricalVolatility, AroonOscillator, WaveTrend, RWI, Vortex, MassIndex, StochRSI, UltimateOscillator, PPO, Coppock, VWMA, MaEnvelope, AccelerationBands, StarcBands, AtrBands, HurstChannel, LinRegChannel, StandardErrorBands, DoubleBollinger, TtmSqueeze, FractalChaosBands, VwapStdDevBands, ClassicPivots, FibonacciPivots, Camarilla, WoodiePivots, DemarkPivots, WilliamsFractals, ZigZag, TDSetup, TDSequential, TDDeMarker, TDREI, TDPressure, TDCombo, TDCountdown, TDLines, TDRangeProjection, TDDifferential, TDOpen, TDRiskLevel, InverseFisherTransform, DecyclerOscillator, RoofingFilter, EmpiricalModeDecomposition, HilbertDominantCycle, AdaptiveCycle, SineWave, MAMA, FAMA, Ichimoku, HeikinAshi, ValueArea, InitialBalance, OpeningRange, Doji, Hammer, InvertedHammer, HangingMan, ShootingStar, Engulfing, Harami, MorningEveningStar, ThreeSoldiersOrCrows, PiercingDarkCloud, Marubozu, Tweezer, SpinningTop, ThreeInside, ThreeOutside, OrderBookImbalanceTop1, OrderBookImbalanceFull, Microprice, QuotedSpread, DepthSlope, OrderBookImbalanceTopN, SignedVolume, CumulativeVolumeDelta, TradeImbalance, EffectiveSpread, RealizedSpread, KylesLambda, Footprint, FundingRate, FundingRateMean, FundingRateZScore, FundingBasis, OpenInterestDelta, OIPriceDivergence, OIWeighted, LongShortRatio, TakerBuySellRatio, LiquidationFeatures, TermStructureBasis, CalendarSpread, SharpeRatio, SortinoRatio, CalmarRatio, OmegaRatio, MaxDrawdown, AverageDrawdown, DrawdownDuration, PainIndex, ValueAtRisk, ConditionalValueAtRisk, ProfitFactor, GainLossRatio, RecoveryFactor, KellyCriterion, TreynorRatio, InformationRatio, Alpha } = nativeBinding
|
||||
|
||||
module.exports.version = version
|
||||
module.exports.SMA = SMA
|
||||
@@ -538,6 +538,8 @@ module.exports.OIWeighted = OIWeighted
|
||||
module.exports.LongShortRatio = LongShortRatio
|
||||
module.exports.TakerBuySellRatio = TakerBuySellRatio
|
||||
module.exports.LiquidationFeatures = LiquidationFeatures
|
||||
module.exports.TermStructureBasis = TermStructureBasis
|
||||
module.exports.CalendarSpread = CalendarSpread
|
||||
module.exports.SharpeRatio = SharpeRatio
|
||||
module.exports.SortinoRatio = SortinoRatio
|
||||
module.exports.CalmarRatio = CalmarRatio
|
||||
|
||||
@@ -9477,6 +9477,42 @@ fn deriv_liquidation(
|
||||
.map_err(map_err)
|
||||
}
|
||||
|
||||
fn deriv_futures_index(futures_price: f64, index_price: f64) -> napi::Result<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) -> napi::Result<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)
|
||||
}
|
||||
|
||||
#[napi(js_name = "FundingRate")]
|
||||
pub struct FundingRateNode {
|
||||
inner: wc::FundingRate,
|
||||
@@ -10015,6 +10051,126 @@ impl LiquidationFeaturesNode {
|
||||
}
|
||||
}
|
||||
|
||||
#[napi(js_name = "TermStructureBasis")]
|
||||
pub struct TermStructureBasisNode {
|
||||
inner: wc::TermStructureBasis,
|
||||
}
|
||||
|
||||
impl Default for TermStructureBasisNode {
|
||||
fn default() -> Self {
|
||||
Self::new()
|
||||
}
|
||||
}
|
||||
|
||||
#[napi]
|
||||
impl TermStructureBasisNode {
|
||||
#[napi(constructor)]
|
||||
pub fn new() -> Self {
|
||||
Self {
|
||||
inner: wc::TermStructureBasis::new(),
|
||||
}
|
||||
}
|
||||
#[napi]
|
||||
pub fn update(&mut self, futures_price: f64, index_price: f64) -> napi::Result<Option<f64>> {
|
||||
Ok(self
|
||||
.inner
|
||||
.update(deriv_futures_index(futures_price, index_price)?))
|
||||
}
|
||||
#[napi]
|
||||
pub fn batch(
|
||||
&mut self,
|
||||
futures_price: Vec<f64>,
|
||||
index_price: Vec<f64>,
|
||||
) -> napi::Result<Vec<f64>> {
|
||||
if futures_price.len() != index_price.len() {
|
||||
return Err(NapiError::from_reason(
|
||||
"futures_price and index_price must be equal length".to_string(),
|
||||
));
|
||||
}
|
||||
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)
|
||||
}
|
||||
#[napi]
|
||||
pub fn reset(&mut self) {
|
||||
self.inner.reset();
|
||||
}
|
||||
#[napi(js_name = "isReady")]
|
||||
pub fn is_ready(&self) -> bool {
|
||||
self.inner.is_ready()
|
||||
}
|
||||
#[napi(js_name = "warmupPeriod")]
|
||||
pub fn warmup_period(&self) -> u32 {
|
||||
self.inner.warmup_period() as u32
|
||||
}
|
||||
}
|
||||
|
||||
#[napi(js_name = "CalendarSpread")]
|
||||
pub struct CalendarSpreadNode {
|
||||
inner: wc::CalendarSpread,
|
||||
}
|
||||
|
||||
impl Default for CalendarSpreadNode {
|
||||
fn default() -> Self {
|
||||
Self::new()
|
||||
}
|
||||
}
|
||||
|
||||
#[napi]
|
||||
impl CalendarSpreadNode {
|
||||
#[napi(constructor)]
|
||||
pub fn new() -> Self {
|
||||
Self {
|
||||
inner: wc::CalendarSpread::new(),
|
||||
}
|
||||
}
|
||||
#[napi]
|
||||
pub fn update(&mut self, futures_price: f64, mark_price: f64) -> napi::Result<Option<f64>> {
|
||||
Ok(self
|
||||
.inner
|
||||
.update(deriv_futures_mark(futures_price, mark_price)?))
|
||||
}
|
||||
#[napi]
|
||||
pub fn batch(
|
||||
&mut self,
|
||||
futures_price: Vec<f64>,
|
||||
mark_price: Vec<f64>,
|
||||
) -> napi::Result<Vec<f64>> {
|
||||
if futures_price.len() != mark_price.len() {
|
||||
return Err(NapiError::from_reason(
|
||||
"futures_price and mark_price must be equal length".to_string(),
|
||||
));
|
||||
}
|
||||
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)
|
||||
}
|
||||
#[napi]
|
||||
pub fn reset(&mut self) {
|
||||
self.inner.reset();
|
||||
}
|
||||
#[napi(js_name = "isReady")]
|
||||
pub fn is_ready(&self) -> bool {
|
||||
self.inner.is_ready()
|
||||
}
|
||||
#[napi(js_name = "warmupPeriod")]
|
||||
pub fn warmup_period(&self) -> u32 {
|
||||
self.inner.warmup_period() as u32
|
||||
}
|
||||
}
|
||||
|
||||
// ============================== Family 15: Risk / Performance ==============================
|
||||
|
||||
// Risk metrics with fallible `new` (most need `period >= 2`), so each wrapper
|
||||
|
||||
@@ -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",
|
||||
|
||||
@@ -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)
|
||||
|
||||
@@ -7228,6 +7228,119 @@ impl WasmLiquidationFeatures {
|
||||
}
|
||||
}
|
||||
|
||||
fn deriv_futures_index(
|
||||
futures_price: f64,
|
||||
index_price: f64,
|
||||
) -> Result<wc::DerivativesTick, JsError> {
|
||||
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) -> Result<wc::DerivativesTick, JsError> {
|
||||
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)
|
||||
}
|
||||
|
||||
#[wasm_bindgen(js_name = TermStructureBasis)]
|
||||
pub struct WasmTermStructureBasis {
|
||||
inner: wc::TermStructureBasis,
|
||||
}
|
||||
|
||||
impl Default for WasmTermStructureBasis {
|
||||
fn default() -> Self {
|
||||
Self::new()
|
||||
}
|
||||
}
|
||||
|
||||
#[wasm_bindgen(js_class = TermStructureBasis)]
|
||||
impl WasmTermStructureBasis {
|
||||
#[wasm_bindgen(constructor)]
|
||||
pub fn new() -> WasmTermStructureBasis {
|
||||
Self {
|
||||
inner: wc::TermStructureBasis::new(),
|
||||
}
|
||||
}
|
||||
pub fn update(&mut self, futures_price: f64, index_price: f64) -> Result<Option<f64>, JsError> {
|
||||
Ok(self
|
||||
.inner
|
||||
.update(deriv_futures_index(futures_price, index_price)?))
|
||||
}
|
||||
pub fn reset(&mut self) {
|
||||
self.inner.reset();
|
||||
}
|
||||
#[wasm_bindgen(js_name = isReady)]
|
||||
pub fn is_ready(&self) -> bool {
|
||||
self.inner.is_ready()
|
||||
}
|
||||
#[wasm_bindgen(js_name = warmupPeriod)]
|
||||
pub fn warmup_period(&self) -> usize {
|
||||
self.inner.warmup_period()
|
||||
}
|
||||
}
|
||||
|
||||
#[wasm_bindgen(js_name = CalendarSpread)]
|
||||
pub struct WasmCalendarSpread {
|
||||
inner: wc::CalendarSpread,
|
||||
}
|
||||
|
||||
impl Default for WasmCalendarSpread {
|
||||
fn default() -> Self {
|
||||
Self::new()
|
||||
}
|
||||
}
|
||||
|
||||
#[wasm_bindgen(js_class = CalendarSpread)]
|
||||
impl WasmCalendarSpread {
|
||||
#[wasm_bindgen(constructor)]
|
||||
pub fn new() -> WasmCalendarSpread {
|
||||
Self {
|
||||
inner: wc::CalendarSpread::new(),
|
||||
}
|
||||
}
|
||||
pub fn update(&mut self, futures_price: f64, mark_price: f64) -> Result<Option<f64>, JsError> {
|
||||
Ok(self
|
||||
.inner
|
||||
.update(deriv_futures_mark(futures_price, mark_price)?))
|
||||
}
|
||||
pub fn reset(&mut self) {
|
||||
self.inner.reset();
|
||||
}
|
||||
#[wasm_bindgen(js_name = isReady)]
|
||||
pub fn is_ready(&self) -> bool {
|
||||
self.inner.is_ready()
|
||||
}
|
||||
#[wasm_bindgen(js_name = warmupPeriod)]
|
||||
pub fn warmup_period(&self) -> usize {
|
||||
self.inner.warmup_period()
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
Reference in New Issue
Block a user