Introduction
In the last two post (Feynman-Kac in SageMath and Feynman-Kac in SageMath II) we built a small symbolic layer over SageMath, with an Ito algebra, an SDE1D class, a Girsanov transform and a backward Kolmogorov operator, and used them all to make a conditional expectation and a PDE shake hands.
This post is about what happened when I needed that for real!
At work I had a pricing problem.
Our pricer values commodity Asianlets (single-period arithmetic-average options) using the two moment-matching approximation of Turnbull and Wakeman. It’s fast, it’s industry-standard, but it’s an approximation. Also, I easily could have implemented it incorrectly. So I really needed something to check my price against.
To answer this question, and also provide a validation of the approximation, I needed an independent benchmark that makes the exact same assumptions about the underlying dynamics but doesn’t approximate the distribution of the average price. There is a beautiful one already well-established in the literature: Jan Večeř’s PDE, which collapses the path-dependent Asian option into a 1-dimensional backward PDE. I already had a working, validated Crank-Nicolson engine built in C# and in Python, so I simply plugged in the PDE and my Asian option price agreed with the Turnbull-Wakeman approximation to within a few cents per barrel.
However, I had taken the PDE straight from the paper. I hadn’t derived it myself!
I thought, “what if I didn’t have that paper?“; and “could my Python code figure it out for me?“. So I came up with this plan:
- State the problem: a fully floating ICE Brent Asianlet.
- Use Večeř’s trick to turn the average into a self-financing portfolio.
- Let my
Itoclass compute the Itô quotient that defines Večeř’s state variable. - Change the numeraire with the
GirsanovTransform1Dclass, so that the drift vanishes. - Read off the infinitesimal generator, and hence the PDE, with
backward_kolmogorov. - Finally, hand the PDE to a Crank-Nicolson PDE solver and price the Brent trade.
Pricing the Commodity Asianlet
The test trade I chose was a long call on the monthly average of ICE Brent crude.
- Valuation Date 31 March 2026
- 21 business-day fixings from 1 April to 30 April 2026 (Good Friday on the 3rd of April was not a fixing)
- Equal weights of 1/21.
- Strike of 80 USD/BBL
- Volume of 5,000 BBL.
- Assume a flat forward spot price of 107.39 USD/BBL
- A volatility of 92.86292253114% held at the JUN26 contract level across the whole window.
- Payment on 7 May 2026 with a discount factor of 0.996125331, with year fractions set to ACT/365.
Writing for the fixing dates, the average and the price are straight-forward:
where is the forward measure for the payment date. With deterministic rates, futures and forwards coincide, so under
the futures price is driftless:
Holding one volatility across the window is deliberate. In reality, the fixing volatility can jump when the referenced futures contract rolls, and that produces a covariance structure that no 1-factor model can reproduce. Freezing it means 2MM and Večeř see identical dynamics, so whatever difference is left over is purely the 2MM distributional approximation.
Why 2MM is an Approximation
A sum of correlated lognormals is not lognormal. 2MM pretends it is: it matches the first two moments of ,
and prices with Black-76 using the total log-variance . Everything beyond the second moment, in particular the shape of the tails, is lost. The benchmark’s job is to tell us what that costs.
Večeř’s Trick: Turning an Average into a Portfolio
Here is the idea that makes the whole thing one-dimensional. A futures position costs nothing to enter, so if we hold futures, our gains evolve as
Večeř’s choice is to hold the fraction of fixings still to come:
and after the last fixing. A quick summation by parts shows that
, so if we start with
then
exactly, path by path. The Asian option is now just a call on a self-financing portfolio: it pays .
This step is pure algebra, so plain Sage is enough to check it:
def vecer_q(k, n):
return SR(n - k + 1) / SR(n) # holding on (t_{k-1}, t_k]
for n in range(1, 13):
Fs = [var(f"F_{i}") for i in range(n + 1)]
A = sum(Fs[1:]) / SR(n)
X_T = (Fs[0] - K) + sum(vecer_q(k, n) * (Fs[k] - Fs[k - 1]) for k in range(1, n + 1))
assert expand(X_T - (A - K)) == 0
Nothing stochastic has happened yet! But now things start moving.
Letting the Ito Layer do the Work
The path-dependence is gone, but still depends on
. Večeř’s next move is to measure the portfolio in units of the futures price:
To find we need the Itô quotient rule, and this is exactly where the
Ito class earns its keep. Recall that an Ito(a, b, c) object is a jet, as , and that its multiplication uses
. So multiplying two jets is the Itô product rule:
So we write and let the layer do the bookkeeping.
comes from
ito_lemma_1d:
dF = futures.dX()
d_invF = ito_lemma_1d(1 / f, t, f, dF)
dX = dF * q
Z_jet = (Ito.scalar(x) + dX) * (Ito.scalar(1 / f) + d_invF)
dZ = Z_jet - Ito.scalar(x / f)
mu_Z = SR(dZ.b).subs(x == z * f).simplify_full()
sig_Z = SR(dZ.c[1]).subs(x == z * f).simplify_full()
SageMath returns
Notice where the drift came from. Part of it is the cross term , which is precisely the piece you lose if you differentiate the quotient the way you would in ordinary calculus. That is the whole reason for having the jet algebra.
A bug worth confessing
The first time I ran this cell, it threw KeyError: 1. The coefficient of
had simply vanished.
The culprit was a single line in Ito.__mul__, which kept a coefficient only if ci != 0. For a SageMath symbolic expression, bool(ci != 0) means provably non-zero. Our coefficient is , which is zero whenever
, so Sage (quite correctly) could not prove it non-zero, and the term was silently dropped. The
assume(...) calls in the notebook made it worse, because they push such tests through Maxima.
The fix is to drop a term only when it is literally zero:
def _is_zero(expr) -> bool:
try:
return SR(expr).is_trivial_zero()
except Exception:
return expr == 0
This matters because it was not a problem with this derivation. It was a latent bug in the layer that would have dropped terms in any product whose coefficients happen to vanish somewhere. A real problem flushed it out, which is exactly what real problems are for.
Changing Numeraire: Girsanov Kills the Drift
The form is practically begging for a measure change. Because
and
, we can use
as a numéraire:
The layer’s Girsanov convention is with density
. Matching
requires
. Before trusting that, we check it:
Z_Q = SDE1D(t=t, x=z, drift=mu_Z, diffusion=sig_Z, name="Z under Q")
to_QF = GirsanovTransform1D(sde=Z_Q, theta=-sigma, from_measure="Q", to_measure="Q^F")
F_over_F0 = exp(sigma * w - sigma**2 * t / 2)
check_zero(to_QF.density().constant_theta_closed_form(w) - F_over_F0, r"\Lambda_t - F_t/F_0")
Z_QF = to_QF.transformed_sde(name="Z under Q^F")
check_zero(Z_QF.drift, r"\mu_Z^{\mathbb Q^F}")
Both residuals are zero!
Under the new measure
The drift is gone, and so is any trace of the average, and is now a one-dimensional, driftless diffusion.
And Suddenly We Have a Generator!
Recall from the Feynman–Kac posts that the infinitesimal generator of a diffusion is
The first term comes from the drift. The second comes only from the Itô correction . And a change of measure only ever moves the first-order term, because quadratic variation doesn’t care which measure you are standing in.
For under
the drift is zero, so the generator is nothing but the Itô correction:
Then, by exactly the argument from the earlier posts, satisfies
, but let’s make the code confirm it:
u = function("u")(t, z)
vecer_pde = backward_kolmogorov(u, t, [z], [Z_QF.drift], [Z_QF.diffusion])
vecer_target = diff(u, t) + sigma**2 / 2 * (q - z)**2 * diff(u, z, 2)
check_zero(vecer_pde - vecer_target, r"\text{derived} - \text{Vecer}")
And it does!
The derived PDE is Večeř’s PDE:
with the price recovered as
For our Brent trade . (If you prefer to keep
in price units, as our production engine does, multiply through by
: then
and
. Same PDE, different units.)
Before leaving SageMath, two cheap sanity checks. The linear payoff solves the PDE (it should: it is the forward,
), and so does
on a single fixing interval. Both residuals come back zero.
From Generator to Grid: Crank–Nicolson
Now the derivation pays off a second time, because it tells us things about the PDE that the paper’s statement of it doesn’t shout about.
No jump conditions at fixing dates. and
are both continuous, so
is too. At a fixing only the coefficient
jumps. So we simply march backwards one fixing interval at a time, with
constant inside each one. This is why the problem is one-dimensional, rather than the usual two-dimensional PDE in the price and the running sum.
An exact upper boundary. If , then
evolves as
and each downward jump of
only pushes it lower. So
and the option is certain to finish in the money:
exactly. Since
, the condition
is exact, not asymptotic.
A lower boundary. As ,
, so we impose
, which is many standard deviations away.
The scheme itself is textbook Crank–Nicolson on a uniform -grid over
, with four fully implicit Rannacher steps at the start to tame the kink in
. The one detail I like is that the diffusion coefficient is not typed in by hand: it is taken from the derived SDE and compiled with SageMath’s
fast_callable:
_a_sym = SR(Z_QF.diffusion)**2 / 2
_a_fc = fast_callable(_a_sym, vars=[z, q, sigma], domain=float)
So the PDE the grid solves is, quite literally, the one the layer derived.
Checking the solver first
With a single fixing, an Asian option is a European option on , so the solver must reproduce Black-76. For
,
= 35%,
, it does, to within 0.011 cents per barrel across strikes 60, 75 and 90. Doubling the grid moves the price at the hundredth-of-a-cent level.
So How Wrong Is Moment Matching?
Back to Brent. The full script is in the Appendix, so you can reproduce every number below.
First, 2MM. Rebuilding the moments independently gives
a matched Asian volatility of 57.13093%, and a trade NPV of 137,502.33 USD, against 137,502.35 USD from our production pricer. The reconstruction matches.
Then Večeř, solving the derived PDE:
against 137,338.71 USD from the production Crank–Nicolson engine. So:
- 2MM exceeds Večeř by 163.62 USD;
- that is about 3.3 cents per barrel (discounted);
- or 0.119% of the Večeř NPV.
Hence 2MM is “fine”, right? Not so fast. This option is deep in the money: about 99.33% of its value is discounted intrinsic value, USD. The time value is only about 919 USD, and 163.62 USD of that is 17.8%.
What the 163.62 USD is actually measuring
For any call, . Take expectations under both methods. 2MM is constructed so that its lognormal
has the same mean as
, so the forward part cancels and we are left with
In other words: the whole difference is the price of a put. It measures how differently the matched lognormal and the true arithmetic average describe the left tail below 80 USD. Paths that finish well above the strike pay linearly, and since both methods agree on the mean, they contribute nothing to the difference.
This matters because it turns “the models differ by 0.1%” into a statement about where they differ. For a deep in-the-money trade you are mostly paying for the forward, and the tail error is diluted. For an at-the-money trade, or a long averaging window, it is not diluted at all. In a synthetic test with 12 monthly fixings over a year at 35% vol, 2MM was off by around +7 c/bbl in the money and −4 c/bbl out of the money.
Conclusion
We started with a real life problem: how wrong is our 2MM Asianlet pricer, and could we use our symbolic Python wrapper over SageMath to validate the steps to building a suitable backward PDE validator? To answer it we needed a benchmark, and to trust the benchmark we needed to derive it (not just read an equation from a paper). The plan went like this:
- Večeř’s portfolio
turned the average into a terminal value,
, we checked in plain Sage.
- The
Itoalgebra produced the Itô quotient, cross term and all, and flushed out a real bug in the layer along the way.
GirsanovTransform1Dwithremoved the drift, and the density check confirmed the numéraire was
.
backward_kolmogorovturned the generatorinto Večeř’s PDE, with a zero residual.
- The derivation also handed us the numerics: no jump conditions at fixings, and an exact boundary at
.
- Crank–Nicolson on the derived PDE reproduced the production Večeř value for the Brent Asianlet, and measured the 2MM error at 163.62 USD, all of it in the left tail.
Why this matters
A symbolic layer like this is not a pricing library, and it never solved the PDE. That was numpy’s job. What it did was make every step of the derivation executable: the quotient rule, the measure change and the generator are each a line of code with an assert behind it. When the time came to put a PDE into a production solver, I knew where it came from, what its boundaries were, and what it was measuring.
Up next
The obvious next step is a Monte Carlo check, with exact lognormal sampling at the fixing dates and as a control variate. After that comes a term structure of volatility,
, which the derivation absorbs without changing shape. Hardest of all is the futures roll. Once the fixings reference more than one contract, a single numéraire no longer does the job, and the
Ito layer will need a proper multi-dimensional Itô lemma. That sounds like a post in its own right.
References
- J. Večeř, “A new PDE approach for pricing arithmetic average Asian options”, Journal of Computational Finance 4(4), 2001.
- J. Večeř, “Unified pricing of Asian options”, Risk, June 2002.
- S. Turnbull and L. Wakeman, “A quick algorithm for pricing European average options”, Journal of Financial and Quantitative Analysis 26(3), 1991.
- B. Øksendal, Stochastic Differential Equations, 6th ed., Springer, 2003.
Appendix: Reproducing the Brent Numbers
This standalone script needs only numpy and scipy. It prints the 2MM moments and NPV, the Večeř NPV and the difference.
import datetime as dt
import numpy as np
from scipy.linalg import solve_banded
from scipy.stats import norm
# --- Trade: fully floating ICE Brent Asianlet (controlled test) ---
F0, K, sigma = 107.39, 80.0, 0.9286292253114
D, volume = 0.996125331, 5000
val = dt.date(2026, 3, 31)
fixings = [dt.date(2026, 4, d) for d in range(1, 31)]
fixings = [d for d in fixings if d.weekday() < 5 and d != dt.date(2026, 4, 3)] # Good Friday
t = np.array([(d - val).days for d in fixings]) / 365.0 # ACT/365
n, T = len(t), t[-1]
# --- 2MM Turnbull-Wakeman ---
m1 = F0
m2 = F0**2 * np.exp(sigma**2 * np.minimum.outer(t, t)).sum() / n**2
vA = np.log(m2 / m1**2)
d1 = (np.log(m1 / K) + 0.5 * vA) / np.sqrt(vA)
d2 = d1 - np.sqrt(vA)
npv_2mm = volume * D * (m1 * norm.cdf(d1) - K * norm.cdf(d2))
# --- Vecer PDE: u_t + 1/2 sigma^2 (q - z)^2 u_zz = 0, u(T,z) = z^+ ---
def vecer_cn(z_min=-3.0, nz=2401, steps=80, dt_max=1e-3, rannacher=4):
z = np.linspace(z_min, 1.0, nz)
dz = z[1] - z[0]
u = np.maximum(z, 0.0)
knots = np.concatenate(([0.0], t))
step = 0
for k in range(n, 0, -1): # backwards, one fixing interval at a time
q = (n - k + 1) / n # fraction of fixings still to come
a = 0.5 * sigma**2 * (q - z[1:-1])**2 / dz**2
m = max(steps, int(np.ceil((knots[k] - knots[k - 1]) / dt_max)))
h = (knots[k] - knots[k - 1]) / m
for _ in range(m):
th = 1.0 if step < rannacher else 0.5 # Rannacher start-up, then Crank-Nicolson
rhs = u[1:-1] + (1 - th) * h * a * (u[2:] - 2 * u[1:-1] + u[:-2])
rhs[-1] += th * h * a[-1] * 1.0 # u(t, 1) = 1 exactly; u(t, z_min) = 0
ab = np.zeros((3, nz - 2))
ab[0, 1:] = -th * h * a[:-1]
ab[1] = 1 + 2 * th * h * a
ab[2, :-1] = -th * h * a[1:]
u = np.concatenate(([0.0], solve_banded((1, 1), ab, rhs), [1.0]))
step += 1
return np.interp(1 - K / F0, z, u) # z_0 = 1 - K/F_0
npv_vecer = volume * D * F0 * vecer_cn()
print(f"m2 = {m2:.7f}")
print(f"v_A = {vA:.11f} (matched vol {np.sqrt(vA / T):.5%})")
print(f"2MM NPV = {npv_2mm:,.2f} USD")
print(f"Vecer NPV = {npv_vecer:,.2f} USD")
print(f"2MM - Vecer = {npv_2mm - npv_vecer:,.2f} USD")
Output:
m2 = 11846.1839557v_A = 0.02682692991 (matched vol 57.13093%)2MM NPV = 137,502.33 USDVecer NPV = 137,338.72 USD2MM - Vecer = 163.62 USD


