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:

  1. State the problem: a fully floating ICE Brent Asianlet.
  2. Use Večeř’s trick to turn the average into a self-financing portfolio.
  3. Let my Ito class compute the Itô quotient that defines Večeř’s state variable.
  4. Change the numeraire with the GirsanovTransform1D class, so that the drift vanishes.
  5. Read off the infinitesimal generator, and hence the PDE, with backward_kolmogorov.
  6. 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 t_1 < \dots < t_n = T for the fixing dates, the average and the price are straight-forward:

\displaystyle A = \frac{1}{n}\sum_{i=1}^{n} F_{t_i}, \qquad V_0 = D \cdot \mathbb{E}^{\mathbb{Q}}\left[(A - K)^+\right]

where \mathbb{Q} is the forward measure for the payment date. With deterministic rates, futures and forwards coincide, so under \mathbb{Q} the futures price is driftless:

\displaystyle dF_t = \sigma F_t , dW_t^{\mathbb{Q}}

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 A,

\displaystyle m_1 = F_0, \qquad m_2 = \frac{F_0^2}{n^2}\sum_{i,j} e^{\sigma^2 \min(t_i, t_j)}

and prices with Black-76 using the total log-variance v_A = \ln(m_2/m_1^2). 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 q(t) futures, our gains evolve as

\displaystyle dX_t = q(t)dF_t

Večeř’s choice is to hold the fraction of fixings still to come:

\displaystyle q(t) = \frac{n - k + 1}{n}, \qquad t \in (t_{k-1}, t_k]

and q(t) = 0 after the last fixing. A quick summation by parts shows that \int_0^T q \, dF = A - F_0, so if we start with X_0 = F_0 - K then

\displaystyle X_T = A - K

exactly, path by path. The Asian option is now just a call on a self-financing portfolio: it pays (X_T)^+.

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 X still depends on F. Večeř’s next move is to measure the portfolio in units of the futures price:

\displaystyle Z_t = \frac{X_t}{F_t}

To find dZ 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 a + b dt + \sum_i c_i dW_i, and that its multiplication uses dW_i dW_j = \delta_{ij} dt. So multiplying two jets is the Itô product rule:

\displaystyle (X + dX)(Y + dY) = XY + X dY + Y dX + dX dY

So we write Z + dZ = (X + dX) \big(1/F + d(1/F)\big) and let the layer do the bookkeeping. d(1/F) 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

\displaystyle dZ_t = \sigma^2 (Z_t - q) dt + \sigma (q - Z_t) dW_t^{\mathbb{Q}} = \sigma (q - Z_t)\left(dW_t^{\mathbb{Q}} - \sigma dt\right)

Notice where the drift came from. Part of it is the cross term dX d(1/F) = -q\sigma^2 dt, 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 dW coefficient of dZ 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 \sigma(q - z), which is zero whenever z = q, 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 \sigma(q - Z)\left(dW - \sigma dt\right) is practically begging for a measure change. Because F_T > 0 and \mathbb{E}^{\mathbb{Q}}[F_T] = F_0, we can use F as a numéraire:

\displaystyle \mathbb{E}^{\mathbb{Q}}\left[(X_T)^+\right] = \mathbb{E}^{\mathbb{Q}}\left[F_T (Z_T)^+\right] = F_0 \mathbb{E}^{\mathbb{Q}^F}\left[(Z_T)^+\right], \qquad \frac{d\mathbb{Q}^F}{d\mathbb{Q}}\Big\vert_{\mathcal{F}_t} = \frac{F_t}{F_0}

The layer’s Girsanov convention is dW^{\text{new}} = dW^{\text{old}} + \theta dt with density \exp\left(-\int \theta dW - \frac{1}{2}\int \theta^2 dt\right). Matching F_t/F_0 = e^{\sigma W_t - \sigma^2 t/2} requires \theta = -\sigma. 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}")
Dark code editor showing stochastic differential equation calculations with three verification results, each equal to zero.
Dark-themed code notebook showing a stochastic differential equation under measure Q^F and output verifying zero drift and variance terms.

Both residuals are zero!

Under the new measure

\displaystyle dZ_t = \sigma (q(t) - Z_t) dW_t^{\mathbb{Q}^F}

The drift is gone, and so is any trace of the average, and Z 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 dX = \mu dt + \sigma dW is

\displaystyle \mathcal{L}g(x) = \lim_{h \downarrow 0} \frac{\mathbb{E}^x[g(X_h)] - g(x)}{h} = \mu(x) g'(x) + \frac{1}{2}\sigma^2(x) g''(x)

The first term comes from the drift. The second comes only from the Itô correction \frac{1}{2}g''(dX)^2. 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 Z under \mathbb{Q}^F the drift is zero, so the generator is nothing but the Itô correction:

\displaystyle \mathcal{L}^Z_t g(z) = \frac{1}{2}\sigma^2\left(q(t) - z\right)^2 g''(z)

Then, by exactly the argument from the earlier posts, u(t,z) = \mathbb{E}^{\mathbb{Q}^F}[(Z_T)^+ \mid Z_t = z] satisfies \partial_t u + \mathcal{L}^Z_t u = 0, 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!

Dark-themed code editor showing Python/SymPy code for a backward Kolmogorov equation, with rendered mathematical equations and zero verification results below.

The derived PDE is Večeř’s PDE:

\displaystyle \frac{\partial u}{\partial t} + \frac{1}{2}\sigma^2\left(q(t) - z\right)^2 \frac{\partial^2 u}{\partial z^2} = 0, \qquad u(T, z) = z^+

with the price recovered as

\displaystyle V_0 = D \cdot F_0 \cdot u(0, z_0), \qquad z_0 = 1 - \frac{K}{F_0}

For our Brent trade z_0 = 1 - 80/107.39 \approx 0.2551. (If you prefer to keep z in price units, as our production engine does, multiply through by F_0: then z_0 = 107.39 - 80 = 27.39 and V_0 = D \cdot u(0, z_0). Same PDE, different units.)

Before leaving SageMath, two cheap sanity checks. The linear payoff u = z solves the PDE (it should: it is the forward, F_0 - K), and so does u = (z - q)^2 e^{\sigma^2 (T - t)} 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. X and F are both continuous, so Z is too. At a fixing only the coefficient q(t) jumps. So we simply march backwards one fixing interval at a time, with q 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 z \geq q(t), then Y = q - Z \le 0 evolves as dY = -\sigma Y dW and each downward jump of q only pushes it lower. So Z_T \geq 0 and the option is certain to finish in the money: u(t,z) = z exactly. Since q \leq 1, the condition u(t, 1) = 1 is exact, not asymptotic.

A lower boundary. As z \to -\infty, u \to 0, so we impose u(t, -3) = 0, which is many standard deviations away.

The scheme itself is textbook Crank–Nicolson on a uniform z-grid over [-3, 1], with four fully implicit Rannacher steps at the start to tame the kink in z^+. 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 F, so the solver must reproduce Black-76. For F_0 = 75, \sigma = 35%, T = 1, 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

\displaystyle m_1 = 107.39, \qquad m_2 = 11846.1839557, \qquad v_A = 0.02682692991

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:

\displaystyle NPV^{\text{Vecer}} = 137{,}338.72 \text{ USD}

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, D \cdot (F_0 - K) \cdot 5000 = 136{,}419.36 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, (A - K)^+ = (A - K) + (K - A)^+. Take expectations under both methods. 2MM is constructed so that its lognormal \widetilde{A} has the same mean as A, so the forward part cancels and we are left with

\displaystyle V^{\text{2MM}} - V^{\text{Vecer}} = D \cdot \left( \mathbb{E}\left[(K - \widetilde{A})^+\right] - \mathbb{E}\left[(K - A)^+\right] \right)

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:

  1. Večeř’s portfolio dX = q dF turned the average into a terminal value, X_T = A - K, we checked in plain Sage.
  2. The Ito algebra produced the Itô quotient dZ, cross term and all, and flushed out a real bug in the layer along the way.
  3. GirsanovTransform1D with \theta = -\sigma removed the drift, and the density check confirmed the numéraire was F.
  4. backward_kolmogorov turned the generator \mathcal{L}^Z_t = \frac{1}{2}\sigma^2(q(t) - z)^2\partial_{zz} into Večeř’s PDE, with a zero residual.
  5. The derivation also handed us the numerics: no jump conditions at fixings, and an exact boundary at z = 1.
  6. 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 A - F_0 as a control variate. After that comes a term structure of volatility, \sigma \to \sigma(t), 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

  1. J. Večeř, “A new PDE approach for pricing arithmetic average Asian options”, Journal of Computational Finance 4(4), 2001.
  2. J. Večeř, “Unified pricing of Asian options”, Risk, June 2002.
  3. S. Turnbull and L. Wakeman, “A quick algorithm for pricing European average options”, Journal of Financial and Quantitative Analysis 26(3), 1991.
  4. 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.1839557
v_A = 0.02682692991 (matched vol 57.13093%)
2MM NPV = 137,502.33 USD
Vecer NPV = 137,338.72 USD
2MM - Vecer = 163.62 USD