THE COMPANION GUIDE / MATHS, CODE & INTERPRETATION
Understand what
the experiment is doing.
Six models, explained from the question to the calculation. This guide connects the equations to the actual JavaScript functions, shows what the tests establish, and identifies the assumptions that deserve scrutiny.
The implementations use established theory and synthetic inputs. Numerical examples below are hand calculations unless explicitly labeled as simulation results.
Live updates run after you pause on a control. Each dial explains the current input, and the scenario panel describes the completed results. Pause live updates to stage several changes, then select Run experiment. Exports and copied links always refer to the last completed run.
Pin a completed run as a baseline to inspect metric differences. Baselines last until you leave the experiment. These differences are descriptive comparisons, not estimates of statistical significance. Chart sliders support keyboard inspection; series buttons control visibility without changing the calculation.
THE SHARED ARCHITECTURE
A model, a renderer and a test suite.
The important separation is between a calculation and its
presentation. models.mjs contains the mathematical
kernels. content.mjs describes the inputs and method
notes. topics.mjs labels the subjects.
app.mjs reads validated controls, runs a kernel and
renders its returned metrics, plots and ledger. The tests call the
kernels directly, without a browser.
live-notes.mjs turns validated inputs and completed
outputs into contextual explanations;
charts.mjs handles inspection and animation, and
network-view.mjs presents bank obligations. These
presentation layers do not modify the model kernels.
URL parameters / form controls
↓ validation and defaults
pure model function(parameters)
↓
{ metrics, charts, rows, insight, raw }
↓
SVG charts + data tables + JSON / CSV exports
“Pure” here means a model starts fresh on each call and has no
external side effects. The lower-level match() helper
deliberately mutates its supplied order book;
orderbook() creates that book locally and preserves a
before-trade snapshot.
Stochastic experiments start a seeded pseudorandom generator,
rng(seed). normal(rng) converts uniform
draws to normal draws using the Box–Muller transformation. The
seed makes a run replayable; it does not make a single run
representative of a real market.
There are three kinds of evidence in the tests: exact accounting identities, independently calculable benchmarks, and stochastic checks with stated tolerances. Passing them supports implementation correctness under the stated model. It does not establish that the model describes actual markets.
Standard deviation: spread of outcomes. A percentile: a location in that outcome distribution. A confidence interval for the mean: uncertainty from sampling a finite number of outcomes. A narrow confidence interval does not mean individual losses are small.
01 / DATA STRUCTURES & MATCHING
Order-book execution
The last quoted price does not tell you what an entire order will cost. Execution depends on how much quantity is available at each price.
The mechanism
A limit order offers to buy or sell a quantity at a specified price or better. A market order takes available liquidity. A buy matches the lowest ask first; a sell matches the highest bid first. At the same price, the earlier order has priority. This is price–time priority.
The interface constructs twenty levels on each side of a $100 midpoint. Quantity at each level varies around the chosen depth using the seed. A market order walks through those levels until it fills or the displayed liquidity is exhausted.
Example: buy 200 shares when 100 are available at $100.10 and 100 at $100.20. The total is $20,030, so VWAP is $100.15. Relative to the $100 midpoint, this costs 15 basis points. One basis point is 0.01 percentage points. The spread explains the first level; consuming depth explains the extra cost.
What the code does
match(book, order) selects the opposite side, sorts
by price and then order ID, repeatedly fills its best order,
updates both quantities and records each fill. It executes at the
resting price. An unfilled limit remainder can join the
book; a market remainder is returned explicitly and discarded in
this model.
sort opposite side by price, then arrival ID
while quantity remains and the best order is executable:
fill = min(quantity remaining, resting quantity)
record resting price and fill quantity
reduce both quantities
remove resting order if exhausted
rest an unfilled limit remainder; report a market remainder
orderbook() computes the before-trade depth chart,
cumulative execution path, notional, VWAP and shortfall from the
fill ledger. Tests check price priority, FIFO ties, partial fills,
uncrossed limits and liquidity exhaustion.
Why it is interesting
This connects a data-structure decision directly to an economic outcome. A narrow spread can coexist with poor execution for a large order. Two venues with the same best quote can offer different total execution costs because their depth differs.
Computational trade-off: sorting M orders costs O(M log M),
but JavaScript shift() can move O(M) elements each
time. Sweeping K orders therefore adds O(KM) work in the current
array implementation. It is clear and adequate for forty synthetic
orders; it is not a production low-latency exchange. A scalable
next step is an ordered price map with FIFO queues at each price
and efficient cancellation by order ID.
Be able to explain
Why not always use a heap? A heap finds the best price, but a full exchange also needs FIFO ordering within prices, cancellations and fast updates. The appropriate structure depends on the operations.
What does the demo leave out? New orders, cancellations, hidden liquidity, fees, multiple venues and latency. It is one static sweep, not an agent-based market simulation.
Read: CME Group, A Trader’s Guide to Futures. The project implements one FIFO-style mechanism; exchanges can use other matching algorithms. Run this model →
02 / NONLINEAR EQUATIONS & INVARIANTS
Automated market makers
A liquidity pool offers trades according to a curve. The curve creates a price without maintaining a queue of buy and sell orders.
Derive the swap
Let x be token A reserves, y token B reserves and k = xy. Selling a units of A into a fee-free constant-product pool requires (x + a)(y − b) = xy. Solving gives b = ya/(x + a), the B tokens received. The initial marginal price is y/x, but a finite trade receives the average price along a changing curve.
With fee f, only the effective input determines output, while the full input enters the reserve. That distinction lets the reserve product grow. A “constant-product” AMM preserves the product exactly for a zero-fee swap; with retained fees, the product increases.
Example: x = 100 A and y = 10,000 B. A fee-free sale of 10 A returns 909.09 B, not the 1,000 B implied by the initial spot price. Average execution is 90.91 B/A; the post-trade marginal price is about 82.64 B/A. Those are three different prices.
Why providing liquidity can underperform holding
The LP chart is a separate fee-free scenario. Suppose the external price of A in B rises by ratio r, and arbitrage realigns the pool. The product remains k and y′/x′ is r times its initial value. Therefore x′ = x/√r and y′ = y√r.
If A doubles, r = 2. The LP-to-hold ratio is 2√2/3 ≈ 0.9428, so the LP underperforms holding by 5.72%, before fees. This does not mean the LP lost 5.72% of its starting wealth. Its absolute value can rise while it underperforms the chosen benchmark.
What the code does
amm() evaluates these closed-form equations, builds
two 101-point curves and returns reserve accounting. The kernel
itself takes O(1) work for a single swap; generating P plotted
points takes O(P) work and memory. There is no random simulation
here. Tests check an exact swap, invariant preservation without
fees, product growth with fees, positive remaining reserves and
zero divergence when r = 1.
Why it is interesting
A few lines of algebra express an entire trading mechanism. The LP comparison also illustrates adverse selection: arbitrageurs trade against a pool as external prices change, and the pool ends up holding relatively less of the appreciating asset. Fee income must be evaluated against that benchmark loss, not treated as free return.
Be able to explain
Why does splitting a fee-free trade not remove price impact? Successive trades along the same unchanged constant-product curve reach the same final reserves. You do not restore the original price by splitting the order.
What is missing? Gas, rounding, MEV, concentrated liquidity, arbitrage timing and the history of fee income. The displayed LP curve cannot answer whether a real pool is profitable.
Read: Adams, Zinsmeister & Robinson, Uniswap v2 Core. Run this model →
03 / STOCHASTIC PROCESSES & ACCOUNTING
Discrete delta hedging
An option-pricing formula describes a replication argument. This experiment asks what happens when the replication trades at intervals, pays fees or uses the wrong volatility.
Start with the option
A European call pays max(ST − K, 0) at expiry. In this demo S₀ = K = 100, maturity T = one year and the continuously compounded rate r = 4%. The model premium and delta come from Black–Scholes, with no dividends.
Here τ is time remaining and Φ is the standard normal cumulative distribution function. Delta is the first-order sensitivity of the call price to the stock price. A short call has negative delta; buying Δ shares offsets that first-order exposure.
Follow the self-financing ledger
Sell the call for C₀, buy Δ₀ shares and put the remaining amount in cash: B₀ = C₀ − Δ₀S₀ − initial trading fee. Negative cash is borrowing. Between trading dates it accrues at r. At each date, the cash account funds the change in stock holdings and the fee. No external money is injected.
The cost rate c is the selected basis points divided by 10,000. For a move from delta 0.50 to 0.60 at S = $100, the hedge purchases $10 of stock per option; at 10 bps the fee is $0.01.
Generate the stock paths
hedge() simulates 600 risk-neutral geometric Brownian
motion paths. The formula above samples GBM exactly at the
selected dates; the hedge is still discrete. Pricing volatility
and path volatility are separate controls. The paths use drift r,
so this is a replication experiment under a risk-neutral model,
not a forecast of stock returns.
for each of 600 paths:
cash = option premium − initial shares − initial fee
for each time interval:
simulate next stock price; accrue cash interest
if before expiry:
compute new model delta
finance stock adjustment and fee from cash
liquidate shares, pay call payoff, record P&L
call() computes the price, delta, gamma and vega,
using a numerical approximation for Φ. A parallel cost-free cash
account uses the exact same stock path. Work is O(PN) for P paths
and N intervals. The kernel retains P terminal outcomes and the
first path, so working output memory is O(P + N), rather than
storing every path.
Why it is interesting
There are three separate errors to discuss: discrete rebalancing, proportional trading costs and pricing-model misspecification. Increasing trading frequency can reduce discretization error while increasing accumulated fees. A tighter hedge before costs need not be a better hedge after costs.
For a small move, the unhedged second-order option exposure is approximately ½Γ(dS)². This explains why delta hedging alone does not eliminate the effect of a finite price move between trades. It is a useful local intuition, not an exact terminal P&L formula.
Be able to explain
How is it tested? A known Black–Scholes benchmark, expiry and zero-volatility cases, near-zero mean cost-free hedge error with matched volatility, and the check that trading costs never improve a paired path’s P&L.
What cannot be inferred? A 95% interval for the simulated mean is not a 95% interval for a trader’s next outcome. The model omits jumps, stochastic volatility, a volatility surface, discrete dividends and unequal borrowing/lending rates. Different interval counts do not share paired underlying paths.
Read: Scholes, Nobel Lecture: Derivatives in a Dynamic Environment. Run this model →
04 / COVARIANCE & DISTRIBUTION TAILS
Portfolio tail risk
Mean and variance describe only part of a distribution. Two models can agree on both and disagree about the severity of rare losses.
The linear algebra
For weights w, asset mean vector μ and covariance matrix Σ, the portfolio mean is wᵀμ and its variance is wᵀΣw. Covariance entries are Σᵢⱼ = ρᵢⱼσᵢσⱼ. Diversification depends on co-movement, not just the number of assets.
The assumed means are 8%, 4% and 5%, and volatilities 20%, 7% and 15%, for equity, bonds and gold. These are teaching inputs, not fitted estimates. A 60/30/10 allocation has mean 6.5%. With equity–bond correlation −0.2, its annual volatility is about 11.86%.
Construct correlated draws
risk() starts with independent standard normal
variables. It sets the bond shock to ρZ₁ + √(1 − ρ²)Z₂ and the
gold shock to an independent Z₃. The first two shocks have
correlation ρ and unit variance. The gold pairwise correlations
are zero. Only one correlation is adjustable, keeping this
covariance specification valid over the controls’ range.
For heavy tails, all three shocks share a multiplier √(3/U), where U is the sum of squares of five independent normals, so U ~ χ²₅. A conventional t₅ draw has multiplier √(5/U). Using 3 instead standardizes the result to unit variance because E[1/U] = 1/(5 − 2). The portfolio’s analytic covariance is therefore preserved.
The common scale produces joint tail dependence: “zero correlation” does not imply independence in this heavy-tail construction. That is a stronger insight than simply making each asset individually noisier.
The simulation and frontier
The kernel generates 12,000 one-year portfolio returns, sorts losses to find an interpolated 95th percentile, and averages the tail at or beyond that threshold. Separately, it enumerates all 1,326 long-only portfolios on a two-percentage-point weight grid. Sorting by volatility and retaining improvements in expected return constructs an approximate grid frontier. It is not a quadratic-programming optimizer.
For M draws and G grid portfolios, the main work is O(M log M + G log G), with O(M + G) storage. The three-asset dimension is fixed. Tests check pure-asset limits, weights summing to one, a hand-computed covariance result and covariance-preserving heavy tails.
Why it is interesting
Expected shortfall asks what losses look like after crossing the threshold. A 95% VaR alone says little about that severity. A variance-standardized heavy-tail model can even have a lower 95% quantile than a Gaussian while having worse expected shortfall. “Heavy tails” does not mean every percentile must increase.
Be able to explain
Is this a backtest? No. Inputs and returns are synthetic. A real application would estimate means and covariance out of sample, include costs and examine stability under estimation error.
Why can simulated returns fall below −100%? These are arithmetic Gaussian or Student-t return models with unbounded support. That is a limitation for limited-liability assets. Clipping would alter the distribution and covariance; a bounded or log-return model requires rethinking calibration.
Read: Boyd and coauthors, Markowitz Portfolio Construction at Seventy. Run this model →
05 / GRAPHS & FIXED-POINT ALGORITHMS
Interbank contagion
A payment is simultaneously one institution’s liability and another institution’s asset. To determine what everyone can pay, solve the balance sheets together.
Represent the network
Lᵢⱼ is what bank i owes creditor j. Total promised payment is p̄ᵢ = ΣⱼLᵢⱼ. The share promised to creditor j is Πᵢⱼ = Lᵢⱼ/p̄ᵢ. If bank i pays less than promised, all its creditors receive the same fraction of their claim. This is proportional repayment.
The formula implements limited liability: a bank pays at most what it owes and at most what it has available. The difficulty is circularity. Bank i’s available assets depend on the payments of other banks, which depend in turn on its own payment.
Solve the fixed point
clearNetwork() starts with full promised payments. It
updates every payment simultaneously using the previous vector,
and repeats until the maximum absolute change is below 10⁻¹⁰ or
10,000 iterations have run. Starting at full payments gives a
decreasing sequence toward the greatest clearing solution.
“Greatest” describes the componentwise payment vector, not a
policy optimization.
payments = total promised liabilities
repeat:
incoming[i] = sum of each debtor's payment × its share owed to i
next[i] = min(promised[i], external_assets[i] + incoming[i])
stop if max absolute change is below tolerance
payments = next
All eight banks owe 100 units to an outside creditor, society. This creates an obligation that does not recycle endlessly inside the banking network and makes these networks regular. It also lets the code report losses to outside creditors separately from the sum of all unpaid claims.
Example: Bank A owes 100 to Bank B and 100 to society. After its shock, A has 100 external assets and no other receipts. It pays half of every claim: 50 to B and 50 to society. If B owes society 100 and has no external assets, B can now pay only 50. B’s missed payment is an indirect consequence of A’s shock.
Make the topology comparison meaningful
contagion() constructs a directed ring, a complete
network or a hub. Each has total interbank liabilities 8E, where E
is the exposure scale. Incoming and outgoing interbank totals
balance at every bank before the shock. In the hub, each
directional hub–spoke link is 4E/7, so the hub concentrates 4E of
outgoing and incoming exposure. Equal system totals do not imply
equal institution-level concentration.
The code separates initial defaults—insolvent even if peers pay in full after the external shock—from secondary defaults that appear only when peers’ actual payments are considered. Dense-matrix clearing takes O(In²) for I iterations and n institutions. Storing the network uses O(n²); saving the full iteration history adds O(In). A sparse graph implementation could replace the n² sum by the number of edges.
Why it is interesting
System risk cannot be inferred from isolated balance sheets. Connections can share a loss or propagate it. The experiment isolates one solvency channel while holding aggregate exposure fixed. It does not show that “more connected is always safer” or “the hub is always worse.” Those statements depend on balance sheets, shock placement and the loss mechanism.
Be able to explain
Are iterations days? No. They are numerical updates in a static clearing calculation. The graph of payments is a convergence trace, not a chronology of a bank run.
How is it validated? Hand-calculated networks, limited-liability bounds, residuals of the clearing equation, full repayment without shocks and payment monotonicity as external assets increase.
What is absent? Liquidity runs, collateral, claim seniority, bankruptcy haircuts, fire sales and rescue policy. Summing unpaid interbank and external claims is not the same as measuring a net economy-wide welfare loss.
Read: Eisenberg & Noe, Systemic Risk in Financial Systems. Run this model →
06 / GAME THEORY & EXPERIMENTAL DESIGN
Auction design
Changing how the winner pays changes the incentive to bid. Comparing mechanisms requires accounting for those behavioral responses.
Why truthful bidding works in a second-price auction
A bidder with private value v wins if their bid exceeds the competing bids, but pays the highest competing bid, subject to the seller’s reserve. Bidding above value can make them win at a loss; bidding below can make them lose a profitable purchase. Truthful bidding is therefore weakly dominant in this independent-private-value setting with a non-personalized reserve.
Derive the first-price bid
Assume n symmetric risk-neutral bidders with independent values uniform on [0,100]. With no reserve, suppose everyone else uses b(v) = αv. If a bidder of value v bids b in the interior range, the chance all others bid less is (b/(100α))ⁿ⁻¹. Expected utility is (v − b) times that probability. Differentiating with respect to b gives (n − 1)(v − b) − b = 0.
The reserve formula respects the boundary b(R) = R. Types below R do not participate. In the second-price format, the eligible winner pays max(R, second-highest value).
Example: with five bidders, someone valuing the item at $90 bids $72 in the no-reserve first-price equilibrium. Second-price payment depends on the runner-up. Across auctions, each format has expected revenue $66.67; payments need not agree in any particular auction.
What the code does
auctions() draws 10,000 value vectors, sorts each
vector and applies both mechanisms to that same draw. The
first-price bid multiplier is 100% at equilibrium. Other
multipliers are deliberate off-equilibrium counterfactuals, not
solutions to a new game. The scaled bids remain monotone in value,
but may fail the reserve or exceed the bidder’s value.
Using the same draws is the common-random-numbers method. It controls for the fact that some auctions just happen to draw higher values. The paired variance is Var(X − Y) = Var(X) + Var(Y) − 2Cov(X,Y). Positive covariance between the two revenues makes the comparison more precise.
Work per auction is O(n log n) because values are sorted, though only the top two are needed. The current running-mean plot also re-sums accumulated arrays every 100 auctions, adding roughly O(N²/100) work over a run. A streaming sum would make that part O(N). At the fixed 10,000-auction size the current version remains small, but this is a useful implementation improvement to identify.
Why it is interesting
The payment rule alone does not determine seller revenue. Bidders respond strategically. Revenue equivalence is an expectation under assumptions about values, risk preferences and allocation/payment boundary conditions. Simulation illustrates the theorem and stresses assumptions; it does not prove the theorem.
Be able to explain
Why does a reserve sometimes reduce welfare? With seller value fixed at zero, an unsold item gives zero realized surplus even when a bidder values it positively. A seller may accept that efficiency loss in exchange for a different revenue distribution.
What does the interval establish? Whether the finite simulation is consistent with a predicted zero mean difference. A confidence interval containing zero is not proof of equality.
What would change the result? Correlated or common values, risk aversion, asymmetric bidders, entry costs or collusion. Those require different equilibrium reasoning; a bid multiplier is not a substitute for that derivation.
UNDERSTAND, DISCUSS, EXTEND
Connect the equation to an engineering decision.
A clear explanation has four parts: the question, the mechanism, a testable prediction, and a limitation. For each model, be ready to work through one numerical example without looking at the interface.
| Model | Core engineering idea | A useful next extension |
|---|---|---|
| Order book | Priority, state mutation and conservation | Per-price queues, cancellation and event replay |
| AMM | Algebraic invariants and reserve accounting | Fee-income paths and arbitrage dynamics |
| Delta hedge | Stochastic simulation and a self-financing ledger | Paired paths across frequencies, jumps or stochastic volatility |
| Portfolio | Covariance-preserving sampling and tail statistics | Out-of-sample estimation and a continuous constrained optimizer |
| Contagion | Directed graphs and monotone fixed points | Sparse networks, seniority and fire-sale feedback |
| Auctions | Equilibrium behavior and paired Monte Carlo | Streaming estimators and an explicitly solved asymmetric game |
A practical learning check
- Predict what a control change should do before running the simulation.
- Show the relevant equation and identify every term.
- Find the function that implements it and explain one edge case.
- Explain a test and why an independent benchmark or invariant is stronger than checking that the screen looks plausible.
- Name a conclusion the experiment cannot support.
The models are established ideas. The implementation work lies in making them reproducible, inspectable and testable, and in designing meaningful comparisons. Use the source, intermediate quantities and tests to explain how each result follows from its assumptions.
“I’m studying six established economics and finance mechanisms through an open-source simulation notebook. The work connects mathematical assumptions to algorithms, numerical checks and interactive counterfactuals.” Add specific first-person implementation or research claims only when you can substantiate them.
Guide version 1. Implementation references describe the current repository. The experiments use synthetic assumptions and do not constitute trading systems or empirical market studies.