PINE LIBRARY
업데이트됨 KalmanEngineLib

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.
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릴리즈 노트
v4Added:
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)
릴리즈 노트
v5Added:
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)
릴리즈 노트
v6Added:
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)
릴리즈 노트
v7Added:
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)
파인 라이브러리
트레이딩뷰의 진정한 정신에 따라, 작성자는 이 파인 코드를 오픈소스 라이브러리로 게시하여 커뮤니티의 다른 파인 프로그래머들이 재사용할 수 있도록 했습니다. 작성자에게 경의를 표합니다! 이 라이브러리는 개인적으로 사용하거나 다른 오픈소스 게시물에서 사용할 수 있지만, 이 코드의 게시물 내 재사용은 하우스 룰에 따라 규제됩니다.
면책사항
해당 정보와 게시물은 금융, 투자, 트레이딩 또는 기타 유형의 조언이나 권장 사항으로 간주되지 않으며, 트레이딩뷰에서 제공하거나 보증하는 것이 아닙니다. 자세한 내용은 이용 약관을 참조하세요.
파인 라이브러리
트레이딩뷰의 진정한 정신에 따라, 작성자는 이 파인 코드를 오픈소스 라이브러리로 게시하여 커뮤니티의 다른 파인 프로그래머들이 재사용할 수 있도록 했습니다. 작성자에게 경의를 표합니다! 이 라이브러리는 개인적으로 사용하거나 다른 오픈소스 게시물에서 사용할 수 있지만, 이 코드의 게시물 내 재사용은 하우스 룰에 따라 규제됩니다.
면책사항
해당 정보와 게시물은 금융, 투자, 트레이딩 또는 기타 유형의 조언이나 권장 사항으로 간주되지 않으며, 트레이딩뷰에서 제공하거나 보증하는 것이 아닙니다. 자세한 내용은 이용 약관을 참조하세요.