Skip to content

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.

Advanced ~16 min9 steps

What runs in CodeSplash

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

01

A level you never see

Read

The 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.

02

Move, reweight, resample

Read

A 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:

  1. Move: each particle steps forward by the model (the level takes a random step).
  2. Reweight: each particle gets a weight for how well it explains the new observation.
  3. 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..

Particle filterRecorded · Python and R agreeRecorded 2026-11-21 · 21 values compared
R

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

flow with the hidden levelHow does the series move over time, and where is an estimated break?
View data
seriesyearflow
Observed1,8711,120
Observed1,8721,160
Observed1,873963
Observed1,8741,210
Observed1,8751,160
Observed1,8761,160
Observed1,877813
Observed1,8781,230
Observed1,8791,370
Observed1,8801,140
Observed1,881995
Observed1,882935
Observed1,8831,110
Observed1,884994
Observed1,8851,020
Observed1,886960
Observed1,8871,180
Observed1,888799
Observed1,889958
Observed1,8901,140
Observed1,8911,100
Observed1,8921,210
Observed1,8931,150
Observed1,8941,250
Observed1,8951,260
Observed1,8961,220
Observed1,8971,030
Observed1,8981,100
Observed1,899774
Observed1,900840
Observed1,901874
Observed1,902694
Observed1,903940
Observed1,904833
Observed1,905701
Observed1,906916
Observed1,907692
Observed1,9081,020
Observed1,9091,050
Observed1,910969
Observed1,911831
Observed1,912726
Observed1,913456
Observed1,914824
Observed1,915702
Observed1,9161,120
Observed1,9171,100
Observed1,918832
Observed1,919764
Observed1,920821
Observed1,921768
Observed1,922845
Observed1,923864
Observed1,924862
Observed1,925698
Observed1,926845
Observed1,927744
Observed1,928796
Observed1,9291,040
Observed1,930759

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

ParameterValue5%95%Effective drawsSource
Observation noise SD123———set
Level noise SD38———set

Log-likelihood

Value
Particle estimate (800 particles)−638.78
SD over five filter runs0.2218
Exact (Kalman filter)−638.66

Hidden state at each step

yearflowFiltered level5%95%Smoothed level5% (smoothed)95% (smoothed)
18711,1201124.72966.781286.221111.771013.351220.32
18721,1601138.901005.351272.491118.301019.781221.07
18739631078.42969.961192.311113.151032.171207.71
18741,2101117.161001.091221.861122.461045.841211.80
18751,1601129.761018.021236.481123.051034.741210.95
18761,1601140.101030.041248.141111.561024.741190.32
18778131055.18970.361158.201099.601015.591189.15
18781,2301100.10999.541206.401108.191031.151202.77
18791,3701171.201067.431278.131119.751028.811219.10
18801,1401163.191056.741268.411098.471028.211189.15
18819951116.601003.111221.081077.45999.171163.69
18829351068.61974.681171.891060.38986.411140.51
18831,1101079.32975.101182.951061.56968.481142.51
18849941055.04939.761156.741053.03958.541132.80
18851,0201047.49943.731152.871048.23973.221139.25
18869601025.07914.651131.211040.59982.271125.28
18871,1801069.06964.041184.661049.97981.231124.34
1888799999.17899.401103.001033.04966.531091.04
1889958990.00889.011093.021048.25971.661135.40
18901,1401022.67927.071120.961070.56984.971130.77
18911,1001043.13941.741142.171089.011016.961153.97
18921,2101090.00983.561188.221104.061024.511176.62
18931,1501107.531000.211208.661110.781052.651181.41
18941,2501141.941043.121240.101111.231045.321192.66
18951,2601171.371072.401268.241101.991020.521169.80
18961,2201184.311076.681286.211077.621016.841155.66
18971,0301143.911035.031253.361038.98985.361117.86
18981,1001132.471034.801238.32995.42929.861069.80
18997741046.82932.081142.12955.49908.571019.99
1900840994.77889.161094.56918.69857.98984.45
1901874963.24861.871067.84895.83813.53961.98
1902694896.32781.72999.72874.21773.58953.12
1903940907.42799.061012.17865.29782.03937.96
1904833885.40777.11993.23855.96786.67936.52
1905701833.53722.79942.36850.30774.69926.13
1906916855.81753.03959.32859.97788.90923.11
1907692810.20713.53910.55857.52765.78932.64
19081,020865.48757.08971.43877.24797.25971.43
19091,050916.60810.351015.70879.71795.87966.38
1910969932.43830.191033.62861.96767.61929.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
))
Python

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

ParameterValue5%95%Effective drawsSource
Observation noise SD123———set
Level noise SD38———set

Log-likelihood

Value
Particle estimate (800 particles)−638.78
SD over five filter runs0.2218
Exact (Kalman filter)−638.66

Hidden state at each step

yearflowFiltered level5%95%Smoothed level5% (smoothed)95% (smoothed)
18711,1201124.72966.781286.221111.771013.351220.32
18721,1601138.901005.351272.491118.301019.781221.07
18739631078.42969.961192.311113.151032.171207.71
18741,2101117.161001.091221.861122.461045.841211.80
18751,1601129.761018.021236.481123.051034.741210.95
18761,1601140.101030.041248.141111.561024.741190.32
18778131055.18970.361158.201099.601015.591189.15
18781,2301100.10999.541206.401108.191031.151202.77
18791,3701171.201067.431278.131119.751028.811219.10
18801,1401163.191056.741268.411098.471028.211189.15
18819951116.601003.111221.081077.45999.171163.69
18829351068.61974.681171.891060.38986.411140.51
18831,1101079.32975.101182.951061.56968.481142.51
18849941055.04939.761156.741053.03958.541132.80
18851,0201047.49943.731152.871048.23973.221139.25
18869601025.07914.651131.211040.59982.271125.28
18871,1801069.06964.041184.661049.97981.231124.34
1888799999.17899.401103.001033.04966.531091.04
1889958990.00889.011093.021048.25971.661135.40
18901,1401022.67927.071120.961070.56984.971130.77
18911,1001043.13941.741142.171089.011016.961153.97
18921,2101090.00983.561188.221104.061024.511176.62
18931,1501107.531000.211208.661110.781052.651181.41
18941,2501141.941043.121240.101111.231045.321192.66
18951,2601171.371072.401268.241101.991020.521169.80
18961,2201184.311076.681286.211077.621016.841155.66
18971,0301143.911035.031253.361038.98985.361117.86
18981,1001132.471034.801238.32995.42929.861069.80
18997741046.82932.081142.12955.49908.571019.99
1900840994.77889.161094.56918.69857.98984.45
1901874963.24861.871067.84895.83813.53961.98
1902694896.32781.72999.72874.21773.58953.12
1903940907.42799.061012.17865.29782.03937.96
1904833885.40777.11993.23855.96786.67936.52
1905701833.53722.79942.36850.30774.69926.13
1906916855.81753.03959.32859.97788.90923.11
1907692810.20713.53910.55857.52765.78932.64
19081,020865.48757.08971.43877.24797.25971.43
19091,050916.60810.351015.70879.71795.87966.38
1910969932.43830.191033.62861.96767.61929.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.

03

The exact answer to compare with

Read

For 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.

04

Predict: more particles

Predict

Predict 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?

It shrinksIt stays about the sameIt grows
Reveal

It shrinks, roughly by half: the noise in the estimate falls like one over the square root of the number of particles.

05

How many particles?

Read

Each 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.

06

Estimating the noise: PMMH

Read

Usually 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.

Particle filterRecorded · Python and R agreeRecorded 2026-11-21 · 27 values compared
R

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

ParameterValue5%95%Effective drawsSource
Observation noise SD123.59106.47138.1030.381PMMH posterior mean
Level noise SD43.41929.08364.8918.164PMMH posterior mean

Log-likelihood

Value
Particle estimate (500 particles)−639.51
SD over five filter runs0.4484
Exact (Kalman filter)−638.76

Hidden state at each step

yearflowFiltered level5%95%Smoothed level5% (smoothed)95% (smoothed)
18711,1201125.52967.551283.001112.061015.671210.42
18721,1601140.121007.441271.961104.741017.411166.61
18739631070.30960.341195.891093.121008.391163.70
18741,2101114.50998.911232.271099.02987.891176.70
18751,1601127.271011.921242.841105.621008.481180.09
18761,1601133.531026.551251.181106.191047.941154.98
18778131041.53928.321144.001090.461025.721136.53
18781,2301098.48992.721203.461119.961047.461200.71
18791,3701175.291067.881280.581127.981041.691184.94
18801,1401166.261050.341279.881107.291019.431184.17
18819951121.371011.891219.271091.291009.091176.63
18829351071.85954.571181.121070.05985.551161.14
18831,1101082.01970.381188.031063.11967.661159.21
18849941057.67952.271168.611045.09980.741131.36
18851,0201046.58937.131154.691036.06951.301114.20
18869601020.12914.561132.411025.14966.241086.58
18871,1801065.12957.401182.111044.47954.281094.51
1888799985.70868.191094.731034.30962.571110.02
1889958979.04864.371089.211064.471007.201121.07
18901,1401028.36914.581135.791083.18993.461151.88
18911,1001049.80936.771142.951103.851060.871186.58
18921,2101096.28986.401198.211110.391047.211176.68
18931,1501111.58999.971214.611114.661036.971197.72
18941,2501150.421045.381246.451122.451062.251188.46
18951,2601175.551074.751282.661106.221047.601196.37
18961,2201189.651080.021290.901077.23998.821142.24
18971,0301144.401040.291251.471035.30959.141102.39
18981,1001132.611031.021247.001002.03930.121059.18
18997741035.63951.651134.70958.11864.001012.01
1900840985.76887.991088.57919.50857.11980.13
1901874956.00852.791063.37891.70803.04962.23
1902694881.25778.74986.51867.75781.17923.53
1903940898.30788.041000.80865.58802.10942.40
1904833880.48773.82986.56851.36771.00935.92
1905701831.37714.10941.68839.33772.31904.43
1906916858.37746.87971.39846.56779.80913.78
1907692808.32692.82920.45844.33773.45915.91
19081,020869.32762.15978.60860.79798.61947.77
19091,050919.50810.051008.54877.67787.56982.69
1910969931.07822.871037.93863.64780.36933.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
))
Python

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

ParameterValue5%95%Effective drawsSource
Observation noise SD123.59106.47138.1030.381PMMH posterior mean
Level noise SD43.41929.08364.8918.164PMMH posterior mean

Log-likelihood

Value
Particle estimate (500 particles)−639.51
SD over five filter runs0.4484
Exact (Kalman filter)−638.76

Hidden state at each step

yearflowFiltered level5%95%Smoothed level5% (smoothed)95% (smoothed)
18711,1201125.52967.551283.001112.061015.671210.42
18721,1601140.121007.441271.961104.741017.411166.61
18739631070.30960.341195.891093.121008.391163.70
18741,2101114.50998.911232.271099.02987.891176.70
18751,1601127.271011.921242.841105.621008.481180.09
18761,1601133.531026.551251.181106.191047.941154.98
18778131041.53928.321144.001090.461025.721136.53
18781,2301098.48992.721203.461119.961047.461200.71
18791,3701175.291067.881280.581127.981041.691184.94
18801,1401166.261050.341279.881107.291019.431184.17
18819951121.371011.891219.271091.291009.091176.63
18829351071.85954.571181.121070.05985.551161.14
18831,1101082.01970.381188.031063.11967.661159.21
18849941057.67952.271168.611045.09980.741131.36
18851,0201046.58937.131154.691036.06951.301114.20
18869601020.12914.561132.411025.14966.241086.58
18871,1801065.12957.401182.111044.47954.281094.51
1888799985.70868.191094.731034.30962.571110.02
1889958979.04864.371089.211064.471007.201121.07
18901,1401028.36914.581135.791083.18993.461151.88
18911,1001049.80936.771142.951103.851060.871186.58
18921,2101096.28986.401198.211110.391047.211176.68
18931,1501111.58999.971214.611114.661036.971197.72
18941,2501150.421045.381246.451122.451062.251188.46
18951,2601175.551074.751282.661106.221047.601196.37
18961,2201189.651080.021290.901077.23998.821142.24
18971,0301144.401040.291251.471035.30959.141102.39
18981,1001132.611031.021247.001002.03930.121059.18
18997741035.63951.651134.70958.11864.001012.01
1900840985.76887.991088.57919.50857.11980.13
1901874956.00852.791063.37891.70803.04962.23
1902694881.25778.74986.51867.75781.17923.53
1903940898.30788.041000.80865.58802.10942.40
1904833880.48773.82986.56851.36771.00935.92
1905701831.37714.10941.68839.33772.31904.43
1906916858.37746.87971.39846.56779.80913.78
1907692808.32692.82920.45844.33773.45915.91
19081,020869.32762.15978.60860.79798.61947.77
19091,050919.50810.051008.54877.67787.56982.69
1910969931.07822.871037.93863.64780.36933.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.

07

Filtered or smoothed?

Read

The 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".

08

Volatility you can't see

Read

Returns 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.

Particle filterRecorded · Python and R agreeRecorded 2026-11-21 · 22 values compared
R

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

ParameterValue5%95%Effective drawsSource
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 runs0.2759

Hidden state at each step

dayretFiltered volatility (median)5%95%Smoothed volatility5% (smoothed)95% (smoothed)
2022-01-03−0.45481.1010.62841.7850.97750.74331.290
2022-01-040.62261.0440.60921.7200.97850.73221.284
2022-01-05−0.74100.99970.60631.6210.98650.76731.222
2022-01-060.98181.0290.64471.6151.0020.79101.261
2022-01-07−0.26940.95150.61751.4961.0020.78011.249
2022-01-08−1.2730.99940.66871.5301.0060.74441.271
2022-01-090.65800.97710.69081.4611.0160.78321.366
2022-01-100.10310.92530.62831.4010.99910.75971.266
2022-01-111.3860.99100.71671.4631.0140.83261.235
2022-01-12−0.82660.98790.71401.4461.0230.81541.249
2022-01-13−0.10340.97390.65691.3671.0130.81291.329
2022-01-141.1661.0080.70841.3971.0190.78161.372
2022-01-150.59960.96020.68021.3711.0300.79531.376
2022-01-16−1.3231.0010.70571.4281.0540.82041.406
2022-01-17−1.1771.0310.71561.4181.0330.82491.446
2022-01-18−1.2451.0470.74711.4241.0370.79621.379
2022-01-19−0.16101.0120.72361.4381.0670.80851.428
2022-01-200.71030.99490.71861.3921.0800.80301.390
2022-01-210.73020.98150.70121.3831.0520.78181.302
2022-01-220.61040.96360.69331.3591.0710.79721.407
2022-01-23−0.54220.94620.64331.3451.0840.79461.452
2022-01-24−0.27550.88900.62221.3141.0980.84601.434
2022-01-25−1.4080.96580.68141.3641.1240.85721.507
2022-01-260.19550.93200.66961.3161.1550.89531.523
2022-01-270.90440.93350.69271.3251.2010.95951.570
2022-01-28−0.06040.89670.65511.2831.2240.94661.698
2022-01-292.2011.0800.80181.4821.2830.99551.694
2022-01-301.3871.1170.83931.4811.3071.0121.712
2022-01-310.12331.0760.78641.4951.3331.0761.733
2022-02-01−0.30731.0390.75771.4411.3160.96331.706
2022-02-02−0.06911.0080.71761.3881.3321.0831.719
2022-02-03−2.2841.1450.85821.6031.3871.1091.704
2022-02-043.1871.3981.0601.8411.4481.1971.882
2022-02-050.17171.3441.0221.7961.4281.1371.850
2022-02-06−2.0591.4011.0551.8701.4451.1761.933
2022-02-070.10591.3430.99821.8611.4361.0901.929
2022-02-08−1.6781.3711.0301.8971.4401.0491.930
2022-02-09−0.47501.3210.97061.8301.3961.0761.881
2022-02-101.5911.3440.97991.8281.3911.0191.821
2022-02-11−1.5141.3610.98671.8051.3691.0821.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
))
Python

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

ParameterValue5%95%Effective drawsSource
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 runs0.2759

Hidden state at each step

dayretFiltered volatility (median)5%95%Smoothed volatility5% (smoothed)95% (smoothed)
2022-01-03−0.45481.1010.62841.7850.97750.74331.290
2022-01-040.62261.0440.60921.7200.97850.73221.284
2022-01-05−0.74100.99970.60631.6210.98650.76731.222
2022-01-060.98181.0290.64471.6151.0020.79101.261
2022-01-07−0.26940.95150.61751.4961.0020.78011.249
2022-01-08−1.2730.99940.66871.5301.0060.74441.271
2022-01-090.65800.97710.69081.4611.0160.78321.366
2022-01-100.10310.92530.62831.4010.99910.75971.266
2022-01-111.3860.99100.71671.4631.0140.83261.235
2022-01-12−0.82660.98790.71401.4461.0230.81541.249
2022-01-13−0.10340.97390.65691.3671.0130.81291.329
2022-01-141.1661.0080.70841.3971.0190.78161.372
2022-01-150.59960.96020.68021.3711.0300.79531.376
2022-01-16−1.3231.0010.70571.4281.0540.82041.406
2022-01-17−1.1771.0310.71561.4181.0330.82491.446
2022-01-18−1.2451.0470.74711.4241.0370.79621.379
2022-01-19−0.16101.0120.72361.4381.0670.80851.428
2022-01-200.71030.99490.71861.3921.0800.80301.390
2022-01-210.73020.98150.70121.3831.0520.78181.302
2022-01-220.61040.96360.69331.3591.0710.79721.407
2022-01-23−0.54220.94620.64331.3451.0840.79461.452
2022-01-24−0.27550.88900.62221.3141.0980.84601.434
2022-01-25−1.4080.96580.68141.3641.1240.85721.507
2022-01-260.19550.93200.66961.3161.1550.89531.523
2022-01-270.90440.93350.69271.3251.2010.95951.570
2022-01-28−0.06040.89670.65511.2831.2240.94661.698
2022-01-292.2011.0800.80181.4821.2830.99551.694
2022-01-301.3871.1170.83931.4811.3071.0121.712
2022-01-310.12331.0760.78641.4951.3331.0761.733
2022-02-01−0.30731.0390.75771.4411.3160.96331.706
2022-02-02−0.06911.0080.71761.3881.3321.0831.719
2022-02-03−2.2841.1450.85821.6031.3871.1091.704
2022-02-043.1871.3981.0601.8411.4481.1971.882
2022-02-050.17171.3441.0221.7961.4281.1371.850
2022-02-06−2.0591.4011.0551.8701.4451.1761.933
2022-02-070.10591.3430.99821.8611.4361.0901.929
2022-02-08−1.6781.3711.0301.8971.4401.0491.930
2022-02-09−0.47501.3210.97061.8301.3961.0761.881
2022-02-101.5911.3440.97991.8281.3911.0191.821
2022-02-11−1.5141.3610.98671.8051.3691.0821.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.

09

Check: particle filters

Checkpoint

Check 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