Skip to content

DOptimization · simulate.monte_carlo

Monte Carlo simulation of a scenario model

What range of outcomes does a model with uncertain inputs produce, and how likely is a target?

Draws thousands of scenarios of a scenario model — uncertain inputs (normal, lognormal, triangular, PERT, beta, gamma, Poisson, discrete, empirical …), decisions held at their values and formulas over both — and summarizes each KPI: mean, SD, percentiles, the chance of meeting a target, value at risk and expected shortfall, and which inputs drive it. Draws come from the shared random stream by inversion, with rank correlations by Iman–Conover, so Python and R simulate the same scenarios.

Verified in Python and R Python and R agree to 6 decimals Seeded

A real result

Example “Newsvendor default”, recorded in both engines. In the app, “Try this example” loads it into Analyze.

Monte Carlo: ProfitRecorded · Python and R agreeRecorded 2026-11-09 · 39 values compared
R

Profit: mean 3357.08, 90% of 5,000 scenarios between 167.13 and 5599.00.

Mean Profit
3357.08
SD
1652.75
5th percentile
167.13
95th percentile
5599.00
P(meets target)
95.8%
Expected shortfall (0.05)
−652.60

Plots

Distribution of ProfitAcross all simulated scenarios, how likely is each outcome — and of missing the target?
View data
Bin endProfitScenarios
−3205.68−3456.082
−2955.28−3205.680
−2704.89−2955.280
−2454.49−2704.896
−2204.09−2454.493
−1953.69−2204.094
−1703.29−1953.6910
−1452.89−1703.2916
−1202.49−1452.8911
−952.09−1202.4915
−701.69−952.0924
−451.29−701.6935
−200.89−451.2938
49.509−200.8957
299.9149.50954
550.31299.9162
800.71550.3168
1051.11800.7193
1301.511051.11118
1551.911301.51124
1802.311551.91175
2052.711802.31166
2303.102052.71155
2553.502303.10211
2803.902553.50198
3054.302803.90212
3304.703054.30212
3555.103304.70260
3805.503555.10305
4055.903805.50360
4306.304055.90367
4556.704306.30385
4807.104556.70328
5057.504807.10263
5307.905057.50218
5558.305307.90166
5808.705558.30135
6059.105808.7074
6309.506059.1044
6559.906309.5026
Rank correlation with ProfitWhich features does the model rely on most?
View data
InputSpearman ρ
demand0.8692
price0.4048

KPIs across scenarios

KPIMeanSD5th pctMedian95th pctP(meets target)VaR (0.05)Expected shortfall
Profit3357.081652.75167.133694.375599.0095.8%167.13−652.60

Uncertain inputs (as drawn)

InputDistributionMeanSD5th pct95th pct
demandnormal1004.64201.24671.651327.74
pricetriangular10.3350.62609.39811.454

What drives Profit

InputRank correlation ρShare of ρ²
demand0.869282.2%
price0.404817.8%
  • 5,000 scenarios from the shared random stream (seed 3); inputs by inversion of their distributions.
  • Value at risk is the 0.05 quantile on the KPI's bad side; expected shortfall averages the worst 5% of scenarios.
Python

Profit: mean 3357.08, 90% of 5,000 scenarios between 167.13 and 5599.00.

Mean Profit
3357.08
SD
1652.75
5th percentile
167.13
95th percentile
5599.00
P(meets target)
95.8%
Expected shortfall (0.05)
−652.60

To keep this page light, the plots are shown once, under the R tab.

KPIs across scenarios

KPIMeanSD5th pctMedian95th pctP(meets target)VaR (0.05)Expected shortfall
Profit3357.081652.75167.133694.375599.0095.8%167.13−652.60

Uncertain inputs (as drawn)

InputDistributionMeanSD5th pct95th pct
demandnormal1004.64201.24671.651327.74
pricetriangular10.3350.62609.39811.454

What drives Profit

InputRank correlation ρShare of ρ²
demand0.869282.2%
price0.404817.8%
  • 5,000 scenarios from the shared random stream (seed 3); inputs by inversion of their distributions.
  • Value at risk is the 0.05 quantile on the KPI's bad side; expected shortfall averages the worst 5% of scenarios.

Do it in CodeSplash Run it on your own data, in Python or R, with the code to prove it.

Worked examples in the app

  • Newsvendor defaultNo data needed
  • Correlated many distsNo data needed
  • Costs below targetNo data needed

In the guides

Where it sits in the decision guides

  • Prescriptive analytics (simulation, OR, causal RL) · DS & ML Decision Guide · Optimize / decide

Choices you make

hypothesis

Scenario model (JSON)default {"inputs":[{"name":"demand","dist":"normal","params":{"mean":1000,"sd":200},"min":0},{"name":"price","dist":"triangular","params":{"min":9,"mode":10,"max":12}}],"decisions":[{"name":"order","value":1100,"min":0,"max":2000}],"formulas":[{"name":"sales","expr":"min(demand, order)"},{"name":"profit","expr":"price * sales - 6 * order"}],"kpis":[{"name":"profit","label":"Profit","target":0,"direction":"above"}],"correlations":[]}

Inputs with distributions, decisions with values, formulas and KPIs — built by the Scenario studio. See the method notes for the format.

Scenariosdefault 10000

Number of random scenarios to simulate. More gives smoother, more stable results.

options

Random seeddefault 1

Fixes the random numbers so reruns give identical results, in Python and in R.

Save every scenariodefault on

Write all draws (inputs, decisions and formulas) to draws.parquet next to the run.

statistics

Risk tail (VaR / expected shortfall)default 0.05

Share of the worst scenarios behind value at risk and expected shortfall (CVaR).

plots

Histogram binsdefault 40

Number of bins in the histogram of simulated outcomes (display only).

What it reports

n
How many independent units the analysis used; it sets precision and power.
n_inputs
How many independent units the analysis used; it sets precision and power.
n_formulas
How many independent units the analysis used; it sets precision and power.
n_kpis
How many independent units the analysis used; it sets precision and power.
kpi
Model name of the KPI the summary describes: the first KPI in the scenario model.
kpi_label
The headline KPI's display label, as used in the summary; falls back to its model name when no label was set.
kpi_mean
Estimating a quantity by drawing many random samples and summarizing the results.
kpi_sd
Estimating a quantity by drawing many random samples and summarizing the results.
kpi_p5
Estimating a quantity by drawing many random samples and summarizing the results.
kpi_p50
Estimating a quantity by drawing many random samples and summarizing the results.
kpi_p95
Estimating a quantity by drawing many random samples and summarizing the results.
kpi_p_meet
Estimating a quantity by drawing many random samples and summarizing the results.
kpi_var
The outcome you would only do worse than in a small share of cases, such as the worst 5%.
kpi_cvar
The average outcome within the worst cases. Unlike VaR, it sees how bad the tail gets.
alpha
The false-positive rate you accept before looking at the data, usually 0.05.

Per group, level or term: <stat>[<kpi>] (mean, sd, se, min, max, p1, p5, p10, p25, p50, p75, p90, p95, p99, p_meet, var, cvar, n_invalid), rank_cor[<kpi>,<input>], input_mean[<input>], input_sd[<input>], achieved_rho[<a>,<b>]

Python and R

Python and R agree to 6 decimals (relative tolerance 1e-9). Python uses numpy, scipy, pandas, pyarrow, codesplash; R uses jsonlite, nanoparquet, codesplashr.

Default traps between the two languages

  • Draws are quantiles of the same shared uniforms: closed-form inverses (uniform, triangular, exponential, Weibull, discrete, empirical) agree exactly; normal/lognormal (scipy ndtri ↔ qnorm), beta/PERT (betaincinv ↔ qbeta) and gamma (gammaincinv ↔ qgamma) agree to ~1e-15 relative.
  • Poisson and binomial draws are integer quantiles (scipy ppf ↔ qpois/qbinom); a uniform within ~1e-15 of a CDF step could round to neighboring counts — not seen in practice.
  • Iman–Conover: Pearson correlation and Cholesky factors differ in the last bits (numpy ↔ R); the reordering uses ranks, so draws are identical unless two transformed scores tie to 1e-15.
Python

The exact script CodeSplash ran for example “Newsvendor default” · Python 3.13.5 · scipy 1.18.1 · pandas 3.1.0

# Monte Carlo simulation of a scenario model
# Generated by CodeSplash Analytics 1.0.0 on 2026-11-09 · method simulate.monte_carlo 1.0.1 · spec 48b067b137893fd7
# Runs on its own: outside the app, cs.publish() writes $CS_RESULT_PATH or prints the result JSON.

# %% Setup
import json
import os

import numpy as np
import pandas as pd

import codesplash as cs
from codesplash import ml as csml
from codesplash.sim import dists, mc  # scenario models on the shared random stream (twin of R cs_sim_*)

# %% Model
# Inputs (distributions), decisions (fixed values), formulas and KPIs, as built in the Scenario studio.
model = mc.load(json.loads("{\"inputs\":[{\"name\":\"demand\",\"dist\":\"normal\",\"params\":{\"mean\":1000,\"sd\":200},\"min\":0},{\"name\":\"price\",\"dist\":\"triangular\",\"params\":{\"min\":9,\"mode\":10,\"max\":12}}],\"decisions\":[{\"name\":\"order\",\"value\":1100,\"min\":0,\"max\":2000}],\"formulas\":[{\"name\":\"sales\",\"expr\":\"min(demand, order)\"},{\"name\":\"profit\",\"expr\":\"price * sales - 6 * order\"}],\"kpis\":[{\"name\":\"profit\",\"label\":\"Profit\",\"target\":0,\"direction\":\"above\"}],\"correlations\":[]}"))
N = int(5000)
SEED = int(3)
ALPHA = 0.05  # risk tail for value at risk / expected shortfall
BINS = int(40)
warnings = []

# %% Simulate
# Each input draws N uniforms from the shared stream (model order) and maps them through its quantile
# function; correlated inputs are then paired by Iman–Conover. Equivalent idiom without the shared
# stream: rng = np.random.default_rng(SEED); demand = rng.normal(1000, 150, N) …
draws = mc.simulate(model, N, SEED)
inputs = [str(i["name"]) for i in model["inputs"]]
kpis = list(model["kpis"]) or [{"name": (model["formulas"] or model["inputs"] or model["decisions"])[-1]["name"]}]

# %% Summaries
values = {"n": N, "n_inputs": len(inputs), "n_formulas": len(model["formulas"]), "n_kpis": len(kpis), "alpha": ALPHA}
kpi_rows, charts, tables = [], [], []
for k in kpis:
    name = str(k["name"])
    s = mc.summarize(draws[name], k, ALPHA)
    for stat in ("mean", "sd", "se", "min", "max", "p1", "p5", "p10", "p25", "p50", "p75", "p90", "p95", "p99", "p_meet", "var", "cvar", "n_invalid"):
        if stat in s:
            values[f"{stat}[{name}]"] = s[stat]
    if s["n_invalid"]:
        warnings.append(f"{name}: {s['n_invalid']:,} scenarios gave no number (division by zero or an invalid function argument) and are left out.")
    kpi_rows.append({
        "kpi": k.get("label") or name, "mean": s.get("mean"), "sd": s.get("sd"), "p5": s.get("p5"), "p50": s.get("p50"),
        "p95": s.get("p95"), "p_meet": s.get("p_meet"), "var": s.get("var"), "cvar": s.get("cvar"),
    })
    for inp in inputs:
        values[f"rank_cor[{name},{inp}]"] = mc.rank_correlation(draws[inp], draws[name])
    h = mc.histogram(draws[name], BINS)
    # Always set the target control (null = none): a missing control shows the recipe default.
    controls = {"percentiles": [5, 50, 95], "target": float(k["target"]) if k.get("target") is not None else None}
    charts.append(cs.chart(
        f"dist_{name}", "mc-distribution", f"Distribution of {k.get('label') or name}",
        {"bin_low": cs.col(k.get("label") or name, h["bin_low"]), "bin_high": cs.col("Bin end", h["bin_high"]), "count": cs.col("Scenarios", h["count"])},
        controls=controls,
    ))
primary = kpis[0]
pname = str(primary["name"])
values.update({
    "kpi": pname, "kpi_label": primary.get("label") or pname,
    "kpi_mean": values.get(f"mean[{pname}]"), "kpi_sd": values.get(f"sd[{pname}]"), "kpi_p5": values.get(f"p5[{pname}]"),
    "kpi_p50": values.get(f"p50[{pname}]"), "kpi_p95": values.get(f"p95[{pname}]"), "kpi_p_meet": values.get(f"p_meet[{pname}]"),
    "kpi_var": values.get(f"var[{pname}]"), "kpi_cvar": values.get(f"cvar[{pname}]"),
})
tables.append({
    "key": "kpis", "title": "KPIs across scenarios",
    "columns": [
        {"key": "kpi", "label": "KPI", "type": "string"}, {"key": "mean", "label": "Mean", "type": "number"},
        {"key": "sd", "label": "SD", "type": "number"}, {"key": "p5", "label": "5th pct", "type": "number"},
        {"key": "p50", "label": "Median", "type": "number"}, {"key": "p95", "label": "95th pct", "type": "number"},
        {"key": "p_meet", "label": "P(meets target)", "type": "percent"}, {"key": "var", "label": f"VaR ({ALPHA:g})", "type": "number"},
        {"key": "cvar", "label": "Expected shortfall", "type": "number"},
    ],
    "rows": kpi_rows,
})

# Inputs as drawn.
input_rows = []
for spec in model["inputs"]:
    nm = str(spec["name"])
    x = draws[nm]
    values[f"input_mean[{nm}]"] = float(np.mean(x))
    values[f"input_sd[{nm}]"] = float(np.std(x, ddof=1))
    q = mc.quantile7(x, [0.05, 0.95])
    input_rows.append({"input": nm, "dist": spec["dist"], "mean": float(np.mean(x)), "sd": float(np.std(x, ddof=1)), "p5": float(q[0]), "p95": float(q[1])})
if input_rows:
    tables.append({
        "key": "inputs", "title": "Uncertain inputs (as drawn)",
        "columns": [
            {"key": "input", "label": "Input", "type": "string"}, {"key": "dist", "label": "Distribution", "type": "string"},
            {"key": "mean", "label": "Mean", "type": "number"}, {"key": "sd", "label": "SD", "type": "number"},
            {"key": "p5", "label": "5th pct", "type": "number"}, {"key": "p95", "label": "95th pct", "type": "number"},
        ],
        "rows": input_rows,
    })

# Drivers of the primary KPI: Spearman correlation with each input; share = ρ² / Σρ².
rho = {inp: values[f"rank_cor[{pname},{inp}]"] for inp in inputs}
finite = {k: v for k, v in rho.items() if np.isfinite(v)}
total = sum(v * v for v in finite.values())
drivers = sorted(finite.items(), key=lambda kv: (-abs(kv[1]), inputs.index(kv[0])))
if drivers:
    tables.append({
        "key": "drivers", "title": f"What drives {primary.get('label') or pname}",
        "columns": [
            {"key": "input", "label": "Input", "type": "string"}, {"key": "rho", "label": "Rank correlation ρ", "type": "number"},
            {"key": "share", "label": "Share of ρ²", "type": "percent"},
        ],
        "rows": [{"input": k, "rho": v, "share": (v * v / total) if total > 0 else None} for k, v in drivers],
    })
    charts.append(cs.chart(
        "drivers", "importance-bar", f"Rank correlation with {primary.get('label') or pname}",
        {"feature": cs.col("Input", [k for k, _ in drivers]), "importance": cs.col("Spearman ρ", [v for _, v in drivers])},
        controls={"top": 20},
    ))

# Correlations achieved by Iman–Conover.
if model["correlations"]:
    corr_rows = []
    for c in model["correlations"]:
        got = mc.rank_correlation(draws[c["a"]], draws[c["b"]])
        values[f"achieved_rho[{c['a']},{c['b']}]"] = got
        corr_rows.append({"pair": f"{c['a']} – {c['b']}", "target": float(c["rho"]), "achieved": got})
    tables.append({
        "key": "correlations", "title": "Rank correlations (target vs achieved)",
        "columns": [{"key": "pair", "label": "Inputs", "type": "string"}, {"key": "target", "label": "Target", "type": "number"}, {"key": "achieved", "label": "Achieved", "type": "number"}],
        "rows": corr_rows,
    })

# %% Save the scenarios
artifacts = []
if True:
    out = csml.out_dir("target/academy-parity/run-57623/simulate.monte_carlo/newsvendor-default/out-python")
    path = os.path.join(out, "draws.parquet")
    pd.DataFrame({"scenario": np.arange(1, N + 1)} | {k: v for k, v in draws.items()}).to_parquet(path, index=False)
    artifacts.append({"key": "draws", "path": path, "format": "parquet", "title": "Simulated scenarios"})

# %% Result
label = primary.get("label") or pname
summary = (f"{label}: mean {cs.fmt_num(values['kpi_mean'])}, 90% of {N:,} scenarios between "
           f"{cs.fmt_num(values['kpi_p5'])} and {cs.fmt_num(values['kpi_p95'])}.")
cs.publish({
    "method": "simulate.monte_carlo",
    "methodVersion": "1.0.1",
    "title": f"Monte Carlo: {label}",
    "engine": cs.engine_info("numpy", "scipy", "pandas"),
    "n": N,
    "summary": summary,
    "statistics": [
        {"key": "kpi_mean", "label": f"Mean {label}", "value": values["kpi_mean"]},
        {"key": "kpi_sd", "label": "SD", "value": values["kpi_sd"]},
        {"key": "kpi_p5", "label": "5th percentile", "value": values["kpi_p5"]},
        {"key": "kpi_p95", "label": "95th percentile", "value": values["kpi_p95"]},
        *([{"key": "kpi_p_meet", "label": "P(meets target)", "value": values["kpi_p_meet"], "format": "percent"}] if values["kpi_p_meet"] is not None else []),
        {"key": "kpi_cvar", "label": f"Expected shortfall ({ALPHA:g})", "value": values["kpi_cvar"]},
    ],
    "tables": tables,
    "charts": charts,
    "warnings": warnings,
    "notes": [
        f"{N:,} scenarios from the shared random stream (seed {SEED}); inputs by inversion of their distributions"
        + ("; rank correlations induced by Iman–Conover." if model["correlations"] else "."),
        f"Value at risk is the {ALPHA:g} quantile on the KPI's bad side; expected shortfall averages the worst {ALPHA:.0%} of scenarios.",
    ],
    "artifacts": artifacts,
    "values": values,
})
R

The exact script CodeSplash ran for example “Newsvendor default” · R version 4.5.1 (2025-06-13)

# Monte Carlo simulation of a scenario model
# Generated by CodeSplash Analytics 1.0.0 on 2026-11-09 · method simulate.monte_carlo 1.0.1 · spec 48b067b137893fd7
# Runs on its own: outside the app, cs_publish() writes $CS_RESULT_PATH or prints the result JSON.

# %% Setup
library(codesplashr) # cs_sim_*: scenario models on the shared random stream (twin of codesplash.sim)

# %% Model
# Inputs (distributions), decisions (fixed values), formulas and KPIs, as built in the Scenario studio.
model <- cs_sim_load("{\"inputs\":[{\"name\":\"demand\",\"dist\":\"normal\",\"params\":{\"mean\":1000,\"sd\":200},\"min\":0},{\"name\":\"price\",\"dist\":\"triangular\",\"params\":{\"min\":9,\"mode\":10,\"max\":12}}],\"decisions\":[{\"name\":\"order\",\"value\":1100,\"min\":0,\"max\":2000}],\"formulas\":[{\"name\":\"sales\",\"expr\":\"min(demand, order)\"},{\"name\":\"profit\",\"expr\":\"price * sales - 6 * order\"}],\"kpis\":[{\"name\":\"profit\",\"label\":\"Profit\",\"target\":0,\"direction\":\"above\"}],\"correlations\":[]}")
N <- as.integer(5000)
SEED <- 3
ALPHA <- 0.05 # risk tail for value at risk / expected shortfall
BINS <- 40
warnings <- list()

# %% Simulate
# Each input draws N uniforms from the shared stream (model order) and maps them through its quantile
# function; correlated inputs are then paired by Iman–Conover. Equivalent idiom without the shared
# stream: set.seed(SEED); demand <- rnorm(N, 1000, 150) …
draws <- cs_sim_simulate(model, N, SEED)
inputs <- vapply(model$inputs, function(i) as.character(i$name), character(1))
kpis <- model$kpis
if (!length(kpis)) {
  last <- if (length(model$formulas)) model$formulas[[length(model$formulas)]] else if (length(model$inputs)) model$inputs[[length(model$inputs)]] else model$decisions[[length(model$decisions)]]
  kpis <- list(list(name = last$name))
}
lab <- function(k) if (!is.null(k$label) && nzchar(k$label)) k$label else as.character(k$name)

# %% Summaries
values <- list(n = N, n_inputs = length(inputs), n_formulas = length(model$formulas), n_kpis = length(kpis), alpha = ALPHA)
kpi_rows <- list(); charts <- list(); tables <- list()
stats_keys <- c("mean", "sd", "se", "min", "max", "p1", "p5", "p10", "p25", "p50", "p75", "p90", "p95", "p99", "p_meet", "var", "cvar", "n_invalid")
for (k in kpis) {
  name <- as.character(k$name)
  s <- cs_sim_summarize(draws[[name]], k, ALPHA)
  for (st in stats_keys) if (!is.null(s[[st]])) values[[sprintf("%s[%s]", st, name)]] <- s[[st]]
  if (s$n_invalid > 0) warnings <- c(warnings, sprintf("%s: %s scenarios gave no number (division by zero or an invalid function argument) and are left out.", name, format(s$n_invalid, big.mark = ",")))
  g <- function(key) if (is.null(s[[key]])) NA else s[[key]]
  kpi_rows[[length(kpi_rows) + 1]] <- list(kpi = lab(k), mean = g("mean"), sd = g("sd"), p5 = g("p5"), p50 = g("p50"),
                                           p95 = g("p95"), p_meet = g("p_meet"), var = g("var"), cvar = g("cvar"))
  for (inp in inputs) values[[sprintf("rank_cor[%s,%s]", name, inp)]] <- cs_sim_rank_cor(draws[[inp]], draws[[name]])
  h <- cs_sim_histogram(draws[[name]], BINS)
  # Always set the target control (NA = none): a missing control shows the recipe default.
  controls <- list(percentiles = c(5, 50, 95), target = if (!is.null(k$target)) as.numeric(k$target) else NA)
  charts[[length(charts) + 1]] <- cs_chart(
    sprintf("dist_%s", name), "mc-distribution", sprintf("Distribution of %s", lab(k)),
    list(bin_low = cs_col(lab(k), h$bin_low), bin_high = cs_col("Bin end", h$bin_high), count = cs_col("Scenarios", h$count)),
    controls = controls
  )
}
primary <- kpis[[1]]
pname <- as.character(primary$name)
pv <- function(st) {
  v <- values[[sprintf("%s[%s]", st, pname)]]
  if (is.null(v)) NA else v
}
values$kpi <- pname
values$kpi_label <- lab(primary)
values$kpi_mean <- pv("mean"); values$kpi_sd <- pv("sd"); values$kpi_p5 <- pv("p5"); values$kpi_p50 <- pv("p50")
values$kpi_p95 <- pv("p95"); values$kpi_p_meet <- pv("p_meet"); values$kpi_var <- pv("var"); values$kpi_cvar <- pv("cvar")
tables[[length(tables) + 1]] <- list(
  key = "kpis", title = "KPIs across scenarios",
  columns = list(
    list(key = "kpi", label = "KPI", type = "string"), list(key = "mean", label = "Mean", type = "number"),
    list(key = "sd", label = "SD", type = "number"), list(key = "p5", label = "5th pct", type = "number"),
    list(key = "p50", label = "Median", type = "number"), list(key = "p95", label = "95th pct", type = "number"),
    list(key = "p_meet", label = "P(meets target)", type = "percent"), list(key = "var", label = sprintf("VaR (%s)", format(ALPHA)), type = "number"),
    list(key = "cvar", label = "Expected shortfall", type = "number")
  ),
  rows = kpi_rows
)

# Inputs as drawn.
input_rows <- list()
for (spec in model$inputs) {
  nm <- as.character(spec$name)
  x <- draws[[nm]]
  values[[sprintf("input_mean[%s]", nm)]] <- mean(x)
  values[[sprintf("input_sd[%s]", nm)]] <- stats::sd(x)
  q <- cs_sim_quantile7(x, c(0.05, 0.95))
  input_rows[[length(input_rows) + 1]] <- list(input = nm, dist = spec$dist, mean = mean(x), sd = stats::sd(x), p5 = q[1], p95 = q[2])
}
if (length(input_rows)) {
  tables[[length(tables) + 1]] <- list(
    key = "inputs", title = "Uncertain inputs (as drawn)",
    columns = list(
      list(key = "input", label = "Input", type = "string"), list(key = "dist", label = "Distribution", type = "string"),
      list(key = "mean", label = "Mean", type = "number"), list(key = "sd", label = "SD", type = "number"),
      list(key = "p5", label = "5th pct", type = "number"), list(key = "p95", label = "95th pct", type = "number")
    ),
    rows = input_rows
  )
}

# Drivers of the primary KPI: Spearman correlation with each input; share = rho^2 / sum(rho^2).
rho <- vapply(inputs, function(inp) values[[sprintf("rank_cor[%s,%s]", pname, inp)]], numeric(1))
keep <- is.finite(rho)
if (any(keep)) {
  idx <- which(keep)
  idx <- idx[order(-abs(rho[idx]), idx)]
  total <- sum(rho[keep]^2)
  tables[[length(tables) + 1]] <- list(
    key = "drivers", title = sprintf("What drives %s", lab(primary)),
    columns = list(list(key = "input", label = "Input", type = "string"), list(key = "rho", label = "Rank correlation ρ", type = "number"),
                   list(key = "share", label = "Share of ρ²", type = "percent")),
    rows = unname(lapply(idx, function(i) list(input = inputs[i], rho = rho[[i]], share = if (total > 0) rho[[i]]^2 / total else NA)))
  )
  charts[[length(charts) + 1]] <- cs_chart(
    "drivers", "importance-bar", sprintf("Rank correlation with %s", lab(primary)),
    list(feature = cs_col("Input", inputs[idx]), importance = cs_col("Spearman ρ", unname(rho[idx]))),
    controls = list(top = 20)
  )
}

# Correlations achieved by Iman–Conover.
if (length(model$correlations)) {
  corr_rows <- list()
  for (cc in model$correlations) {
    got <- cs_sim_rank_cor(draws[[cc$a]], draws[[cc$b]])
    values[[sprintf("achieved_rho[%s,%s]", cc$a, cc$b)]] <- got
    corr_rows[[length(corr_rows) + 1]] <- list(pair = sprintf("%s – %s", cc$a, cc$b), target = as.numeric(cc$rho), achieved = got)
  }
  tables[[length(tables) + 1]] <- list(
    key = "correlations", title = "Rank correlations (target vs achieved)",
    columns = list(list(key = "pair", label = "Inputs", type = "string"), list(key = "target", label = "Target", type = "number"),
                   list(key = "achieved", label = "Achieved", type = "number")),
    rows = corr_rows
  )
}

# %% Save the scenarios
artifacts <- list()
if (TRUE) {
  out <- cs_ml_out_dir("target/academy-parity/run-57623/simulate.monte_carlo/newsvendor-default/out-r")
  path <- file.path(out, "draws.parquet")
  nanoparquet::write_parquet(as.data.frame(c(list(scenario = seq_len(N)), draws), check.names = FALSE), path)
  artifacts <- list(list(key = "draws", path = path, format = "parquet", title = "Simulated scenarios"))
}

# %% Result
label <- lab(primary)
stats_list <- list(
  list(key = "kpi_mean", label = sprintf("Mean %s", label), value = values$kpi_mean),
  list(key = "kpi_sd", label = "SD", value = values$kpi_sd),
  list(key = "kpi_p5", label = "5th percentile", value = values$kpi_p5),
  list(key = "kpi_p95", label = "95th percentile", value = values$kpi_p95)
)
if (!is.na(values$kpi_p_meet)) stats_list <- c(stats_list, list(list(key = "kpi_p_meet", label = "P(meets target)", value = values$kpi_p_meet, format = "percent")))
stats_list <- c(stats_list, list(list(key = "kpi_cvar", label = sprintf("Expected shortfall (%s)", format(ALPHA)), value = values$kpi_cvar)))
cs_publish(list(
  method = "simulate.monte_carlo",
  methodVersion = "1.0.1",
  title = sprintf("Monte Carlo: %s", label),
  engine = cs_engine_info("stats", "jsonlite"),
  n = N,
  summary = sprintf("%s: mean %s, 90%% of %s scenarios between %s and %s.", label, cs_fmt_num(values$kpi_mean), format(N, big.mark = ","),
                    cs_fmt_num(values$kpi_p5), cs_fmt_num(values$kpi_p95)),
  statistics = stats_list,
  tables = tables,
  charts = charts,
  warnings = warnings,
  notes = c(
    sprintf("%s scenarios from the shared random stream (seed %s); inputs by inversion of their distributions%s", format(N, big.mark = ","), format(SEED),
            if (length(model$correlations)) "; rank correlations induced by Iman–Conover." else "."),
    sprintf("Value at risk is the %s quantile on the KPI's bad side; expected shortfall averages the worst %s%% of scenarios.", format(ALPHA), format(round(100 * ALPHA)))
  ),
  artifacts = artifacts,
  values = values
))

Sources

  • Iman RL, Conover WJ (1982). A distribution-free approach to inducing rank correlation among input variables. Communications in Statistics — Simulation and Computation 11(3):311–334.
  • Vose D (2008). Risk Analysis: A Quantitative Guide (3rd ed.). Wiley.
  • Rockafellar RT, Uryasev S (2000). Optimization of conditional value-at-risk. Journal of Risk 2:21–42.

From the CodeSplash method registry · simulate.monte_carlo v1.0.1.