Tracking a hidden state: particle filters
A noisy series often hides a smoother level or a changing volatility. A particle filter tracks it with thousands of weighted guesses, and PMMH estimates how noisy each part is.
What runs in CodeSplash
- Particle filter (state-space model with PMMH) Verified in Python and R
You will be able to
- Describe a bootstrap particle filter as move, reweight and resample
- Tell filtered from smoothed states
- Use the Kalman filter as the exact answer a particle filter should approach
- Judge whether there are enough particles from the log-likelihood's SD over repeated runs
- Read a PMMH run's acceptance rate and effective draws
Read first
A level you never see
ReadThe yearly flow of the Nile jumps around, but most of that is noise around a level that moves slowly. A local level modelLocal level modelA hidden level that drifts as a random walk, seen through noise; the trend version adds a slope that also drifts. says exactly that: a hidden level drifts as a random walk, and each year's flow is that level plus noise.
Two standard deviations describe it: how much the level moves per step, and how much noise surrounds it. The question at each year is where the hidden level was.
Move, reweight, resample
ReadA particle filterParticle filterTracks a hidden state with many weighted guesses: each step moves them by the model and reweights them by the new observation. answers with many guesses at once:
- Move: each particle steps forward by the model (the level takes a random step).
- Reweight: each particle gets a weight for how well it explains the new observation.
- Resample: when a few particles carry most of the weight, the filter copies the good ones and drops the poor ones.
The weighted particles at each step approximate the hidden state's distribution: their mean and 90% band are the filtered stateFiltered stateThe hidden state's estimate at a step from the observations up to that step only, with a 90% band..
A local level particle filter of flow (100 steps, 800 particles; parameters set) has log-likelihood -638.78 (SD 0.22 over five runs); the exact Kalman value is -638.66. The last filtered level is 794.2 (90% band 682.5 to 897.2).
- Log-likelihood (particle)
- −638.78
- Log-likelihood SD
- 0.2218
- Log-likelihood (Kalman)
- −638.66
Plots
View data
| series | year | flow |
|---|---|---|
| Observed | 1,871 | 1,120 |
| Observed | 1,872 | 1,160 |
| Observed | 1,873 | 963 |
| Observed | 1,874 | 1,210 |
| Observed | 1,875 | 1,160 |
| Observed | 1,876 | 1,160 |
| Observed | 1,877 | 813 |
| Observed | 1,878 | 1,230 |
| Observed | 1,879 | 1,370 |
| Observed | 1,880 | 1,140 |
| Observed | 1,881 | 995 |
| Observed | 1,882 | 935 |
| Observed | 1,883 | 1,110 |
| Observed | 1,884 | 994 |
| Observed | 1,885 | 1,020 |
| Observed | 1,886 | 960 |
| Observed | 1,887 | 1,180 |
| Observed | 1,888 | 799 |
| Observed | 1,889 | 958 |
| Observed | 1,890 | 1,140 |
| Observed | 1,891 | 1,100 |
| Observed | 1,892 | 1,210 |
| Observed | 1,893 | 1,150 |
| Observed | 1,894 | 1,250 |
| Observed | 1,895 | 1,260 |
| Observed | 1,896 | 1,220 |
| Observed | 1,897 | 1,030 |
| Observed | 1,898 | 1,100 |
| Observed | 1,899 | 774 |
| Observed | 1,900 | 840 |
| Observed | 1,901 | 874 |
| Observed | 1,902 | 694 |
| Observed | 1,903 | 940 |
| Observed | 1,904 | 833 |
| Observed | 1,905 | 701 |
| Observed | 1,906 | 916 |
| Observed | 1,907 | 692 |
| Observed | 1,908 | 1,020 |
| Observed | 1,909 | 1,050 |
| Observed | 1,910 | 969 |
| Observed | 1,911 | 831 |
| Observed | 1,912 | 726 |
| Observed | 1,913 | 456 |
| Observed | 1,914 | 824 |
| Observed | 1,915 | 702 |
| Observed | 1,916 | 1,120 |
| Observed | 1,917 | 1,100 |
| Observed | 1,918 | 832 |
| Observed | 1,919 | 764 |
| Observed | 1,920 | 821 |
| Observed | 1,921 | 768 |
| Observed | 1,922 | 845 |
| Observed | 1,923 | 864 |
| Observed | 1,924 | 862 |
| Observed | 1,925 | 698 |
| Observed | 1,926 | 845 |
| Observed | 1,927 | 744 |
| Observed | 1,928 | 796 |
| Observed | 1,929 | 1,040 |
| Observed | 1,930 | 759 |
First 60 of 300 rows.
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 800 particles gave log-likelihoods with SD 0.22 (≤ 1).
- MCMC mixing — The parameters were set, not estimated, so there is no MCMC chain.
Parameters
| Parameter | Value | 5% | 95% | Effective draws | Source |
|---|---|---|---|---|---|
| Observation noise SD | 123 | — | — | — | set |
| Level noise SD | 38 | — | — | — | set |
Log-likelihood
| Value | |
|---|---|
| Particle estimate (800 particles) | −638.78 |
| SD over five filter runs | 0.2218 |
| Exact (Kalman filter) | −638.66 |
Hidden state at each step
| year | flow | Filtered level | 5% | 95% | Smoothed level | 5% (smoothed) | 95% (smoothed) |
|---|---|---|---|---|---|---|---|
| 1871 | 1,120 | 1124.72 | 966.78 | 1286.22 | 1111.77 | 1013.35 | 1220.32 |
| 1872 | 1,160 | 1138.90 | 1005.35 | 1272.49 | 1118.30 | 1019.78 | 1221.07 |
| 1873 | 963 | 1078.42 | 969.96 | 1192.31 | 1113.15 | 1032.17 | 1207.71 |
| 1874 | 1,210 | 1117.16 | 1001.09 | 1221.86 | 1122.46 | 1045.84 | 1211.80 |
| 1875 | 1,160 | 1129.76 | 1018.02 | 1236.48 | 1123.05 | 1034.74 | 1210.95 |
| 1876 | 1,160 | 1140.10 | 1030.04 | 1248.14 | 1111.56 | 1024.74 | 1190.32 |
| 1877 | 813 | 1055.18 | 970.36 | 1158.20 | 1099.60 | 1015.59 | 1189.15 |
| 1878 | 1,230 | 1100.10 | 999.54 | 1206.40 | 1108.19 | 1031.15 | 1202.77 |
| 1879 | 1,370 | 1171.20 | 1067.43 | 1278.13 | 1119.75 | 1028.81 | 1219.10 |
| 1880 | 1,140 | 1163.19 | 1056.74 | 1268.41 | 1098.47 | 1028.21 | 1189.15 |
| 1881 | 995 | 1116.60 | 1003.11 | 1221.08 | 1077.45 | 999.17 | 1163.69 |
| 1882 | 935 | 1068.61 | 974.68 | 1171.89 | 1060.38 | 986.41 | 1140.51 |
| 1883 | 1,110 | 1079.32 | 975.10 | 1182.95 | 1061.56 | 968.48 | 1142.51 |
| 1884 | 994 | 1055.04 | 939.76 | 1156.74 | 1053.03 | 958.54 | 1132.80 |
| 1885 | 1,020 | 1047.49 | 943.73 | 1152.87 | 1048.23 | 973.22 | 1139.25 |
| 1886 | 960 | 1025.07 | 914.65 | 1131.21 | 1040.59 | 982.27 | 1125.28 |
| 1887 | 1,180 | 1069.06 | 964.04 | 1184.66 | 1049.97 | 981.23 | 1124.34 |
| 1888 | 799 | 999.17 | 899.40 | 1103.00 | 1033.04 | 966.53 | 1091.04 |
| 1889 | 958 | 990.00 | 889.01 | 1093.02 | 1048.25 | 971.66 | 1135.40 |
| 1890 | 1,140 | 1022.67 | 927.07 | 1120.96 | 1070.56 | 984.97 | 1130.77 |
| 1891 | 1,100 | 1043.13 | 941.74 | 1142.17 | 1089.01 | 1016.96 | 1153.97 |
| 1892 | 1,210 | 1090.00 | 983.56 | 1188.22 | 1104.06 | 1024.51 | 1176.62 |
| 1893 | 1,150 | 1107.53 | 1000.21 | 1208.66 | 1110.78 | 1052.65 | 1181.41 |
| 1894 | 1,250 | 1141.94 | 1043.12 | 1240.10 | 1111.23 | 1045.32 | 1192.66 |
| 1895 | 1,260 | 1171.37 | 1072.40 | 1268.24 | 1101.99 | 1020.52 | 1169.80 |
| 1896 | 1,220 | 1184.31 | 1076.68 | 1286.21 | 1077.62 | 1016.84 | 1155.66 |
| 1897 | 1,030 | 1143.91 | 1035.03 | 1253.36 | 1038.98 | 985.36 | 1117.86 |
| 1898 | 1,100 | 1132.47 | 1034.80 | 1238.32 | 995.42 | 929.86 | 1069.80 |
| 1899 | 774 | 1046.82 | 932.08 | 1142.12 | 955.49 | 908.57 | 1019.99 |
| 1900 | 840 | 994.77 | 889.16 | 1094.56 | 918.69 | 857.98 | 984.45 |
| 1901 | 874 | 963.24 | 861.87 | 1067.84 | 895.83 | 813.53 | 961.98 |
| 1902 | 694 | 896.32 | 781.72 | 999.72 | 874.21 | 773.58 | 953.12 |
| 1903 | 940 | 907.42 | 799.06 | 1012.17 | 865.29 | 782.03 | 937.96 |
| 1904 | 833 | 885.40 | 777.11 | 993.23 | 855.96 | 786.67 | 936.52 |
| 1905 | 701 | 833.53 | 722.79 | 942.36 | 850.30 | 774.69 | 926.13 |
| 1906 | 916 | 855.81 | 753.03 | 959.32 | 859.97 | 788.90 | 923.11 |
| 1907 | 692 | 810.20 | 713.53 | 910.55 | 857.52 | 765.78 | 932.64 |
| 1908 | 1,020 | 865.48 | 757.08 | 971.43 | 877.24 | 797.25 | 971.43 |
| 1909 | 1,050 | 916.60 | 810.35 | 1015.70 | 879.71 | 795.87 | 966.38 |
| 1910 | 969 | 932.43 | 830.19 | 1033.62 | 861.96 | 767.61 | 929.82 |
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 at every step.
- 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.
The exact R script · R 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 d3fb0d755c492ddb
# 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 <- "fixed"
N_FINAL <- as.integer(800)
N_PMMH <- as.integer(200)
ITERATIONS <- as.integer(2000)
BURN_IN <- as.integer(500)
THRESHOLD <- if ("always" == "always") 1 else 0.5 # resample when ESS < threshold * N
SMOOTH <- TRUE
SMOOTH_PATHS <- as.integer(100)
SEED <- 42
FIXED <- list(sigma_obs = 123, sigma_level = 38, 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
))
A local level particle filter of flow (100 steps, 800 particles; parameters set) has log-likelihood -638.78 (SD 0.22 over five runs); the exact Kalman value is -638.66. The last filtered level is 794.2 (90% band 682.5 to 897.2).
- Log-likelihood (particle)
- −638.78
- Log-likelihood SD
- 0.2218
- Log-likelihood (Kalman)
- −638.66
To keep this page light, the plots are shown once, under the R tab.
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 800 particles gave log-likelihoods with SD 0.22 (≤ 1).
- MCMC mixing — The parameters were set, not estimated, so there is no MCMC chain.
Parameters
| Parameter | Value | 5% | 95% | Effective draws | Source |
|---|---|---|---|---|---|
| Observation noise SD | 123 | — | — | — | set |
| Level noise SD | 38 | — | — | — | set |
Log-likelihood
| Value | |
|---|---|
| Particle estimate (800 particles) | −638.78 |
| SD over five filter runs | 0.2218 |
| Exact (Kalman filter) | −638.66 |
Hidden state at each step
| year | flow | Filtered level | 5% | 95% | Smoothed level | 5% (smoothed) | 95% (smoothed) |
|---|---|---|---|---|---|---|---|
| 1871 | 1,120 | 1124.72 | 966.78 | 1286.22 | 1111.77 | 1013.35 | 1220.32 |
| 1872 | 1,160 | 1138.90 | 1005.35 | 1272.49 | 1118.30 | 1019.78 | 1221.07 |
| 1873 | 963 | 1078.42 | 969.96 | 1192.31 | 1113.15 | 1032.17 | 1207.71 |
| 1874 | 1,210 | 1117.16 | 1001.09 | 1221.86 | 1122.46 | 1045.84 | 1211.80 |
| 1875 | 1,160 | 1129.76 | 1018.02 | 1236.48 | 1123.05 | 1034.74 | 1210.95 |
| 1876 | 1,160 | 1140.10 | 1030.04 | 1248.14 | 1111.56 | 1024.74 | 1190.32 |
| 1877 | 813 | 1055.18 | 970.36 | 1158.20 | 1099.60 | 1015.59 | 1189.15 |
| 1878 | 1,230 | 1100.10 | 999.54 | 1206.40 | 1108.19 | 1031.15 | 1202.77 |
| 1879 | 1,370 | 1171.20 | 1067.43 | 1278.13 | 1119.75 | 1028.81 | 1219.10 |
| 1880 | 1,140 | 1163.19 | 1056.74 | 1268.41 | 1098.47 | 1028.21 | 1189.15 |
| 1881 | 995 | 1116.60 | 1003.11 | 1221.08 | 1077.45 | 999.17 | 1163.69 |
| 1882 | 935 | 1068.61 | 974.68 | 1171.89 | 1060.38 | 986.41 | 1140.51 |
| 1883 | 1,110 | 1079.32 | 975.10 | 1182.95 | 1061.56 | 968.48 | 1142.51 |
| 1884 | 994 | 1055.04 | 939.76 | 1156.74 | 1053.03 | 958.54 | 1132.80 |
| 1885 | 1,020 | 1047.49 | 943.73 | 1152.87 | 1048.23 | 973.22 | 1139.25 |
| 1886 | 960 | 1025.07 | 914.65 | 1131.21 | 1040.59 | 982.27 | 1125.28 |
| 1887 | 1,180 | 1069.06 | 964.04 | 1184.66 | 1049.97 | 981.23 | 1124.34 |
| 1888 | 799 | 999.17 | 899.40 | 1103.00 | 1033.04 | 966.53 | 1091.04 |
| 1889 | 958 | 990.00 | 889.01 | 1093.02 | 1048.25 | 971.66 | 1135.40 |
| 1890 | 1,140 | 1022.67 | 927.07 | 1120.96 | 1070.56 | 984.97 | 1130.77 |
| 1891 | 1,100 | 1043.13 | 941.74 | 1142.17 | 1089.01 | 1016.96 | 1153.97 |
| 1892 | 1,210 | 1090.00 | 983.56 | 1188.22 | 1104.06 | 1024.51 | 1176.62 |
| 1893 | 1,150 | 1107.53 | 1000.21 | 1208.66 | 1110.78 | 1052.65 | 1181.41 |
| 1894 | 1,250 | 1141.94 | 1043.12 | 1240.10 | 1111.23 | 1045.32 | 1192.66 |
| 1895 | 1,260 | 1171.37 | 1072.40 | 1268.24 | 1101.99 | 1020.52 | 1169.80 |
| 1896 | 1,220 | 1184.31 | 1076.68 | 1286.21 | 1077.62 | 1016.84 | 1155.66 |
| 1897 | 1,030 | 1143.91 | 1035.03 | 1253.36 | 1038.98 | 985.36 | 1117.86 |
| 1898 | 1,100 | 1132.47 | 1034.80 | 1238.32 | 995.42 | 929.86 | 1069.80 |
| 1899 | 774 | 1046.82 | 932.08 | 1142.12 | 955.49 | 908.57 | 1019.99 |
| 1900 | 840 | 994.77 | 889.16 | 1094.56 | 918.69 | 857.98 | 984.45 |
| 1901 | 874 | 963.24 | 861.87 | 1067.84 | 895.83 | 813.53 | 961.98 |
| 1902 | 694 | 896.32 | 781.72 | 999.72 | 874.21 | 773.58 | 953.12 |
| 1903 | 940 | 907.42 | 799.06 | 1012.17 | 865.29 | 782.03 | 937.96 |
| 1904 | 833 | 885.40 | 777.11 | 993.23 | 855.96 | 786.67 | 936.52 |
| 1905 | 701 | 833.53 | 722.79 | 942.36 | 850.30 | 774.69 | 926.13 |
| 1906 | 916 | 855.81 | 753.03 | 959.32 | 859.97 | 788.90 | 923.11 |
| 1907 | 692 | 810.20 | 713.53 | 910.55 | 857.52 | 765.78 | 932.64 |
| 1908 | 1,020 | 865.48 | 757.08 | 971.43 | 877.24 | 797.25 | 971.43 |
| 1909 | 1,050 | 916.60 | 810.35 | 1015.70 | 879.71 | 795.87 | 966.38 |
| 1910 | 969 | 932.43 | 830.19 | 1033.62 | 861.96 | 767.61 | 929.82 |
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 at every step.
- 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.
The exact Python script · Python 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 d3fb0d755c492ddb
# 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 = "fixed"
N_FINAL = int(800)
N_PMMH = int(200)
ITERATIONS = int(2000)
BURN_IN = int(500)
THRESHOLD = 1.0 if "always" == "always" else 0.5 # resample when ESS < threshold · N
SMOOTH = True
SMOOTH_PATHS = int(100)
SEED = 42
FIXED = {"sigma_obs": 123, "sigma_level": 38, "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,
})
With the noise SDs set to 123 (observation) and 38 (level), the filtered level ends near 794.
The exact answer to compare with
ReadFor this linear model with Gaussian noise the Kalman filterKalman filterExact filtering for linear-Gaussian state-space models: the hidden state's mean and variance, updated step by step. gives the exact answer. CodeSplash reports it beside the particle estimate. The particle log-likelihood is −638.78; the exact value is −638.66.
The particle filter earns its keep when the model isn't linear-Gaussian, such as the volatility model below. There's no exact answer to compare with there, so the linear case is where you see how close it gets.
Predict: more particles
PredictPredict first
Five filter runs with 1,000 particles give log-likelihoods with an SD of 0.4. What happens to that SD with 4,000 particles?
Reveal
It shrinks, roughly by half: the noise in the estimate falls like one over the square root of the number of particles.
How many particles?
ReadEach run's log-likelihood estimateParticle log-likelihood estimateThe filter's estimate of the data's log-likelihood; it varies from run to run, and its SD over repeats shows if particles suffice. differs a little. CodeSplash runs the final filter five times and reports the SD. An SD near 1 or below is steady enough. Above that, comparisons between models and the PMMH chain below both get noisy.
Estimating the noise: PMMH
ReadUsually you don't know the two SDs. PMMHParticle marginal Metropolis–Hastings (PMMH)MCMC over a state-space model's parameters that uses a particle filter's likelihood estimate at each step. is MCMC over them. At each step it proposes new values, runs a particle filter for their likelihood, and accepts or rejects them.
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.
The exact R script · R 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
))
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.
The exact Python script · Python 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,
})
Shortened for the Academy: 4 chart(s) dropped to stay under 100 KB; 4 chart(s) dropped to stay under 100 KB.
The posterior means are 124 for the observation noise and 43 for the level's steps. Durbin and Koopman's maximum-likelihood values for these data are about 123 and 38.
Two numbers tell you whether to trust the chain. The acceptance rate was 38.0%, and the smallest number of effective draws was 8. This example is deliberately short. A real run needs at least 100 effective draws per parameter, so give it more iterations.
Filtered or smoothed?
ReadThe filtered level at a year uses only the flows up to that year: it's what you could have known then. The smoothed stateSmoothed stateThe hidden state's estimate at a step from the whole series, drawn by tracing paths backward through the stored particles. uses the whole series. It traces paths backward through the stored particles, so it's calmer and closer to the truth. Use filtered values for "what did we know at the time" and smoothed values for "what actually happened".
Volatility you can't see
ReadReturns are calm for a while, then turbulent. A stochastic volatility modelStochastic volatility modelReturns whose log-variance follows its own AR(1): μ is its level, φ its persistence, σ the size of its shocks. gives the log-variance its own AR(1). μ is its level, φ how long calm or turbulent spells last, and σ how jumpy it is. That makes the model nonlinear, so there's no Kalman filter for it.
A stochastic volatility particle filter of ret (800 steps, 500 particles; parameters set) has log-likelihood -1205.63 (SD 0.28 over five runs). The last filtered volatility is 0.9204 (90% band 0.664 to 1.313).
- Log-likelihood (particle)
- −1205.63
- Log-likelihood SD
- 0.2759
Assumptions
- Model form — Assumed, not checked from the data: the series follows a stochastic volatility model with Gaussian noise and equally spaced steps.
- Enough particles — Five filter runs with 500 particles gave log-likelihoods with SD 0.28 (≤ 1).
- MCMC mixing — The parameters were set, not estimated, so there is no MCMC chain.
Parameters
| Parameter | Value | 5% | 95% | Effective draws | Source |
|---|---|---|---|---|---|
| Mean log-variance μ | 0.3298 | — | — | — | from the data |
| Persistence φ | 0.9700 | — | — | — | set |
| Volatility of volatility σ | 0.1500 | — | — | — | set |
Log-likelihood
| Value | |
|---|---|
| Particle estimate (500 particles) | −1205.63 |
| SD over five filter runs | 0.2759 |
Hidden state at each step
| day | ret | Filtered volatility (median) | 5% | 95% | Smoothed volatility | 5% (smoothed) | 95% (smoothed) |
|---|---|---|---|---|---|---|---|
| 2022-01-03 | −0.4548 | 1.101 | 0.6284 | 1.785 | 0.9775 | 0.7433 | 1.290 |
| 2022-01-04 | 0.6226 | 1.044 | 0.6092 | 1.720 | 0.9785 | 0.7322 | 1.284 |
| 2022-01-05 | −0.7410 | 0.9997 | 0.6063 | 1.621 | 0.9865 | 0.7673 | 1.222 |
| 2022-01-06 | 0.9818 | 1.029 | 0.6447 | 1.615 | 1.002 | 0.7910 | 1.261 |
| 2022-01-07 | −0.2694 | 0.9515 | 0.6175 | 1.496 | 1.002 | 0.7801 | 1.249 |
| 2022-01-08 | −1.273 | 0.9994 | 0.6687 | 1.530 | 1.006 | 0.7444 | 1.271 |
| 2022-01-09 | 0.6580 | 0.9771 | 0.6908 | 1.461 | 1.016 | 0.7832 | 1.366 |
| 2022-01-10 | 0.1031 | 0.9253 | 0.6283 | 1.401 | 0.9991 | 0.7597 | 1.266 |
| 2022-01-11 | 1.386 | 0.9910 | 0.7167 | 1.463 | 1.014 | 0.8326 | 1.235 |
| 2022-01-12 | −0.8266 | 0.9879 | 0.7140 | 1.446 | 1.023 | 0.8154 | 1.249 |
| 2022-01-13 | −0.1034 | 0.9739 | 0.6569 | 1.367 | 1.013 | 0.8129 | 1.329 |
| 2022-01-14 | 1.166 | 1.008 | 0.7084 | 1.397 | 1.019 | 0.7816 | 1.372 |
| 2022-01-15 | 0.5996 | 0.9602 | 0.6802 | 1.371 | 1.030 | 0.7953 | 1.376 |
| 2022-01-16 | −1.323 | 1.001 | 0.7057 | 1.428 | 1.054 | 0.8204 | 1.406 |
| 2022-01-17 | −1.177 | 1.031 | 0.7156 | 1.418 | 1.033 | 0.8249 | 1.446 |
| 2022-01-18 | −1.245 | 1.047 | 0.7471 | 1.424 | 1.037 | 0.7962 | 1.379 |
| 2022-01-19 | −0.1610 | 1.012 | 0.7236 | 1.438 | 1.067 | 0.8085 | 1.428 |
| 2022-01-20 | 0.7103 | 0.9949 | 0.7186 | 1.392 | 1.080 | 0.8030 | 1.390 |
| 2022-01-21 | 0.7302 | 0.9815 | 0.7012 | 1.383 | 1.052 | 0.7818 | 1.302 |
| 2022-01-22 | 0.6104 | 0.9636 | 0.6933 | 1.359 | 1.071 | 0.7972 | 1.407 |
| 2022-01-23 | −0.5422 | 0.9462 | 0.6433 | 1.345 | 1.084 | 0.7946 | 1.452 |
| 2022-01-24 | −0.2755 | 0.8890 | 0.6222 | 1.314 | 1.098 | 0.8460 | 1.434 |
| 2022-01-25 | −1.408 | 0.9658 | 0.6814 | 1.364 | 1.124 | 0.8572 | 1.507 |
| 2022-01-26 | 0.1955 | 0.9320 | 0.6696 | 1.316 | 1.155 | 0.8953 | 1.523 |
| 2022-01-27 | 0.9044 | 0.9335 | 0.6927 | 1.325 | 1.201 | 0.9595 | 1.570 |
| 2022-01-28 | −0.0604 | 0.8967 | 0.6551 | 1.283 | 1.224 | 0.9466 | 1.698 |
| 2022-01-29 | 2.201 | 1.080 | 0.8018 | 1.482 | 1.283 | 0.9955 | 1.694 |
| 2022-01-30 | 1.387 | 1.117 | 0.8393 | 1.481 | 1.307 | 1.012 | 1.712 |
| 2022-01-31 | 0.1233 | 1.076 | 0.7864 | 1.495 | 1.333 | 1.076 | 1.733 |
| 2022-02-01 | −0.3073 | 1.039 | 0.7577 | 1.441 | 1.316 | 0.9633 | 1.706 |
| 2022-02-02 | −0.0691 | 1.008 | 0.7176 | 1.388 | 1.332 | 1.083 | 1.719 |
| 2022-02-03 | −2.284 | 1.145 | 0.8582 | 1.603 | 1.387 | 1.109 | 1.704 |
| 2022-02-04 | 3.187 | 1.398 | 1.060 | 1.841 | 1.448 | 1.197 | 1.882 |
| 2022-02-05 | 0.1717 | 1.344 | 1.022 | 1.796 | 1.428 | 1.137 | 1.850 |
| 2022-02-06 | −2.059 | 1.401 | 1.055 | 1.870 | 1.445 | 1.176 | 1.933 |
| 2022-02-07 | 0.1059 | 1.343 | 0.9982 | 1.861 | 1.436 | 1.090 | 1.929 |
| 2022-02-08 | −1.678 | 1.371 | 1.030 | 1.897 | 1.440 | 1.049 | 1.930 |
| 2022-02-09 | −0.4750 | 1.321 | 0.9706 | 1.830 | 1.396 | 1.076 | 1.881 |
| 2022-02-10 | 1.591 | 1.344 | 0.9799 | 1.828 | 1.391 | 1.019 | 1.821 |
| 2022-02-11 | −1.514 | 1.361 | 0.9867 | 1.805 | 1.369 | 1.082 | 1.788 |
First 40 of 50 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.
- Returns are centered (mean -0.03609 removed); the volatility is exp(h/2) and its band maps h's quantiles.
The exact R script · R 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 dee48044d35a1fde
# Dataset: f7_garch_sim (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/f7_garch_sim.parquet", col_select = c("ret", "day")))
n_input <- nrow(df)
df <- df[stats::complete.cases(df[c("ret", "day")]), , 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("ret", "day")) # infinite values stop the run (registry/errors.yaml)
# %% Series
VALUE <- "ret"
TIME <- "day"
TEMPORAL <- TRUE
MODEL <- "stochastic_volatility"
ESTIMATE <- "fixed"
N_FINAL <- as.integer(500)
N_PMMH <- as.integer(200)
ITERATIONS <- as.integer(2000)
BURN_IN <- as.integer(500)
THRESHOLD <- if ("ess" == "always") 1 else 0.5 # resample when ESS < threshold * N
SMOOTH <- TRUE
SMOOTH_PATHS <- as.integer(30)
SEED <- 42
FIXED <- list(sigma_obs = NULL, sigma_level = NULL, sigma_slope = NULL,
mu = NULL, phi = 0.97, sigma = 0.15)
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
))
A stochastic volatility particle filter of ret (800 steps, 500 particles; parameters set) has log-likelihood -1205.63 (SD 0.28 over five runs). The last filtered volatility is 0.9204 (90% band 0.664 to 1.313).
- Log-likelihood (particle)
- −1205.63
- Log-likelihood SD
- 0.2759
Assumptions
- Model form — Assumed, not checked from the data: the series follows a stochastic volatility model with Gaussian noise and equally spaced steps.
- Enough particles — Five filter runs with 500 particles gave log-likelihoods with SD 0.28 (≤ 1).
- MCMC mixing — The parameters were set, not estimated, so there is no MCMC chain.
Parameters
| Parameter | Value | 5% | 95% | Effective draws | Source |
|---|---|---|---|---|---|
| Mean log-variance μ | 0.3298 | — | — | — | from the data |
| Persistence φ | 0.9700 | — | — | — | set |
| Volatility of volatility σ | 0.1500 | — | — | — | set |
Log-likelihood
| Value | |
|---|---|
| Particle estimate (500 particles) | −1205.63 |
| SD over five filter runs | 0.2759 |
Hidden state at each step
| day | ret | Filtered volatility (median) | 5% | 95% | Smoothed volatility | 5% (smoothed) | 95% (smoothed) |
|---|---|---|---|---|---|---|---|
| 2022-01-03 | −0.4548 | 1.101 | 0.6284 | 1.785 | 0.9775 | 0.7433 | 1.290 |
| 2022-01-04 | 0.6226 | 1.044 | 0.6092 | 1.720 | 0.9785 | 0.7322 | 1.284 |
| 2022-01-05 | −0.7410 | 0.9997 | 0.6063 | 1.621 | 0.9865 | 0.7673 | 1.222 |
| 2022-01-06 | 0.9818 | 1.029 | 0.6447 | 1.615 | 1.002 | 0.7910 | 1.261 |
| 2022-01-07 | −0.2694 | 0.9515 | 0.6175 | 1.496 | 1.002 | 0.7801 | 1.249 |
| 2022-01-08 | −1.273 | 0.9994 | 0.6687 | 1.530 | 1.006 | 0.7444 | 1.271 |
| 2022-01-09 | 0.6580 | 0.9771 | 0.6908 | 1.461 | 1.016 | 0.7832 | 1.366 |
| 2022-01-10 | 0.1031 | 0.9253 | 0.6283 | 1.401 | 0.9991 | 0.7597 | 1.266 |
| 2022-01-11 | 1.386 | 0.9910 | 0.7167 | 1.463 | 1.014 | 0.8326 | 1.235 |
| 2022-01-12 | −0.8266 | 0.9879 | 0.7140 | 1.446 | 1.023 | 0.8154 | 1.249 |
| 2022-01-13 | −0.1034 | 0.9739 | 0.6569 | 1.367 | 1.013 | 0.8129 | 1.329 |
| 2022-01-14 | 1.166 | 1.008 | 0.7084 | 1.397 | 1.019 | 0.7816 | 1.372 |
| 2022-01-15 | 0.5996 | 0.9602 | 0.6802 | 1.371 | 1.030 | 0.7953 | 1.376 |
| 2022-01-16 | −1.323 | 1.001 | 0.7057 | 1.428 | 1.054 | 0.8204 | 1.406 |
| 2022-01-17 | −1.177 | 1.031 | 0.7156 | 1.418 | 1.033 | 0.8249 | 1.446 |
| 2022-01-18 | −1.245 | 1.047 | 0.7471 | 1.424 | 1.037 | 0.7962 | 1.379 |
| 2022-01-19 | −0.1610 | 1.012 | 0.7236 | 1.438 | 1.067 | 0.8085 | 1.428 |
| 2022-01-20 | 0.7103 | 0.9949 | 0.7186 | 1.392 | 1.080 | 0.8030 | 1.390 |
| 2022-01-21 | 0.7302 | 0.9815 | 0.7012 | 1.383 | 1.052 | 0.7818 | 1.302 |
| 2022-01-22 | 0.6104 | 0.9636 | 0.6933 | 1.359 | 1.071 | 0.7972 | 1.407 |
| 2022-01-23 | −0.5422 | 0.9462 | 0.6433 | 1.345 | 1.084 | 0.7946 | 1.452 |
| 2022-01-24 | −0.2755 | 0.8890 | 0.6222 | 1.314 | 1.098 | 0.8460 | 1.434 |
| 2022-01-25 | −1.408 | 0.9658 | 0.6814 | 1.364 | 1.124 | 0.8572 | 1.507 |
| 2022-01-26 | 0.1955 | 0.9320 | 0.6696 | 1.316 | 1.155 | 0.8953 | 1.523 |
| 2022-01-27 | 0.9044 | 0.9335 | 0.6927 | 1.325 | 1.201 | 0.9595 | 1.570 |
| 2022-01-28 | −0.0604 | 0.8967 | 0.6551 | 1.283 | 1.224 | 0.9466 | 1.698 |
| 2022-01-29 | 2.201 | 1.080 | 0.8018 | 1.482 | 1.283 | 0.9955 | 1.694 |
| 2022-01-30 | 1.387 | 1.117 | 0.8393 | 1.481 | 1.307 | 1.012 | 1.712 |
| 2022-01-31 | 0.1233 | 1.076 | 0.7864 | 1.495 | 1.333 | 1.076 | 1.733 |
| 2022-02-01 | −0.3073 | 1.039 | 0.7577 | 1.441 | 1.316 | 0.9633 | 1.706 |
| 2022-02-02 | −0.0691 | 1.008 | 0.7176 | 1.388 | 1.332 | 1.083 | 1.719 |
| 2022-02-03 | −2.284 | 1.145 | 0.8582 | 1.603 | 1.387 | 1.109 | 1.704 |
| 2022-02-04 | 3.187 | 1.398 | 1.060 | 1.841 | 1.448 | 1.197 | 1.882 |
| 2022-02-05 | 0.1717 | 1.344 | 1.022 | 1.796 | 1.428 | 1.137 | 1.850 |
| 2022-02-06 | −2.059 | 1.401 | 1.055 | 1.870 | 1.445 | 1.176 | 1.933 |
| 2022-02-07 | 0.1059 | 1.343 | 0.9982 | 1.861 | 1.436 | 1.090 | 1.929 |
| 2022-02-08 | −1.678 | 1.371 | 1.030 | 1.897 | 1.440 | 1.049 | 1.930 |
| 2022-02-09 | −0.4750 | 1.321 | 0.9706 | 1.830 | 1.396 | 1.076 | 1.881 |
| 2022-02-10 | 1.591 | 1.344 | 0.9799 | 1.828 | 1.391 | 1.019 | 1.821 |
| 2022-02-11 | −1.514 | 1.361 | 0.9867 | 1.805 | 1.369 | 1.082 | 1.788 |
First 40 of 50 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.
- Returns are centered (mean -0.03609 removed); the volatility is exp(h/2) and its band maps h's quantiles.
The exact Python script · Python 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 dee48044d35a1fde
# Dataset: f7_garch_sim (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/f7_garch_sim.parquet", columns=["ret", "day"])
n_input = len(df)
df = df.dropna(subset=["ret", "day"]) # 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, ["ret", "day"]) # infinite values stop the run (registry/errors.yaml)
# %% Series
VALUE = "ret"
TIME = "day"
TEMPORAL = True
MODEL = "stochastic_volatility"
ESTIMATE = "fixed"
N_FINAL = int(500)
N_PMMH = int(200)
ITERATIONS = int(2000)
BURN_IN = int(500)
THRESHOLD = 1.0 if "ess" == "always" else 0.5 # resample when ESS < threshold · N
SMOOTH = True
SMOOTH_PATHS = int(30)
SEED = 42
FIXED = {"sigma_obs": None, "sigma_level": None, "sigma_slope": None,
"mu": None, "phi": 0.97, "sigma": 0.15}
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,
})
Shortened for the Academy: 1 chart(s) dropped to stay under 100 KB; a table cut from 800 to 50 rows; 1 chart(s) dropped to stay under 100 KB; a table cut from 800 to 50 rows.
The band in the chart is the filtered volatility: wide in turbulent stretches, narrow in calm ones.
Check: particle filters
CheckpointCheck yourself
What does a bootstrap particle filter do at each step?
Show the answer
Answer: a
Move by the model, reweight by the observation, resample: the weighted particles approximate the hidden state at that step.
Check yourself
You want to know what the hidden level was in 1899, using everything recorded since. Which estimate do you use?
Show the answer
Answer: a
Smoothed states use the whole series; filtered states use only the observations up to that step.
Check yourself
Five filter runs give log-likelihoods with an SD of 3.2. What should you do before running PMMH?
Show the answer
Answer: a
A noisy likelihood estimate makes PMMH stick and accept rarely; aim for an SD near 1 or below.
Concepts in this lesson