| Item | Value |
|---|---|
| R | R version 4.5.2 (2025-10-31) |
| Platform | aarch64-apple-darwin20 |
| Quarto | 1.8.26 |
| Packages | In sync with renv.lock |
| MASS | 7.3.65 |
| posterior | 1.7.0 |
| ggplot2 | 4.0.3 |
| gt | 1.3.0 |
Reproducibility
How to rerun the analysis and where the results can mislead
Every number on this site is computed from one synthetic data file, data/synthetic_returns.csv, which R/generate_data.R generates from a fixed seed. Every Markov chain is run with an explicit seed. Nothing is downloaded during a render, so rendering the same commit with the same package versions gives the same results. This page explains how to rebuild the site, records the environment it was built in, and states where the results can mislead.
Quick start
The code and data are in the GitHub repository patrick-lefler/markov-chain-monte-carlo. To rebuild everything from a clean copy:
git clone https://github.com/patrick-lefler/markov-chain-monte-carlo
cd markov-chain-monte-carlo
Rscript -e 'renv::restore()' # once: install the package versions pinned in renv.lock
quarto renderThe rendered site is written to docs/. The data file is committed, so quarto render does not need to regenerate it (see Data).
Environment
How to read the table
Each row is one piece of software this page was built with and its version. The “Packages” row says whether the installed R packages match the versions pinned in renv.lock.
What the table tells you
If your versions match these and the packages are in sync, rebuilding the project should give the same numbers. If they differ, small differences in the results may come from the software rather than the analysis.
Pipeline
| Script | What it does | Main outputs |
|---|---|---|
R/generate_data.R |
Draws 250 days of returns for 10 correlated assets from a multivariate normal distribution with fixed means, volatilities and correlations. Run once by hand, not during a render. synthetic_params() returns the true generating parameters, which the Audit & Diagnostics page quotes. |
data/synthetic_returns.csv, synthetic_params() |
R/metropolis_sampler.R |
Random-Walk Metropolis-Hastings sampler written in base R, with no MCMC packages | run_metropolis() |
R/risk_functions.R |
Builds the joint log-posterior for the 10 mean returns from the data file, and turns posterior draws into Value at Risk and Expected Shortfall | build_risk_target(), evaluate_portfolio_tail_risk(), generate_dimension_comparison() |
R/plots.R |
Shared ggplot2 theme and plotting functions | theme_mcmc(), plot helpers |
R/diagnostics.R |
Convergence diagnostics used by R/analysis.R |
compute_ess_robust() (Geyer ESS), compute_split_rhat() |
R/analysis.R |
Sets the 10-factor settings and seeds (analysis_settings()), then runs the four chains, the tail-risk estimates, the exact-posterior benchmark and the convergence diagnostics (run_analysis()). Takes about a second. |
res, the list of results that the home, Portfolio Risk and Audit & Diagnostics pages quote |
R/verify_sampler.R, R/verify_risk_functions.R, R/verify_diagnostics.R |
Sanity checks you run by hand (for example Rscript R/verify_diagnostics.R). They are not sourced by any page. |
Console output |
R/repro_env.R |
Builds the Environment table on this page | repro_env_table() |
Each page sources the scripts it needs in a hidden first chunk. The home, Portfolio Risk and Audit & Diagnostics pages each call run_analysis(), so every number they quote comes from the same code, settings and seeds; nothing in their text is typed in by hand.
Data
The data are synthetic. R/generate_data.R draws 250 trading days of daily returns for 10 asset classes from a multivariate normal distribution using MASS::mvrnorm() with seed 20260924. The script fixes the annualized means (3.5% to 11.0%), annualized volatilities (8% to 26%) and a correlation matrix (−0.30 to +0.78). The output file is committed to the repository. To regenerate it, run Rscript R/generate_data.R from the project root, which overwrites data/synthetic_returns.csv. On the platform recorded in Environment, this reproduces the committed file byte for byte.
File in data/ |
Source | Role |
|---|---|---|
synthetic_returns.csv |
Generated by R/generate_data.R (seed 20260924) |
250 days × 10 assets of daily returns: the data behind the 10-factor posterior on every page except the 2D toy examples |
The checksum below identifies the exact file used in this render. A different checksum means a different file.
| File | Size (MB) | MD5 |
|---|---|---|
| synthetic_returns.csv | 0.05 | d5873cbd57f458b8dc00b48daf017070 |
How to read the table
Each row is one data file. The MD5 column is a checksum: a short fingerprint computed from the file’s exact contents, so changing even one character gives a completely different fingerprint.
What the table tells you
Anyone rerunning the analysis can compute the same checksums on their copies. If every fingerprint matches, they are working from identical inputs; a mismatch means a file differs, and any difference in results should be traced to that file first.
Parameters and seeds
The project has no params.yaml. The settings that drive the results are set directly in the code:
| Setting | Value | Where it is set |
|---|---|---|
| Data: days, assets, generator seed | 250 days, 10 assets, seed 20260924 |
R/generate_data.R |
| Prior on the mean vector | \(\mathcal{N}(\mathbf{0}, 10^{3}\,\mathbf{I})\) (inv_prior_var = 1e-3) |
build_risk_target() in R/risk_functions.R |
| Covariance | Fixed at the sample covariance of the data | build_risk_target() in R/risk_functions.R |
| 10-factor chains: iterations, proposal SD, burn-in, overdispersed starts | 3,000 iterations, proposal_sd = 0.00032, first 500 draws discarded, chains 2–4 started ±3 posterior SDs from the center |
analysis_settings() in R/analysis.R |
| Portfolio and risk measure | Equal weights, 1-day horizon, 95% VaR and Expected Shortfall | analysis_settings() and run_analysis() in R/analysis.R |
| Convergence thresholds | split-\(\hat{R}\) < 1.01, ESS ≥ 400 (Vehtari et al., 2021) | analysis_settings() in R/analysis.R |
| 2D toy chains | Intuition & The Walk: 300 iterations, proposal_sd = 0.45. The Metropolis Engine: 2,000 iterations with proposal_sd of 0.03, 3.20 and 1.20 |
index.qmd, 01-mechanics.qmd |
Every random stream is seeded explicitly. run_metropolis() calls set.seed(seed) before each chain, and the seeds are:
42for chain 1 of the 10-factor analysis (R/analysis.R), and42for the 2D hero chain on the home page (index.qmd).101for the three step-size chains on The Metropolis Engine page.99, 123, 456for chains 2–4 of the 10-factor analysis.2026(inrun_analysis()) for the random signs of the “mixed” starting point.
Because each chain resets the seed, results do not depend on the order in which pages are rendered.
Caching
- Quarto freeze (
_freeze/)._quarto.ymlsetsfreeze: auto, so a fullquarto renderre-executes a page only when that page’s.qmdfile changes. Edits to theR/scripts do not count as a change. After editing a script, render each page explicitly (for examplequarto render 03-diagnostics.qmd), because Quarto always executes a page that is rendered on its own._freeze/is committed to git, so a fresh clone renders from the stored results until a page changes.
Known limitations
Limits of reproducibility
- Bit-for-bit equality is expected only on the same platform and package versions. Floating-point and BLAS differences across machines can change low-order digits.
MASS::mvrnorm()uses an eigendecomposition of the covariance matrix, which can differ slightly across BLAS/LAPACK libraries. RerunningR/generate_data.Ron another platform may therefore produce a slightly different data file. The committed file and its checksum above are the reference.- The Metropolis chains are sensitive to every random draw. A tiny numerical difference in the data or the log-posterior can change an accept/reject decision, after which the chain follows a different path. The headline values (acceptance rate, split-\(\hat{R}\), ESS, credible-interval widths) would then differ in their later digits, though not in their conclusions.
- Quarto versions affect rendering, not the numbers.
Model limitations
The Scope & Limitations callout on the home page summarizes these for a first-time reader. In full:
- Synthetic data. All results use a 250-day sample from a known multivariate normal distribution. Real returns show regime shifts, volatility clustering and structural breaks that this data set does not.
- Covariance is fixed. \(\mathbf{\Sigma}\) is set to its sample estimate, so only uncertainty in the mean vector is modeled. Covariance uncertainty, usually the larger driver of VaR error, is excluded, so the reported credible intervals are lower bounds on total parameter risk.
- Gaussian tails. The normal likelihood cannot represent fat tails or skew. VaR and ES here are parametric Gaussian measures and will understate losses in stressed markets.
- The sampler has not converged. All ten factors are at or above the split-\(\hat{R}\) threshold of 1.01, pooled bulk ESS is well below 400, and the MCMC VaR credible interval is narrower than the exact one. See Audit & Diagnostics.
- Short run and burn-in. The chains run 3,000 iterations with a 500-draw burn-in, which the trace plots show is insufficient for overdispersed starts.
- Deliberately simple setting. The model is conjugate, so MCMC is not needed here; it is used so that every result can be checked against an exact answer. Performance on non-conjugate models is untested.
- Narrow portfolio specification. Results cover one equal-weighted portfolio at a 1-day horizon and a 95% confidence level.
- Illustrative scaling figures. The grid-versus-MCMC timings in the Dimensional Complexity table are illustrative estimates, not measured benchmarks.
What would change the conclusions
| Change | Likely effect |
|---|---|
| Longer chains, or a covariance-preconditioned or gradient-based sampler (HMC/NUTS) | Split-\(\hat{R}\) and ESS would likely meet their thresholds, and the MCMC credible intervals would move toward the exact ones. The “sampler understates risk” finding is specific to this isotropic sampler. |
| Treating the covariance as uncertain | Wider VaR and ES credible intervals, since covariance uncertainty adds to the mean uncertainty modeled here. |
| Fat-tailed likelihood (for example Student-t) | Higher VaR and ES, and a non-conjugate posterior with no exact benchmark. |
| A different generator seed or sample length | Different sample means (the Portfolio Risk page shows that the Tech Growth sample drift sits well below its true value by chance), and so different posterior centers. |
What real data would replace each assumption
| Assumption | Real-data replacement |
|---|---|
| Synthetic multivariate normal returns | Daily total returns for the portfolio’s actual factor exposures or index proxies |
| Equal weights | The portfolio’s actual position weights |
| Fixed sample covariance | A covariance estimated jointly with the means, or a shrinkage or factor-model estimate with its own uncertainty |
| Known true parameters | None: with real data the truth is unknown, so the exact-posterior benchmark is only available for conjugate models like this one |
How to use these results. Use them to learn how Random-Walk Metropolis works, why a healthy acceptance rate is not evidence of convergence, and how to audit a sampler with multi-chain diagnostics and an exact benchmark. Do not use the VaR and ES figures, or the sampler as configured, for risk decisions on a real portfolio.
Licenses
The code on this site is released under the MIT License. The data are generated by the project’s own code (R/generate_data.R) and carry the same MIT License. Third-party software keeps its own terms:
| Source | Terms |
|---|---|
| R | GPL-2 | GPL-3 |
| MASS (generates the data) | GPL-2 | GPL-3 |
| posterior (reference ESS, split-\(\hat{R}\)) | BSD 3-clause |
| sessioninfo | GPL-2 |
| tidyverse, ggplot2, dplyr, scales, gt, reactable | MIT (see each package’s CRAN page) |
Session information
The site was built with R and Quarto. The analysis loads dplyr, ggplot2, gt, posterior, reactable, scales, tibble, tidyr, readr and tidyverse, and also calls MASS, knitr and sessioninfo. Package versions are pinned in renv.lock; run renv::restore() to install them.