Skip to content

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.

Applied ~9 min7 steps

What runs in CodeSplash

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

01

Two plans with the same average

Read

Suppose 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.
02

Which is worse?

Predict

Predict first

Take the worst 5% of simulated profits in the stocking model. Which number will be lower: value at risk, or expected shortfall?

Value at risk is lowerExpected shortfall is lowerThey're equal
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.

03

Find them on the card

In the app
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.
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
))
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.
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.

04

When low is good

Predict

Predict first

Now the KPI is project cost, with a target it should stay below. Which end of the distribution is the risky tail?

Its low endIts high end
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.

Monte Carlo: Project costRecorded · Python and R agreeRecorded 2026-11-09 · 48 values compared
R

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

Distribution of Project costAcross all simulated scenarios, how likely is each outcome — and of missing the target?
View data
Bin endProject costScenarios
2419.021806.548
3031.512419.0223
3643.993031.5162
4256.473643.99105
4868.964256.47139
5481.444868.96191
6093.925481.44221
6706.416093.92227
7318.896706.41224
7931.377318.89239
8543.857931.37216
9156.348543.85209
9768.829156.34193
10381.309768.82169
10993.7910381.30140
11606.2710993.79113
12218.7511606.27110
12831.2412218.7573
13443.7212831.2466
14056.2013443.7272
14668.6914056.2032
15281.1714668.6938
15893.6515281.1727
16506.1315893.6527
17118.6216506.1315
17731.1017118.6213
18343.5817731.1010
18956.0718343.588
19568.5518956.0713
20181.0319568.551
20793.5220181.036
21406.0020793.522
22018.4821406.002
22630.9622018.481
23243.4522630.961
23855.9323243.451
24468.4123855.930
25080.9024468.410
25693.3825080.900
26305.8625693.383
Rank correlation with Project costWhich features does the model rely on most?
View data
InputSpearman ρ
hours0.6953
delay0.6169
labour0.1464
materials0.1030
overrun0.0713

KPIs across scenarios

KPIMeanSD5th pctMedian95th pctP(meets target)VaR (0.05)Expected shortfall
Project cost8597.243397.683982.948093.3814993.9660.4%14993.9617291.53

Uncertain inputs (as drawn)

InputDistributionMeanSD5th pct95th pct
labouruniform49.8965.72741.06058.896
hoursweibull87.27045.92122.283170.27
materialsempirical139.0426.78190180
delayexponential4.9374.8820.245714.427
overrunbinomial1.5291.12704

What drives Project cost

InputRank correlation ρShare of ρ²
hours0.695353.6%
delay0.616942.2%
labour0.14642.4%
materials0.10301.2%
overrun0.07130.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
))
Python

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

KPIMeanSD5th pctMedian95th pctP(meets target)VaR (0.05)Expected shortfall
Project cost8597.243397.683982.948093.3814993.9660.4%14993.9617291.53

Uncertain inputs (as drawn)

InputDistributionMeanSD5th pct95th pct
labouruniform49.8965.72741.06058.896
hoursweibull87.27045.92122.283170.27
materialsempirical139.0426.78190180
delayexponential4.9374.8820.245714.427
overrunbinomial1.5291.12704

What drives Project cost

InputRank correlation ρShare of ρ²
hours0.695353.6%
delay0.616942.2%
labour0.14642.4%
materials0.10301.2%
overrun0.07130.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,
})
05

Check your understanding

Checkpoint

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

06

Try it

In the app

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

07

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