feat: expand rust parity, wasm exports, and api conformance

Move several hot Python analysis paths to Rust-backed helpers. This adds Rust implementations for backtest strategy signal generation and the core portfolio loop, options and futures payoff aggregation, Greeks aggregation, ratio calculation, trade extraction, chunked close-only indicator runs, and forward-fill helpers. Wire the Python analysis and data modules to prefer these paths, and add coverage for the new batch fast path.

Expand the WASM package to export WMA, ADX, and MFI from ferro_ta_core, refresh the Node examples, benchmarks, and README, and add a Node-vs-Python conformance test so the browser and node surface stays aligned with the main Python package.

Introduce a generated cross-surface API manifest in docs/, along with scripts to rebuild and verify it from source exports. Enforce manifest freshness in the Python and WASM CI workflows so release candidates catch surface drift before push.
This commit is contained in:
Pratik Bhadane
2026-03-24 14:28:51 +05:30
parent ba77fbd418
commit 53566b9d82
27 changed files with 7012 additions and 198 deletions
+130 -5
View File
@@ -8,11 +8,15 @@
//!
//! Functions
//! ---------
//! - `trim_overlap` — remove the first *overlap* elements from an array
//! (to strip the warm-up from a chunk's indicator output).
//! - `stitch_chunks` — concatenate trimmed chunk results into one array.
//! - `make_chunk_ranges` — compute start/end indices for a series given chunk
//! size and overlap, for use by the Python caller.
//! - `trim_overlap` — remove the first *overlap* elements from
//! an array (to strip the warm-up from a chunk's indicator output).
//! - `stitch_chunks` — concatenate trimmed chunk results into one
//! array.
//! - `make_chunk_ranges` — compute start/end indices for a series
//! given chunk size and overlap, for use by the Python caller.
//! - `chunk_apply_close_indicator`— run chunked close-only indicators fully in
//! Rust (SMA/EMA/RSI).
//! - `forward_fill_nan` — forward-fill NaN values in a 1-D array.
use numpy::{IntoPyArray, PyArray1, PyReadonlyArray1};
use pyo3::exceptions::PyValueError;
@@ -132,6 +136,125 @@ pub fn make_chunk_ranges<'py>(
Ok(ranges.into_pyarray(py))
}
// ---------------------------------------------------------------------------
// chunk_apply_close_indicator
// ---------------------------------------------------------------------------
fn compute_close_indicator(
indicator: &str,
series: &[f64],
timeperiod: usize,
) -> PyResult<Vec<f64>> {
match indicator {
"SMA" => Ok(ferro_ta_core::overlap::sma(series, timeperiod)),
"EMA" => Ok(ferro_ta_core::overlap::ema(series, timeperiod)),
"RSI" => Ok(ferro_ta_core::momentum::rsi(series, timeperiod)),
_ => Err(PyValueError::new_err(format!(
"chunk_apply_close_indicator does not support indicator '{indicator}'"
))),
}
}
/// Run chunked execution for close-only indicators in Rust.
///
/// Parameters
/// ----------
/// series : 1-D float64 array
/// indicator : one of {"SMA", "EMA", "RSI"}
/// timeperiod : indicator period (>= 1)
/// chunk_size : output bars per chunk (>= 1)
/// overlap : warm-up bars prepended to each chunk
///
/// Returns
/// -------
/// 1-D float64 array with the same length as `series`.
#[pyfunction]
#[pyo3(signature = (series, indicator, timeperiod, chunk_size = 10_000, overlap = 100))]
pub fn chunk_apply_close_indicator<'py>(
py: Python<'py>,
series: PyReadonlyArray1<'py, f64>,
indicator: &str,
timeperiod: usize,
chunk_size: usize,
overlap: usize,
) -> PyResult<Bound<'py, PyArray1<f64>>> {
if timeperiod == 0 {
return Err(PyValueError::new_err("timeperiod must be >= 1"));
}
if chunk_size == 0 {
return Err(PyValueError::new_err("chunk_size must be >= 1"));
}
let values = series.as_slice()?;
if values.is_empty() {
return Ok(Vec::<f64>::new().into_pyarray(py));
}
let name = indicator.to_ascii_uppercase();
let n = values.len();
let mut stitched: Vec<f64> = Vec::with_capacity(n);
let mut start = 0usize;
let mut chunk_index = 0usize;
loop {
let end = (start + chunk_size + overlap).min(n);
let chunk = &values[start..end];
let out = compute_close_indicator(name.as_str(), chunk, timeperiod)?;
let discard = if chunk_index == 0 { 0 } else { overlap };
if discard > out.len() {
return Err(PyValueError::new_err(format!(
"overlap ({discard}) must be <= chunk output length ({})",
out.len()
)));
}
stitched.extend_from_slice(&out[discard..]);
if end >= n {
break;
}
start = end.saturating_sub(overlap);
chunk_index += 1;
}
if stitched.len() != n {
return Err(PyValueError::new_err(format!(
"internal chunk stitching error: expected output length {n}, got {}",
stitched.len()
)));
}
Ok(stitched.into_pyarray(py))
}
// ---------------------------------------------------------------------------
// forward_fill_nan
// ---------------------------------------------------------------------------
/// Forward-fill NaN values in a 1-D array.
///
/// Leading NaN values are preserved until the first non-NaN value appears.
#[pyfunction]
pub fn forward_fill_nan<'py>(
py: Python<'py>,
values: PyReadonlyArray1<'py, f64>,
) -> PyResult<Bound<'py, PyArray1<f64>>> {
let input = values.as_slice()?;
let mut out = Vec::with_capacity(input.len());
let mut last = f64::NAN;
for &value in input {
if value.is_nan() {
out.push(last);
} else {
last = value;
out.push(value);
}
}
Ok(out.into_pyarray(py))
}
// ---------------------------------------------------------------------------
// Register
// ---------------------------------------------------------------------------
@@ -140,5 +263,7 @@ pub fn register(m: &Bound<'_, PyModule>) -> PyResult<()> {
m.add_function(wrap_pyfunction!(trim_overlap, m)?)?;
m.add_function(wrap_pyfunction!(stitch_chunks, m)?)?;
m.add_function(wrap_pyfunction!(make_chunk_ranges, m)?)?;
m.add_function(wrap_pyfunction!(chunk_apply_close_indicator, m)?)?;
m.add_function(wrap_pyfunction!(forward_fill_nan, m)?)?;
Ok(())
}