Twelve topics of code later, how do you know that miniql is right? Not by looking at it: by comparing it with something that is trusted. We priced 27 cases with miniql and with QuantLib 1.35, the open-source library that banks use: a call, a put and five Greeks, 12 Heston calls, 3 caplets, 3 bond prices and 2 puts. All 27 of 27 agree to a tolerance chosen for each method; the worst is the American put, 0.12% apart, because our grid and QuantLib's grid are different grids. This topic writes the tools of that check: the size of a difference, a comparison of two tables, the order of convergence, Greeks by bumping the inputs, and the z-score of a simulation, which was 0.57 standard errors on the last day of SPY.
Two ways to measure a difference
Where we are. In topics 5, 9, 11 and 12 you wrote prices with a formula, a simulation, a grid and a characteristic function. Each topic checked its own code against a test, but a test written by the same person who wrote the code can share its mistakes. A second implementation, written by other people with other conventions, is a much stronger check. We use QuantLib for that. It cannot run in the browser, so its values for 27 cases are given in a table called QUANTLIB, computed once with QuantLib 1.35 from the same inputs.
A difference can be measured in two ways. The absolute difference |value − reference| is in the unit of the number: dollars. The relative difference divides it by the size of the reference, so that it does not depend on the unit or the size of the price: |value − reference| ÷ |reference|. A difference of 0.01 is nothing for a price of 6000 and a disaster for a price of 0.0007. To keep the division safe when the reference is zero, the size of the reference is never allowed below 1e-12. A tolerance is the difference we accept; it has an absolute part and a relative part, and they add up: two numbers agree if |value − reference| ≤ abs_tol + rel_tol × |reference|.
Worked example 1. *Problem:* for four of the cases (a call, a Heston call, a caplet and an American put), find the absolute and the relative difference between miniql and QuantLib. Then ask whether the American put agrees with a tolerance of 1e-9 for both parts, with (0.01, 0.002), and with a relative tolerance of 0.1% only. *Plan:* use abs_rel_diff and is_close. *Steps:* below.
ours = miniql_values()for name in ("bsm_call", "heston_a_100", "hw_caplet_1.0_0.04", "american_put_fd400"): absolute, relative = abs_rel_diff(ours[name], QUANTLIB[name])1 print(name, f"{absolute:.2e}", f"{relative:.2e}")2value, reference = ours["american_put_fd400"], QUANTLIB["american_put_fd400"]print(is_close(value, reference, 1e-9, 1e-9), is_close(value, reference, 1e-2, 2e-3), is_close(value, reference, 0.0, 1e-3))3
bsm_call 6.22e-15 9.77e-16 heston_a_100 1.95e-12 2.27e-13 hw_caplet_1.0_0.04 5.59e-17 7.58e-14 american_put_fd400 7.39e-03 1.21e-03 False True False
- 1The two differences of one case.
- 2Printed in scientific notation: 6.22e-15 is 0.00000000000000622.
- 3Three tolerances for the same pair of numbers.
*Check:* the call differs by 6.22e-15 (relative 9.78e-16), the Heston call by 1.95e-12 (relative 2.27e-13), the caplet by 5.59e-17 (relative 7.58e-14) and the American put by 7.39e-03 (relative 1.21e-03). The first three are rounding errors of floating-point arithmetic: the two libraries compute the same formula. The last is a real difference. The three tolerances give False, True and False. *What to notice:* the caplet's absolute difference is tiny only because the caplet is tiny (0.00074); its relative difference of 7.6e-14 is the fair measure. A tolerance should be set for the method, not for convenience.
Comparing two tables
A library has hundreds of cases, so the comparison is made on a table: a name and a value for each case. Different methods deserve different tolerances. An analytic formula and a characteristic function should agree to about 10 digits. A grid or a tree has a discretisation error, which should be small but not 10 digits small. A simulation never agrees exactly (we deal with it in the last section). The tolerance is chosen by the start of the name: heston for every Heston case, american for the grids. When two keys match, the longest is the most specific and wins. Names not in any key use default.
Two rules make the report honest. First, a case in the reference that your table lacks is a failure, not a skip: a table that silently loses a case looks perfect. Second, the report names the worst case, the one with the largest relative difference, because that is where to look first.
Worked example 2. *Problem:* compare all 27 values with the tolerances of the topic. Then compare them again with one very tight tolerance, 1e-12 for both parts, and list the first four that fail. Last, delete one case from miniql's table and find the worst case of the new report. *Plan:* use compare_prices and worst_row. *Steps:* below.
ours = miniql_values()reference = {name: QUANTLIB[name] for name in ours}rows = compare_prices(ours, reference, TOLERANCES)1print(len(rows), sum(1 for r in rows if r["ok"]), worst_row(rows)["name"], round(worst_row(rows)["rel"], 5))tight = compare_prices(ours, reference, {"default": (1e-12, 1e-12)})2print(sum(1 for r in tight if r["ok"]), sorted(r["name"] for r in tight if not r["ok"])[:4])partial = {name: value for name, value in ours.items() if name != "hw_caplet_2.0_0.04"}rows = compare_prices(partial, reference, TOLERANCES)3print(sum(1 for r in rows if r["ok"]), worst_row(rows)["name"], worst_row(rows)["rel"])
27 27 american_put_fd400 0.00121 17 ['american_put_fd400', 'heston_b_100', 'heston_b_110', 'heston_b_90'] 26 hw_caplet_2.0_0.04 inf
- 1The report of the topic.
- 2The same report with one tolerance for all.
- 3A table with one case left out.
*Check:* with the topic's tolerances all 27 are ok, and the worst case is american_put_fd400 at 0.00121. With 1e-12 for everything only 17 are ok, and the first four failures are american_put_fd400, heston_b_100, heston_b_110 and heston_b_90: the Heston values agree to about 1e-11, not 1e-12, because the integral is computed with a finite number of points. After the deletion 26 are ok, and the worst case is the missing one, with a relative difference of inf. *What to notice:* one tolerance for every method either fails the good cases or lets the bad ones pass.
How fast does it converge?
A grid or a tree has a step: the size of one cell of the grid. As the step shrinks, the price gets closer to the true one. How fast? If the error is proportional to step^p, then taking logarithms gives ln(error) = ln(C) + p × ln(step): a straight line of slope p. This p is the order of convergence. With order 1, halving the step halves the error; with order 2, it divides it by 4. A least-squares line through the points (a line that comes as close as possible to all of them) estimates p. It is a strong check, because a wrong formula often still converges, but at the wrong speed, or not at all.
Worked example 3. *Problem:* price a European put with the finite-difference grid of topic 9, for grids of 25, 50, 100 and 200 points in the price and in time, and compare it with the Black-Scholes-Merton formula. Find the errors, how much each is smaller than the one before, and the order of convergence over all four points and over the last two. *Plan:* use fd_price, bsm_price and convergence_order; the step is 1 / n. *Steps:* below.
errors = [abs(fd_price(100.0, 100.0, 0.05, 0.0, 0.2, 1.0, "put", False, n, n) - bsm_price(100.0, 100.0, 0.05, 0.0, 0.2, 1.0, "put")) for n in GRIDS]print(GRIDS, [round(e, 5) for e in errors])1print([round(errors[i] / errors[i + 1], 2) for i in range(3)])2steps = [1.0 / n for n in GRIDS]print(round(convergence_order(steps, errors), 2), round(convergence_order(steps[-2:], errors[-2:]), 2))3
[25, 50, 100, 200] [0.18759, 0.12669, 0.04927, 0.01457] [1.48, 2.57, 3.38] 1.24 1.76
- 1The error of each grid.
- 2How many times smaller each error is than the one before.
- 3The order over all points and over the finest two.
*Check:* the errors are 0.18759, 0.12669, 0.04927 and 0.01457. Each is smaller than the one before by a factor of 1.48, 2.57 and 3.38: the factor grows toward 4, the sign of order 2. The order over all four points is 1.24, and over the finest two 1.76. *What to notice:* the order is not exactly 2 because the coarse grids are not yet in the regime where the error follows the law. This is why the order is read from fine grids. An order near 0, or a negative one, means that refining the grid does not help, and that something is wrong.
Greeks by bumping
The Greeks of the earlier topics came from formulas. A model without formulas, such as a simulation, a grid or any engine of the next topic, has none, but it has a price. The Greeks of any pricing function can be estimated by bumping: change one input a little, price again, and look at the change. With a central difference the input is moved up and down by the same amount h: (P(x + h) − P(x − h)) ÷ 2h. It has an error proportional to h², much better than the error proportional to h of the one-sided difference (P(x + h) − P(x)) ÷ h. The second derivative, gamma, is (P(x + h) − 2P + P(x − h)) ÷ h².
Two cautions. The bump must be small enough for the difference to follow the curve and large enough for the rounding errors of the computer not to dominate: the price is a number with about 16 digits, and dividing a difference of two nearly equal prices by a tiny h amplifies the lost digits. And theta is the change as time passes. The price depends on the time left to expiry t, which falls as time passes, so theta is minus the derivative with respect to t.
Worked example 4. *Problem:* bump the Black-Scholes-Merton call of topic 5 (spot 100, strike 105, rate 3%, dividend yield 1%, volatility 22%, 292 days) and compare delta and gamma with QuantLib's for spot bumps of 10, 1, 0.01, 0.0001 and 0.000001. Then show all five Greeks for the bump 0.01. *Plan:* use bump_greeks and abs_rel_diff. *Steps:* below.
price = lambda s, r, v, t: bsm_price(s, 105.0, r, 0.01, v, t, "call")for bump in (10.0, 1.0, 0.01, 0.0001, 0.000001):1 greeks = bump_greeks(price, 100.0, 0.03, 0.22, 292 / 365, bump, 0.0001, 0.00001, 0.0001)2 print(bump, f"{abs_rel_diff(greeks['delta'], QUANTLIB['bsm_delta'])[1]:.1e}", f"{abs_rel_diff(greeks['gamma'], QUANTLIB['bsm_gamma'])[1]:.1e}")3greeks = bump_greeks(price, 100.0, 0.03, 0.22, 292 / 365, 0.01, 0.0001, 0.00001, 0.0001)print({name: round(value, 4) for name, value in greeks.items()})4
10.0 4.2e-03 2.0e-02
1.0 4.7e-05 2.1e-04
0.01 4.7e-09 2.2e-08
0.0001 3.6e-11 3.7e-06
1e-06 7.3e-09 6.2e-02
{'delta': 0.469, 'gamma': 0.0201, 'vega': 35.3158, 'theta': -5.6032, 'rho': 32.4337}- 1Five sizes of spot bump.
- 2Delta and gamma from the bumped prices.
- 3Their relative difference from QuantLib's.
- 4All five Greeks.
*Check:* the relative differences of delta and gamma are 4.2e-03 and 2.0e-02 for a bump of 10, 4.7e-05 and 2.1e-04 for 1, 4.7e-09 and 2.2e-08 for 0.01, 3.6e-11 and 3.7e-06 for 0.0001, and 7.3e-09 and 6.2e-02 for 0.000001. The Greeks are {'delta': 0.469, 'gamma': 0.0201, 'vega': 35.3158, 'theta': -5.6032, 'rho': 32.4337}. *What to notice:* the error shrinks like h² (a hundred times smaller bump, ten thousand times smaller error) until the rounding takes over. Gamma needs the larger bump, because it divides by h²: at 0.000001 it is wrong in the second digit. A bump of 0.01 for a price near 100 is a good compromise.
Is the simulation right?
A simulation never gives the exact price, so a tolerance does not fit it. It gives a price and a standard error, the typical size of its random error. The question is how many standard errors the price is from the reference: the z-score, (price − reference) ÷ standard error. If the simulation is right, the z-score is a random number with mean 0 and spread 1: between −2 and 2 about 95% of the time, and beyond 3 only 1 time in 370. If the reference has an error of its own (another simulation, for instance) the two errors add as squares: √(error² + reference_error²).
Worked example 5. *Problem:* price the call of example 4 by simulation with 52 steps and the seed 1, for 5,000, 20,000, 80,000 and 320,000 paths, and give the z-score against the formula each time. Then give the z-score of a price of 6.4 with a standard error of 0.05. *Plan:* use simulate_paths, path_payoffs, mc_estimate and z_score. *Steps:* below.
for paths in (5000, 20000, 80000, 320000):1 sample = simulate_paths(100.0, 0.03, 0.01, 0.22, 292 / 365, 52, paths, 1) price, error = mc_estimate(path_payoffs(sample, 105.0, "call", "european"), 0.03, 292 / 365)2 print(paths, round(price, 4), round(error, 4), round(z_score(price, error, QUANTLIB["bsm_call"]), 2))3print(round(z_score(6.4, 0.05, QUANTLIB["bsm_call"]), 2))4
5000 6.053 0.1609 -1.91 20000 6.3222 0.0822 -0.46 80000 6.4007 0.0415 0.97 320000 6.3574 0.0207 -0.14 0.79
- 1Four sizes of simulation.
- 2The price and its standard error.
- 3The z-score against the formula.
- 4The z-score of a given price.
*Check:* the prices are 6.053, 6.3222, 6.4007 and 6.3574 with standard errors 0.1609, 0.0822, 0.0415 and 0.0207, and the z-scores −1.91, −0.46, 0.97 and −0.14. The price of 6.4 with an error of 0.05 has a z-score of 0.79. The formula gives 6.3604. *What to notice:* the error falls like 1 ÷ √paths (four times more paths, half the error), but the z-scores do not shrink: they stay around 0 and move randomly. That is what a correct simulation looks like. A bias would show as a z-score that grows with the number of paths.
Validating miniql on SPY
Worked example 6. *Problem:* run the whole check: the 27 comparisons with the tolerances of the topic, the order of the grid, the Greeks by bumping against QuantLib's, and, on the last day of the data, a simulation of the at-the-money one-year call of SPY (spot the close of 21 August 2026, rate the 1-year Treasury yield, volatility the historical volatility of all the days, 20,000 paths and the seed 3) against the formula. *Plan:* study combines the functions. *Steps:* below.
out = study(load_data())print(out["passed"], "of", out["checks"], out["worst_name"], f"{out['worst_rel']:.2e}")1print(round(out["fd_order"], 2), f"{out['greek_error']:.2e}", round(out["mc_z"], 2))2
27 of 27 american_put_fd400 1.21e-03 1.24 2.22e-08 0.57
- 1The comparison with QuantLib and its worst case.
- 2The order of the grid, the error of the Greeks, and the z-score.
*Check:* 27 of 27 american_put_fd400 1.21e-03, then 1.24 2.22e-08 0.57. All the cases agree, and the worst is the American put with a difference of 0.12%. The grid has an order of 1.24 on the coarse grids, the Greeks by bumping agree with QuantLib's to 2.2e-08, and the simulation is 0.57 standard errors from the formula. *What to notice:* the American put is the only case where miniql and QuantLib use different grids; our grid at 800 points gives 6.0865, and a tree of 4,000 steps in QuantLib gives 6.0902. Both converge to the same price, from below, so the 0.12% is the discretisation error of our grid, which is as expected.
Agreement with QuantLib shows that two programs give the same number, not that the number is right. Check that the inputs mean the same thing: the day count, the compounding of the rates, the way the dividend is treated, the calendar. Many disagreements come from conventions, not from mistakes. Check also that the test can fail: change one formula on purpose and see that some comparison turns red. And keep the reference values with their date and the library version: QuantLib 1.35 here. In QuantLib the engines used for the table are AnalyticEuropeanEngine, AnalyticHestonEngine, AnalyticCapFloorEngine, BinomialVanillaEngine and FdBlackScholesVanillaEngine.
- NameQuestion it answers
- abs_rel_diff(value, reference)How far apart are they?two measures, in the unit and as a fraction
- is_close(value, reference, abs_tol, rel_tol)Do they agree?tolerance = absolute + relativenumpy: isclose
- compare_prices(ours, reference, tolerances)Which cases agree?uses abs_rel_diffuses is_close
- worst_row(rows)Where should I look first?the largest relative difference
- convergence_order(steps, errors)How fast does the method improve?slope of ln error against ln step
- bump_greeks(price, spot, rate, vol, t, bump_spot, bump_vol, bump_rate, bump_t)What are the Greeks of this model?central differencesQuantLib: the Greeks of an instrument
- z_score(price, error, reference, reference_error)Is the simulation consistent with the reference?in standard errors
What you will build
The lab follows the lecture. Task 1 is the size of a difference, in two ways, and task 2 is the tolerance test. Task 3 compares a table of prices with a table of references, with a tolerance for each method, and task 4 finds the worst case. Task 5 measures the order of convergence from the errors of a sequence of grids. Task 6 gives the Greeks of any pricing function by bumping, and task 7 is the z-score of a simulation. Task 8 validates miniql: its 27 prices against QuantLib, the order of its grid, its Greeks by bumping, and a simulation on the last real day of SPY.
Next topic: Capstone: pricing and risking a small book. The last topic puts the parts together. A book of positions, a bond, a swap, options and a Heston option, is priced on the real curve and the last SPY price with the engines you wrote; its risk is measured by bumping, as in this topic; and its numbers are validated, position by position.
Lab · what's graded
8 tasks · 100 pts- Two measures of a difference6 pts
- The tolerance test6 pts
- Comparing two tables16 pts
- The worst case8 pts
- The order of convergence12 pts
- Greeks by bumping22 pts
- The z-score10 pts
- Validating miniql20 pts