Skip to content

Monte Carlo simulation

Draw thousands of futures from your inputs to see the range of outcomes, and find out why the plan built on averages misleads.

Applied ~12 min8 steps

What runs in CodeSplash

You will be able to

  • Explain Monte Carlo simulation as repeated draws through a model
  • Show why the average outcome differs from the outcome at average inputs
  • Judge simulation error, and account for correlated inputs

Read first

01

Many futures

Read

Monte Carlo simulationMonte Carlo simulationRuns a model many times with inputs drawn at random, so you see a range of outcomes instead of one number. replaces each uncertain input with a distribution. It then repeats three steps:

  1. Draw a value for every input.
  2. Run the model.
  3. Record the KPI.

After thousands of draws, you have a distribution of outcomes.

Here, demand is normal, with mean 1,000 and SD 200. Price is triangular, from 9 to 12. You order 1,100, at a cost of 6 each.

02

Will the average match the plan?

Predict

Predict first

At average demand and price, the model gives a profit of 3,733. What will the average profit across all the simulated futures be?

About the same as the planLower than the planHigher than the plan
Reveal

3,357, which is lower. You can't sell more than you stocked, so high demand gains little and low demand costs a lot. That one kink is enough to break the plan: the outcome at average inputs isn't the average outcome.

03

Bend it yourself

Explore

DExplorable · Monte Carlo risk and the flaw of averages

If you plan on average demand and average price, how wrong can the average plan be?

Compared with plugging in average demand and price, will the average simulated profit be…

How sure?
250
2.0
1000

You can't sell more than you can make.

5000
plug-in 2000average 1186break even

Commit your prediction above to see the result

Make your prediction first; the figure appears when you commit.

Make your prediction to see the result.

Raise the demand uncertainty, with capacity held fixed. The gap between the average plan and the simulated average widens. Now raise capacity far above demand. What happens to the gap once the limit stops mattering?

04

Read the result

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,
})

Across 5,000 simulated futures, profit averages 3,357, with SD 1,653. Ninety percent of the outcomes fall between 167 and 5,599.

The median, 3,694, is above the mean: the distribution has a long tail of poor outcomes.

Rank correlations on the card show which inputs drive the KPI. Here, demand matters most.

05

How many draws?

Checkpoint

A simulated mean has error of its own, about SD/n\text{SD} / \sqrt{n}.

Check yourself

With SD = 1652.8 and n = 5,000, what is the standard error of the simulated mean? Give one decimal.

Show the answer

Answer: 23.3734404526836

/ √5,000 = . That's small next to the gap of about 376 between the plan and the simulated mean. Quadrupling the draws would halve it.

Check yourself

You raise the number of scenarios from 5,000 to 500,000. What improves?

Show the answer

Answer: a

More draws reduce simulation error only. If the inputs or formulas are wrong, you get a very precise wrong answer.

06

Inputs that move together

Predict

Predict first

A price rise tends to reduce demand. Revenue is price × demand. With a negative correlation between the two, how would treating them as independent mislead you about the spread of revenue?

It makes no differenceTreating them as independent understates the riskTreating them as independent overstates the risk
Reveal

Here it overstates the spread, because a high price tends to come with low demand, and those partly offset. With positive correlations, independence understates risk. The studio's model can hold correlations between inputs, and the card reports the rank correlation it achieved.

07

Reproduce it

In the app

In Scenarios & optimization, open the Simulate step and press Run. Fixing the seed makes reruns identical, in Python and in R, because they share one random stream.

Python
import numpy as np

rng = np.random.default_rng(3)
n = 5000
demand = np.clip(rng.normal(1000, 200, n), 0, None)
price = rng.triangular(9, 10, 12, n)
order = 1100

profit = price * np.minimum(demand, order) - 6 * order
print(profit.mean(), np.quantile(profit, [0.05, 0.5, 0.95]), (profit >= 0).mean())
R
set.seed(3)
n <- 5000
demand <- pmax(rnorm(n, 1000, 200), 0)
u <- runif(n)
price <- ifelse(u < 1 / 3, 9 + sqrt(3 * u), 12 - sqrt(6 * (1 - u)))  # triangular(9, 10, 12)
order <- 1100

profit <- price * pmin(demand, order) - 6 * order
c(mean(profit), quantile(profit, c(0.05, 0.5, 0.95)), mean(profit >= 0))

These scripts use each language's own random generator, so their numbers differ slightly from each other and from CodeSplash's.

08

Recap

Recap
  • Simulation pushes distributions through a model, and gives a distribution back.
  • With a limit in the model, the outcome at average inputs isn't the average outcome.
  • More draws only reduce simulation error. They can't fix a wrong model.
  • Say how inputs move together.

Concepts in this lesson