DNA — Dynamic Nonlinear Adaptive time series forecaster and audience segmentation toolkit
Project description
universitybox
DNA — Dynamic Nonlinear Adaptive Time Series Forecaster
A pure-NumPy/SciPy time series forecasting library built around the DNA model — a three-stage hierarchical forecaster combining classical decomposition, nonlinear basis expansion, and adaptive Kalman filtering.
No TensorFlow. No PyTorch. No black boxes. Every equation is documented.
Full mathematical derivations: MATH.md on GitHub
Install
pip install universitybox
With optional extras:
pip install "universitybox[full]" # + pandas + matplotlib
pip install "universitybox[viz]" # + matplotlib only
pip install "universitybox[data]" # + pandas only
Quick start
import numpy as np
from universitybox import DNA
# Any 1-D time series
y = np.array([112, 118, 132, 129, 121, 135, 148, 148, 136, 119,
104, 118, 115, 126, 141, 135, 125, 149, 170, 170,
158, 133, 114, 140, 145, 150, 178, 163, 172, 178,
199, 199, 184, 162, 146, 166, 171, 180, 193, 181])
model = DNA(period=12)
model.fit(y)
point_forecast = model.forecast(h=12)
lower, upper = model.predict_interval(h=12, level=0.95)
test_metrics = model.evaluate(y[-6:])
model.summary()
The DNA Model
DNA decomposes the time series into three progressively finer layers:
y(t) = mu(t) Stage D — trend, Henderson moving average
+ s(t) Stage D — seasonal, Fourier OLS
+ f(Phi(x_t)) Stage N — nonlinear correction, Ridge + RBF features
+ l(t) Stage A — adaptive correction, Kalman LLT filter
+ noise
Each stage is fitted on the residual of the previous stage. The final forecast is an inverse-variance weighted combination of all four components.
Stage D — Decomposition
- Trend: Henderson symmetric moving average of half-length
m. Weights minimise the third-difference roughness of the trend while exactly reproducing polynomials up to degree 2 (closed-form, Doherty 2001). - Seasonal: Fourier regression of order
Kon the detrended series, estimated by OLS. Normalised to zero mean over each complete period. - Period: Auto-estimated from the periodogram when
period='auto'.
Stage N — Nonlinear Basis Expansion
Feature map composed of three dictionaries:
Phi(t) = [ polynomial(t) | AR lags of residual | RBF kernels ]
- Polynomial: time index normalised to [0,1], up to degree
p. - AR lags: standardised lagged residuals (lags 1 to L).
- RBF: squared-exponential kernels centred by k-means++ seeding, bandwidth set by the median heuristic.
Ridge regression (L2 regularised least squares, closed-form Cholesky solve) fits the feature map to the D-stage residual.
Stage A — Adaptive Kalman Filter
Local Linear Trend (LLT) state-space model on the N-stage residual:
State: x(t) = [level, slope]
Transition: x(t) = F x(t-1) + noise_process
Observation: r(t) = H x(t) + noise_obs
Kalman filter recursion (prediction → innovation → gain → update).
Optional MLE estimation of noise parameters (kalman_mle=True).
h-step forecast: level(n) + h * slope(n).
Ensemble Combination
Component forecasts combined as:
y_hat(n+h) = alpha * trend(n+h)
+ beta * seasonal(n+h)
+ gamma * nonlinear(n+h)
+ delta * adaptive(n+h)
Weights computed by:
'iv'— inverse-variance (Bates & Granger 1969), default'ols'— non-negative least-squares stacking'equal'— 0.25 each
Prediction Intervals
- Analytical:
forecast ± z * sigma * sqrt(h), where sigma is the in-sample RMSE. - Bootstrap: resample in-sample residuals B times, propagate as cumulative shocks, take empirical quantiles.
All parameters
DNA(
period = "auto", # int or 'auto' — seasonal period (4, 12, 7, ...)
trend_window = "auto", # Henderson filter half-length m
n_fourier = 3, # Fourier harmonics K
poly_degree = 2, # polynomial degree in N-stage feature map
n_lags = 4, # AR lag count in N-stage feature map
n_rbf = 10, # RBF centres (k-means++ selected)
rbf_gamma = "auto", # RBF bandwidth ('auto' = median heuristic)
ridge_alpha = 1e-3, # L2 regularisation lambda
kalman_q_level = 1e-4, # Kalman level process noise
kalman_q_slope = 1e-6, # Kalman slope process noise
kalman_obs_var = 1e-2, # Kalman observation noise
kalman_mle = False, # estimate Kalman noise by MLE
ensemble = "iv", # 'iv' | 'equal' | 'ols'
ci_method = "analytical", # 'analytical' | 'bootstrap'
ci_bootstrap_n = 500, # bootstrap replications
random_state = None, # reproducibility seed
)
API reference
| Method / Property | Description |
|---|---|
fit(y) |
Fit the model. y must be 1-D, finite, length >= 4. |
forecast(h) |
Point forecasts for horizons 1 to h. Returns array of shape (h,). |
predict_interval(h, level=0.95) |
Returns (lower, upper) arrays of shape (h,). |
evaluate(y_test) |
MAE, RMSE, MAPE, sMAPE, MASE vs held-out test set. |
fitted_values |
In-sample fitted values, shape (n,). |
residuals |
In-sample residuals y - y_hat, shape (n,). |
components |
Dict: trend, seasonal, nonlinear, adaptive — each shape (n,). |
weights |
Dict: alpha, beta, gamma, delta ensemble weights. |
summary() |
Print model card. |
Metrics
from universitybox import metrics
metrics.mae(y_true, y_pred)
metrics.rmse(y_true, y_pred)
metrics.mape(y_true, y_pred)
metrics.smape(y_true, y_pred)
metrics.mase(y_true, y_pred, y_train=y_train, period=4)
metrics.crps_gaussian(y_true, mu=fc, sigma=sigma_h)
metrics.summary(y_true, y_pred) # dict of all metrics
Audience segmentation (Club)
from universitybox.segments import Club
category_map = {
"lenovo": "Technology",
"hp store": "Technology",
"samsung": "Technology",
"zara": "Fashion",
}
club = Club(category_map=category_map, min_cta=6)
club.fit(events_df) # DataFrame: user_id, brand, cta_count
club.size("Technology") # int — number of members
club.share("Technology") # float — fraction of classified users
club.members("Technology") # list of user_ids
club.summary() # dict: all clubs with size + share
Extending DNA — adding a custom forecaster
All forecasters extend BaseForecaster:
from universitybox.forecast._base import BaseForecaster
import numpy as np
class MyForecaster(BaseForecaster):
def __init__(self, alpha=0.3):
self.alpha = alpha
def fit(self, y: np.ndarray, **kwargs) -> "MyForecaster":
y = self._validate_y(y)
# ... fit logic ...
self._insample_rmse = float(np.std(y))
return self
def forecast(self, h: int) -> np.ndarray:
# ... return array of shape (h,) ...
...
predict_interval() and score() are provided by the base class automatically.
Mathematical documentation
Full derivations for every formula in the package: MATH.md, covering:
- Notation and problem statement
- The DNA decomposition equation
- Stage D — Henderson filter weights (closed-form), Fourier OLS, periodogram period estimation
- Stage N — polynomial / AR-lag / RBF feature map, k-means++ seed selection, median heuristic bandwidth, Ridge regression (primal & dual), RKHS interpretation
- Stage A — LLT state-space model, Kalman filter recursion (all equations), h-step forecast, MLE log-likelihood
- Ensemble combination — inverse-variance weighting, OLS stacking
- Prediction intervals — analytical Gaussian and bootstrap
- Evaluation metrics — MAE, RMSE, MAPE, sMAPE, MASE, CRPS (Gaussian closed-form)
- Identifiability and consistency proofs
- Computational complexity table
- Full bibliography
Design principles
- Pure NumPy/SciPy — no heavy ML framework required
- Minimal core dependencies — only
numpyandscipy - sklearn-compatible —
fit/forecast/scoreinterface - Fully typed —
py.typedmarker, complete type annotations - 22 unit tests — all components, edge cases, and metrics covered
Contributing
git clone https://github.com/Parsa-Hajian/universitybox
cd universitybox
pip install -e ".[dev]"
pytest tests/ -v
See CONTRIBUTING.md.
Citation
@software{universitybox2026,
author = {UniversityBox Data Team},
title = {universitybox: DNA Dynamic Nonlinear Adaptive Forecaster},
year = {2026},
url = {https://github.com/Parsa-Hajian/universitybox},
version = {0.1.2}
}
License
MIT — see LICENSE.
Project details
Download files
Download the file for your platform. If you're not sure which to choose, learn more about installing packages.
Source Distribution
Built Distribution
Filter files by name, interpreter, ABI, and platform.
If you're not sure about the file name format, learn more about wheel file names.
Copy a direct link to the current filters
File details
Details for the file universitybox-0.1.4.tar.gz.
File metadata
- Download URL: universitybox-0.1.4.tar.gz
- Upload date:
- Size: 29.4 kB
- Tags: Source
- Uploaded using Trusted Publishing? No
- Uploaded via: twine/6.2.0 CPython/3.13.5
File hashes
| Algorithm | Hash digest | |
|---|---|---|
| SHA256 |
31c4680b7f2e6488c78be4b9ca6c7e3aace0bb54591d734a798d26fa83e36801
|
|
| MD5 |
d9613ec32c2540192a6e15323f671609
|
|
| BLAKE2b-256 |
c48280a5184fa276321a9691463dafb3ab43b5f42d11044c51fdb5c90d97782a
|
File details
Details for the file universitybox-0.1.4-py3-none-any.whl.
File metadata
- Download URL: universitybox-0.1.4-py3-none-any.whl
- Upload date:
- Size: 28.3 kB
- Tags: Python 3
- Uploaded using Trusted Publishing? No
- Uploaded via: twine/6.2.0 CPython/3.13.5
File hashes
| Algorithm | Hash digest | |
|---|---|---|
| SHA256 |
a4d7466e83037bfb9704e3ab9d01f7ca31d22c2993e18e4d53768abea1835616
|
|
| MD5 |
a4d7c83a7fbd20035e5153288136d156
|
|
| BLAKE2b-256 |
be7ce5a0b2ba10c57cc465130d3381a324b81029d9b42bfe4dc69c0db848dffa
|