Read the tail
Describe risk with the chance of a target, value at risk and expected shortfall, and choose among options that trade average against tail.
What runs in CodeSplash
- Monte Carlo simulation of a scenario model Verified in Python and R
You will be able to
- Compute and read the chance of meeting a target
- Tell value at risk from expected shortfall
- Compare options on average and tail together
Read first
Two plans with the same average
ReadSuppose two plans each average a profit of 3,000. One always earns close to that. The other often earns 8,000, and sometimes loses 5,000.
An average can't tell them apart, so you need more numbers. Three are common:
- The chance of meeting a target, such as making any profit at all.
- Value at riskValue at riskThe outcome you would only do worse than in a small share of cases, such as the worst 5%.: the outcome you'd only do worse than in a small share of cases.
- Expected shortfallConditional value at riskThe average outcome within the worst cases. Unlike VaR, it sees how bad the tail gets. (CVaR): the average within those worst cases.
Which is worse?
PredictPredict first
Take the worst 5% of simulated profits in the stocking model. Which number will be lower: value at risk, or expected shortfall?
Reveal
Expected shortfall. Value at risk is the edge of the tail: 167. Expected shortfall averages everything past that edge: −653. So at the edge you still make a profit, yet the tail's average is a loss.
Find them on the card
In the appProfit: 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
View data
| Bin end | Profit | Scenarios |
|---|---|---|
| −3205.68 | −3456.08 | 2 |
| −2955.28 | −3205.68 | 0 |
| −2704.89 | −2955.28 | 0 |
| −2454.49 | −2704.89 | 6 |
| −2204.09 | −2454.49 | 3 |
| −1953.69 | −2204.09 | 4 |
| −1703.29 | −1953.69 | 10 |
| −1452.89 | −1703.29 | 16 |
| −1202.49 | −1452.89 | 11 |
| −952.09 | −1202.49 | 15 |
| −701.69 | −952.09 | 24 |
| −451.29 | −701.69 | 35 |
| −200.89 | −451.29 | 38 |
| 49.509 | −200.89 | 57 |
| 299.91 | 49.509 | 54 |
| 550.31 | 299.91 | 62 |
| 800.71 | 550.31 | 68 |
| 1051.11 | 800.71 | 93 |
| 1301.51 | 1051.11 | 118 |
| 1551.91 | 1301.51 | 124 |
| 1802.31 | 1551.91 | 175 |
| 2052.71 | 1802.31 | 166 |
| 2303.10 | 2052.71 | 155 |
| 2553.50 | 2303.10 | 211 |
| 2803.90 | 2553.50 | 198 |
| 3054.30 | 2803.90 | 212 |
| 3304.70 | 3054.30 | 212 |
| 3555.10 | 3304.70 | 260 |
| 3805.50 | 3555.10 | 305 |
| 4055.90 | 3805.50 | 360 |
| 4306.30 | 4055.90 | 367 |
| 4556.70 | 4306.30 | 385 |
| 4807.10 | 4556.70 | 328 |
| 5057.50 | 4807.10 | 263 |
| 5307.90 | 5057.50 | 218 |
| 5558.30 | 5307.90 | 166 |
| 5808.70 | 5558.30 | 135 |
| 6059.10 | 5808.70 | 74 |
| 6309.50 | 6059.10 | 44 |
| 6559.90 | 6309.50 | 26 |
View data
| Input | Spearman ρ |
|---|---|
| demand | 0.8692 |
| price | 0.4048 |
KPIs across scenarios
| KPI | Mean | SD | 5th pct | Median | 95th pct | P(meets target) | VaR (0.05) | Expected shortfall |
|---|---|---|---|---|---|---|---|---|
| Profit | 3357.08 | 1652.75 | 167.13 | 3694.37 | 5599.00 | 95.8% | 167.13 | −652.60 |
Uncertain inputs (as drawn)
| Input | Distribution | Mean | SD | 5th pct | 95th pct |
|---|---|---|---|---|---|
| demand | normal | 1004.64 | 201.24 | 671.65 | 1327.74 |
| price | triangular | 10.335 | 0.6260 | 9.398 | 11.454 |
What drives Profit
| Input | Rank correlation ρ | Share of ρ² |
|---|---|---|
| demand | 0.8692 | 82.2% |
| price | 0.4048 | 17.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.
The exact R script · R 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
))
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
| KPI | Mean | SD | 5th pct | Median | 95th pct | P(meets target) | VaR (0.05) | Expected shortfall |
|---|---|---|---|---|---|---|---|---|
| Profit | 3357.08 | 1652.75 | 167.13 | 3694.37 | 5599.00 | 95.8% | 167.13 | −652.60 |
Uncertain inputs (as drawn)
| Input | Distribution | Mean | SD | 5th pct | 95th pct |
|---|---|---|---|---|---|
| demand | normal | 1004.64 | 201.24 | 671.65 | 1327.74 |
| price | triangular | 10.335 | 0.6260 | 9.398 | 11.454 |
What drives Profit
| Input | Rank correlation ρ | Share of ρ² |
|---|---|---|
| demand | 0.8692 | 82.2% |
| price | 0.4048 | 17.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.
The exact Python script · Python 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,
})
The target here is any profit above zero, which 95.8% of simulated futures meet. The tail setting is 5%.
Value at risk says nothing about how bad things get beyond its edge. Two tails can share an edge and differ a lot beyond it, and expected shortfall sees the difference.
When low is good
PredictPredict first
Now the KPI is project cost, with a target it should stay below. Which end of the distribution is the risky tail?
Reveal
The high end. Here, the value at risk is 14,994, and the expected shortfall is 17,292, against a mean of 8,597. The chance of staying below target is 60.4%. The KPI's direction decides which tail is bad.
Project cost: mean 8597.24, 90% of 3,000 scenarios between 3982.94 and 14993.96.
- Mean Project cost
- 8597.24
- SD
- 3397.68
- 5th percentile
- 3982.94
- 95th percentile
- 14993.96
- P(meets target)
- 60.4%
- Expected shortfall (0.05)
- 17291.53
Plots
View data
| Bin end | Project cost | Scenarios |
|---|---|---|
| 2419.02 | 1806.54 | 8 |
| 3031.51 | 2419.02 | 23 |
| 3643.99 | 3031.51 | 62 |
| 4256.47 | 3643.99 | 105 |
| 4868.96 | 4256.47 | 139 |
| 5481.44 | 4868.96 | 191 |
| 6093.92 | 5481.44 | 221 |
| 6706.41 | 6093.92 | 227 |
| 7318.89 | 6706.41 | 224 |
| 7931.37 | 7318.89 | 239 |
| 8543.85 | 7931.37 | 216 |
| 9156.34 | 8543.85 | 209 |
| 9768.82 | 9156.34 | 193 |
| 10381.30 | 9768.82 | 169 |
| 10993.79 | 10381.30 | 140 |
| 11606.27 | 10993.79 | 113 |
| 12218.75 | 11606.27 | 110 |
| 12831.24 | 12218.75 | 73 |
| 13443.72 | 12831.24 | 66 |
| 14056.20 | 13443.72 | 72 |
| 14668.69 | 14056.20 | 32 |
| 15281.17 | 14668.69 | 38 |
| 15893.65 | 15281.17 | 27 |
| 16506.13 | 15893.65 | 27 |
| 17118.62 | 16506.13 | 15 |
| 17731.10 | 17118.62 | 13 |
| 18343.58 | 17731.10 | 10 |
| 18956.07 | 18343.58 | 8 |
| 19568.55 | 18956.07 | 13 |
| 20181.03 | 19568.55 | 1 |
| 20793.52 | 20181.03 | 6 |
| 21406.00 | 20793.52 | 2 |
| 22018.48 | 21406.00 | 2 |
| 22630.96 | 22018.48 | 1 |
| 23243.45 | 22630.96 | 1 |
| 23855.93 | 23243.45 | 1 |
| 24468.41 | 23855.93 | 0 |
| 25080.90 | 24468.41 | 0 |
| 25693.38 | 25080.90 | 0 |
| 26305.86 | 25693.38 | 3 |
View data
| Input | Spearman ρ |
|---|---|
| hours | 0.6953 |
| delay | 0.6169 |
| labour | 0.1464 |
| materials | 0.1030 |
| overrun | 0.0713 |
KPIs across scenarios
| KPI | Mean | SD | 5th pct | Median | 95th pct | P(meets target) | VaR (0.05) | Expected shortfall |
|---|---|---|---|---|---|---|---|---|
| Project cost | 8597.24 | 3397.68 | 3982.94 | 8093.38 | 14993.96 | 60.4% | 14993.96 | 17291.53 |
Uncertain inputs (as drawn)
| Input | Distribution | Mean | SD | 5th pct | 95th pct |
|---|---|---|---|---|---|
| labour | uniform | 49.896 | 5.727 | 41.060 | 58.896 |
| hours | weibull | 87.270 | 45.921 | 22.283 | 170.27 |
| materials | empirical | 139.04 | 26.781 | 90 | 180 |
| delay | exponential | 4.937 | 4.882 | 0.2457 | 14.427 |
| overrun | binomial | 1.529 | 1.127 | 0 | 4 |
What drives Project cost
| Input | Rank correlation ρ | Share of ρ² |
|---|---|---|
| hours | 0.6953 | 53.6% |
| delay | 0.6169 | 42.2% |
| labour | 0.1464 | 2.4% |
| materials | 0.1030 | 1.2% |
| overrun | 0.0713 | 0.6% |
- 3,000 scenarios from the shared random stream (seed 11); 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.
The exact R script · R 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 2602afddb146d3c9
# 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\":\"labour\",\"dist\":\"uniform\",\"params\":{\"min\":40,\"max\":60}},{\"name\":\"hours\",\"dist\":\"weibull\",\"params\":{\"shape\":2,\"scale\":100}},{\"name\":\"materials\",\"dist\":\"empirical\",\"params\":{\"values\":[120,135,150,90,180,140,160]}},{\"name\":\"delay\",\"dist\":\"exponential\",\"params\":{\"rate\":0.2}},{\"name\":\"overrun\",\"dist\":\"binomial\",\"params\":{\"size\":10,\"prob\":0.15}}],\"decisions\":[],\"formulas\":[{\"name\":\"cost\",\"expr\":\"labour * hours + materials * 10 + 500 * delay + 250 * overrun\"}],\"kpis\":[{\"name\":\"cost\",\"label\":\"Project cost\",\"target\":9000,\"direction\":\"below\"}]}")
N <- as.integer(3000)
SEED <- 11
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 (FALSE) {
out <- cs_ml_out_dir("target/academy-parity/run-57623/simulate.monte_carlo/costs-below-target/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
))
Project cost: mean 8597.24, 90% of 3,000 scenarios between 3982.94 and 14993.96.
- Mean Project cost
- 8597.24
- SD
- 3397.68
- 5th percentile
- 3982.94
- 95th percentile
- 14993.96
- P(meets target)
- 60.4%
- Expected shortfall (0.05)
- 17291.53
To keep this page light, the plots are shown once, under the R tab.
KPIs across scenarios
| KPI | Mean | SD | 5th pct | Median | 95th pct | P(meets target) | VaR (0.05) | Expected shortfall |
|---|---|---|---|---|---|---|---|---|
| Project cost | 8597.24 | 3397.68 | 3982.94 | 8093.38 | 14993.96 | 60.4% | 14993.96 | 17291.53 |
Uncertain inputs (as drawn)
| Input | Distribution | Mean | SD | 5th pct | 95th pct |
|---|---|---|---|---|---|
| labour | uniform | 49.896 | 5.727 | 41.060 | 58.896 |
| hours | weibull | 87.270 | 45.921 | 22.283 | 170.27 |
| materials | empirical | 139.04 | 26.781 | 90 | 180 |
| delay | exponential | 4.937 | 4.882 | 0.2457 | 14.427 |
| overrun | binomial | 1.529 | 1.127 | 0 | 4 |
What drives Project cost
| Input | Rank correlation ρ | Share of ρ² |
|---|---|---|
| hours | 0.6953 | 53.6% |
| delay | 0.6169 | 42.2% |
| labour | 0.1464 | 2.4% |
| materials | 0.1030 | 1.2% |
| overrun | 0.0713 | 0.6% |
- 3,000 scenarios from the shared random stream (seed 11); 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.
The exact Python script · Python 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 2602afddb146d3c9
# 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\":\"labour\",\"dist\":\"uniform\",\"params\":{\"min\":40,\"max\":60}},{\"name\":\"hours\",\"dist\":\"weibull\",\"params\":{\"shape\":2,\"scale\":100}},{\"name\":\"materials\",\"dist\":\"empirical\",\"params\":{\"values\":[120,135,150,90,180,140,160]}},{\"name\":\"delay\",\"dist\":\"exponential\",\"params\":{\"rate\":0.2}},{\"name\":\"overrun\",\"dist\":\"binomial\",\"params\":{\"size\":10,\"prob\":0.15}}],\"decisions\":[],\"formulas\":[{\"name\":\"cost\",\"expr\":\"labour * hours + materials * 10 + 500 * delay + 250 * overrun\"}],\"kpis\":[{\"name\":\"cost\",\"label\":\"Project cost\",\"target\":9000,\"direction\":\"below\"}]}"))
N = int(3000)
SEED = int(11)
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 False:
out = csml.out_dir("target/academy-parity/run-57623/simulate.monte_carlo/costs-below-target/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,
})
Check your understanding
CheckpointCheck yourself
Your five worst outcomes out of 100 are −50, −80, −100, −150 and −220. What's the expected shortfall at 5%?
Show the answer
Answer: -120
The average of those five: (−50 − 80 − 100 − 150 − 220) / 5 = −600 / 5 = −120. Value at risk is about −50, the edge of the tail.
Check yourself
Option A has a higher mean and a much worse expected shortfall than option B. Which should you choose?
Show the answer
Answer: c
The analysis shows the trade-off. A business that could absorb A's worst cases might take them. One that couldn't survive them shouldn't.
Check yourself
A report says "value at risk at 5% is −1,000". What can you conclude?
Show the answer
Answer: b
Value at risk marks an edge, and the tail beyond it could be short or long. Pair it with expected shortfall.
Try it
In the appIn Scenarios & optimization, set a target on a KPI in the Model step, then open Simulate. The Risk tail option sets the share of worst cases behind value at risk and expected shortfall.
Simulate the model at a few order sizes, and compare mean and tail at each. A smaller order may give up a little average for a much safer tail.
Recap
Recap- An average hides risk, so also report a target's chance and the tail.
- Value at risk is the tail's edge. Expected shortfall is its average.
- A KPI's direction decides which tail is bad.
- How much tail to accept is a judgment about what you could absorb.
Concepts in this lesson