feat(seasonality): add the Seasonality & Session family (12 indicators) (#161)
## Summary Adds the **Seasonality & Session** family — the first family that reads the wall-clock fields of `Candle::timestamp`. A new private `calendar` module decomposes an epoch-millisecond instant (shifted by a per-indicator `utc_offset_minutes`) into civil fields via Howard Hinnant's branch-light `civil_from_days` algorithm. Session / day / month rollovers are detected automatically, so callers never have to invoke `reset()` at a boundary. Indicator counter **339 → 351**; family count **20 → 21**. ## Indicators | Shape | Indicators | |-------|-----------| | Scalar (`f64`) | `SessionVwap`, `AverageDailyRange`, `OvernightGap`, `TurnOfMonth`, `SeasonalZScore` | | Struct | `SessionHighLow`, `SessionRange` (Asia/EU/US), `OvernightIntradayReturn` | | Profile (`Vec<f64>`) | `TimeOfDayReturnProfile`, `DayOfWeekProfile`, `IntradayVolatilityProfile`, `VolumeByTimeProfile` | ## Bindings The input is the **full** candle (`open, high, low, close, volume, timestamp`), not the `high/low/close` slice the value-indicator helper assumes, so the Python / Node / WASM bindings are custom full-candle implementations: - **Python** — `update((o,h,l,c,v,ts))`; `batch(open, high, low, close, volume, timestamp)` → `PyArray1` (scalar) / `PyArray2` (struct & profile), warmup rows `NaN`. - **Node** — `update(open, high, low, close, volume, timestamp)`; `batch(...)` → flat `Vec<f64>`; struct outputs as `#[napi(object)]` values. - **WASM** — `update` only (multi-input precedent); profiles as `Float64Array`, structs as camelCase objects, `timestamp` as `BigInt`. ## Verification - `wickra-core`: full per-branch unit tests, **100%** coverage target; 2852 lib tests + 334 doctests green. - `cargo clippy --workspace --all-targets --all-features -- -D warnings`: clean. - Node: 428 tests (dedicated `seasonality.test.js` streaming-vs-batch). - Python: full suite + dedicated `test_seasonality.py` streaming-vs-batch. - Counter check: mod-count == counted lib block == 351.
This commit is contained in:
@@ -385,6 +385,19 @@ from ._wickra import (
|
||||
TreynorRatio,
|
||||
InformationRatio,
|
||||
Alpha,
|
||||
# Seasonality & Session
|
||||
SessionVwap,
|
||||
SessionHighLow,
|
||||
SessionRange,
|
||||
AverageDailyRange,
|
||||
OvernightGap,
|
||||
OvernightIntradayReturn,
|
||||
TurnOfMonth,
|
||||
SeasonalZScore,
|
||||
TimeOfDayReturnProfile,
|
||||
DayOfWeekProfile,
|
||||
IntradayVolatilityProfile,
|
||||
VolumeByTimeProfile,
|
||||
)
|
||||
|
||||
__all__ = [
|
||||
@@ -749,4 +762,17 @@ __all__ = [
|
||||
"TreynorRatio",
|
||||
"InformationRatio",
|
||||
"Alpha",
|
||||
# Seasonality & Session
|
||||
"SessionVwap",
|
||||
"SessionHighLow",
|
||||
"SessionRange",
|
||||
"AverageDailyRange",
|
||||
"OvernightGap",
|
||||
"OvernightIntradayReturn",
|
||||
"TurnOfMonth",
|
||||
"SeasonalZScore",
|
||||
"TimeOfDayReturnProfile",
|
||||
"DayOfWeekProfile",
|
||||
"IntradayVolatilityProfile",
|
||||
"VolumeByTimeProfile",
|
||||
]
|
||||
|
||||
@@ -17243,6 +17243,593 @@ impl PyPointAndFigureBars {
|
||||
|
||||
// ============================== Module ==============================
|
||||
|
||||
// ====================== Seasonality & Session (full-candle) ======================
|
||||
//
|
||||
// These indicators read the wall-clock fields of `Candle::timestamp`, so the
|
||||
// bindings consume the FULL candle (open, high, low, close, volume, timestamp)
|
||||
// — unlike the high/low/close candle indicators above.
|
||||
|
||||
fn build_seasonality_candles<'py>(
|
||||
open: &PyReadonlyArray1<'py, f64>,
|
||||
high: &PyReadonlyArray1<'py, f64>,
|
||||
low: &PyReadonlyArray1<'py, f64>,
|
||||
close: &PyReadonlyArray1<'py, f64>,
|
||||
volume: &PyReadonlyArray1<'py, f64>,
|
||||
timestamp: &PyReadonlyArray1<'py, i64>,
|
||||
) -> PyResult<Vec<wc::Candle>> {
|
||||
let o = open
|
||||
.as_slice()
|
||||
.map_err(|_| PyValueError::new_err(NON_CONTIGUOUS))?;
|
||||
let h = high
|
||||
.as_slice()
|
||||
.map_err(|_| PyValueError::new_err(NON_CONTIGUOUS))?;
|
||||
let l = low
|
||||
.as_slice()
|
||||
.map_err(|_| PyValueError::new_err(NON_CONTIGUOUS))?;
|
||||
let c = close
|
||||
.as_slice()
|
||||
.map_err(|_| PyValueError::new_err(NON_CONTIGUOUS))?;
|
||||
let v = volume
|
||||
.as_slice()
|
||||
.map_err(|_| PyValueError::new_err(NON_CONTIGUOUS))?;
|
||||
let t = timestamp
|
||||
.as_slice()
|
||||
.map_err(|_| PyValueError::new_err(NON_CONTIGUOUS))?;
|
||||
let n = o.len();
|
||||
if [h.len(), l.len(), c.len(), v.len(), t.len()]
|
||||
.iter()
|
||||
.any(|&x| x != n)
|
||||
{
|
||||
return Err(PyValueError::new_err(
|
||||
"open, high, low, close, volume, timestamp must be equal length",
|
||||
));
|
||||
}
|
||||
let mut candles = Vec::with_capacity(n);
|
||||
for i in 0..n {
|
||||
candles.push(wc::Candle::new(o[i], h[i], l[i], c[i], v[i], t[i]).map_err(map_err)?);
|
||||
}
|
||||
Ok(candles)
|
||||
}
|
||||
|
||||
macro_rules! py_seasonality_offset_scalar {
|
||||
($pytype:ident, $name:literal, $rust:ident) => {
|
||||
#[pyclass(name = $name, module = "wickra._wickra", skip_from_py_object)]
|
||||
#[derive(Clone)]
|
||||
struct $pytype {
|
||||
inner: wc::$rust,
|
||||
}
|
||||
#[pymethods]
|
||||
impl $pytype {
|
||||
#[new]
|
||||
#[pyo3(signature = (utc_offset_minutes = 0))]
|
||||
fn new(utc_offset_minutes: i32) -> Self {
|
||||
Self {
|
||||
inner: wc::$rust::new(utc_offset_minutes),
|
||||
}
|
||||
}
|
||||
fn update(&mut self, candle: &Bound<'_, PyAny>) -> PyResult<Option<f64>> {
|
||||
Ok(self.inner.update(extract_candle(candle)?))
|
||||
}
|
||||
#[allow(clippy::too_many_arguments)]
|
||||
fn batch<'py>(
|
||||
&mut self,
|
||||
py: Python<'py>,
|
||||
open: PyReadonlyArray1<'py, f64>,
|
||||
high: PyReadonlyArray1<'py, f64>,
|
||||
low: PyReadonlyArray1<'py, f64>,
|
||||
close: PyReadonlyArray1<'py, f64>,
|
||||
volume: PyReadonlyArray1<'py, f64>,
|
||||
timestamp: PyReadonlyArray1<'py, i64>,
|
||||
) -> PyResult<Bound<'py, PyArray1<f64>>> {
|
||||
let candles =
|
||||
build_seasonality_candles(&open, &high, &low, &close, &volume, ×tamp)?;
|
||||
let out: Vec<f64> = candles
|
||||
.into_iter()
|
||||
.map(|c| self.inner.update(c).unwrap_or(f64::NAN))
|
||||
.collect();
|
||||
Ok(out.into_pyarray(py))
|
||||
}
|
||||
#[getter]
|
||||
fn utc_offset_minutes(&self) -> i32 {
|
||||
self.inner.utc_offset_minutes()
|
||||
}
|
||||
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!(
|
||||
"{}(utc_offset_minutes={})",
|
||||
$name,
|
||||
self.inner.utc_offset_minutes()
|
||||
)
|
||||
}
|
||||
}
|
||||
};
|
||||
}
|
||||
|
||||
macro_rules! py_seasonality_bucket_profile {
|
||||
($pytype:ident, $name:literal, $rust:ident) => {
|
||||
#[pyclass(name = $name, module = "wickra._wickra", skip_from_py_object)]
|
||||
#[derive(Clone)]
|
||||
struct $pytype {
|
||||
inner: wc::$rust,
|
||||
}
|
||||
#[pymethods]
|
||||
impl $pytype {
|
||||
#[new]
|
||||
#[pyo3(signature = (buckets = 24, utc_offset_minutes = 0))]
|
||||
fn new(buckets: usize, utc_offset_minutes: i32) -> PyResult<Self> {
|
||||
Ok(Self {
|
||||
inner: wc::$rust::new(buckets, utc_offset_minutes).map_err(map_err)?,
|
||||
})
|
||||
}
|
||||
fn update<'py>(
|
||||
&mut self,
|
||||
py: Python<'py>,
|
||||
candle: &Bound<'_, PyAny>,
|
||||
) -> PyResult<Option<Bound<'py, PyArray1<f64>>>> {
|
||||
let c = extract_candle(candle)?;
|
||||
Ok(self.inner.update(c).map(|o| o.bins.into_pyarray(py)))
|
||||
}
|
||||
#[allow(clippy::too_many_arguments)]
|
||||
fn batch<'py>(
|
||||
&mut self,
|
||||
py: Python<'py>,
|
||||
open: PyReadonlyArray1<'py, f64>,
|
||||
high: PyReadonlyArray1<'py, f64>,
|
||||
low: PyReadonlyArray1<'py, f64>,
|
||||
close: PyReadonlyArray1<'py, f64>,
|
||||
volume: PyReadonlyArray1<'py, f64>,
|
||||
timestamp: PyReadonlyArray1<'py, i64>,
|
||||
) -> PyResult<Bound<'py, PyArray2<f64>>> {
|
||||
let candles =
|
||||
build_seasonality_candles(&open, &high, &low, &close, &volume, ×tamp)?;
|
||||
let k = self.inner.params().0;
|
||||
let n = candles.len();
|
||||
let mut out = vec![f64::NAN; n * k];
|
||||
for (i, c) in candles.into_iter().enumerate() {
|
||||
if let Some(o) = self.inner.update(c) {
|
||||
for (j, b) in o.bins.iter().enumerate() {
|
||||
out[i * k + j] = *b;
|
||||
}
|
||||
}
|
||||
}
|
||||
Ok(numpy::ndarray::Array2::from_shape_vec((n, k), out)
|
||||
.expect("shape consistent")
|
||||
.into_pyarray(py))
|
||||
}
|
||||
#[getter]
|
||||
fn params(&self) -> (usize, i32) {
|
||||
self.inner.params()
|
||||
}
|
||||
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 {
|
||||
let (buckets, offset) = self.inner.params();
|
||||
format!("{}(buckets={buckets}, utc_offset_minutes={offset})", $name)
|
||||
}
|
||||
}
|
||||
};
|
||||
}
|
||||
|
||||
macro_rules! py_seasonality_offset_profile {
|
||||
($pytype:ident, $name:literal, $rust:ident, $k:expr) => {
|
||||
#[pyclass(name = $name, module = "wickra._wickra", skip_from_py_object)]
|
||||
#[derive(Clone)]
|
||||
struct $pytype {
|
||||
inner: wc::$rust,
|
||||
}
|
||||
#[pymethods]
|
||||
impl $pytype {
|
||||
#[new]
|
||||
#[pyo3(signature = (utc_offset_minutes = 0))]
|
||||
fn new(utc_offset_minutes: i32) -> Self {
|
||||
Self {
|
||||
inner: wc::$rust::new(utc_offset_minutes),
|
||||
}
|
||||
}
|
||||
fn update<'py>(
|
||||
&mut self,
|
||||
py: Python<'py>,
|
||||
candle: &Bound<'_, PyAny>,
|
||||
) -> PyResult<Option<Bound<'py, PyArray1<f64>>>> {
|
||||
let c = extract_candle(candle)?;
|
||||
Ok(self.inner.update(c).map(|o| o.bins.into_pyarray(py)))
|
||||
}
|
||||
#[allow(clippy::too_many_arguments)]
|
||||
fn batch<'py>(
|
||||
&mut self,
|
||||
py: Python<'py>,
|
||||
open: PyReadonlyArray1<'py, f64>,
|
||||
high: PyReadonlyArray1<'py, f64>,
|
||||
low: PyReadonlyArray1<'py, f64>,
|
||||
close: PyReadonlyArray1<'py, f64>,
|
||||
volume: PyReadonlyArray1<'py, f64>,
|
||||
timestamp: PyReadonlyArray1<'py, i64>,
|
||||
) -> PyResult<Bound<'py, PyArray2<f64>>> {
|
||||
let candles =
|
||||
build_seasonality_candles(&open, &high, &low, &close, &volume, ×tamp)?;
|
||||
let k = $k;
|
||||
let n = candles.len();
|
||||
let mut out = vec![f64::NAN; n * k];
|
||||
for (i, c) in candles.into_iter().enumerate() {
|
||||
if let Some(o) = self.inner.update(c) {
|
||||
for (j, b) in o.bins.iter().enumerate() {
|
||||
out[i * k + j] = *b;
|
||||
}
|
||||
}
|
||||
}
|
||||
Ok(numpy::ndarray::Array2::from_shape_vec((n, k), out)
|
||||
.expect("shape consistent")
|
||||
.into_pyarray(py))
|
||||
}
|
||||
#[getter]
|
||||
fn utc_offset_minutes(&self) -> i32 {
|
||||
self.inner.utc_offset_minutes()
|
||||
}
|
||||
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!(
|
||||
"{}(utc_offset_minutes={})",
|
||||
$name,
|
||||
self.inner.utc_offset_minutes()
|
||||
)
|
||||
}
|
||||
}
|
||||
};
|
||||
}
|
||||
|
||||
py_seasonality_offset_scalar!(PySessionVwap, "SessionVwap", SessionVwap);
|
||||
py_seasonality_offset_scalar!(PyOvernightGap, "OvernightGap", OvernightGap);
|
||||
py_seasonality_offset_scalar!(PySeasonalZScore, "SeasonalZScore", SeasonalZScore);
|
||||
py_seasonality_bucket_profile!(
|
||||
PyTimeOfDayReturnProfile,
|
||||
"TimeOfDayReturnProfile",
|
||||
TimeOfDayReturnProfile
|
||||
);
|
||||
py_seasonality_bucket_profile!(
|
||||
PyIntradayVolatilityProfile,
|
||||
"IntradayVolatilityProfile",
|
||||
IntradayVolatilityProfile
|
||||
);
|
||||
py_seasonality_bucket_profile!(
|
||||
PyVolumeByTimeProfile,
|
||||
"VolumeByTimeProfile",
|
||||
VolumeByTimeProfile
|
||||
);
|
||||
py_seasonality_offset_profile!(PyDayOfWeekProfile, "DayOfWeekProfile", DayOfWeekProfile, 7);
|
||||
|
||||
#[pyclass(
|
||||
name = "AverageDailyRange",
|
||||
module = "wickra._wickra",
|
||||
skip_from_py_object
|
||||
)]
|
||||
#[derive(Clone)]
|
||||
struct PyAverageDailyRange {
|
||||
inner: wc::AverageDailyRange,
|
||||
}
|
||||
#[pymethods]
|
||||
impl PyAverageDailyRange {
|
||||
#[new]
|
||||
#[pyo3(signature = (period = 14, utc_offset_minutes = 0))]
|
||||
fn new(period: usize, utc_offset_minutes: i32) -> PyResult<Self> {
|
||||
Ok(Self {
|
||||
inner: wc::AverageDailyRange::new(period, utc_offset_minutes).map_err(map_err)?,
|
||||
})
|
||||
}
|
||||
fn update(&mut self, candle: &Bound<'_, PyAny>) -> PyResult<Option<f64>> {
|
||||
Ok(self.inner.update(extract_candle(candle)?))
|
||||
}
|
||||
#[allow(clippy::too_many_arguments)]
|
||||
fn batch<'py>(
|
||||
&mut self,
|
||||
py: Python<'py>,
|
||||
open: PyReadonlyArray1<'py, f64>,
|
||||
high: PyReadonlyArray1<'py, f64>,
|
||||
low: PyReadonlyArray1<'py, f64>,
|
||||
close: PyReadonlyArray1<'py, f64>,
|
||||
volume: PyReadonlyArray1<'py, f64>,
|
||||
timestamp: PyReadonlyArray1<'py, i64>,
|
||||
) -> PyResult<Bound<'py, PyArray1<f64>>> {
|
||||
let candles = build_seasonality_candles(&open, &high, &low, &close, &volume, ×tamp)?;
|
||||
let out: Vec<f64> = candles
|
||||
.into_iter()
|
||||
.map(|c| self.inner.update(c).unwrap_or(f64::NAN))
|
||||
.collect();
|
||||
Ok(out.into_pyarray(py))
|
||||
}
|
||||
#[getter]
|
||||
fn params(&self) -> (usize, i32) {
|
||||
self.inner.params()
|
||||
}
|
||||
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 {
|
||||
let (period, offset) = self.inner.params();
|
||||
format!("AverageDailyRange(period={period}, utc_offset_minutes={offset})")
|
||||
}
|
||||
}
|
||||
|
||||
#[pyclass(name = "TurnOfMonth", module = "wickra._wickra", skip_from_py_object)]
|
||||
#[derive(Clone)]
|
||||
struct PyTurnOfMonth {
|
||||
inner: wc::TurnOfMonth,
|
||||
}
|
||||
#[pymethods]
|
||||
impl PyTurnOfMonth {
|
||||
#[new]
|
||||
#[pyo3(signature = (n_first = 3, n_last = 1, utc_offset_minutes = 0))]
|
||||
fn new(n_first: u32, n_last: u32, utc_offset_minutes: i32) -> PyResult<Self> {
|
||||
Ok(Self {
|
||||
inner: wc::TurnOfMonth::new(n_first, n_last, utc_offset_minutes).map_err(map_err)?,
|
||||
})
|
||||
}
|
||||
fn update(&mut self, candle: &Bound<'_, PyAny>) -> PyResult<Option<f64>> {
|
||||
Ok(self.inner.update(extract_candle(candle)?))
|
||||
}
|
||||
#[allow(clippy::too_many_arguments)]
|
||||
fn batch<'py>(
|
||||
&mut self,
|
||||
py: Python<'py>,
|
||||
open: PyReadonlyArray1<'py, f64>,
|
||||
high: PyReadonlyArray1<'py, f64>,
|
||||
low: PyReadonlyArray1<'py, f64>,
|
||||
close: PyReadonlyArray1<'py, f64>,
|
||||
volume: PyReadonlyArray1<'py, f64>,
|
||||
timestamp: PyReadonlyArray1<'py, i64>,
|
||||
) -> PyResult<Bound<'py, PyArray1<f64>>> {
|
||||
let candles = build_seasonality_candles(&open, &high, &low, &close, &volume, ×tamp)?;
|
||||
let out: Vec<f64> = candles
|
||||
.into_iter()
|
||||
.map(|c| self.inner.update(c).unwrap_or(f64::NAN))
|
||||
.collect();
|
||||
Ok(out.into_pyarray(py))
|
||||
}
|
||||
#[getter]
|
||||
fn params(&self) -> (u32, u32, i32) {
|
||||
self.inner.params()
|
||||
}
|
||||
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 {
|
||||
let (n_first, n_last, offset) = self.inner.params();
|
||||
format!("TurnOfMonth(n_first={n_first}, n_last={n_last}, utc_offset_minutes={offset})")
|
||||
}
|
||||
}
|
||||
|
||||
#[pyclass(
|
||||
name = "SessionHighLow",
|
||||
module = "wickra._wickra",
|
||||
skip_from_py_object
|
||||
)]
|
||||
#[derive(Clone)]
|
||||
struct PySessionHighLow {
|
||||
inner: wc::SessionHighLow,
|
||||
}
|
||||
#[pymethods]
|
||||
impl PySessionHighLow {
|
||||
#[new]
|
||||
#[pyo3(signature = (utc_offset_minutes = 0))]
|
||||
fn new(utc_offset_minutes: i32) -> Self {
|
||||
Self {
|
||||
inner: wc::SessionHighLow::new(utc_offset_minutes),
|
||||
}
|
||||
}
|
||||
fn update(&mut self, candle: &Bound<'_, PyAny>) -> PyResult<Option<(f64, f64)>> {
|
||||
let c = extract_candle(candle)?;
|
||||
Ok(self.inner.update(c).map(|o| (o.high, o.low)))
|
||||
}
|
||||
#[allow(clippy::too_many_arguments)]
|
||||
fn batch<'py>(
|
||||
&mut self,
|
||||
py: Python<'py>,
|
||||
open: PyReadonlyArray1<'py, f64>,
|
||||
high: PyReadonlyArray1<'py, f64>,
|
||||
low: PyReadonlyArray1<'py, f64>,
|
||||
close: PyReadonlyArray1<'py, f64>,
|
||||
volume: PyReadonlyArray1<'py, f64>,
|
||||
timestamp: PyReadonlyArray1<'py, i64>,
|
||||
) -> PyResult<Bound<'py, PyArray2<f64>>> {
|
||||
let candles = build_seasonality_candles(&open, &high, &low, &close, &volume, ×tamp)?;
|
||||
let n = candles.len();
|
||||
let mut out = vec![f64::NAN; n * 2];
|
||||
for (i, c) in candles.into_iter().enumerate() {
|
||||
if let Some(o) = self.inner.update(c) {
|
||||
out[i * 2] = o.high;
|
||||
out[i * 2 + 1] = o.low;
|
||||
}
|
||||
}
|
||||
Ok(numpy::ndarray::Array2::from_shape_vec((n, 2), out)
|
||||
.expect("shape consistent")
|
||||
.into_pyarray(py))
|
||||
}
|
||||
#[getter]
|
||||
fn utc_offset_minutes(&self) -> i32 {
|
||||
self.inner.utc_offset_minutes()
|
||||
}
|
||||
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!(
|
||||
"SessionHighLow(utc_offset_minutes={})",
|
||||
self.inner.utc_offset_minutes()
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
#[pyclass(name = "SessionRange", module = "wickra._wickra", skip_from_py_object)]
|
||||
#[derive(Clone)]
|
||||
struct PySessionRange {
|
||||
inner: wc::SessionRange,
|
||||
}
|
||||
#[pymethods]
|
||||
impl PySessionRange {
|
||||
#[new]
|
||||
#[pyo3(signature = (utc_offset_minutes = 0))]
|
||||
fn new(utc_offset_minutes: i32) -> Self {
|
||||
Self {
|
||||
inner: wc::SessionRange::new(utc_offset_minutes),
|
||||
}
|
||||
}
|
||||
fn update(&mut self, candle: &Bound<'_, PyAny>) -> PyResult<Option<(f64, f64, f64)>> {
|
||||
let c = extract_candle(candle)?;
|
||||
Ok(self.inner.update(c).map(|o| (o.asia, o.eu, o.us)))
|
||||
}
|
||||
#[allow(clippy::too_many_arguments)]
|
||||
fn batch<'py>(
|
||||
&mut self,
|
||||
py: Python<'py>,
|
||||
open: PyReadonlyArray1<'py, f64>,
|
||||
high: PyReadonlyArray1<'py, f64>,
|
||||
low: PyReadonlyArray1<'py, f64>,
|
||||
close: PyReadonlyArray1<'py, f64>,
|
||||
volume: PyReadonlyArray1<'py, f64>,
|
||||
timestamp: PyReadonlyArray1<'py, i64>,
|
||||
) -> PyResult<Bound<'py, PyArray2<f64>>> {
|
||||
let candles = build_seasonality_candles(&open, &high, &low, &close, &volume, ×tamp)?;
|
||||
let n = candles.len();
|
||||
let mut out = vec![f64::NAN; n * 3];
|
||||
for (i, c) in candles.into_iter().enumerate() {
|
||||
if let Some(o) = self.inner.update(c) {
|
||||
out[i * 3] = o.asia;
|
||||
out[i * 3 + 1] = o.eu;
|
||||
out[i * 3 + 2] = o.us;
|
||||
}
|
||||
}
|
||||
Ok(numpy::ndarray::Array2::from_shape_vec((n, 3), out)
|
||||
.expect("shape consistent")
|
||||
.into_pyarray(py))
|
||||
}
|
||||
#[getter]
|
||||
fn utc_offset_minutes(&self) -> i32 {
|
||||
self.inner.utc_offset_minutes()
|
||||
}
|
||||
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!(
|
||||
"SessionRange(utc_offset_minutes={})",
|
||||
self.inner.utc_offset_minutes()
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
#[pyclass(
|
||||
name = "OvernightIntradayReturn",
|
||||
module = "wickra._wickra",
|
||||
skip_from_py_object
|
||||
)]
|
||||
#[derive(Clone)]
|
||||
struct PyOvernightIntradayReturn {
|
||||
inner: wc::OvernightIntradayReturn,
|
||||
}
|
||||
#[pymethods]
|
||||
impl PyOvernightIntradayReturn {
|
||||
#[new]
|
||||
#[pyo3(signature = (utc_offset_minutes = 0))]
|
||||
fn new(utc_offset_minutes: i32) -> Self {
|
||||
Self {
|
||||
inner: wc::OvernightIntradayReturn::new(utc_offset_minutes),
|
||||
}
|
||||
}
|
||||
fn update(&mut self, candle: &Bound<'_, PyAny>) -> PyResult<Option<(f64, f64)>> {
|
||||
let c = extract_candle(candle)?;
|
||||
Ok(self.inner.update(c).map(|o| (o.overnight, o.intraday)))
|
||||
}
|
||||
#[allow(clippy::too_many_arguments)]
|
||||
fn batch<'py>(
|
||||
&mut self,
|
||||
py: Python<'py>,
|
||||
open: PyReadonlyArray1<'py, f64>,
|
||||
high: PyReadonlyArray1<'py, f64>,
|
||||
low: PyReadonlyArray1<'py, f64>,
|
||||
close: PyReadonlyArray1<'py, f64>,
|
||||
volume: PyReadonlyArray1<'py, f64>,
|
||||
timestamp: PyReadonlyArray1<'py, i64>,
|
||||
) -> PyResult<Bound<'py, PyArray2<f64>>> {
|
||||
let candles = build_seasonality_candles(&open, &high, &low, &close, &volume, ×tamp)?;
|
||||
let n = candles.len();
|
||||
let mut out = vec![f64::NAN; n * 2];
|
||||
for (i, c) in candles.into_iter().enumerate() {
|
||||
if let Some(o) = self.inner.update(c) {
|
||||
out[i * 2] = o.overnight;
|
||||
out[i * 2 + 1] = o.intraday;
|
||||
}
|
||||
}
|
||||
Ok(numpy::ndarray::Array2::from_shape_vec((n, 2), out)
|
||||
.expect("shape consistent")
|
||||
.into_pyarray(py))
|
||||
}
|
||||
#[getter]
|
||||
fn utc_offset_minutes(&self) -> i32 {
|
||||
self.inner.utc_offset_minutes()
|
||||
}
|
||||
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!(
|
||||
"OvernightIntradayReturn(utc_offset_minutes={})",
|
||||
self.inner.utc_offset_minutes()
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
#[pymodule]
|
||||
#[allow(clippy::too_many_lines)]
|
||||
fn _wickra(_py: Python<'_>, m: &Bound<'_, PyModule>) -> PyResult<()> {
|
||||
@@ -17596,5 +18183,18 @@ fn _wickra(_py: Python<'_>, m: &Bound<'_, PyModule>) -> PyResult<()> {
|
||||
m.add_class::<PyRocr100>()?;
|
||||
m.add_class::<PyLinRegIntercept>()?;
|
||||
m.add_class::<PyTsf>()?;
|
||||
// Family 16: Seasonality & Session.
|
||||
m.add_class::<PySessionVwap>()?;
|
||||
m.add_class::<PySessionHighLow>()?;
|
||||
m.add_class::<PySessionRange>()?;
|
||||
m.add_class::<PyAverageDailyRange>()?;
|
||||
m.add_class::<PyOvernightGap>()?;
|
||||
m.add_class::<PyOvernightIntradayReturn>()?;
|
||||
m.add_class::<PyTurnOfMonth>()?;
|
||||
m.add_class::<PySeasonalZScore>()?;
|
||||
m.add_class::<PyTimeOfDayReturnProfile>()?;
|
||||
m.add_class::<PyDayOfWeekProfile>()?;
|
||||
m.add_class::<PyIntradayVolatilityProfile>()?;
|
||||
m.add_class::<PyVolumeByTimeProfile>()?;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
@@ -0,0 +1,132 @@
|
||||
"""Streaming-vs-batch equivalence and reference values for the Seasonality &
|
||||
Session family.
|
||||
|
||||
These indicators read the full candle (including ``timestamp``), so they have a
|
||||
dedicated test rather than joining the timestamp-less parametrize harness in
|
||||
``test_new_indicators.py``.
|
||||
"""
|
||||
|
||||
import numpy as np
|
||||
import pytest
|
||||
|
||||
import wickra as ta
|
||||
|
||||
HOUR_MS = 3_600_000
|
||||
|
||||
|
||||
@pytest.fixture(scope="module")
|
||||
def candle_columns():
|
||||
"""240 hourly candles (10 days) with valid OHLCV and epoch-ms timestamps."""
|
||||
n = 240
|
||||
t = np.arange(n, dtype=np.float64)
|
||||
close = 100.0 + np.sin(t * 0.3) * 5.0 + np.cos(t * 0.1) * 3.0
|
||||
open_ = close + np.sin(t * 0.5) * 0.5
|
||||
high = np.maximum(open_, close) + 1.0
|
||||
low = np.minimum(open_, close) - 1.0
|
||||
volume = 1000.0 + (t % 24) * 50.0
|
||||
timestamp = (np.arange(n, dtype=np.int64)) * HOUR_MS
|
||||
return open_, high, low, close, volume, timestamp
|
||||
|
||||
|
||||
def _candles(cols):
|
||||
open_, high, low, close, volume, timestamp = cols
|
||||
return [
|
||||
(open_[i], high[i], low[i], close[i], volume[i], int(timestamp[i]))
|
||||
for i in range(len(close))
|
||||
]
|
||||
|
||||
|
||||
def _check_scalar(make, cols):
|
||||
candles = _candles(cols)
|
||||
a, b = make(), make()
|
||||
stream = np.array(
|
||||
[np.nan if (v := a.update(c)) is None else v for c in candles],
|
||||
dtype=np.float64,
|
||||
)
|
||||
batch = np.asarray(b.batch(*cols))
|
||||
np.testing.assert_allclose(stream, batch, equal_nan=True, rtol=1e-9, atol=1e-9)
|
||||
|
||||
|
||||
def _check_matrix(make, k, cols):
|
||||
candles = _candles(cols)
|
||||
a, b = make(), make()
|
||||
rows = []
|
||||
for c in candles:
|
||||
out = a.update(c)
|
||||
rows.append(np.full(k, np.nan) if out is None else np.asarray(out, dtype=float))
|
||||
stream = np.vstack(rows)
|
||||
batch = np.asarray(b.batch(*cols))
|
||||
assert batch.shape == (len(candles), k)
|
||||
np.testing.assert_allclose(stream, batch, equal_nan=True, rtol=1e-9, atol=1e-9)
|
||||
|
||||
|
||||
SCALAR = [
|
||||
lambda: ta.SessionVwap(0),
|
||||
lambda: ta.OvernightGap(0),
|
||||
lambda: ta.SeasonalZScore(0),
|
||||
lambda: ta.AverageDailyRange(3, 0),
|
||||
lambda: ta.TurnOfMonth(3, 1, 0),
|
||||
]
|
||||
|
||||
MATRIX = [
|
||||
(lambda: ta.SessionHighLow(0), 2),
|
||||
(lambda: ta.SessionRange(0), 3),
|
||||
(lambda: ta.OvernightIntradayReturn(0), 2),
|
||||
(lambda: ta.TimeOfDayReturnProfile(24, 0), 24),
|
||||
(lambda: ta.IntradayVolatilityProfile(12, 0), 12),
|
||||
(lambda: ta.VolumeByTimeProfile(24, 0), 24),
|
||||
(lambda: ta.DayOfWeekProfile(0), 7),
|
||||
]
|
||||
|
||||
|
||||
@pytest.mark.parametrize("make", SCALAR)
|
||||
def test_scalar_streaming_equals_batch(make, candle_columns):
|
||||
_check_scalar(make, candle_columns)
|
||||
|
||||
|
||||
@pytest.mark.parametrize("make,k", MATRIX)
|
||||
def test_matrix_streaming_equals_batch(make, k, candle_columns):
|
||||
_check_matrix(make, k, candle_columns)
|
||||
|
||||
|
||||
def test_session_vwap_reference():
|
||||
vwap = ta.SessionVwap(0)
|
||||
# typical = close for a flat candle; volume-weighted within the day.
|
||||
v1 = vwap.update((100.0, 100.0, 100.0, 100.0, 10.0, 0))
|
||||
assert v1 == pytest.approx(100.0)
|
||||
v2 = vwap.update((110.0, 110.0, 110.0, 110.0, 30.0, HOUR_MS))
|
||||
assert v2 == pytest.approx(107.5)
|
||||
# New day re-anchors.
|
||||
v3 = vwap.update((200.0, 200.0, 200.0, 200.0, 5.0, 24 * HOUR_MS))
|
||||
assert v3 == pytest.approx(200.0)
|
||||
|
||||
|
||||
def test_overnight_gap_reference():
|
||||
gap = ta.OvernightGap(0)
|
||||
assert gap.update((99.0, 101.0, 98.0, 100.0, 1.0, 0)) is None
|
||||
g = gap.update((105.0, 106.0, 104.0, 105.5, 1.0, 24 * HOUR_MS))
|
||||
assert g == pytest.approx(0.05)
|
||||
|
||||
|
||||
def test_session_high_low_reference():
|
||||
shl = ta.SessionHighLow(0)
|
||||
shl.update((100.0, 105.0, 99.0, 101.0, 1.0, 0))
|
||||
out = shl.update((101.0, 108.0, 100.0, 107.0, 1.0, HOUR_MS))
|
||||
assert out == (108.0, 99.0)
|
||||
|
||||
|
||||
def test_volume_by_time_profile_reference():
|
||||
prof = ta.VolumeByTimeProfile(24, 0)
|
||||
out = prof.update((100.0, 100.0, 100.0, 100.0, 500.0, HOUR_MS)) # 01:00 -> bucket 1
|
||||
assert out[1] == pytest.approx(500.0)
|
||||
assert out[0] == pytest.approx(0.0)
|
||||
|
||||
|
||||
def test_rejects_zero_buckets():
|
||||
with pytest.raises(ValueError):
|
||||
ta.TimeOfDayReturnProfile(0, 0)
|
||||
|
||||
|
||||
def test_average_daily_range_rejects_zero_period():
|
||||
with pytest.raises(ValueError):
|
||||
ta.AverageDailyRange(0, 0)
|
||||
Reference in New Issue
Block a user