PINE LIBRARY
Updated

KalmanEngineLib

196
KalmanEngineLib

A Pine Script v6 library that provides a reusable engine for multi-state Kalman filtering, symmetric covariance packing, sequential scalar measurement updates, Mahalanobis gating, adaptive noise estimation, online coupling estimation, multi-scale trajectory storage, covariance-derived confidence bands, and k-step covariance propagation.

What it does

Implements a generic N-state Kalman filter where the posterior covariance P is stored as a packed upper triangle (n*(n+1)/2 elements), saving ~47% memory vs a full matrix.new<float>(n,n) at n=14.

Supports block-diagonal transition matrices via separate sub-blocks (3×3 kinematics, 6×6 z-score dynamics, 5×5 Mahalanobis, 3×5 cross-coupling Γ_lag) instead of a single n×n F matrix.

Provides a sequential scalar measurement update in Joseph form for numerical stability; calling it once per observation is equivalent to a batch update but avoids allocating an m×n H matrix.

Core components

UDTs: KalmanState_N, TransitionConfig, TrajectoryStore, ConceptConfig — callers own all persistent state; library functions are stateless transforms.

Triangle primitives: f_tri_idx, f_tri_get, f_tri_set, f_tri_new, f_tri_diag, f_tri_add_outer_product for packed symmetric matrix arithmetic.

Prediction: f_predict_block, f_predict_identity, f_P_predict_diag, f_P_predict_cross.

Update: f_sequential_update returning [innovation, S] for external diagnostics.

Gating: f_mahalanobis_3d (analytic 3×3 inverse with Ledoit-Wolf shrinkage and diagonal fallback near singularity), f_nis_test, f_gating_gain_mod.

Adaptive noise: f_adaptive_Q_scalar (windowed MLE), f_adaptive_R_scalar (innovation z-score ratchet).

Coupling: f_gamma_lag_update (scalar 1-D Kalman β-tracker for Γ_lag elements).

Trajectory: f_traj_init, f_traj_update, f_traj_xcorr — circular buffers at Δ={3,5,7} bar skips with Pearson cross-correlation for lag calibration.

Bands and projection: f_covariance_band_width, f_confidence_envelope, f_k_step_cov_propagation, f_z_spread.

Derived outputs: KMEMA (adaptive EMA modulated by innovation shock, TE confidence, velocity), online OLS beta update, execution-score helpers.

Architecture notes

All functions are stateless transforms operating on UDTs passed by the caller; no var declarations inside library functions.

Element budget: ~3,600 for the core engine; ~1,800 for TrajectoryStore at depth=100, n_feat=6. Total ~22K elements under Pine's 100K limit.

Self-healing: f_state_sanitize resets na or overflow entries in x and P diagonals to caller-supplied defaults.

Usage pattern

Declare a var KalmanState_N state = f_init_regression(n, P0, Q0, R0) in the indicator.

Each bar: call f_predict_block → f_P_predict_diag/f_P_predict_cross → one or more f_sequential_update per scalar observation → optional f_mahalanobis_3d/f_adaptive_Q_scalar/f_adaptive_R_scalar → read outputs via f_z_spread, f_confidence_envelope, f_k_step_cov_propagation.

Scope

General-purpose Kalman infrastructure; no market-specific logic, no signals, no thresholds embedded. Intended as a dependency for indicators and strategies that need rigorous multi-state filtering with adaptive noise and regime-aware gating.

License

Mozilla Public License 2.0.
Release Notes
v2
Release Notes
v3
Release Notes
v4

Added:
f_kalman1d_init(P0, Q, R)
  Initialize 1D Kalman filter
  Parameters:
    P0 (float): Initial estimate variance
    Q (float): Process noise variance
    R (float): Measurement noise variance
  Returns: Initialized KalmanState1D

method update(s, z)
  Update 1D Kalman filter with new measurement
  Namespace types: KalmanState1D
  Parameters:
    s (KalmanState1D): KalmanState1D to update (mutated in-place)
    z (float): New measurement
  Returns: Updated state (same reference as input)

KalmanState1D
  Simple 1D Kalman filter for scalar smoothing (ergonomic wrapper over N-dim API)
  Fields:
    x (series float)
    P (series float)
    Q (series float)
    R (series float)

Disclaimer

The information and publications are not meant to be, and do not constitute, financial, investment, trading, or other types of advice or recommendations supplied or endorsed by TradingView. Read more in the Terms of Use.