PINE LIBRARY
Обновлено

KalmanEngineLib

229
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.
Информация о релизе
v2
Информация о релизе
v3
Информация о релизе
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)
Информация о релизе
v5

Added:
f_sep_pair5(mu_a, sigma_a, mu_b, sigma_b, use_f4, use_f5, var_floor)
  Parameters:
    mu_a (array<float>)
    sigma_a (matrix<float>)
    mu_b (array<float>)
    sigma_b (matrix<float>)
    use_f4 (bool)
    use_f5 (bool)
    var_floor (float)
Информация о релизе
v6

Added:
method update_value(s, z, Q, R)
  Namespace types: KalmanState1D
  Parameters:
    s (KalmanState1D)
    z (float)
    Q (float)
    R (float)

f_inverse_covariance3_diag(sigma, active_dims, variance_floor, determinant_floor)
  Parameters:
    sigma (matrix<float>)
    active_dims (array<bool>)
    variance_floor (float)
    determinant_floor (float)
Информация о релизе
v7

Added:
f_sequential_update_metric(x, P_tri, z, H_row, R, n, use_lorentzian, bandwidth, max_r_multiplier)
  Parameters:
    x (array<float>)
    P_tri (array<float>)
    z (float)
    H_row (array<float>)
    R (float)
    n (int)
    use_lorentzian (bool)
    bandwidth (float)
    max_r_multiplier (float)

Отказ от ответственности

Информация и публикации не предназначены для предоставления и не являются финансовыми, инвестиционными, торговыми или другими видами советов или рекомендаций, предоставленных или одобренных TradingView. Подробнее читайте в Условиях использования.