σμimplied vol · KKmax(S−K,0)udβρᵢⱼfat tailsPnL · drawdownyield · TdSₜ = μSₜ dt + σSₜ dWₜC = S·N(d₁) − K·e⁻ʳᵀ·N(d₂)σₚ² = wᵀΣwd₁ = [ln(S/K) + (r + σ²⁄2)T] ⁄ σ√T∂V/∂t + ½σ²S²·∂²V/∂S² + rS·∂V/∂S − rV = 0Sharpe = (Rₚ − R_f) ⁄ σₚVaR₉₉ = μ − 2.33σρ = Cov(X,Y) ⁄ σₓσᵧE[Rₚ] = Σ wᵢ·E[Rᵢ]φ(x) = e^(−x²/2) ⁄ √2πE[Rᵢ] = R_f + βᵢ(E[Rₘ] − R_f)dXₜ = θ(μ − Xₜ)dt + σ dWₜσ²ₜ = ω + α·ε²ₜ₋₁ + β·σ²ₜ₋₁C − P = S − K·e⁻ʳᵀΔ = ∂V/∂S Γ = ∂²V/∂S²p = (e^(rΔt) − d) ⁄ (u − d)rₜ = ln(Pₜ ⁄ Pₜ₋₁)E[Xₜ₊₁ | ℱₜ] = Xₜf* = (bp − q) ⁄ bz = (x − μ) ⁄ σP(N=k) = λᵏe^(−λ) ⁄ k!Θ = −∂V/∂Tν = S·φ(d₁)·√Tmin wᵀΣw s.t. wᵀμ = μ*∫Σ∂∞λ
uantCraft AcademyRoadmapsSkills
Ctrl K
AO
+1.2k Learners
LoginJoin ↗
RoadmapsSkills
AO
+1.2k Learners
Login
  • English
  • Français
  • Español
  • العربية
  • Português
  • Deutsch
  • 日本語
  • 中文
σμimplied vol · KKmax(S−K,0)udβρᵢⱼfat tailsPnL · drawdownyield · TdSₜ = μSₜ dt + σSₜ dWₜC = S·N(d₁) − K·e⁻ʳᵀ·N(d₂)σₚ² = wᵀΣwd₁ = [ln(S/K) + (r + σ²⁄2)T] ⁄ σ√T∂V/∂t + ½σ²S²·∂²V/∂S² + rS·∂V/∂S − rV = 0Sharpe = (Rₚ − R_f) ⁄ σₚVaR₉₉ = μ − 2.33σρ = Cov(X,Y) ⁄ σₓσᵧE[Rₚ] = Σ wᵢ·E[Rᵢ]φ(x) = e^(−x²/2) ⁄ √2πE[Rᵢ] = R_f + βᵢ(E[Rₘ] − R_f)dXₜ = θ(μ − Xₜ)dt + σ dWₜσ²ₜ = ω + α·ε²ₜ₋₁ + β·σ²ₜ₋₁C − P = S − K·e⁻ʳᵀΔ = ∂V/∂S Γ = ∂²V/∂S²p = (e^(rΔt) − d) ⁄ (u − d)rₜ = ln(Pₜ ⁄ Pₜ₋₁)E[Xₜ₊₁ | ℱₜ] = Xₜf* = (bp − q) ⁄ bz = (x − μ) ⁄ σP(N=k) = λᵏe^(−λ) ⁄ k!Θ = −∂V/∂Tν = S·φ(d₁)·√Tmin wᵀΣw s.t. wᵀμ = μ*∫Σ∂∞λ
uantCraft AcademyRoadmapsSkills
Ctrl K
AO
+1.2k Learners
LoginJoin ↗
RoadmapsSkills
AO
+1.2k Learners
Login
  • English
  • Français
  • Español
  • العربية
  • Português
  • Deutsch
  • 日本語
  • 中文
QuantLib skill›Module 3 · Curves, instruments and engines›Topic 3.4·~1 hrAdvanced

Monte Carlo and finite-difference engines

Skill positionModule 3 of 5 · Topic 4 of 4
3.4 Monte Carlo and finite-difference engines
—Lab score— / 100Total XP—Streak—
Lecture0% read

10 min readCode examples: 5

  1. 01Pricing by simulation
  2. 02From paths to a price
  3. 03Pricing on a grid
  4. 04One option, three engines
  5. 05Options on real SPY
  6. 06What you will build

On 21 August 2026 a one-year at-the-money call on SPY has an exact price of 49.31 from the formula of topic 5. A simulation of 20,000 random paths gives 49.48 with a standard error of 0.48, and a grid of finite differences gives 49.16. Three engines, one instrument. Now the options that have no formula: an American put, which can be exercised at any time, costs 30.93 against 28.95 for the European put, and an Asian call, which pays on the average price of the year, costs 27.66. The first needs a grid, the second needs paths. This topic writes both engines and swaps them under the same option.

01

Pricing by simulation

Where we are. In topic 5 the engine was a formula, and in topic 7 you learned to swap engines under an instrument. A formula exists only for simple payoffs. An option that depends on the whole path of the price, such as one on the average price, has none. The method that always works is Monte Carlo: simulate many random futures of the share, compute what the option would pay in each, and take the discounted average. The law of large numbers makes the average converge to the price.

The share is simulated with the model that stands behind the Black-Scholes-Merton formula, geometric Brownian motion. Time up to expiry is cut into steps equal dates. At each date the log-price changes by a drift, (r − q − σ²/2) dt, plus a random shock, σ √dt times a standard normal number z. Each path is a row of prices, one per date; paths rows make the sample. The random numbers come from numpy's generator, started with a seed: the same seed gives the same paths, which makes a simulation repeatable and testable.

S(k+1) = S(k) × exp( ( r − q − σ²/2 ) dt + σ √dt × z ), dt = T ÷ steps(1)S(k) is the price after k steps, r the interest rate, q the dividend yield, σ the volatility, T the time to expiry and z a draw from the standard normal distribution

Worked example 1. *Problem:* simulate 3 paths with 4 steps over one year for a share at 100 with a rate of 5%, a dividend yield of 2% and a volatility of 0. Then simulate 100,000 one-step paths with a volatility of 20% and compare the mean of the final price and the volatility of the log-return with their theory. *Plan:* use simulate_paths. *Steps:* below.

main.pyPython
paths = simulate_paths(100.0, 0.05, 0.02, 0.0, 1.0, 4, 3, 1)1print(paths.shape, [round(float(x), 4) for x in paths[0]])big = simulate_paths(100.0, 0.05, 0.02, 0.2, 1.0, 1, 100000, 11)2print(round(big[:, -1].mean(), 3), round(100.0 * math.exp(0.03), 3), round(float(np.log(big[:, -1] / 100.0).std()), 4))
(3, 5) [100.0, 100.7528, 101.5113, 102.2755, 103.0455]
103.042 103.045 0.2001
  1. 1No volatility: no randomness; the share grows at rate − dividend.
  2. 2100,000 paths of one step, to test the generator.

*Check:* the shape is (3, 5): 3 paths, the start and 4 steps. With no volatility the first path is [100.0, 100.7528, 101.5113, 102.2755, 103.0455], the same for every path, a growth of 3% a year in four steps. With a volatility of 20% the mean final price is 103.042 against the theory 103.045, and the standard deviation of the log-return is 0.2001. *What to notice:* the drift r − q − σ²/2 has the σ²/2 so that the *mean* of the price (not of its logarithm) grows at r − q.

02

From paths to a price

Each path gives one payoff. A call pays max(price − strike, 0) and a put max(strike − price, 0). What price counts depends on the style. An European option looks at the last price of the path. An Asian option looks at the average of the prices on the monitoring dates, so it needs the whole path; the start is not a monitoring date. The Monte Carlo price is the discounted mean of the payoffs. Its standard error, the sample standard deviation divided by √n and discounted, says how far the estimate is likely to be from the truth: about two thirds of the time within one standard error, and 95% within two.

price ≈ e^(−rT) × mean( payoff_i ), error = e^(−rT) × std( payoff_i ) ÷ √n(2)payoff_i is the payoff on path i, n the number of paths, std the sample standard deviation and T the time to expiry

Worked example 2. *Problem:* price a one-year at-the-money call (spot 100, rate 5%, dividend yield 2%, volatility 20%) as a European and as an Asian option, with 40,000 weekly paths, and compare the first with the formula. Then see how the error shrinks when the number of paths grows from 1,000 to 64,000. *Plan:* use simulate_paths, path_payoffs and mc_estimate. *Steps:* below.

main.pyPython
paths = simulate_paths(100.0, 0.05, 0.02, 0.2, 1.0, 52, 40000, 3)for style in ("european", "asian"):    price, error = mc_estimate(path_payoffs(paths, 100.0, "call", style), 0.05, 1.0)1    print(style, round(price, 3), round(error, 3))2print(round(bsm_price(100.0, 100.0, 0.05, 0.02, 0.2, 1.0, "call"), 4))3for count in (1000, 4000, 16000, 64000):    sample = simulate_paths(100.0, 0.05, 0.02, 0.2, 1.0, 1, count, 3)    price, error = mc_estimate(path_payoffs(sample, 100.0, "call", "european"), 0.05, 1.0)4    print(count, round(price, 3), round(error, 3))
european 9.165 0.069
asian 5.234 0.038
9.227
1000 9.679 0.446
4000 9.417 0.218
16000 9.291 0.109
64000 9.274 0.055
  1. 1The payoffs of each style, then the estimate.
  2. 2Price and standard error.
  3. 3The formula, for the European call.
  4. 4The error for more and more paths.

*Check:* the European call is 9.165 with a standard error of 0.069, within one error of the formula, 9.227. The Asian call is 5.234 with an error of 0.038: much cheaper, because the average of a path moves less than its last price. With 1,000, 4,000, 16,000 and 64,000 paths the errors are 0.446, 0.218, 0.109 and 0.055. *What to notice:* each factor of 4 in the number of paths halves the error. Simulation is slow to converge, but its error does not depend on how complicated the payoff is.

03

Pricing on a grid

A second family of engines solves the pricing equation. Under the same model the price of an option, as a function of the share price S and the time to expiry τ, follows a partial differential equation. It says that the option's value changes with time because of the curvature of the price in S (the volatility term), the drift of the share, and the discount. The equation is solved on a grid of share prices from 0 to a high value s_max. At expiry the value is the payoff. Then it is stepped back in time, one dt at a time, and at each step the grid values satisfy a system of linear equations with only three diagonals, which is solved in a few operations.

∂V/∂τ = ½ σ² S² ∂²V/∂S² + ( r − q ) S ∂V/∂S − r V(3)V is the option value, S the share price, τ the time to expiry, σ the volatility, r the interest rate and q the dividend yield; at τ = 0 the value is the payoff

The second derivative and the first derivative on the grid are replaced by differences of the neighbours: (V(j+1) − 2V(j) + V(j−1)) ÷ ds² and (V(j+1) − V(j−1)) ÷ (2 ds). The implicit scheme takes the differences at the new time step, which makes it stable for any step size. At the two ends of the grid the value is known: a call is worth nothing at 0 and about S − K discounted at s_max; a put is worth the discounted strike at 0 and nothing at s_max. The price for the actual share price is read by linear interpolation between the two nearest nodes.

An American option may be exercised at any time. Its value can never be below the payoff, so after each step the grid values are raised to the payoff where they fall below it, max(value, payoff). This one line is all the engine needs for early exercise; Monte Carlo cannot do it simply. An American call on a share with no dividend is never exercised early, which is a useful test.

Worked example 3. *Problem:* price the one-year at-the-money call of example 2 on grids of 50, 100, 200 and 400 points and steps, and compare with the formula. Then, for a share at 100 with no dividend, price the European and the American put on a grid of 200 and compare the first with its formula. Finally price an American put at spot 70 (strike 100). *Plan:* use fd_price. *Steps:* below.

main.pyPython
for steps in (50, 100, 200, 400):    print(steps, round(fd_price(100.0, 100.0, 0.05, 0.02, 0.2, 1.0, "call", False, steps, steps), 4))1european = fd_price(100.0, 100.0, 0.05, 0.0, 0.2, 1.0, "put", False, 200, 200)american = fd_price(100.0, 100.0, 0.05, 0.0, 0.2, 1.0, "put", True, 200, 200)print(round(european, 4), round(american, 4), round(bsm_price(100.0, 100.0, 0.05, 0.0, 0.2, 1.0, "put"), 4))2print(round(fd_price(70.0, 100.0, 0.05, 0.0, 0.2, 1.0, "put", True, 200, 200), 4))3
50 9.3572
100 9.177
200 9.2118
400 9.2218
5.559 6.0674 5.5735
30.0
  1. 1Finer and finer grids.
  2. 2European, American, and the formula for the European.
  3. 3Deep in the money: exercise at once.

*Check:* the call prices are 9.3572, 9.177, 9.2118 and 9.2218 for the four grids, against 9.227 from the formula: the error falls from about 0.13 to 0.005, though not smoothly, because the spot falls between grid nodes in different places. The European put is 5.559 and the formula says 5.5735. The American put is 6.0674, half a unit more: the value of the right to exercise early. With the share at 70 the American put is worth 30.0, the payoff 100 − 70, which means: exercise at once. *What to notice:* the grid is another approximation, with its own error that falls as the grid is refined; the simulation error falls with more paths.

04

One option, three engines

The engines of this topic follow the design of topic 7. Each one registers with the four quotes (spot, rate, dividend yield and volatility), so a change of any of them marks the option out of date. Each takes an option with its strike, t, kind and style, and returns a price. The simulation engine also keeps the standard error of its last price. Swapping the engine under the same option is one line, and the three answers can be compared.

Worked example 4. *Problem:* give one at-the-money call (spot 100, rate 5%, dividend yield 2%, volatility 20%) the formula engine, then the simulation engine with 40,000 paths, then the finite-difference engine on a grid of 200, and read its price each time. *Plan:* use BSMEngine, MCEngine, FDEngine and set_pricing_engine. *Steps:* below.

main.pyPython
spot, rate = SimpleQuote(100.0), SimpleQuote(0.05)div, vol = SimpleQuote(0.02), SimpleQuote(0.2)option = Option(100.0, 1.0, "call")for engine in (BSMEngine(spot, rate, div, vol), MCEngine(spot, rate, div, vol, 52, 40000, 3), FDEngine(spot, rate, div, vol, 200, 200)):    option.set_pricing_engine(engine)1    print(type(engine).__name__, round(option.NPV(), 4))2
BSMEngine 9.227
MCEngine 9.1648
FDEngine 9.2118
  1. 1A new engine, same option.
  2. 2The price of that engine.

*Check:* the engines print BSMEngine 9.227, MCEngine 9.1648 and FDEngine 9.2118. The simulation is within its error of 0.069 of the formula and the grid is within 0.015. *What to notice:* for this option you would use the formula, since it is exact. The other two matter for the options the formula cannot price, and now you have seen that they agree with it where it can.

05

Options on real SPY

Worked example 5. *Problem:* take the last day of the data: the SPY close as spot and as strike, the 1-year Treasury yield as the rate, a dividend yield of 1.3%, and the volatility of the previous year. Price the one-year European call with the three engines, the European put with the formula and the grid, the American put with the grid, and the Asian call with the simulation. *Plan:* study builds the quotes, the engines and the options. *Steps:* below.

main.pyPython
out = study(load_data())print(round(out["vol"], 4), round(out["bsm_call"], 3), round(out["mc_call"], 3), round(out["mc_error"], 3), round(out["fd_call"], 3))1print(round(out["bsm_put"], 3), round(out["fd_put"], 3), round(out["fd_american_put"], 3))2print(round(out["asian_call"], 3), round(out["asian_error"], 3))3
0.1287 49.305 49.484 0.48 49.161
28.95 28.808 30.929
27.66 0.269
  1. 1The call by the three engines.
  2. 2The put, and the American put.
  3. 3The Asian call and its error.

*Check:* the volatility is 0.1287. The call is 49.305 by the formula, 49.484 by simulation with an error of 0.48, and 49.161 by finite differences. The European put is 28.95 by the formula and 28.808 on the grid, and the American put 30.929: the right to exercise early adds about 2.1, because with the 1-year rate at 4.5% there is interest to earn on the strike. The Asian call is 27.66 with an error of 0.269. *What to notice:* the grid is off by 0.14 on the call, the simulation by 0.18; each engine has its own kind of error, and the formula is the reference you check them against.

Fix the seed, but know the error

A simulation with a fixed seed gives the same answer every time, which is what a test needs, but the answer is still one random sample. Another seed gives another price within the standard error. Never read digits beyond the error: here 49.484 means 49.5 give or take 0.5. A finite-difference price has no randomness but has a discretisation error that depends on the grid, and the boundary at s_max must be far from the spot, or the edge pollutes the price.

  • NameQuestion it answers
  • simulate_paths(spot, rate, div, vol, t, steps, paths, seed)What could the share do?QuantLib: GeometricBrownianMotionProcess and PathGenerator
  • path_payoffs(paths, strike, kind, style)What does the option pay on each path?QuantLib: Payoff and the exercise
  • mc_estimate(payoffs, rate, t)What is the price, and how sure are we?QuantLib: MCEuropeanEngine.errorEstimate()
  • MCEngine(spot, rate, div, vol)Prices any payoff by simulationuses simulate_pathsQuantLib: MCEuropeanEngine
  • fd_price(spot, strike, rate, div, vol, t, kind, american, s_steps, t_steps)What does the grid say?uses solve_tridiagonalQuantLib: FdBlackScholesVanillaEngine
  • FDEngine(spot, rate, div, vol)Prices a European or American option on a griduses fd_priceQuantLib: FdBlackScholesVanillaEngine
What the real data saysA one-year at-the-money option on SPY on 21 August 2026, priced with three engines; the volatility is that of the previous year, 12.9%
Call, formula and simulation49.30549.484 ± 0.48 by simulation
Call, finite differences49.1610.14 below the formula
American put against European put+1.9830.929 against 28.95
Asian call27.66about 44% below the European call

Key takeaways

  • Simulation prices any payoff. Simulate paths, take the payoff of each, discount the mean; the standard error says how far the answer may be from the truth.
  • The error falls with the square root of the paths. Four times the paths for half the error; a fixed seed makes the sample repeatable, not exact.
  • A grid prices early exercise. Solve the pricing equation backwards from the payoff, and take max(value, payoff) at each step for an American option.
  • The engine is the part you swap. The same option takes the formula, the simulation or the grid, and each engine registers with the quotes it reads.
Quick check
Your turn. A Monte Carlo price has a standard error of 0.40 with 10,000 paths. About how many paths bring the standard error to 0.10?
Pick an answer.
06

What you will build

The lab follows the lecture. Task 1 simulates random paths of a share, task 2 takes the payoff of an option on each path, and task 3 turns the payoffs into a price and a standard error. Task 4 is the engine that prices an option by simulation. Task 5 prices an option on a grid, with early exercise, and task 6 is the engine for it. Task 7 prices options on the last real day of SPY with the formula, the simulation and the grid.

Next topic: Implied volatility surfaces. So far one volatility was enough, either historical or typed in. The market quotes the options for many strikes and expiries, and each price has its own implied volatility. Next you build a surface of implied volatilities from quotes of options, interpolate it, and let the pricing engines read their volatility from the surface instead of one number.

Lab · what's graded

7 tasks · 100 pts
  • Random paths10 pts
  • Payoffs8 pts
  • The estimate8 pts
  • The simulation engine14 pts
  • Finite differences28 pts
  • The grid engine10 pts
  • Options on SPY22 pts
Explorer · lab-sqt-09
▾ lab-sqt-09
▾ data
…
bash · in-browser
learner@quantcraft:~/lab-sqt-09$
Python not loaded yetPythonLn 1, Col 1Spaces: 4UTF-8

Reset this topic?

Everything in lab-sqt-09 goes back to the starter files and the terminal is cleared. Your current solution will be lost — this can't be undone.

Will be reset
  • main.py → starter code
  • Terminal history and test output
  • Unsubmitted changes
Will be kept
  • Best lab score
  • Your XP and streak
  • Lecture progress and notes