Skip to main content

DNA — Dynamic Nonlinear Adaptive time series forecaster and audience segmentation toolkit

Project description

universitybox

DNA — Dynamic Nonlinear Adaptive Time Series Forecaster

PyPI Python License: MIT Tests

A pure-NumPy/SciPy time series forecasting library built around the DNA model — a three-stage hierarchical forecaster that combines classical decomposition, nonlinear basis expansion, and adaptive Kalman filtering.

No TensorFlow. No PyTorch. No black boxes. Every equation is documented.


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)
metrics             = model.evaluate(y[-6:])   # held-out test

model.summary()

The DNA Model

DNA decomposes the time series into three progressively finer layers:

y_t  =  μ_t          (D-stage: trend via Henderson filter)
      + s_t          (D-stage: seasonal via Fourier OLS)
      + f(Φ(x_t))   (N-stage: nonlinear correction via Ridge + RBF)
      + ℓ_t          (A-stage: adaptive correction via Kalman LLT)
      + η_t          (irreducible noise)

Each stage is fit on the residual of the previous stage. Final forecast = inverse-variance weighted combination of all four components.

Full mathematical derivation (Henderson weights, RKHS interpretation, Kalman recursion, MLE, consistency proofs): see MATH.md.


All parameters

DNA(
    period        = "auto",   # int or 'auto' — seasonal period (e.g. 4, 12, 7)
    trend_window  = "auto",   # Henderson filter half-length m
    n_fourier     = 3,        # Fourier harmonics K
    poly_degree   = 2,        # polynomial degree for N-stage feature map
    n_lags        = 4,        # AR lags for 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 λ
    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

DNA.fit(y)

Fit the model. y must be a 1-D array with ≥ 4 observations and no NaN/Inf.

DNA.forecast(h)

Return point forecasts for horizons 1 … h.

DNA.predict_interval(h, level=0.95)

Return (lower, upper) prediction interval arrays of length h.

DNA.evaluate(y_test)

Compute MAE, RMSE, MAPE, sMAPE, MASE against a held-out test set.

DNA.fitted_values

In-sample fitted values ŷ₁, ..., ŷₙ.

DNA.residuals

In-sample residuals y − ŷ.

DNA.components

Dict of in-sample arrays: trend, seasonal, nonlinear, adaptive.

DNA.weights

Ensemble weights α, β, γ, δ for each component.

DNA.summary()

Print a human-readable 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

from universitybox.segments import Club

category_map = {
    "lenovo":     "Technology",
    "hp store":   "Technology",
    "samsung":    "Technology",
    "zara":       "Fashion",
    "zalando":    "Fashion",
}

club = Club(category_map=category_map, min_cta=6)
club.fit(events_df)   # DataFrame with columns: user_id, brand, cta_count

print(club.size("Technology"))           # number of members
print(club.share("Technology"))          # fraction of classified users
print(club.summary())                    # all clubs with size + share
tech_users = club.members("Technology") # list of user_ids

Design principles

  • Pure NumPy/SciPy — no heavy ML framework required
  • Minimal dependenciesnumpy + scipy only for the core forecaster
  • Fully documented math — every formula in the code has an equation tag in MATH.md
  • sklearn-compatible interfacefit / forecast / score
  • Typedpy.typed marker, full type annotations
  • Tested — 22 unit tests covering all components, edge cases, and metrics

Contributing

  1. Fork the repository
  2. Create a feature branch: git checkout -b feature/my-feature
  3. Install dev dependencies: pip install -e ".[dev]"
  4. Run tests: pytest tests/ -v
  5. Open a pull request

All contributions welcome — new forecasters (implement BaseForecaster), new metrics, new segmentation methods.


Citation

If you use this package in research, please cite:

@software{universitybox2026,
  author  = {UniversityBox Data Team},
  title   = {universitybox: DNA Dynamic Nonlinear Adaptive Forecaster},
  year    = {2026},
  url     = {https://github.com/universitybox/universitybox-pkg},
  version = {0.1.0}
}

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

universitybox-0.1.0.tar.gz (27.1 kB view details)

Uploaded Source

Built Distribution

If you're not sure about the file name format, learn more about wheel file names.

universitybox-0.1.0-py3-none-any.whl (27.1 kB view details)

Uploaded Python 3

File details

Details for the file universitybox-0.1.0.tar.gz.

File metadata

  • Download URL: universitybox-0.1.0.tar.gz
  • Upload date:
  • Size: 27.1 kB
  • Tags: Source
  • Uploaded using Trusted Publishing? No
  • Uploaded via: twine/6.2.0 CPython/3.13.5

File hashes

Hashes for universitybox-0.1.0.tar.gz
Algorithm Hash digest
SHA256 e92336bef922c61dacfbf9393ba8ae12b373cf02d451c7d319044645feb214ef
MD5 281e9ef7a04d088666060a750aa23418
BLAKE2b-256 17ce1247def3629c882caa740fe0f6cd49c7167cce5c1fc455adc007e013644a

See more details on using hashes here.

File details

Details for the file universitybox-0.1.0-py3-none-any.whl.

File metadata

  • Download URL: universitybox-0.1.0-py3-none-any.whl
  • Upload date:
  • Size: 27.1 kB
  • Tags: Python 3
  • Uploaded using Trusted Publishing? No
  • Uploaded via: twine/6.2.0 CPython/3.13.5

File hashes

Hashes for universitybox-0.1.0-py3-none-any.whl
Algorithm Hash digest
SHA256 87ed8fce6ef03a6c6df287c16b864a0e4e5b71e0ac477c41d5fbef8b80302a13
MD5 75e6f88a6fc25566de7cbaea69796fb1
BLAKE2b-256 0b7775fa3bf3a38b037e7091e3461f0445a788228f87a8e0c3937a8d992ac74c

See more details on using hashes here.

Supported by

AWS Cloud computing and Security Sponsor Datadog Monitoring Depot Continuous Integration Fastly CDN Google Download Analytics Pingdom Monitoring Sentry Error logging StatusPage Status page