Build a Monte Carlo engine with NumPy and volatility scaling
Published: 2025-12-13
URL: https://pyquantnews.substack.com/p/monte-carlo-without-the-mystery
Each week, I send out one Python tutorial to help you get started with algorithmic trading, market data analysis, and quant finance. You can subscribe for free. If you need support with code or strategy design, join our network. Youâll instantly join our group chat and get access to the code notebooks. Grab an Alpha Lab membership to get monthly backtested trading strategies.
In todayâs post, youâll simulate GBM price paths and link parameters to clear market intuition. GBM in plain terms Geometric Brownian Motion models a price that grows multiplicatively with a constant drift and constant volatility. Louis Bachelier proposed a Brownian model for prices, and Paul Samuelson popularized lognormal dynamics for compounding growth. Black and Scholes used the model to derive option prices, and Monte Carlo methods carried it into production risk systems.
How pros use it Today, teams use GBM as a baseline generator for pricing tasks and simple scenario analysis. Option desks simulate thousands of paths to estimate expected payoffs, then discount the average to price exotics. Risk teams bump drift or volatility, rerun the engine, and read changes in exposure to spot or variance. Researchers use GBM to validate backtest logic because it isolates code errors without the quirks of historical data.
Why beginners should care Learning GBM teaches controlled experimentation and helps you catch data bugs before touching live markets. You will build intuition for how drift sets direction and how volatility interacts with the chosen time step. You will also learn to seed randomness so runs are reproducible and visual checks reveal mistakes early. Letâs see how it works with Python. Library installation Install numpy and matplotlib so the notebook can simulate and plot GBM paths.
This ensures a clean, reproducible environment regardless of your local setup. If you are running in an environment that already ships these libraries (such as Colab or some IDEs), this command will simply confirm versions. Keeping dependencies minimal lets us focus on modeling choices like time-step units and volatility scaling rather than environment issues. Imports and setup We use numpy for fast vectorized arrays and random draws, and matplotlib.pyplot for quick visual checks of simulated price paths.
Visual checks are a core part of simulation work because they surface unit mismatches early. If you want reproducible runs later, you can set a seed with numpyâs RNG before calling any functions; reproducibility is essential when diagnosing differences across parameter choices. Define simulation parameters and units Set the initial price, annualized volatility, and annualized drift, then define the Monte Carlo grid (paths, daily time step, total horizon). Using delta = 1/252 converts annual inputs into daily increments, and time = 252*5 targets a five-year window.
Locking units up front prevents the classic mistake of feeding annual parameters into daily steps without the proper scaling. Consistent definitions make results interpretable and comparable as you vary drift or volatility. paths controls Monte Carlo precision, so increasing it is how we check convergence of any statistic we care about. Build GBM and helper functions Generate Brownian shocks whose variance matches the chosen time step and whose scale reflects the (annualized) volatility.
Each column is an independent price path, and rows step forward in time. Scaling by sqrt(delta) gives the correct time-step variance, and multiplying by sigma downscales the annual volatility to the per-step level.
This independence-by-path assumption is the default baseline in pricing engines and is ideal for sandbox learning. Vectorized generation keeps the simulation fast enough to run thousands of paths interactively. Convert Brownian shocks into multiplicative GBM returns using the closed-form step of a constant-drift, constant-vol process.
The (mu - 0.5sigma2)delta term applies the ItĂ´ correction so expected log returns line up with the specified drift. Many beginners omit the 0.5*sigma^2 term and end up with biased levels that drift too high. Keeping drift and volatility annualized while applying delta per step is the key to unit consistency.
This block encodes those rules in one place so we can change parameters confidently. Compound the simulated returns from the initial price to produce level paths while ensuring strictly positive prices. We prepend ones so the first row represents the starting point before any move. Working with levels is how option desks and risk teams visualize scenarios and payoffs. GBMâs multiplicative compounding matches how real prices behave and avoids negative levels that plague additive models. Including the initial price makes plots and summary stats easier to interpret.
Run scenarios and visualize paths Simulate paths with a positive drift and compute how many finishes end above the starting price as a quick sanity check. In notebooks this last expression will display and gives a rough sense of the distributionâs tilt under positive drift.
This quick diagnostic connects drift to long-run tendency without overfitting historical quirks. As you scale paths higher, the fraction should stabilize, which is a simple convergence check. Itâs a habit pros use before trusting any simulated payoff estimates. Plot the simulated paths to visually verify unit choices and compounding behavior. Thin lines help us inspect many paths at once.
The result is something that looks like this. Early plots catch mistakes like mismatched time steps or mis-scaled volatility before you burn time on strategy code. Visual checks pair with seeded randomness to make discrepancies obvious when you tweak parameters. Treat these figures as fast feedback loops, not final analyses. Rerun the engine with zero drift to isolate volatilityâs effect and compare to the positive-drift case. Visualizing both back-to-back reinforces how drift sets direction while volatility controls dispersion.
The result is something that looks like this. A zero-drift scenario is a common baseline in pricing and risk because it mirrors a risk-neutral setting for intuition-building. You should see no systematic trend in log space, yet level paths remain positively skewed due to compounding. Use this contrast to validate that your step size and scaling behave as expected. Your next steps Now you can generate GBM price paths with clear units, seeded randomness, and stable time steps, then see how drift and volatility drive outcomes.
Use these paths to validate backtests, spot-check payoff code, and stress simple strategies before you waste hours on noisy historical data.