Skip to content
Tutorials Center
My learning

Topics

Lesson 36 of 40 · Projects

Project: Monte Carlo Estimation

Estimate pi and price a stock option with Monte Carlo simulation in Julia: random numbers, standard error, variance reduction and multi-threading.

Monte Carlo methods answer hard questions by random sampling. To find the area of a shape you throw random points at a box and count how many land inside. To price a financial option you simulate thousands of possible futures and average the payoff. The method is simple, it works in any number of dimensions, and it is a perfect fit for Julia: the inner loop is plain numeric code that compiles to fast machine code, and independent samples are easy to run on several threads.

In this project you will estimate π, learn how the error shrinks with the number of samples, price a European call option and check it against the exact formula, and then split the work across threads. Julia is not installed on this site, so the Julia code is read-only; NumPy ports run here. The ports use NumPy's random generator, so their random digits differ from Julia's, but the behavior, including the error sizes, is the same. The background is in Random Numbers and Statistics and Threads, Tasks and Distributed Computing.

Monte Carlo in four steps

Sample Draw random inputs.
Evaluate Compute a result for each draw.
Average The mean estimates the answer.
Error bar Standard error says how much to trust it.
1 / 2

Estimating pi

Draw a point (x, y) with both coordinates uniform in [0, 1). It lies inside the quarter circle of radius 1 when x² + y² ≤ 1. The quarter circle has area π/4 and the square has area 1, so the fraction of points inside is about π/4. Multiply by 4 to estimate π.

JULIA
using Random

function estimate_pi(n; rng = Xoshiro(2024))
    inside = 0
    for _ in 1:n
        x = rand(rng)
        y = rand(rng)
        inside += (x^2 + y^2 <= 1)     # a Bool adds as 0 or 1
    end
    return 4 * inside / n
end

estimate_pi(1_000_000)    # about 3.14, the exact digits depend on the generator

The loop is deliberately scalar: no arrays are allocated, the types are known (Int and Float64), and the compiler produces a tight loop. In NumPy the same idea would be vectorized, because a Python-level loop would be far too slow. Julia lets you choose; the vectorized form is also valid and shorter, but allocates two arrays of length n:

JULIA
estimate_pi_vec(n) = 4 * count(rand(n) .^ 2 .+ rand(n) .^ 2 .<= 1) / n

Passing the generator as a keyword argument (rng) is a good habit: it makes runs reproducible, and a function can be given its own independent generator, which matters for threads below.

How accurate is it?

Each point is a coin flip that lands inside with probability p = π/4. The estimate is 4 times an average of n such flips, so its standard error is 4 √(p(1-p)/n) ≈ 1.64/√n. To get one more correct digit you need 100 times as many samples. The port prints the actual error next to this scale for three sample sizes:

Python Estimating pi and the error

Press Run (or Ctrl + Enter) to see the result here.

Program input · what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

The actual error is a random number, so it bounces around the "expected scale": sometimes below it, sometimes a bit above, and its typical size shrinks by about ten times when n grows by a hundred. That square-root law is why Monte Carlo is a tool of last resort for π (there are far better formulas) but a first choice for problems with many dimensions, where grids are impossible.

Pricing an option

A European call option gives its owner the right to buy a stock at a strike price K at time T. The payoff at the end is max(S_T - K, 0): nothing if the stock finishes below the strike, otherwise the difference. A common model says the stock price follows geometric Brownian motion, so the price at time T is

Text
S_T = S0 · exp((r − σ²/2)·T + σ·√T·Z)

where Z is a standard normal random number, r is the interest rate and σ the volatility. The option's fair price today is the average payoff, discounted by exp(−r·T). This model is a textbook simplification, not trading advice.

JULIA
using Random, Statistics, Distributions

# the exact Black–Scholes price, to check the simulation against
function bs_call(S0, K, r, σ, T)
    d1 = (log(S0 / K) + (r + σ^2 / 2) * T) / (σ * sqrt(T))
    d2 = d1 - σ * sqrt(T)
    N = Normal()
    return S0 * cdf(N, d1) - K * exp(-r * T) * cdf(N, d2)
end

function mc_call(S0, K, r, σ, T, n; rng = Xoshiro(42))
    z = randn(rng, n)
    ST = @. S0 * exp((r - σ^2 / 2) * T + σ * sqrt(T) * z)
    payoff = @. max(ST - K, 0)
    disc = exp(-r * T)
    price = disc * mean(payoff)
    stderr = disc * std(payoff) / sqrt(n)
    return price, stderr
end

S0, K, r, σ, T = 100.0, 105.0, 0.05, 0.2, 1.0
bs_call(S0, K, r, σ, T)               # 8.0214
price, se = mc_call(S0, K, r, σ, T, 1_000_000)
println("MC price = ", round(price, digits = 3), " ± ", round(se, digits = 3))

The @. macro puts a dot on every operation in the expression, so each line is one fused broadcast. Always report the standard error next to a Monte Carlo number. A price of 8.03 alone is incomplete; 8.03 ± 0.013 tells the reader how many digits to trust, and the exact formula lets you confirm that the true value lies within a few standard errors.

A variance-reduction trick

If Z is a valid draw, so is −Z. Using both (antithetic variates) pairs a high payoff with a low one, so their average has less noise. Averaging each pair first, and then taking the standard error of the pair averages, gives the same cost in random numbers for a smaller error. Variance reduction is the main way practitioners get a better answer without simulating more paths.

Python Option pricing against the exact formula

Press Run (or Ctrl + Enter) to see the result here.

Program input · what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

For this option the antithetic pairs cut the standard error by about a fifth (0.0105 against 0.0132 for a million plain draws) at the same number of random numbers; the gain depends on the payoff. Your exact digits depend on the seed, but the standard errors follow the same pattern. In Julia the same code gives different random digits and the same story.

Parallelism with threads

The draws are independent, so we can give each thread its own share. Start Julia with several threads (julia -t 4, or -t auto) and check Threads.nthreads(). Two rules keep the answer correct:

  1. Each task needs its own random generator. Sharing one generator between threads would be a data race. Julia's default rand() is already safe, because each task has its own generator. For reproducible results, create explicit generators with different seeds.
  2. Each thread writes only its own slot. Collect one count per thread in an array and add them at the end. Never update one shared counter from all threads without protection.
JULIA
using Base.Threads, Random

function estimate_pi_threaded(n)
    nt = nthreads()
    per_thread = n ÷ nt
    counts = zeros(Int, nt)

    @threads :static for t in 1:nt
        rng = Xoshiro(1000 + t)          # an independent stream per thread
        c = 0
        for _ in 1:per_thread
            x = rand(rng)
            y = rand(rng)
            c += (x^2 + y^2 <= 1)
        end
        counts[t] = c                    # each thread writes its own element
    end

    return 4 * sum(counts) / (per_thread * nt)
end

estimate_pi_threaded(10_000_000)

The :static schedule pins each iteration to one thread, which is what you want when the iterations are equally expensive. Another way to run the same pattern is with tasks: @spawn one task per chunk and fetch the counts. With four threads this version can process about four times as many points per second, as long as the loop body does no allocation (an allocating loop makes threads wait for the garbage collector). Time it with @btime to see your machine's speedup (Debugging and Profiling).

Python threads would not help here, because of the global interpreter lock, and the browser cannot start processes. This stand-in shows the structure of the parallel version: independent random streams, one count per worker, and a combine step at the end. Numpy's SeedSequence.spawn gives each worker a statistically independent stream, the equivalent of the per-thread Xoshiro generators above:

Python Independent streams per worker

Press Run (or Ctrl + Enter) to see the result here.

Program input · what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

Going further

  • Estimate the error of a threaded run by computing the estimate on each thread and taking the spread of the thread estimates.
  • Control variates: subtract a correlated quantity whose mean you know exactly, such as S_T itself with mean S0·exp(r·T), to reduce variance.
  • Path-dependent options (Asian or barrier options) need the whole price path, not just the end. Simulate steps increments per path and use a matrix of shape (steps, paths); broadcasting and cumsum do the rest.
  • Quasi-Monte Carlo uses low-discrepancy sequences (the Sobol.jl package) that fill the space more evenly than random points.
  • Turn your pieces into a small package with tests: check that estimate_pi is within five standard errors of π for a fixed seed (Project: A Small Generic Package).

Check your understanding

Quick check · 5 questions

of 5 answered You scored / 5 · perfect!

  1. 1. If you want one more correct decimal digit of a Monte Carlo estimate, roughly how many more samples do you need?

    The error shrinks like 1/sqrt(n), so a ten-fold smaller error needs a hundred times more samples.
  2. 2. Why should a Monte Carlo result be reported with its standard error?

    A single estimate is random. The standard error describes the typical size of its noise.
  3. 3. In the threaded version, why does each thread create its own Xoshiro generator?

    A generator has mutable state. Separate generators with different seeds give independent streams and reproducible results.
  4. 4. What do antithetic variates do?

    A high payoff from Z tends to pair with a low payoff from -Z, so their average is steadier than two independent draws.
  5. 5. Which pattern is safe for counting in parallel?

    Separate slots have no overlap, so no two threads write the same memory. The combine step happens after the threads finish.

Summary

  • Monte Carlo estimates a quantity as the average over random samples; the standard error shrinks like 1/√n.
  • Pass an rng argument for reproducibility, keep the inner loop allocation-free, and always report the error with the estimate.
  • Option pricing simulates S_T, averages the discounted payoff, and can be verified against the Black–Scholes formula.
  • Variance reduction, such as antithetic variates, gives a smaller error for the same number of random draws.
  • Threads need independent generators and separate output slots; combine the results after the loop.

Next: test yourself with Practice Exercises with Solutions.