DTime series · ts.particle_filter
Particle filter (state-space model with PMMH)
What hidden level, trend or volatility lies behind a noisy series, how sure can we be at each step, and which noise levels fit the data?
Tracks a hidden state through a series with a bootstrap particle filter: thousands of weighted guesses (particles) are moved forward by the model and reweighted by each observation. Three models: a local level (random walk plus noise), a local linear trend, and stochastic volatility for returns. The noise levels are estimated by particle marginal Metropolis–Hastings (PMMH) — Bayesian MCMC that uses the filter's likelihood estimate — or set by hand. Reports filtered and smoothed states with 90% bands, the log-likelihood estimate and its noise, and, for the linear models, the exact Kalman-filter log-likelihood it should approach. Every random number comes from the shared stream, so Python and R run the same filter.
A real result
Example “Nile level pmmh”, recorded in both engines. In the app, “Try this example” loads it into Analyze.
A local level particle filter of flow (100 steps, 500 particles; parameters estimated by PMMH) has log-likelihood -639.51 (SD 0.45 over five runs); the exact Kalman value is -638.76. The last filtered level is 783.1 (90% band 652.7 to 906.1).
- Log-likelihood (particle)
- −639.51
- Log-likelihood SD
- 0.4484
- Log-likelihood (Kalman)
- −638.76
- Acceptance rate
- 0.3800
Assumptions
- Model form — Assumed, not checked from the data: the series follows a local level model with Gaussian noise and equally spaced steps.
- Enough particles — Five filter runs with 500 particles gave log-likelihoods with SD 0.45 (≤ 1).
- MCMC mixing — The chain accepted 38% of proposals after burn-in; the smallest effective sample size is 8. Aim for 10–50% acceptance and at least 100 effective draws: run more iterations, or more particles per step when acceptance is low.
Parameters
| Parameter | Value | 5% | 95% | Effective draws | Source |
|---|---|---|---|---|---|
| Observation noise SD | 123.59 | 106.47 | 138.10 | 30.381 | PMMH posterior mean |
| Level noise SD | 43.419 | 29.083 | 64.891 | 8.164 | PMMH posterior mean |
Log-likelihood
| Value | |
|---|---|
| Particle estimate (500 particles) | −639.51 |
| SD over five filter runs | 0.4484 |
| Exact (Kalman filter) | −638.76 |
Hidden state at each step
| year | flow | Filtered level | 5% | 95% | Smoothed level | 5% (smoothed) | 95% (smoothed) |
|---|---|---|---|---|---|---|---|
| 1871 | 1,120 | 1125.52 | 967.55 | 1283.00 | 1112.06 | 1015.67 | 1210.42 |
| 1872 | 1,160 | 1140.12 | 1007.44 | 1271.96 | 1104.74 | 1017.41 | 1166.61 |
| 1873 | 963 | 1070.30 | 960.34 | 1195.89 | 1093.12 | 1008.39 | 1163.70 |
| 1874 | 1,210 | 1114.50 | 998.91 | 1232.27 | 1099.02 | 987.89 | 1176.70 |
| 1875 | 1,160 | 1127.27 | 1011.92 | 1242.84 | 1105.62 | 1008.48 | 1180.09 |
| 1876 | 1,160 | 1133.53 | 1026.55 | 1251.18 | 1106.19 | 1047.94 | 1154.98 |
| 1877 | 813 | 1041.53 | 928.32 | 1144.00 | 1090.46 | 1025.72 | 1136.53 |
| 1878 | 1,230 | 1098.48 | 992.72 | 1203.46 | 1119.96 | 1047.46 | 1200.71 |
| 1879 | 1,370 | 1175.29 | 1067.88 | 1280.58 | 1127.98 | 1041.69 | 1184.94 |
| 1880 | 1,140 | 1166.26 | 1050.34 | 1279.88 | 1107.29 | 1019.43 | 1184.17 |
| 1881 | 995 | 1121.37 | 1011.89 | 1219.27 | 1091.29 | 1009.09 | 1176.63 |
| 1882 | 935 | 1071.85 | 954.57 | 1181.12 | 1070.05 | 985.55 | 1161.14 |
| 1883 | 1,110 | 1082.01 | 970.38 | 1188.03 | 1063.11 | 967.66 | 1159.21 |
| 1884 | 994 | 1057.67 | 952.27 | 1168.61 | 1045.09 | 980.74 | 1131.36 |
| 1885 | 1,020 | 1046.58 | 937.13 | 1154.69 | 1036.06 | 951.30 | 1114.20 |
| 1886 | 960 | 1020.12 | 914.56 | 1132.41 | 1025.14 | 966.24 | 1086.58 |
| 1887 | 1,180 | 1065.12 | 957.40 | 1182.11 | 1044.47 | 954.28 | 1094.51 |
| 1888 | 799 | 985.70 | 868.19 | 1094.73 | 1034.30 | 962.57 | 1110.02 |
| 1889 | 958 | 979.04 | 864.37 | 1089.21 | 1064.47 | 1007.20 | 1121.07 |
| 1890 | 1,140 | 1028.36 | 914.58 | 1135.79 | 1083.18 | 993.46 | 1151.88 |
| 1891 | 1,100 | 1049.80 | 936.77 | 1142.95 | 1103.85 | 1060.87 | 1186.58 |
| 1892 | 1,210 | 1096.28 | 986.40 | 1198.21 | 1110.39 | 1047.21 | 1176.68 |
| 1893 | 1,150 | 1111.58 | 999.97 | 1214.61 | 1114.66 | 1036.97 | 1197.72 |
| 1894 | 1,250 | 1150.42 | 1045.38 | 1246.45 | 1122.45 | 1062.25 | 1188.46 |
| 1895 | 1,260 | 1175.55 | 1074.75 | 1282.66 | 1106.22 | 1047.60 | 1196.37 |
| 1896 | 1,220 | 1189.65 | 1080.02 | 1290.90 | 1077.23 | 998.82 | 1142.24 |
| 1897 | 1,030 | 1144.40 | 1040.29 | 1251.47 | 1035.30 | 959.14 | 1102.39 |
| 1898 | 1,100 | 1132.61 | 1031.02 | 1247.00 | 1002.03 | 930.12 | 1059.18 |
| 1899 | 774 | 1035.63 | 951.65 | 1134.70 | 958.11 | 864.00 | 1012.01 |
| 1900 | 840 | 985.76 | 887.99 | 1088.57 | 919.50 | 857.11 | 980.13 |
| 1901 | 874 | 956.00 | 852.79 | 1063.37 | 891.70 | 803.04 | 962.23 |
| 1902 | 694 | 881.25 | 778.74 | 986.51 | 867.75 | 781.17 | 923.53 |
| 1903 | 940 | 898.30 | 788.04 | 1000.80 | 865.58 | 802.10 | 942.40 |
| 1904 | 833 | 880.48 | 773.82 | 986.56 | 851.36 | 771.00 | 935.92 |
| 1905 | 701 | 831.37 | 714.10 | 941.68 | 839.33 | 772.31 | 904.43 |
| 1906 | 916 | 858.37 | 746.87 | 971.39 | 846.56 | 779.80 | 913.78 |
| 1907 | 692 | 808.32 | 692.82 | 920.45 | 844.33 | 773.45 | 915.91 |
| 1908 | 1,020 | 869.32 | 762.15 | 978.60 | 860.79 | 798.61 | 947.77 |
| 1909 | 1,050 | 919.50 | 810.05 | 1008.54 | 877.67 | 787.56 | 982.69 |
| 1910 | 969 | 931.07 | 822.87 | 1037.93 | 863.64 | 780.36 | 933.26 |
First 40 of 100 rows.
- A bootstrap particle filter (Gordon, Salmond & Smith 1993): particles move by the model, are reweighted by each observation, and are resampled systematically when the effective sample size drops below half the particles.
- Filtered states use the observations up to each step; smoothed states (forward filtering, backward simulation) use the whole series.
- The first hidden state starts at the first observation with the series' variance; the Kalman filter uses the same start, so its exact log-likelihood is what the particle estimate approaches.
- PMMH ran 300 iterations (100 burn-in, step size adapted during burn-in) with 100 particles per step; priors: normal on log σ centered at the data-based value (SD 2). The final filter uses the posterior means.
A local level particle filter of flow (100 steps, 500 particles; parameters estimated by PMMH) has log-likelihood -639.51 (SD 0.45 over five runs); the exact Kalman value is -638.76. The last filtered level is 783.1 (90% band 652.7 to 906.1).
- Log-likelihood (particle)
- −639.51
- Log-likelihood SD
- 0.4484
- Log-likelihood (Kalman)
- −638.76
- Acceptance rate
- 0.3800
Assumptions
- Model form — Assumed, not checked from the data: the series follows a local level model with Gaussian noise and equally spaced steps.
- Enough particles — Five filter runs with 500 particles gave log-likelihoods with SD 0.45 (≤ 1).
- MCMC mixing — The chain accepted 38% of proposals after burn-in; the smallest effective sample size is 8. Aim for 10–50% acceptance and at least 100 effective draws: run more iterations, or more particles per step when acceptance is low.
Parameters
| Parameter | Value | 5% | 95% | Effective draws | Source |
|---|---|---|---|---|---|
| Observation noise SD | 123.59 | 106.47 | 138.10 | 30.381 | PMMH posterior mean |
| Level noise SD | 43.419 | 29.083 | 64.891 | 8.164 | PMMH posterior mean |
Log-likelihood
| Value | |
|---|---|
| Particle estimate (500 particles) | −639.51 |
| SD over five filter runs | 0.4484 |
| Exact (Kalman filter) | −638.76 |
Hidden state at each step
| year | flow | Filtered level | 5% | 95% | Smoothed level | 5% (smoothed) | 95% (smoothed) |
|---|---|---|---|---|---|---|---|
| 1871 | 1,120 | 1125.52 | 967.55 | 1283.00 | 1112.06 | 1015.67 | 1210.42 |
| 1872 | 1,160 | 1140.12 | 1007.44 | 1271.96 | 1104.74 | 1017.41 | 1166.61 |
| 1873 | 963 | 1070.30 | 960.34 | 1195.89 | 1093.12 | 1008.39 | 1163.70 |
| 1874 | 1,210 | 1114.50 | 998.91 | 1232.27 | 1099.02 | 987.89 | 1176.70 |
| 1875 | 1,160 | 1127.27 | 1011.92 | 1242.84 | 1105.62 | 1008.48 | 1180.09 |
| 1876 | 1,160 | 1133.53 | 1026.55 | 1251.18 | 1106.19 | 1047.94 | 1154.98 |
| 1877 | 813 | 1041.53 | 928.32 | 1144.00 | 1090.46 | 1025.72 | 1136.53 |
| 1878 | 1,230 | 1098.48 | 992.72 | 1203.46 | 1119.96 | 1047.46 | 1200.71 |
| 1879 | 1,370 | 1175.29 | 1067.88 | 1280.58 | 1127.98 | 1041.69 | 1184.94 |
| 1880 | 1,140 | 1166.26 | 1050.34 | 1279.88 | 1107.29 | 1019.43 | 1184.17 |
| 1881 | 995 | 1121.37 | 1011.89 | 1219.27 | 1091.29 | 1009.09 | 1176.63 |
| 1882 | 935 | 1071.85 | 954.57 | 1181.12 | 1070.05 | 985.55 | 1161.14 |
| 1883 | 1,110 | 1082.01 | 970.38 | 1188.03 | 1063.11 | 967.66 | 1159.21 |
| 1884 | 994 | 1057.67 | 952.27 | 1168.61 | 1045.09 | 980.74 | 1131.36 |
| 1885 | 1,020 | 1046.58 | 937.13 | 1154.69 | 1036.06 | 951.30 | 1114.20 |
| 1886 | 960 | 1020.12 | 914.56 | 1132.41 | 1025.14 | 966.24 | 1086.58 |
| 1887 | 1,180 | 1065.12 | 957.40 | 1182.11 | 1044.47 | 954.28 | 1094.51 |
| 1888 | 799 | 985.70 | 868.19 | 1094.73 | 1034.30 | 962.57 | 1110.02 |
| 1889 | 958 | 979.04 | 864.37 | 1089.21 | 1064.47 | 1007.20 | 1121.07 |
| 1890 | 1,140 | 1028.36 | 914.58 | 1135.79 | 1083.18 | 993.46 | 1151.88 |
| 1891 | 1,100 | 1049.80 | 936.77 | 1142.95 | 1103.85 | 1060.87 | 1186.58 |
| 1892 | 1,210 | 1096.28 | 986.40 | 1198.21 | 1110.39 | 1047.21 | 1176.68 |
| 1893 | 1,150 | 1111.58 | 999.97 | 1214.61 | 1114.66 | 1036.97 | 1197.72 |
| 1894 | 1,250 | 1150.42 | 1045.38 | 1246.45 | 1122.45 | 1062.25 | 1188.46 |
| 1895 | 1,260 | 1175.55 | 1074.75 | 1282.66 | 1106.22 | 1047.60 | 1196.37 |
| 1896 | 1,220 | 1189.65 | 1080.02 | 1290.90 | 1077.23 | 998.82 | 1142.24 |
| 1897 | 1,030 | 1144.40 | 1040.29 | 1251.47 | 1035.30 | 959.14 | 1102.39 |
| 1898 | 1,100 | 1132.61 | 1031.02 | 1247.00 | 1002.03 | 930.12 | 1059.18 |
| 1899 | 774 | 1035.63 | 951.65 | 1134.70 | 958.11 | 864.00 | 1012.01 |
| 1900 | 840 | 985.76 | 887.99 | 1088.57 | 919.50 | 857.11 | 980.13 |
| 1901 | 874 | 956.00 | 852.79 | 1063.37 | 891.70 | 803.04 | 962.23 |
| 1902 | 694 | 881.25 | 778.74 | 986.51 | 867.75 | 781.17 | 923.53 |
| 1903 | 940 | 898.30 | 788.04 | 1000.80 | 865.58 | 802.10 | 942.40 |
| 1904 | 833 | 880.48 | 773.82 | 986.56 | 851.36 | 771.00 | 935.92 |
| 1905 | 701 | 831.37 | 714.10 | 941.68 | 839.33 | 772.31 | 904.43 |
| 1906 | 916 | 858.37 | 746.87 | 971.39 | 846.56 | 779.80 | 913.78 |
| 1907 | 692 | 808.32 | 692.82 | 920.45 | 844.33 | 773.45 | 915.91 |
| 1908 | 1,020 | 869.32 | 762.15 | 978.60 | 860.79 | 798.61 | 947.77 |
| 1909 | 1,050 | 919.50 | 810.05 | 1008.54 | 877.67 | 787.56 | 982.69 |
| 1910 | 969 | 931.07 | 822.87 | 1037.93 | 863.64 | 780.36 | 933.26 |
First 40 of 100 rows.
- A bootstrap particle filter (Gordon, Salmond & Smith 1993): particles move by the model, are reweighted by each observation, and are resampled systematically when the effective sample size drops below half the particles.
- Filtered states use the observations up to each step; smoothed states (forward filtering, backward simulation) use the whole series.
- The first hidden state starts at the first observation with the series' variance; the Kalman filter uses the same start, so its exact log-likelihood is what the particle estimate approaches.
- PMMH ran 300 iterations (100 burn-in, step size adapted during burn-in) with 100 particles per step; priors: normal on log σ centered at the data-based value (SD 2). The final filter uses the posterior means.
Shortened for the Academy: 4 chart(s) dropped to stay under 100 KB; 4 chart(s) dropped to stay under 100 KB.
Do it in CodeSplash Run it on your own data, in Python or R, with the code to prove it.
Worked examples in the app
- Nile level pmmhml_nile · time: year · value: flow
- Nile level fixedml_nile · time: year · value: flow
- Nile trend fixed blankml_nile · value: flow
- Nile trend pmmhml_nile · time: year · value: flow
- Returns sv fixedf7_garch_sim · time: day · value: ret
- Returns sv pmmhf7_garch_sim · time: day · value: ret
- Degenerate constantml_nile · value: flow
- Degenerate n3ml_nile · value: flow
In the guides
Where it sits in the decision guides
- Time series (ARIMA, ETS) · DS & ML Decision Guide · Predict — forecast or classify outcomes
What you need
- Observationnumeric · 1 column
- The noisy series the hidden state produces: a level that drifts, or returns whose volatility changes.
- Time (optional)temporal / numeric · 0–1 column
- Orders the observations; omit to use the row order. Steps are taken as equally spaced.
Choices you make
model
- State-space modeldefault local_level
How the hidden state moves and how it produces the observations.
- Local level (random walk plus noise)(default) — A level that drifts as a random walk, observed with noise: flows, demand, sensor readings.
- Local linear trend — A level plus a slope that both drift, observed with noise: series that grow or shrink at a changing rate.
- Stochastic volatility — Returns whose log-variance follows an AR(1): calm and turbulent stretches in financial returns.
- Noise levelsdefault pmmh
Estimate the model's parameters from the data, or set them yourself.
- Estimate (PMMH)(default) — Particle marginal Metropolis–Hastings: MCMC over the parameters, each step running a particle filter for the likelihood.
- Set them — Use the values below; blanks take a value from the data (shown in the results).
- Observation noise SDdefault —
Standard deviation of the noise around the hidden level. Blank: SD of the differences / √3.
- Level noise SDdefault —
How far the hidden level moves per step (SD). Blank: SD of the differences / √3.
- Slope noise SDdefault —
How far the slope moves per step (SD). Blank: SD of the differences / 10.
- Mean log-variance (μ)default —
Long-run level of the log-variance h. Blank: log of the sample variance.
- Persistence (φ)default —
How strongly the log-variance carries over from one step to the next (between −1 and 1).
- Volatility of volatility (σ)default —
SD of the log-variance's step-to-step shocks.
statistics
- Particlesdefault 1000
Particles in the final filter that gives the states and the log-likelihood. More particles, less noise and more time.
- Particles per MCMC stepdefault 200
Particles in each filter run inside PMMH; aim for a log-likelihood SD near 1 (shown in the results).
- MCMC iterationsdefault 2000
PMMH steps in total, including the burn-in.
- Burn-indefault 500
Early steps left out of the estimates while the chain finds the posterior and the step size adapts.
- Smoothed statesdefault on
Also estimate each state from the whole series (forward filtering, backward simulation), not only from the past.
Advanced
- Resamplingdefault ess
When the filter resamples its particles (systematic resampling).
- When weights get uneven(default) — Resample when the effective sample size drops below half the particles (the usual rule).
- Every step — Resample at every step (the original bootstrap filter).
- Smoothing pathsdefault 100
State paths drawn backward through the stored particles; more paths, smoother bands.
options
- Random seeddefault 1
Fixes the random numbers so reruns give identical results, in Python and in R.
Checks and remedies
CodeSplash checks each testable assumption on every run and shows the result on the card; premises the data can’t test are marked. If a check fails, these are the ways forward.
Model formNot checked from data: state why it holds
The series follows the chosen state-space model with Gaussian noise and equally spaced steps; the filter can't check this from the data.
Enough particles
The log-likelihood estimate from five independent filter runs should vary by about 1 or less; more variation means more particles are needed.
MCMC mixing
PMMH only: the chain should accept 10–50% of its proposals and give at least 100 effective draws for every parameter.
What it reports
- n_obs
- Tracks a hidden state with many weighted guesses: each step moves them by the model and reweights them by the new observation.
- model
- Tracks a hidden state with many weighted guesses: each step moves them by the model and reweights them by the new observation.
- model_label
- Tracks a hidden state with many weighted guesses: each step moves them by the model and reweights them by the new observation.
- estimate
- MCMC over a state-space model's parameters that uses a particle filter's likelihood estimate at each step.
- particles
- Tracks a hidden state with many weighted guesses: each step moves them by the model and reweights them by the new observation.
- loglik
- The filter's estimate of the data's log-likelihood; it varies from run to run, and its SD over repeats shows if particles suffice.
- loglik_sd
- The filter's estimate of the data's log-likelihood; it varies from run to run, and its SD over repeats shows if particles suffice.
- kalman_loglik
- Exact filtering for linear-Gaussian state-space models: the hidden state's mean and variance, updated step by step.
- mean_ess
- How many equally weighted particles the current weights are worth; when it drops below half, the filter resamples.
- resamples
- How many equally weighted particles the current weights are worth; when it drops below half, the filter resamples.
- iterations
- MCMC over a state-space model's parameters that uses a particle filter's likelihood estimate at each step.
- burn_in
- MCMC over a state-space model's parameters that uses a particle filter's likelihood estimate at each step.
- acceptance
- MCMC over a state-space model's parameters that uses a particle filter's likelihood estimate at each step.
- ess_min
- MCMC over a state-space model's parameters that uses a particle filter's likelihood estimate at each step.
- last_state
- The hidden state's estimate at a step from the observations up to that step only, with a 90% band.
- last_state_lo
- The hidden state's estimate at a step from the observations up to that step only, with a 90% band.
- last_state_hi
- The hidden state's estimate at a step from the observations up to that step only, with a 90% band.
- kalman_last_state
- Exact filtering for linear-Gaussian state-space models: the hidden state's mean and variance, updated step by step.
- y_mean
- Returns whose log-variance follows its own AR(1): μ is its level, φ its persistence, σ the size of its shocks.
Per group, level or term: param[<name>], param_lo[<name>], param_hi[<name>], param_ess[<name>]
Python and R
Python and R agree to 6 decimals (relative tolerance 1e-6). Python uses pandas, numpy, scipy, codesplash; R uses stats, nanoparquet, codesplashr.
Default traps between the two languages
- Both engines run the same twins (codesplash.stats.particle ↔ codesplashr R/stats_particle.R): the same models and first-state distributions, normals as qnorm/ndtri of the same Wichmann–Hill uniforms in the same fixed layout, systematic resampling on sequential cumulative sums, the same backward-simulation smoother and the same PMMH proposals and accept steps. Python's and R's normal quantiles and sums differ in the last bits, so a resampling or accept decision could only change if a threshold fell within ~1e-15 of a cumulative weight — not seen in practice; measured agreement on the fixtures is about 1e-13 relative.
The exact script CodeSplash ran for example “Nile level pmmh” · Python 3.13.5 · scipy 1.18.1 · pandas 3.1.0
# Particle filter (state-space model with PMMH)
# Generated by CodeSplash Analytics 1.0.0 on 2026-11-09 · method ts.particle_filter 1.0.0 · spec 0a0d9d82db3e9bac
# Dataset: ml_nile (version 1)
# Runs on its own: outside the app, cs.publish() writes $CS_RESULT_PATH or prints the result JSON.
# %% Setup
import math
import numpy as np
import pandas as pd
import codesplash as cs
from codesplash.errors import check_not_constant
from codesplash.stats import particle as pf # bootstrap filter, smoother, PMMH (twin of codesplashr cs_pf_*)
from codesplash.stats import ts
from codesplash.stats.rng import Rng
# %% Data
df = pd.read_parquet("tests/parity/fixtures/ml_nile.parquet", columns=["flow", "year"])
n_input = len(df)
df = df.dropna(subset=["flow", "year"]) # listwise deletion over the analysis columns
n_dropped = n_input - len(df)
warnings = []
if n_dropped:
warnings.append(cs.cs_warning("CS_W_ROWS_DROPPED", dropped=n_dropped, total=n_input))
if n_input and not len(df):
cs.cs_error("CS_E_NO_ROWS")
cs.check_finite_columns(df, ["flow", "year"]) # infinite values stop the run (registry/errors.yaml)
# %% Series
VALUE = "flow"
TIME = "year"
TEMPORAL = False
MODEL = "local_level"
ESTIMATE = "pmmh"
N_FINAL = int(500)
N_PMMH = int(100)
ITERATIONS = int(300)
BURN_IN = int(100)
THRESHOLD = 1.0 if "ess" == "always" else 0.5 # resample when ESS < threshold · N
SMOOTH = True
SMOOTH_PATHS = int(40)
SEED = 42
FIXED = {"sigma_obs": None, "sigma_level": None, "sigma_slope": None,
"mu": None, "phi": None, "sigma": None}
d = df.sort_values(TIME, kind="mergesort").reset_index(drop=True) if TIME else df.reset_index(drop=True)
y_raw = d[VALUE].to_numpy(dtype=float)
cs.check_rows(len(y_raw), 10, "A particle filter")
check_not_constant(y_raw, VALUE)
if ESTIMATE == "pmmh" and BURN_IN >= ITERATIONS:
cs.cs_error("CS_E_INVALID_OPTION", option="Burn-in", allowed=f"fewer than the {ITERATIONS} MCMC iterations", value=BURN_IN)
y_mean = float(np.mean(y_raw))
y = y_raw - y_mean if MODEL == "stochastic_volatility" else y_raw # the volatility model describes centered returns
T = len(y)
labels = ts.time_labels(d[TIME].to_numpy(), TEMPORAL) if TIME else list(range(1, T + 1))
names = pf.param_names(MODEL)
LABELS = {"sigma_obs": "Observation noise SD", "sigma_level": "Level noise SD", "sigma_slope": "Slope noise SD",
"mu": "Mean log-variance μ", "phi": "Persistence φ", "sigma": "Volatility of volatility σ"}
MODEL_LABEL = {"local_level": "local level", "local_trend": "local linear trend", "stochastic_volatility": "stochastic volatility"}[MODEL]
start = pf.defaults(MODEL, y)
# %% Parameters: PMMH (Andrieu, Doucet & Holenstein 2010) or set by hand
values = {}
param_rows = []
chain_nat = None
mcmc = None
if ESTIMATE == "pmmh":
mcmc = pf.pmmh(MODEL, y, start, N_PMMH, ITERATIONS, BURN_IN, SEED, THRESHOLD)
kept = mcmc["chain"][BURN_IN:]
chain_nat = np.array([[pf.from_free(MODEL, row)[k] for k in names] for row in mcmc["chain"]])
kept_nat = chain_nat[BURN_IN:]
params = {}
ess_all = []
for j, k in enumerate(names):
col = kept_nat[:, j]
est = float(np.mean(col))
lo, hi = (float(v) for v in np.quantile(col, [0.05, 0.95], method="linear"))
e = pf.ess(col)
ess_all.append(e)
params[k] = est
values[f"param[{k}]"], values[f"param_lo[{k}]"], values[f"param_hi[{k}]"], values[f"param_ess[{k}]"] = est, lo, hi, e
param_rows.append({"param": LABELS[k], "estimate": est, "lo": lo, "hi": hi, "ess": e, "source": "PMMH posterior mean"})
values.update({"iterations": ITERATIONS, "burn_in": BURN_IN, "acceptance": mcmc["acceptance"], "ess_min": float(min(ess_all))})
else:
params = {}
for k in names:
v = FIXED[k]
params[k] = float(v) if v is not None else float(start[k])
values[f"param[{k}]"] = params[k]
param_rows.append({"param": LABELS[k], "estimate": params[k], "lo": None, "hi": None, "ess": None,
"source": "set" if v is not None else "from the data"})
values.update({"iterations": None, "burn_in": None, "acceptance": None, "ess_min": None})
try:
pf.check_params(MODEL, params)
except ValueError as e:
cs.cs_error("CS_E_INVALID_OPTION", option="Model parameters", allowed="valid values for the model", value=str(e))
# %% Final filter at the estimates, repeated runs for the likelihood's noise, smoother, Kalman
B = pf.block_size(MODEL, N_FINAL, T)
run = pf.filter_run(MODEL, y, params, N_FINAL, Rng(SEED + 1).uniform(B), THRESHOLD, store=SMOOTH)
if run["failed"]:
cs.cs_error("CS_E_UNDEFINED", what="The particle filter", reason="every particle got zero weight at some step; check the parameters")
lls = [run["loglik"]] + [pf.filter_run(MODEL, y, params, N_FINAL, Rng(SEED + 10 + r).uniform(B), THRESHOLD, summarize=False)["loglik"] for r in range(1, 5)]
ll_sd = float(np.std(lls, ddof=1))
sm = pf.smooth(MODEL, run, params, SMOOTH_PATHS, SEED + 2) if SMOOTH else None
kal = pf.kalman(MODEL, y, params)
if MODEL == "stochastic_volatility":
vol = lambda h: np.exp(h / 2.0) # noqa: E731 volatility = exp(h/2); quantiles map exactly
f_mid, f_lo, f_hi = vol(run["median"][:, 0]), vol(run["lo"][:, 0]), vol(run["hi"][:, 0])
s_mid = vol(sm["mean"][:, 0]) if sm else None
s_lo, s_hi = (vol(sm["lo"][:, 0]), vol(sm["hi"][:, 0])) if sm else (None, None)
else:
f_mid, f_lo, f_hi = run["mean"][:, 0], run["lo"][:, 0], run["hi"][:, 0]
s_mid = sm["mean"][:, 0] if sm else None
s_lo, s_hi = (sm["lo"][:, 0], sm["hi"][:, 0]) if sm else (None, None)
values.update({
"n_obs": T, "model": MODEL, "model_label": MODEL_LABEL, "estimate": ESTIMATE, "particles": N_FINAL,
"loglik": run["loglik"], "loglik_sd": ll_sd, "kalman_loglik": kal["loglik"] if kal else None,
"mean_ess": run["mean_ess"], "resamples": run["resamples"],
"last_state": float(f_mid[-1]), "last_state_lo": float(f_lo[-1]), "last_state_hi": float(f_hi[-1]),
"kalman_last_state": float(kal["mean"][-1, 0]) if kal else None,
"y_mean": y_mean if MODEL == "stochastic_volatility" else None,
})
# %% Assumptions
assumptions = [{"key": "model_form", "label": "Model form", "status": "info",
"detail": f"Assumed, not checked from the data: the series follows a {MODEL_LABEL} model with Gaussian noise and equally spaced steps."}]
if ll_sd <= 1.0:
assumptions.append({"key": "particle_count", "label": "Enough particles", "status": "pass",
"detail": f"Five filter runs with {N_FINAL} particles gave log-likelihoods with SD {ll_sd:.2f} (≤ 1)."})
else:
assumptions.append({"key": "particle_count", "label": "Enough particles", "status": "warn",
"detail": f"Five filter runs with {N_FINAL} particles gave log-likelihoods with SD {ll_sd:.2f}; use more particles for a steadier estimate."})
if ESTIMATE == "pmmh":
acc, emin = mcmc["acceptance"], values["ess_min"]
ok = 0.1 <= acc <= 0.5 and emin >= 100
assumptions.append({"key": "mixing", "label": "MCMC mixing", "status": "pass" if ok else "warn",
"detail": f"The chain accepted {acc:.0%} of proposals after burn-in; the smallest effective sample size is {emin:.0f}"
+ ("." if ok else ". Aim for 10–50% acceptance and at least 100 effective draws: run more iterations, or more particles per step when acceptance is low.")})
else:
assumptions.append({"key": "mixing", "label": "MCMC mixing", "status": "info", "detail": "The parameters were set, not estimated, so there is no MCMC chain."})
# %% Charts
charts = []
xkind = "temporal" if TEMPORAL else "numeric"
xname = TIME or "step"
if MODEL == "stochastic_volatility":
charts.append(cs.chart("states", "volatility-band", f"{VALUE} (centered) with the filtered volatility exp(h/2)", {
"time": cs.col(xname, labels, kind=xkind), "sigma": cs.col("volatility", f_mid), "value": cs.col(VALUE, y),
"mean": cs.col("mean", np.zeros(T))}))
else:
groups = [("Observed", y), ("Filtered level", f_mid)] + ([("Smoothed level", s_mid)] if sm else [])
charts.append(cs.chart("states", "series-line", f"{VALUE} with the hidden level", {
"x": cs.col(xname, [v for _ in groups for v in labels], kind=xkind),
"y": cs.col(VALUE, np.concatenate([g[1] for g in groups])),
"group": cs.col("series", [g[0] for g in groups for _ in range(T)], kind="categorical")}))
if mcmc is not None:
step = max(1, ITERATIONS // 500)
it_idx = list(range(0, ITERATIONS, step))
charts.append(cs.chart("trace", "series-line", "PMMH chains (every parameter, natural scale)", {
"x": cs.col("iteration", [float(i + 1) for _ in names for i in it_idx]),
"y": cs.col("value", np.concatenate([chain_nat[it_idx, j] for j in range(len(names))])),
"group": cs.col("parameter", [LABELS[k] for k in names for _ in it_idx], kind="categorical")}))
for j, k in enumerate(names):
col = chain_nat[BURN_IN:, j]
grid = pf.density_grid(col)
post = pf.kde(col, grid)
prior = pf.prior_density(mcmc["prior"][j], grid)
charts.append(cs.chart(f"posterior_{k}", "prior-posterior", f"{LABELS[k]}: prior and PMMH posterior", {
"x": cs.col(LABELS[k], np.concatenate([grid, grid])), "density": cs.col("density", np.concatenate([prior, post])),
"curve": cs.col("curve", ["prior"] * len(grid) + ["posterior"] * len(grid), kind="categorical")}))
# %% Tables
tables = [{"key": "parameters", "title": "Parameters",
"columns": [{"key": "param", "label": "Parameter", "type": "string"}, {"key": "estimate", "label": "Value", "type": "number"},
{"key": "lo", "label": "5%", "type": "number"}, {"key": "hi", "label": "95%", "type": "number"},
{"key": "ess", "label": "Effective draws", "type": "number"}, {"key": "source", "label": "Source", "type": "string"}],
"rows": param_rows},
{"key": "likelihood", "title": "Log-likelihood",
"columns": [{"key": "what", "label": "", "type": "string"}, {"key": "value", "label": "Value", "type": "number"}],
"rows": [{"what": f"Particle estimate ({N_FINAL} particles)", "value": run["loglik"]},
{"what": "SD over five filter runs", "value": ll_sd}]
+ ([{"what": "Exact (Kalman filter)", "value": kal["loglik"]}] if kal else [])}]
CAP = 2000
st_label = "volatility" if MODEL == "stochastic_volatility" else "level"
state_rows = []
for t in range(min(T, CAP)):
r = {"time": str(labels[t]), "observed": float(y_raw[t]), "filtered": float(f_mid[t]), "f_lo": float(f_lo[t]), "f_hi": float(f_hi[t])}
if sm:
r.update({"smoothed": float(s_mid[t]), "s_lo": float(s_lo[t]), "s_hi": float(s_hi[t])})
if MODEL == "local_trend":
r["slope"] = float(run["mean"][t, 1])
state_rows.append(r)
state_cols = [{"key": "time", "label": TIME or "Step", "type": "string"}, {"key": "observed", "label": VALUE, "type": "number"},
{"key": "filtered", "label": f"Filtered {st_label}" + (" (median)" if MODEL == "stochastic_volatility" else ""), "type": "number"},
{"key": "f_lo", "label": "5%", "type": "number"}, {"key": "f_hi", "label": "95%", "type": "number"}]
if sm:
state_cols += [{"key": "smoothed", "label": f"Smoothed {st_label}", "type": "number"},
{"key": "s_lo", "label": "5% (smoothed)", "type": "number"}, {"key": "s_hi", "label": "95% (smoothed)", "type": "number"}]
if MODEL == "local_trend":
state_cols.append({"key": "slope", "label": "Filtered slope", "type": "number"})
tables.append({"key": "states", "title": "Hidden state at each step" + (f" (first {CAP} of {T})" if T > CAP else ""), "columns": state_cols, "rows": state_rows})
# %% Result
est_txt = "estimated by PMMH" if ESTIMATE == "pmmh" else "set"
summary = (f"A {MODEL_LABEL} particle filter of {VALUE} ({T} steps, {N_FINAL} particles; parameters {est_txt}) has log-likelihood "
f"{run['loglik']:.2f} (SD {ll_sd:.2f} over five runs)" + (f"; the exact Kalman value is {kal['loglik']:.2f}" if kal else "")
+ f". The last filtered {st_label} is {f_mid[-1]:.4g} (90% band {f_lo[-1]:.4g} to {f_hi[-1]:.4g}).")
notes = ["A bootstrap particle filter (Gordon, Salmond & Smith 1993): particles move by the model, are reweighted by each observation, and are "
"resampled systematically " + ("at every step." if THRESHOLD >= 1.0 else "when the effective sample size drops below half the particles."),
"Filtered states use the observations up to each step; smoothed states (forward filtering, backward simulation) use the whole series."]
if MODEL == "stochastic_volatility":
notes.append(f"Returns are centered (mean {y_mean:.4g} removed); the volatility is exp(h/2) and its band maps h's quantiles.")
else:
notes.append("The first hidden state starts at the first observation with the series' variance" + (" (slope at 0 with the differences' variance)" if MODEL == "local_trend" else "")
+ "; the Kalman filter uses the same start, so its exact log-likelihood is what the particle estimate approaches.")
if ESTIMATE == "pmmh":
notes.append(f"PMMH ran {ITERATIONS} iterations ({BURN_IN} burn-in, step size adapted during burn-in) with {N_PMMH} particles per step; priors: normal on log σ "
"centered at the data-based value (SD 2)" + (", normal on μ (SD 3), uniform φ on (−1, 1)" if MODEL == "stochastic_volatility" else "")
+ ". The final filter uses the posterior means.")
statistics = [{"key": "loglik", "label": "Log-likelihood (particle)", "value": run["loglik"]}, {"key": "loglik_sd", "label": "Log-likelihood SD", "value": ll_sd}]
if kal:
statistics.append({"key": "kalman_loglik", "label": "Log-likelihood (Kalman)", "value": kal["loglik"]})
if mcmc is not None:
statistics.append({"key": "acceptance", "label": "Acceptance rate", "value": mcmc["acceptance"]})
cs.publish({
"method": "ts.particle_filter",
"methodVersion": "1.0.0",
"title": "Particle filter",
"engine": cs.engine_info("numpy", "pandas", "scipy"),
"n": T,
"summary": summary,
"statistics": statistics,
"tables": tables,
"assumptions": assumptions,
"warnings": warnings,
"notes": notes,
"charts": charts,
"values": values,
})
The exact script CodeSplash ran for example “Nile level pmmh” · R version 4.5.1 (2025-06-13)
# Particle filter (state-space model with PMMH)
# Generated by CodeSplash Analytics 1.0.0 on 2026-11-09 · method ts.particle_filter 1.0.0 · spec 0a0d9d82db3e9bac
# Dataset: ml_nile (version 1)
# Runs on its own: outside the app, cs_publish() writes $CS_RESULT_PATH or prints the result JSON.
# %% Setup
library(codesplashr)
# %% Data
df <- as.data.frame(nanoparquet::read_parquet("tests/parity/fixtures/ml_nile.parquet", col_select = c("flow", "year")))
n_input <- nrow(df)
df <- df[stats::complete.cases(df[c("flow", "year")]), , drop = FALSE] # listwise deletion
df[] <- lapply(df, function(x) if (is.factor(x)) droplevels(x) else x)
n_dropped <- n_input - nrow(df)
warnings <- list()
if (n_dropped > 0) {
warnings <- c(warnings, cs_warning("CS_W_ROWS_DROPPED", dropped = n_dropped, total = n_input))
}
if (n_input > 0 && nrow(df) == 0) cs_error("CS_E_NO_ROWS")
cs_check_finite_columns(df, c("flow", "year")) # infinite values stop the run (registry/errors.yaml)
# %% Series
VALUE <- "flow"
TIME <- "year"
TEMPORAL <- FALSE
MODEL <- "local_level"
ESTIMATE <- "pmmh"
N_FINAL <- as.integer(500)
N_PMMH <- as.integer(100)
ITERATIONS <- as.integer(300)
BURN_IN <- as.integer(100)
THRESHOLD <- if ("ess" == "always") 1 else 0.5 # resample when ESS < threshold * N
SMOOTH <- TRUE
SMOOTH_PATHS <- as.integer(40)
SEED <- 42
FIXED <- list(sigma_obs = NULL, sigma_level = NULL, sigma_slope = NULL,
mu = NULL, phi = NULL, sigma = NULL)
d <- df
if (!is.null(TIME)) d <- d[order(d[[TIME]], method = "radix"), , drop = FALSE]
rownames(d) <- NULL
y_raw <- as.numeric(d[[VALUE]])
cs_check_rows(length(y_raw), 10, "A particle filter")
cs_check_not_constant(y_raw, VALUE)
if (ESTIMATE == "pmmh" && BURN_IN >= ITERATIONS)
cs_error("CS_E_INVALID_OPTION", option = "Burn-in", allowed = sprintf("fewer than the %d MCMC iterations", ITERATIONS), value = BURN_IN)
y_mean <- mean(y_raw)
y <- if (MODEL == "stochastic_volatility") y_raw - y_mean else y_raw # the volatility model describes centered returns
TT <- length(y)
labels <- if (!is.null(TIME)) cs_ts_time_labels(d[[TIME]], TEMPORAL) else seq_len(TT)
pnames <- cs_pf_param_names(MODEL)
LABELS <- c(sigma_obs = "Observation noise SD", sigma_level = "Level noise SD", sigma_slope = "Slope noise SD",
mu = "Mean log-variance μ", phi = "Persistence φ", sigma = "Volatility of volatility σ")
MODEL_LABEL <- c(local_level = "local level", local_trend = "local linear trend", stochastic_volatility = "stochastic volatility")[[MODEL]]
start <- cs_pf_defaults(MODEL, y)
# %% Parameters: PMMH (Andrieu, Doucet & Holenstein 2010) or set by hand
values <- list()
param_rows <- list()
chain_nat <- NULL
mcmc <- NULL
params <- list()
if (ESTIMATE == "pmmh") {
mcmc <- cs_pf_pmmh(MODEL, y, start, N_PMMH, ITERATIONS, BURN_IN, SEED, THRESHOLD)
chain_nat <- t(apply(mcmc$chain, 1, function(row) unlist(cs_pf_from_free(MODEL, row)[pnames])))
kept_nat <- chain_nat[(BURN_IN + 1):ITERATIONS, , drop = FALSE]
ess_all <- numeric(0)
for (j in seq_along(pnames)) {
k <- pnames[j]
colv <- kept_nat[, j]
est <- mean(colv)
qq <- stats::quantile(colv, c(0.05, 0.95), type = 7, names = FALSE)
e <- cs_pf_ess(colv)
ess_all <- c(ess_all, e)
params[[k]] <- est
values[sprintf("param[%s]", k)] <- list(est)
values[sprintf("param_lo[%s]", k)] <- list(qq[1])
values[sprintf("param_hi[%s]", k)] <- list(qq[2])
values[sprintf("param_ess[%s]", k)] <- list(e)
param_rows[[length(param_rows) + 1]] <- list(param = LABELS[[k]], estimate = est, lo = qq[1], hi = qq[2], ess = e, source = "PMMH posterior mean")
}
values$iterations <- ITERATIONS
values$burn_in <- BURN_IN
values$acceptance <- mcmc$acceptance
values$ess_min <- min(ess_all)
} else {
for (k in pnames) {
v <- FIXED[[k]]
params[[k]] <- if (!is.null(v)) as.numeric(v) else start[[k]]
values[sprintf("param[%s]", k)] <- list(params[[k]])
param_rows[[length(param_rows) + 1]] <- list(param = LABELS[[k]], estimate = params[[k]], lo = NULL, hi = NULL, ess = NULL,
source = if (!is.null(v)) "set" else "from the data")
}
values["iterations"] <- list(NULL)
values["burn_in"] <- list(NULL)
values["acceptance"] <- list(NULL)
values["ess_min"] <- list(NULL)
}
chk <- tryCatch({
cs_pf_check_params(MODEL, params)
NULL
}, error = function(e) conditionMessage(e))
if (!is.null(chk)) cs_error("CS_E_INVALID_OPTION", option = "Model parameters", allowed = "valid values for the model", value = chk)
# %% Final filter at the estimates, repeated runs for the likelihood's noise, smoother, Kalman
B <- cs_pf_block_size(MODEL, N_FINAL, TT)
run <- cs_pf_filter(MODEL, y, params, N_FINAL, cs_runif(cs_rng(SEED + 1), B), THRESHOLD, store = SMOOTH)
if (run$failed) cs_error("CS_E_UNDEFINED", what = "The particle filter", reason = "every particle got zero weight at some step; check the parameters")
lls <- c(run$loglik, vapply(1:4, function(r) cs_pf_filter(MODEL, y, params, N_FINAL, cs_runif(cs_rng(SEED + 10 + r), B), THRESHOLD, summarize = FALSE)$loglik, numeric(1)))
ll_sd <- stats::sd(lls)
sm <- if (SMOOTH) cs_pf_smooth(MODEL, run, params, SMOOTH_PATHS, SEED + 2) else NULL
kal <- cs_pf_kalman(MODEL, y, params)
if (MODEL == "stochastic_volatility") {
vol <- function(h) exp(h / 2) # volatility = exp(h/2); quantiles map exactly
f_mid <- vol(run$median[, 1]); f_lo <- vol(run$lo[, 1]); f_hi <- vol(run$hi[, 1])
s_mid <- if (!is.null(sm)) vol(sm$mean[, 1]) else NULL
s_lo <- if (!is.null(sm)) vol(sm$lo[, 1]) else NULL
s_hi <- if (!is.null(sm)) vol(sm$hi[, 1]) else NULL
} else {
f_mid <- run$mean[, 1]; f_lo <- run$lo[, 1]; f_hi <- run$hi[, 1]
s_mid <- if (!is.null(sm)) sm$mean[, 1] else NULL
s_lo <- if (!is.null(sm)) sm$lo[, 1] else NULL
s_hi <- if (!is.null(sm)) sm$hi[, 1] else NULL
}
values$n_obs <- TT
values$model <- MODEL
values$model_label <- MODEL_LABEL
values$estimate <- ESTIMATE
values$particles <- N_FINAL
values$loglik <- run$loglik
values$loglik_sd <- ll_sd
values["kalman_loglik"] <- list(if (!is.null(kal)) kal$loglik else NULL)
values$mean_ess <- run$mean_ess
values$resamples <- run$resamples
values$last_state <- f_mid[TT]
values$last_state_lo <- f_lo[TT]
values$last_state_hi <- f_hi[TT]
values["kalman_last_state"] <- list(if (!is.null(kal)) kal$mean[TT, 1] else NULL)
values["y_mean"] <- list(if (MODEL == "stochastic_volatility") y_mean else NULL)
# %% Assumptions
assumptions <- list(list(key = "model_form", label = "Model form", status = "info",
detail = sprintf("Assumed, not checked from the data: the series follows a %s model with Gaussian noise and equally spaced steps.", MODEL_LABEL)))
if (ll_sd <= 1) {
assumptions[[2]] <- list(key = "particle_count", label = "Enough particles", status = "pass",
detail = sprintf("Five filter runs with %d particles gave log-likelihoods with SD %.2f (≤ 1).", N_FINAL, ll_sd))
} else {
assumptions[[2]] <- list(key = "particle_count", label = "Enough particles", status = "warn",
detail = sprintf("Five filter runs with %d particles gave log-likelihoods with SD %.2f; use more particles for a steadier estimate.", N_FINAL, ll_sd))
}
if (ESTIMATE == "pmmh") {
acc <- mcmc$acceptance
emin <- values$ess_min
ok <- acc >= 0.1 && acc <= 0.5 && emin >= 100
assumptions[[3]] <- list(key = "mixing", label = "MCMC mixing", status = if (ok) "pass" else "warn",
detail = paste0(sprintf("The chain accepted %s of proposals after burn-in; the smallest effective sample size is %s", sprintf("%.0f%%", 100 * acc), sprintf("%.0f", emin)),
if (ok) "." else ". Aim for 10–50% acceptance and at least 100 effective draws: run more iterations, or more particles per step when acceptance is low."))
} else {
assumptions[[3]] <- list(key = "mixing", label = "MCMC mixing", status = "info", detail = "The parameters were set, not estimated, so there is no MCMC chain.")
}
# %% Charts
charts <- list()
xkind <- if (TEMPORAL) "temporal" else "numeric"
xname <- if (is.null(TIME)) "step" else TIME
if (MODEL == "stochastic_volatility") {
charts[[1]] <- cs_chart("states", "volatility-band", sprintf("%s (centered) with the filtered volatility exp(h/2)", VALUE), list(
time = cs_col(xname, labels, kind = xkind), sigma = cs_col("volatility", f_mid), value = cs_col(VALUE, y),
mean = cs_col("mean", rep(0, TT))))
} else {
gnames <- c("Observed", "Filtered level")
gvals <- list(y, f_mid)
if (!is.null(sm)) {
gnames <- c(gnames, "Smoothed level")
gvals[[3]] <- s_mid
}
charts[[1]] <- cs_chart("states", "series-line", sprintf("%s with the hidden level", VALUE), list(
x = cs_col(xname, rep(labels, times = length(gnames)), kind = xkind),
y = cs_col(VALUE, unlist(gvals)),
group = cs_col("series", rep(gnames, each = TT), kind = "categorical")))
}
if (!is.null(mcmc)) {
stp <- max(1L, ITERATIONS %/% 500L)
it_idx <- seq(1L, ITERATIONS, by = stp)
charts[[length(charts) + 1]] <- cs_chart("trace", "series-line", "PMMH chains (every parameter, natural scale)", list(
x = cs_col("iteration", rep(as.numeric(it_idx), times = length(pnames))),
y = cs_col("value", as.vector(chain_nat[it_idx, , drop = FALSE])),
group = cs_col("parameter", rep(unname(LABELS[pnames]), each = length(it_idx)), kind = "categorical")))
for (j in seq_along(pnames)) {
k <- pnames[j]
colv <- chain_nat[(BURN_IN + 1):ITERATIONS, j]
grid <- cs_pf_density_grid(colv)
post <- cs_pf_kde(colv, grid)
prior <- cs_pf_prior_density(mcmc$prior[[j]], grid)
charts[[length(charts) + 1]] <- cs_chart(paste0("posterior_", k), "prior-posterior", sprintf("%s: prior and PMMH posterior", LABELS[[k]]), list(
x = cs_col(LABELS[[k]], c(grid, grid)), density = cs_col("density", c(prior, post)),
curve = cs_col("curve", c(rep("prior", length(grid)), rep("posterior", length(grid))), kind = "categorical")))
}
}
# %% Tables
lik_rows <- list(list(what = sprintf("Particle estimate (%d particles)", N_FINAL), value = run$loglik),
list(what = "SD over five filter runs", value = ll_sd))
if (!is.null(kal)) lik_rows[[3]] <- list(what = "Exact (Kalman filter)", value = kal$loglik)
tables <- list(
list(key = "parameters", title = "Parameters",
columns = list(list(key = "param", label = "Parameter", type = "string"), list(key = "estimate", label = "Value", type = "number"),
list(key = "lo", label = "5%", type = "number"), list(key = "hi", label = "95%", type = "number"),
list(key = "ess", label = "Effective draws", type = "number"), list(key = "source", label = "Source", type = "string")),
rows = param_rows),
list(key = "likelihood", title = "Log-likelihood",
columns = list(list(key = "what", label = "", type = "string"), list(key = "value", label = "Value", type = "number")),
rows = lik_rows))
CAP <- 2000
st_label <- if (MODEL == "stochastic_volatility") "volatility" else "level"
state_rows <- lapply(seq_len(min(TT, CAP)), function(t) {
r <- list(time = as.character(labels[[t]]), observed = y_raw[t], filtered = f_mid[t], f_lo = f_lo[t], f_hi = f_hi[t])
if (!is.null(sm)) {
r$smoothed <- s_mid[t]
r$s_lo <- s_lo[t]
r$s_hi <- s_hi[t]
}
if (MODEL == "local_trend") r$slope <- run$mean[t, 2]
r
})
state_cols <- list(list(key = "time", label = if (is.null(TIME)) "Step" else TIME, type = "string"), list(key = "observed", label = VALUE, type = "number"),
list(key = "filtered", label = paste0("Filtered ", st_label, if (MODEL == "stochastic_volatility") " (median)" else ""), type = "number"),
list(key = "f_lo", label = "5%", type = "number"), list(key = "f_hi", label = "95%", type = "number"))
if (!is.null(sm)) {
state_cols <- c(state_cols, list(list(key = "smoothed", label = paste0("Smoothed ", st_label), type = "number"),
list(key = "s_lo", label = "5% (smoothed)", type = "number"), list(key = "s_hi", label = "95% (smoothed)", type = "number")))
}
if (MODEL == "local_trend") state_cols <- c(state_cols, list(list(key = "slope", label = "Filtered slope", type = "number")))
tables[[3]] <- list(key = "states", title = paste0("Hidden state at each step", if (TT > CAP) sprintf(" (first %d of %d)", CAP, TT) else ""),
columns = state_cols, rows = state_rows)
# %% Result
g4 <- function(v) sprintf("%.4g", v)
est_txt <- if (ESTIMATE == "pmmh") "estimated by PMMH" else "set"
summary <- paste0(sprintf("A %s particle filter of %s (%d steps, %d particles; parameters %s) has log-likelihood %.2f (SD %.2f over five runs)",
MODEL_LABEL, VALUE, TT, N_FINAL, est_txt, run$loglik, ll_sd),
if (!is.null(kal)) sprintf("; the exact Kalman value is %.2f", kal$loglik) else "",
sprintf(". The last filtered %s is %s (90%% band %s to %s).", st_label, g4(f_mid[TT]), g4(f_lo[TT]), g4(f_hi[TT])))
notes <- c(paste0("A bootstrap particle filter (Gordon, Salmond & Smith 1993): particles move by the model, are reweighted by each observation, and are ",
"resampled systematically ", if (THRESHOLD >= 1) "at every step." else "when the effective sample size drops below half the particles."),
"Filtered states use the observations up to each step; smoothed states (forward filtering, backward simulation) use the whole series.")
if (MODEL == "stochastic_volatility") {
notes <- c(notes, sprintf("Returns are centered (mean %s removed); the volatility is exp(h/2) and its band maps h's quantiles.", g4(y_mean)))
} else {
notes <- c(notes, paste0("The first hidden state starts at the first observation with the series' variance",
if (MODEL == "local_trend") " (slope at 0 with the differences' variance)" else "",
"; the Kalman filter uses the same start, so its exact log-likelihood is what the particle estimate approaches."))
}
if (ESTIMATE == "pmmh") {
notes <- c(notes, paste0(sprintf("PMMH ran %d iterations (%d burn-in, step size adapted during burn-in) with %d particles per step; priors: normal on log σ ", ITERATIONS, BURN_IN, N_PMMH),
"centered at the data-based value (SD 2)", if (MODEL == "stochastic_volatility") ", normal on μ (SD 3), uniform φ on (−1, 1)" else "",
". The final filter uses the posterior means."))
}
statistics <- list(list(key = "loglik", label = "Log-likelihood (particle)", value = run$loglik), list(key = "loglik_sd", label = "Log-likelihood SD", value = ll_sd))
if (!is.null(kal)) statistics[[length(statistics) + 1]] <- list(key = "kalman_loglik", label = "Log-likelihood (Kalman)", value = kal$loglik)
if (!is.null(mcmc)) statistics[[length(statistics) + 1]] <- list(key = "acceptance", label = "Acceptance rate", value = mcmc$acceptance)
cs_publish(list(
method = "ts.particle_filter",
methodVersion = "1.0.0",
title = "Particle filter",
engine = cs_engine_info("stats", "nanoparquet"),
n = TT,
summary = summary,
statistics = statistics,
tables = tables,
assumptions = assumptions,
warnings = warnings,
notes = notes,
charts = charts,
values = values
))
Sources
- Gordon, N. J., Salmond, D. J., & Smith, A. F. M. (1993). Novel approach to nonlinear/non-Gaussian Bayesian state estimation. IEE Proceedings F, 140(2), 107–113.
- Andrieu, C., Doucet, A., & Holenstein, R. (2010). Particle Markov chain Monte Carlo methods. Journal of the Royal Statistical Society B, 72(3), 269–342.
- Godsill, S. J., Doucet, A., & West, M. (2004). Monte Carlo smoothing for nonlinear time series. Journal of the American Statistical Association, 99(465), 156–168.
- Doucet, A., Pitt, M. K., Deligiannidis, G., & Kohn, R. (2015). Efficient implementation of Markov chain Monte Carlo when using an unbiased likelihood estimator. Biometrika, 102(2), 295–313.
- Durbin, J., & Koopman, S. J. (2012). Time Series Analysis by State Space Methods (2nd ed.). Oxford University Press.
- Chopin, N., & Papaspiliopoulos, O. (2020). An Introduction to Sequential Monte Carlo. Springer.
From the CodeSplash method registry · ts.particle_filter v1.0.0.