rollit.apply: NumPy Rolling Custom Function
The rollit.apply() function serves as a flexible escape hatch, enabling you to execute any custom Python callback or mathematical reduction (like rolling medians, percentiles, or geometric means) across a sliding window of a 1D NumPy array.
Performance Note: While core functions like rollit.mean() and rollit.std() are fully vectorized and execute in optimized C-loops, rollit.apply()runs a Python loop internally to invoke your custom callback. It is significantly faster than writing a manual nested loop in pure Python, but slower than rollit's vectorized primitives.
Parameters
arr (np.ndarray)
The input 1D numerical NumPy array.
window (int)
The sliding window frame size. Must be a positive integer greater than zero.
fn (callable)
A Python callable function (e.g. np.median, scipy.stats.gmean, or a custom lambda) that accepts a 1D NumPy slice of length window and returns a single numeric scalar.
min_periods (int | None, optional)
Minimum number of valid observations required in the window. If set, slices are pre-filtered to remove NaNs before invoking the callback.
Returns
np.ndarray
A flat 1D NumPy array containing the computed custom values. The length matches standard window contraction: Output Length = len(arr) - window + 1.
Usage Examples
import numpy as np
import rollit
prices = np.array([100.0, 102.0, 101.0, 105.0, 110.0, 95.0, 100.0])
# 1. Custom function: rolling median using np.median
medians = rollit.apply(prices, window=3, fn=np.median)
print("Rolling Medians:", medians)
# Output: [101.0, 102.0, 105.0, 105.0, 100.0]
# 2. Custom lambda function: range (max - min)
ranges = rollit.apply(prices, window=3, fn=lambda x: np.max(x) - np.min(x))
print("Rolling Ranges: ", ranges)
# Output: [2.0, 4.0, 9.0, 15.0, 15.0]