QQuant, Built

Act I · Markets and Money

Part 2 of 43

The Machinery of Markets

Undergraduatestarts at this level65 min of film 21 chaptersprerequisites: Part 1

What actually happens between pressing 'buy' and owning the share, and where can it break?

One order is followed through the machine: the book or the auction that matches it, the clearing house that steps between buyer and seller, the two days (now one) before it settles, and the margin that makes the promise credible. Leverage, short selling, repo and prime brokerage are the same idea seen from different desks: someone lends, someone posts collateral, and a rule says when the position is closed for you. The crisis file is the day in September 2019 when the repo rate more than doubled.

What you need. Nothing beyond Part 1.

What you will be able to do

Undergraduate

  • Describe the life of a trade: order, match, clearing, settlement, and who bears the risk at each step.
  • Compute a liquidation price from leverage and a maintenance margin, for a long and for a short.

Master's

  • Price a future by cost of carry and compute a minimum-variance hedge ratio.
  • Size initial margin from a volatility forecast and a confidence level, and net exposures bilaterally and through a central counterparty.

PhD

  • Backtest a margin model: derive Kupiec's likelihood-ratio test and its exact size, and add Christoffersen's test of independence.

Industry

  • Explain repo, haircuts, specials, securities lending and what a prime broker does when a client cannot meet a call.

Contents

Each chapter has a home level. Choose a track to see what to read and watch: Undergraduate 28 min · Master's 58 min · PhD 65 min · Industry 43 min.

  1. 0What happens when you press buy?Undergraduate2 min
  2. 1Instruments and how they are quotedUndergraduate3 min
  3. 2Futures: carry, basis and the hedgeUndergraduate4 min
  4. 3The order bookUndergraduate3 min
  5. 4Auctions: one price for everyoneUndergraduate3 min
  6. 5Dealers, RFQ and wholesalersMaster's3 min
  7. 6Clearing: novation, netting, the waterfallUndergraduate3 min
  8. 7Settlement and the depositMaster's3 min
  9. 8Margin and liquidationUndergraduate4 min
  10. 9How much margin?Master's3 min
  11. 10Short selling and the squeezeUndergraduate4 min
  12. 11Repo, lending and specialsMaster's3 min
  13. 12The day repo brokeIndustry3 min
  14. 13Prime brokers and the race to sellIndustry3 min
  15. 14Who earns whatIndustry3 min
  16. 15Benchmarks and indicesMaster's3 min
  17. 16Markets around the worldIndustry3 min
  18. 17Industry: who runs the machineIndustry3 min
  19. 18Frontier, 2023 to 2026PhD2 min
  20. For the researcher: backtesting a margin modelPhD5 min
  21. The funding desk; recap, desk questions, problemsAll tracks2 min

Also on this page: Lecture · Key results · Try it · Lab · Problems · Reading · 中文 · Build the film.

Lecture

The text of each chapter is the film's narration, as it is spoken, so you can read along or revise without the film. The pictures are in the film. A dashed box stands for a number the film computes when it is rendered (hover over it to see what is computed); the README's figures for each chapter, where it lists them, follow the chapter's text.

What happens when you press buy?Undergraduate2 min

The machinery of markets. Press buy: you see a trade in seconds. Why do the shares and cash arrive later?

Here is what happens when you press buy on a share. Your broker routes the order to an exchange or a wholesaler. It meets a seller: you see a trade, but settlement has not happened. The clearing house steps between its members, becoming buyer to every seller and seller to every buyer. For US stocks, shares and cash normally move one business day later. Until then, a member could fail to pay. The clearing house collects collateral against that risk: watch it build while the trade waits. That waiting has a cost.

That collateral once decided who could trade. On 27 January 2021, NSCC called six point nine billion dollars from thirty-six members: two point one billion mark-to-market, four point eight billion special charge. Total required deposits reached twenty-five point five billion. Next morning, NSCC waived an excess capital premium. Without it, the SEC says, one unnamed retail broker would owe an additional charge exceeding twice its one point four billion dollar margin requirement. Robinhood restricted GameStop buying, citing its clearing deposit. Short interest had reached a hundred and twenty-three percent of float. Collateral constrained who could buy.

How we got here. Shares in Amsterdam, futures in Osaka and Chicago, and exchanges in New York. Independent clearing and electronic depositories replaced chains of bilateral promises and paper certificates. Decimal quotes, market-system rules and shorter settlement changed the machine again. The timeline marks the milestones.

The plan: follow a trade, measure collateral and funding, then compare the firms and rules behind the machine.

The House gets its second desk. Treasury and funding: the cash and collateral a position needs. Every backtest pays.

1Instruments and how they are quotedUndergraduate3 min

Six instruments carry almost everything in this series. A share: a slice of a company, quoted per share. A bond: a loan that pays coupons and then its face value, quoted per hundred of face or as the yield that price implies; Part eighteen builds the arithmetic. A future: an agreement to trade later at a price fixed now, settled every single day, which is why it needs margin. A swap: two parties exchange cash flows, typically fixed against floating, and the quote is the fixed rate. An option: a right without an obligation, quoted in dollars or in implied volatility. And an exchange-traded fund: a basket that trades like a share, kept near the value of what it holds by market makers who create and redeem its units, as Part thirty-eight shows.

Bond quotes hide one trap. Between coupons, interest accrues to whoever holds the bond. Bonds are quoted clean, without that interest, and the buyer pays the dirty price: clean plus accrued. The accrued part is the coupon times the fraction of the period that has passed since the last payment. Watch a year of a five percent bond paying twice a year, whose clean quote stays at ninety-eight seventy-five. What you pay climbs every day by the coupon's share, then drops by two and a half on each coupon date, when the interest is paid out: a saw-tooth over a flat line. Ninety-one days in, half a period, the buyer pays a hundred, of which one twenty-five is the seller's interest. Quoting clean keeps the quote from jumping on coupon days, so price changes mean what they should. A question: the clean price hasn't moved for a month. Did the holder earn anything? Yes: a month of accrued interest, about forty cents per hundred on this bond. The clean price hides the carry; the dirty price shows it. Of all these contracts the simplest is the future, and it already holds the central idea of this series: a price set by what it costs to build the same thing another way.

A listed derivative is a standard contract. The E-mini S and P five hundred future is fifty dollars times the index, moves in quarter points, twelve fifty a tick, expires quarterly and settles in cash: at sixty-one twenty-five, three hundred thousand dollars of exposure. An American equity option is on a hundred shares, and every one is cleared by the Options Clearing Corporation.

Keep one word straight: notional, the size a derivative refers to, not its value. A five-year swap on a hundred million dollars may be worth only a few hundred thousand, and gains or loses about forty-five thousand per basis point. A future on a million dollars of an index can be held with fifty thousand of margin. Exposure over the money put up is leverage, and leverage is what turns the plumbing of this part into a matter of survival.

2Futures: carry, basis and the hedgeUndergraduate4 min

On the tenth of February 2021 the March Bitcoin future on Binance traded percent above the coin, with days to go. Start with an ideal forward: frictionless trading, unlimited borrowing and shorting at a fixed rate, and no default. Futures share this price when rates are deterministic. Borrow cash, buy the coin, sell it forward at F nought: no money down. At expiry deliver it and repay the loan. That profit is riskless, so it can't be positive. Run it in reverse and the inequality flips: the forward is spot grown at the interest rate. An asset paying a yield q grows at r minus q. Read backwards, a future tells you the carry the market charges: that February, about percent a year, paid by leveraged longs to whoever bought the coin and sold the future.

Now watch a real future converge. The orange line is Bitcoin; the blue line, the March 2021 future, hour by hour from the first of December, with its implied carry below. Bitcoin triples. The future stays above it the whole way, and the gap, measured as a yearly rate, swings between about fifteen and fifty percent: percent on average, at most , whenever more than ten days were left. That is the price of leverage in a bull market: longs who wanted the coin without the cash paid it. As expiry nears the two ribbons zip shut, because at expiry a future is the asset. That gap between spot and future is the basis, and its convergence is what a hedger, or a carry trader, is betting on.

Hedgers use futures the other way round, often on something close to the asset but not the same: basis risk. How many futures? Sell h of them; the hedged variance is the variance of a difference. Set its slope in h to zero. The best ratio is the correlation times the ratio of volatilities, a minimum since the curvature is positive. What's left is one minus rho squared of the variance: the hedge's effectiveness is rho squared. In contracts, scale by the sizes; for a stock portfolio, use its beta; and roll the hedge from one expiry to the next.

Here is the whole hedging problem as a landscape. Across, the hedge ratio; into the screen, the correlation between asset and future; up, the variance left over, as a share of the unhedged variance. For any correlation the leftover variance is a parabola in h. Take rho equal to point eight, the yellow slice, and let a ball roll down it: it settles at h star, one point two times rho. The valley floor runs diagonally, and its depth is one minus rho squared. Near rho of one the valley reaches zero, a perfect hedge; at rho of a half the best hedge still leaves three quarters of the variance. The depth of the valley is the effectiveness.

The House does it on data: hedge Ether with Bitcoin, fitted on 2021 and 2022. The ratio is , between and by bootstrap, and in sample it removes percent of the variance. Keep that ratio through 2023: it removes percent. A desk question: future a hundred and two, spot a hundred, six months, rates three percent. Trade? Fair value is a hundred times e to the one and a half percent: a hundred and one fifty-one. The future is forty-nine cents rich: sell it, borrow a hundred, buy the coin, deliver it at expiry. All of these prices are set somewhere. Next, the machine that sets them: the order book.

3The order bookUndergraduate3 min

Two kinds of order do almost all the work. A market order says: trade now, at whatever price is there. It is urgent, but a halt or missing liquidity can prevent a fill. A limit order says: buy at this price or lower, sell at this price or higher. It bounds the price, not the chance of a trade, and can wait in the book. A stop order waits for a trigger price, then becomes a market order: a way to cut a loss, and, when many trigger at once, a way to deepen a crash. Orders also say how long they live: for the day, until cancelled, immediate-or-cancel, or fill-or-kill. And some hide: an iceberg shows a slice of its size, a hidden order shows none, and for that privilege it queues behind every displayed order at its price. The rule of the equity book is often price first, then visibility, then time. Other venues may use different priority rules.

Here is a book running: one row per price, asks above and bids below, each block one share waiting. It is simulated, by the zero-intelligence model of Smith, Farmer, Gillemot and Krishnamurthy: orders arrive at random prices, market orders at random times, and resting orders are cancelled at random. Watch a level: a new order joins the back of its queue, a cancel pulls a block out of the middle, a market order bites the front, and the spread, in yellow, breathes. Nobody in this model thinks, and the book still has a spread of one to four ticks and thin queues at the front: much of a book's shape is plumbing, not strategy.

What does impatience cost? Say every tick above the best ask holds d shares. A market buy of Q shares takes the best level first, then the next: price priority. It fills Q over d levels. The prices form an arithmetic series, so the average is the best ask plus half a tick for every extra level the order eats. Against the mid price the cost is half the spread plus that walk; twice the distance is the effective spread, the cost measure Parts thirty-six and thirty-seven use. Doubling the order more than doubles the walk. Now measure it in the simulated book, four seeds, against the uniform formula:

More market orders relative to limit orders widen the spread: about , , then ticks. The tick itself is a rule. In 2024 the SEC amended Rule 612: stocks with average spreads of a cent and a half or less would quote in half-pennies, and access fees were cut from thirty to ten hundredths of a cent. Compliance was scheduled for November 2026; in June 2026 the SEC moved it to November 2027. A question: halve the tick on a stock with a one-tick spread and long queues. What happens? The spread can halve, but fewer orders sit at each finer price, so the depth at the best quote thins, and anyone can step ahead of the queue for half a cent. Small orders pay less; large ones may not. The book trades all day, but the day opens and closes differently: with an auction.

4Auctions: one price for everyoneUndergraduate3 min

Most exchanges open and close the day with a call auction. For a few minutes orders are collected, nothing trades, and the exchange publishes what would happen if it stopped now: an indicative price, the shares that would match, and the imbalance left over. Watch three hundred orders arrive one at a time. Each buy adds a step to the green staircase, the shares wanted at each price or higher; each sell adds a step to the red one, the shares offered at each price or lower. The indicative price jumps around while the book is thin, then settles as it fills, at . At the end everyone who trades pays the same price: a uniform-price auction. The continuous book, where each order pays its own price, is discriminatory.

Why the crossing? Demand at a price p counts the bids at p or higher, so it can only fall as p rises. Supply counts the asks at p or lower, so it can only rise. At any price the shares that can actually trade are the smaller of the two. To the left of the crossing supply is the smaller and rising; to the right, demand is the smaller and falling. So the volume climbs, then falls, and it peaks where the staircases cross. When several prices tie, exchanges take the one with the least imbalance, then the one nearest a reference price.

Now add one more order: a market-on-close buy of two thousand shares, willing to pay any price. It shifts the whole demand staircase right by two thousand shares. The crossing moves from to , and every share in the auction trades there. Bought instead by walking the continuous book, the same two thousand shares would have averaged and pushed the last fill to . That's why the close matters. Index funds and many mutual funds are valued at the closing price, so they trade there, in size: Bogousslavsky and Muravyev measured closing auctions at seven and a half percent of American volume in 2018, up from three percent in 2010. Big orders meet in one place, at one price, and the price that results is the one indices are computed from.

The House's version is nine lines: every order price is a candidate, demand and supply at each, the volume that clears, ties broken by imbalance. Run on the three hundred orders, it prints and shares. And the question: does a two-thousand-share buy move the price more in the auction or in the book? In the book. In the auction it shifts the whole demand staircase and moves the crossing a little; in the book it walks up the ladder, as the numbers showed. That is why index funds trade the close. Books and auctions need a central venue. Most bonds, currencies and swaps have none.

5Dealers, RFQ and wholesalersMaster's3 min

Most bonds, currencies and swaps don't trade in a central book. They trade with dealers, who quote from their own inventory, often by request for quote: the client asks several dealers at once and takes the best answer. Each dealer's price differs a little, because each holds a different inventory: one is long and keen to sell, another short. Ask one dealer and you get one draw. Ask three, and the best of three. Repeat it a hundred thousand times. The distribution of the best quote slides left as more dealers are asked: competition works. But it slides by less and less with each dealer added.

Write it down. Each quote is the mid plus a dealer's private cost, sigma times a standard normal. The best of n is the mid minus sigma times the expected maximum of n normals, an order statistic, which grows only like the square root of two log n: slowly. And every dealer you ask learns that you want to trade, and can trade ahead of you: call that leakage lambda per dealer. The total cost is a U: savings that flatten, against leakage that grows in a straight line. With lambda at sigma the best is to ask ; and as leakage rises, the best number falls fast. Real platforms cap requests at a handful of dealers for exactly this reason.

Now American retail stock orders. Most never reach an exchange: wholesalers fill them, and pay the broker for the flow. Why pay to trade against someone? Because of who that someone is. A dealer's markout is what a fill is worth a minute later. In this simulation, flow with a few informed traders costs the dealer almost nothing, per share a minute later; flow where a third know where the price is going costs . Retail orders are mostly uninformed, so filling them earns the spread. A wholesaler keeps half the spread, less the adverse selection, less the price improvement it gives the customer, less what it pays the broker. Competition decides how that surplus is split. In GameStop's January, about eighty percent of off-exchange trading was internalized, eighty-eight percent of it by three wholesalers, and on the 27th Citadel Securities alone internalized nearly four point two billion dollars of it. Ernst and Spatt find payment for order flow small in stocks and large in options; Battalio, Corwin and Jennings found that brokers routing for rebates got worse fills on their customers' limit orders. Brokers owe their customers best execution, and these papers are how anyone checks. However a trade is made, in a book, an auction or with a dealer, it leaves a promise between two parties. Next: who stands behind it.

6Clearing: novation, netting, the waterfallUndergraduate3 min

A trade is a promise between two strangers; if one fails, the other is exposed. A central counterparty replaces the trade by two, buyer with clearing house and clearing house with seller, so everyone faces one closely watched counterparty. Since 2008 regulators have pushed standardized derivatives into clearing.

The second gift is netting. A simulated day: trades among members. Settled one by one, billion dollars. Let each pair net: opposite lines cancel, billion. Now pull every arrow into the clearing house: each member settles only its net position, billion, percent less. The real clearing house for American stocks says its netting removes ninety-eight percent of payments on an average day.

Netting can only help, and here is why. Gross is the sum of every obligation; bilateral settles only each pair's difference. The difference of two amounts is at most their sum, the triangle inequality pair by pair, so bilateral is at most gross. Through a clearing house each member settles only its net position, what it owes everyone less what everyone owes it. The positive part of a sum is at most the sum of the positive parts, so a member's net debt is at most its bilateral debts added up: multilateral is at most bilateral. And the net positions sum to zero: every dollar owed is owed to someone, so the clearing house is flat. The House's code is six lines, and on the simulated day it prints the three numbers you just watched. A question: A owes B ten, B owes C ten, C owes A ten. What moves through a clearing house? Nothing. Each owes ten and is owed ten, so every net position is zero and not a dollar moves. Clearing nets the promises; settlement is when they are kept.

Can clearing ever make things worse? Duffie and Zhu showed that it can. Before clearing, two dealers net all their trades with each other, across every asset class. Move one class to a clearing house and that class nets across all members, but it no longer offsets the other classes bilaterally. With independent exposures the arithmetic is clean: the expected positive part of a sum of K normals grows like the square root of K, so bilateral exposure grows with the root of the classes, and the cleared class with the root of the members. Compare the two, and clearing one class lowers exposure only if the number of members minus one exceeds one over the gap between root K and root K minus one, squared. With ten classes that is members. The Monte Carlo grid agrees with the formula cell by cell: green where clearing helps, red where it hurts.

If a member defaults, who pays? The waterfall: the defaulter's margin, its default-fund contribution, the clearing house's own capital, then the survivors' default fund, and finally assessments on them. Pour in five stress days, to standard deviations against the biggest member: small shocks stop in its own margin. Over a hundred thousand fat-tailed days, the worst-hit member's loss beats its margin on percent of days but reaches survivors' money on percent. Systemically important clearing houses must survive their two largest members failing at once: cover two.

7Settlement and the depositMaster's3 min

Settlement is when shares and cash actually move. American stocks once settled five business days after the trade, then three from 1995, two from 2017, and since the 28th of May 2024, one. Settlement is delivery versus payment: shares move only against cash, at the same moment, so neither side can deliver and not be paid. And it is netted: the clearing house turns each member's day of trades in a stock into one delivery or one receipt. Between trade and settlement the clearing house holds the risk, and each member pays into a clearing fund to cover it. The biggest piece is a ninety-nine percent value-at-risk on the member's unsettled positions; on top come mark-to-market calls, special charges for volatile names, and the excess capital premium when a member's risk outgrows its capital: the charge of January 2021.

Here is the deposit as a machine. Each day the member's customers buy, net, and that day's purchases ride a conveyor belt until they settle, two days at T plus two. Under the belt is the clearing house's shadow: the deposit, proportional to the volatility of what's on it. Now volatility jumps, from sixty percent a year to four hundred, as GameStop's did. The crates are the same, but the deposit grows about -fold. This is the answer to the hook's question: a broker whose customers only buy still owes the cash on settlement day, for shares that may have collapsed by then, and the clearing house wants that covered today. Shorten the belt to one day, and the shadow shrinks with it.

The arithmetic behind the belt. The exposure is the last h days of net buying, added up. The deposit is a ninety-nine percent value-at-risk on it: two point three three times the volatility, times the square root of the days needed to close out a defaulter, times the exposure. If the flow runs all one way, the exposure is h times the daily flow, and going from two days to one halves the deposit. But most members' flow nets out over days, and flow that nets grows like a random walk, with the square root of h. Halving h then saves only one minus one over root two: twenty-nine percent. The simulation agrees: percent less for one-way flow, percent less for two-way.

What actually happened? After T plus one, NSCC's average clearing fund fell by two point four billion dollars, from twelve point two to nine point eight: twenty percent, not fifty, as netted flow predicts. The industry had to confirm trades on the trade date itself; affirmation by nine in the evening rose from seventy-three percent to about ninety-five. Failed settlements stayed at their old rate, about two percent. Europe and Britain follow on the eleventh of October 2027. A question: settle on the same day. Does the deposit vanish? Not entirely. The overnight risk goes, but between trade and settlement a member can still fail while prices move, and cash and shares must be in place before the trade. And for as long as a derivative stays open, the clearing house holds collateral against it. Next: margin.

8Margin and liquidationUndergraduate4 min

A future or a perpetual swap costs nothing to enter, but the exchange wants collateral. The initial margin: the position's size divided by the leverage allowed. Then the position is marked to market: every day, and on crypto exchanges continuously, gains are paid in and losses paid out. If the account falls below the maintenance margin, the trader gets a margin call, or, on most crypto exchanges, is liquidated on the spot. A hedged book gets a discount: under portfolio margin, a long future and a short in a close cousin are margined on their net risk. How big the margin should be is the next chapter.

How far can the price fall? Hold one coin opened at P nought with margin P nought over L; equity is the margin plus the gain. Liquidation comes when equity falls to a fraction m of the position. Solve: with m at half a percent, ten times leverage survives a nine and a half percent fall, three times a third, two times a half.

A teaching simulation on real hourly closes. On the first of March 2020 Bitcoin was at dollars. Three model accounts go long one coin each on a perpetual, at ten, three and two times leverage: dashed lines for their liquidation prices, and on the right, each account's equity. On the ninth of March the price slips under the first line: the ten-times account is gone. On the twelfth, Part one's crisis, the three-times account goes that evening, and early on the thirteenth, at dollars, even two times closes below zero in this simulator. Real exchanges monitor mark prices much more often and have their own liquidation rules; this is not an actual insurance-fund loss. Within weeks Bitcoin was back above seven thousand. None of these accounts saw it.

The House's margin account is that loop: each hour, pay the funding, add the gain or loss, and check the maintenance line; the first hour below it, close the account at that price. Run on March 2020 it closes the three accounts at the hours you just saw, and reports what's left. Funding is real money too: a perpetual never expires, so every eight hours longs pay shorts when it trades above spot. Through 2020 longs paid in percent of settlements, about percent a year, the same carry the futures basis charged in chapter two.

How likely is liquidation before it happens? Measure the distance to the liquidation price in log terms. For a driftless Brownian log price with constant volatility and a fixed barrier, the reflection principle says the chance of touching it within H days is twice the chance of ending below it. So it is two Phi of minus d over sigma root H. At five times, d is ; at ten, , less than half. Predict what that does to the odds.

Check it on six years of Bitcoin: a long opened every day from 2020 to 2025, at leverage from one and a half to fifty, liquidated if the hourly lows touched its line within H days. Colour is the data; the white mesh, the formula. Leverage turns a slope into a cliff. The pin is ten times for nineteen days, the March 2020 trade: liquidated from percent of starting days. Over ninety days, So how much margin should an exchange ask for? That is the next chapter.

9How much margin?Master's3 min

Models, and procyclicality. How big should margin be? The CME's classic answer, SPAN, revalues a position under sixteen scenarios: the price unchanged or moved a third, two thirds or a whole scan range each way, with volatility up and down, plus two extreme moves counted at thirty percent. A short straddle earns a little when nothing happens and loses on every big move. The margin is the worst scenario: simple, and blind outside its grid.

Most clearing houses now use value-at-risk models instead. The simplest worth using is the exponentially weighted variance of RiskMetrics: today's variance estimate is yesterday's, nudged by yesterday's squared return, with a memory lambda. A lambda of point nine seven gives yesterday's return a weight of three percent and a memory of about a month. Initial margin is then a ninety-nine percent Gaussian value-at-risk over the days it would take to close out a defaulter. How fast should it forget? Choose lambda by maximum likelihood: the Gaussian log-likelihood of the returns, given the variances the recursion predicts. And check it the way a regulator would: count the days losses broke through the margin, and test the count against the promised one percent with Kupiec's likelihood ratio.

Run it through 1987, lambda point nine seven. The band is the one-day ninety-nine percent level; bars are daily returns, red when they break through. The nineteenth of October: percent, far through the band. Only afterwards does margin balloon, from percent of notional to . Margin arrives after the loss. The House's implementation is the recursion, five lines.

Now fit lambda, and watch the fit run. The curve is the log-likelihood over lambda on ninety-four years of daily returns; the band is the same curve computed separately in five eras of nineteen years. A golden-section search closes in on the peak, iteration by iteration. It lands at for the American market, a memory of about two weeks, and for Bitcoin. Then the backtest. With lambda at point nine seven, losses broke the ninety-nine percent margin on percent of days, times in days, double the promise, and Kupiec rejects the model resoundingly. The constant-volatility baseline fails too, at percent, with its misses bunched in crises. The culprit in both is the Gaussian assumption: daily returns have fatter tails than any normal. Clearing houses add stress add-ons for exactly this.

And the bite: within the year, this model's margin rose -fold in 1987, -fold in 2008, -fold in 2020. It asks for cash exactly when cash is scarce. European rules make clearing houses add a damper: a releasable buffer, weight on stressed history, or a ten-year floor. When calls outrun markets, things break: LME nickel in March 2022, trading suspended and trades cancelled, later fined; British pension funds' gilt hedges that September, until the Bank of England bought. So, is a faster margin model safer? It can track changing risk faster, but it can also amplify funding stress. Its members get their biggest calls on the worst day, when cash is scarcest. Hence the dampers. Margin lets you buy with borrowed money; the mirror image is selling what you have borrowed.

10Short selling and the squeezeUndergraduate4 min

To bet that a price will fall, you sell something you don't own. First your broker locates a lender: often a pension fund or an index fund, which lends its shares for a fee. You borrow the shares, post cash collateral worth a little more than they are, and sell them. The lender pays you interest on that cash, the rebate, less its fee. It can recall its shares at any moment, and then you must buy them back, at whatever the price is. And any dividend paid while you are short is yours to pay.

The arithmetic. The collateral, about a hundred and two percent of the price, earns the rebate: the market rate less the fee. Profit is the price fall plus the rebate, less dividends. When shares are scarce the fee can exceed the rate and the rebate turns negative. A stock falling from a hundred to ninety, rates at five percent: borrowed cheaply, the short makes ; at a twenty percent fee it loses , though right about the price. How common? In D'Avolio's data from a large lender, ninety-one percent of stocks on loan cost seventeen basis points; nine percent were special, averaging four point three percent; under one percent cost more than the interest rate.

How can short interest exceed a hundred percent of the shares available? Follow one share. The lender lends it to a short seller, who sells it to buyer B. B now owns a share like any other, and can lend it too: to a second short seller, who sells it to C. One share exists, two are sold short, and short interest counts two. The SEC's staff report gives exactly this example. Repeat it enough and short interest passes a hundred percent of the float: GameStop's reached a hundred and twenty-three. Every short is a future buyer.

Why do squeezes explode? Picture the float as a tank: locked-up holders at the bottom, the free float on top, the only shares anyone can buy. Buying drains the free layer and lifts the price; each short covers past its own pain threshold. A thousand shorts holding one point two times the free float, and a nudge: a few cover, their buying trips the next thresholds, and the price explodes. Across short interest, eight seeds each: below about times the free float a nudge stays a nudge; above it, it runs away. In this model only the ratio matters.

The crisis file: Volkswagen. On Sunday the 26th of October 2008 Porsche disclosed forty-two point six percent of the ordinary shares, plus cash-settled options on thirty-one point five: seventy-four point one. Lower Saxony held about a fifth. About percent was left to buy, less than short interest. In two days the price went from about two hundred and eleven euros to above a thousand, and Volkswagen was briefly the world's most valuable company, until Porsche said it would release up to five percent. Hedge funds later sued, alleging Porsche misled the market; Porsche denied it. A question: short interest at a hundred and twenty percent of float. How? The same share is lent twice. A fund lends it, a short seller sells it, the buyer's broker lends it again. Each short owes a share back, and the long positions add up to more than the float as well. Borrowed shares and borrowed cash are two sides of one market. Next: repo.

11Repo, lending and specialsMaster's3 min

Most leverage is funded overnight by repo: a fund hands over Treasuries and gets cash, and tomorrow repays it with interest. Legally a sale and repurchase; economically a secured loan, the collateral worth a bit more than the cash: the haircut. Interest is cash times rate times days over three sixty. Money funds lend to dealers in tri-party repo, through a clearing bank; dealers lend on to hedge funds bilaterally; securities lending is the same trade from the stock side. In 2008, Copeland, Martin and Walker found, tri-party haircuts barely moved for most dealers while Lehman's collapsed: runs on firms, not on the market.

The haircut is a leverage limit, and it has a shape. At two percent, a dollar of collateral borrows ninety-eight cents, which buys more collateral, which borrows again: a tower, each block ninety-eight percent of the one below, summing to one over the haircut: fifty times. Now the lender raises the haircut to four percent. The tower may only be half as tall: half the book must be sold at once. And selling moves the price, which cuts the fund's equity, which shrinks the tower again. The House's deleverage function plays it out: sales of , then , then percent of the original book, times the first round in all: the loop's gain turned into a multiplier.

Now ten funds near the limit in the same asset, with haircuts that rise as prices fall: Brunnermeier and Pedersen's spiral. To three percent, total selling is times the first round; to four, ; to six, . Small shocks are amplified most, and every case ends about percent lower. The House's code is the loop itself.

One more repo idea. When many traders want to short the same bond, they all need to borrow it, and its owner can lend it out in repo in exchange for cash at a low rate. The bond is special: its repo rate falls below general collateral. Duffie showed what that does to the price. The owner's saving, the rate gap on the bond's value for as long as it stays special, is worth something, so it is priced into the bond: the present value of the cheap borrowing. A bond special at minus one percent for three months, while general repo pays four, carries about a point and a quarter of extra price. The sign: the owner borrows cash at minus one instead of four, five points a year for a quarter, so the special bond trades rich, not cheap. That's one reason the newest Treasury trades rich to its older twins. Repo usually works so smoothly that nobody notices it. One day in 2019, it didn't.

12The day repo brokeIndustry3 min

The crisis file is a day few outside finance noticed. In the summer of 2019 overnight rates sat just above what the Fed paid on reserves. The New York Fed publishes not only SOFR, the median overnight Treasury repo rate, but its spread across the day's trades: the fan. On Monday the 16th of September, corporate taxes fell due and new Treasuries settled, draining cash at once. The median barely moved; the top of the fan jumped to . On Tuesday the whole fan lifted: median percent, ninety-ninth percentile . The New York Fed offered up to seventy-five billion dollars in repo, its first in a decade; dealers took fifty-three. By Thursday the fan had folded back.

Why did one tax date break the market? Since 2017 the Federal Reserve had been shrinking its balance sheet, and the reserves banks keep with it fell from about trillion dollars to trillion the week of the spike. A bank with spare reserves lends them in repo only if repo pays more than the Fed pays on reserves: that spread is the opportunity cost of holding them. When reserves are plentiful the spread is near zero; when they are scarce, banks hold on to them for their own liquidity needs, and the price of cash rises steeply. That's a demand curve for reserves, and it can be measured.

Each dot is a week of 2018 to 2021: reserves across, repo's spread over interest on reserves up. Fit a flat part plus an exponential wall by Gauss-Newton. Within a few iterations the curve bends into the wall; eight bootstrap fits make the band, and it beats a straight line, error against . Below one and a half trillion the spread averaged basis points and reached ; above three and a half, . In September 2019 the system sat on the steep part without knowing it.

The file: on the 17th of September 2019 the safest overnight loan cost percent at the median, and some trades paid . Afonso and colleagues at the New York Fed traced it to reserves concentrated in a few large banks slow to lend them. Every leveraged position in this series is funded overnight. The House charges SOFR plus a spread, and stress-tests a day like this; March 2020's worse failure is Part forty-one. The cash in this story went to dealers. Next, the banks that lend to hedge funds: prime brokers.

13Prime brokers and the race to sellIndustry3 min

Hedge funds borrow through prime brokers: divisions of large banks that lend them cash and securities, hold their assets, clear their trades, and net margin across everything they hold there. Much of the exposure is synthetic. In a total return swap the fund receives the stock's price change and dividends and pays a financing rate, and the bank buys the stock to hedge itself. The fund owns nothing, so it doesn't appear in the quarterly filings that report large shareholders. It can run the same trade with five banks at once, and none of them sees the whole.

When such a client defaults, every bank holds the same shares as its hedge, and every bank must sell. Here are four banks, each with a block of q shares, and a price that falls by lambda for every share sold. The first bank sells into an untouched market. The second sells after the first has pushed the price down; the third, lower still. The j-th seller's average price is the start less everything sold before it, plus half its own block. Its loss is lambda q squared times j minus a half: it grows in a straight line with its place in the queue, and the last of K sellers loses two K minus one times what the first does. With four banks, seven times.

With square-root impact and random sizes, two to eight banks, eight seeds, the picture holds: loss rises with your place in the queue. So two banks decide. Both wait and unwind in order: three quarters each. If the other waits, selling first costs a half; if the other sells, selling too costs one, not one and a half. Selling now is each bank's best response, so both sell and both lose more: a prisoner's dilemma, played in hours.

In March 2021 it was played for real. Archegos, a family office, built concentrated positions through swaps with several prime brokers; the SEC alleges it grew from about one and a half billion dollars, with ten billion of exposure, to over thirty-six billion with a hundred and sixty billion. When its stocks fell it missed margin calls. Banks that sold early lost little; Credit Suisse lost about five and a half billion and Nomura nearly three, as they reported. Its founder was convicted in 2024. Duffie describes the mirror image: clients run from a weak dealer, as from Bear Stearns and Lehman. A question: you hear first. What do you do? Sell, and sell first. The first to unwind gets the better prices and leaves the losses to the slower banks, which is what the early banks did with Archegos. Each bank's best move makes the run worse. Prime brokerage is one of the sell side's businesses. Next: who earns what.

14Who earns whatIndustry3 min

The industry divides in two. The sell side, banks and dealers, makes markets, earns spreads and fees, designs products and lends to everyone else. Acting as agent it works for the client; as principal it trades against the client, from its own book. The buy side invests: asset managers, pension funds, insurers, hedge funds. It charges a fee on assets, and hedge funds take a share of profits too. The big multi-manager platforms often charge their costs, salaries included, straight through to investors instead of a fixed management fee. In between sit proprietary traders and market makers, trading only their own money.

Fees compound, just like returns. Take the American market's calendar years from 1927 to 2020 as a fund's returns before fees. A dollar becomes dollars. Now charge the classic hedge-fund fee: two percent of assets every year, and twenty percent of any gain above the fund's previous peak, the high-water mark. The same dollar becomes . Growth falls from percent a year to , and the investor keeps percent of the profit. Even a plain one percent fee leaves . That's why every Track Record result in this series is charged its fees.

The performance fee pays nothing below the high-water mark and a fifth above it: a call on the fund, struck at its peak. After a bad year it is far out of the money, so funds sometimes close and relaunch, and like any option holder the manager gains from volatility. Fung and Hsieh found hedge-fund returns themselves option-like, nonlinear in the market.

Funds holding illiquid assets mark them with stale or averaged prices. Grey is a fund's true monthly return; gold what it reports: fifty percent of this month, thirty percent of last, twenty percent of the one before. The report is a shadow, same mean, less wiggle, and its Sharpe ratio rises times with no skill at all. It happens in plain indices: the smallest decile of American stocks had daily autocorrelation before 1990, since.

Getmansky, Lo and Makarov: reported returns average the true ones. Variance shrinks by the sum of squared weights. Autocorrelation appears. The mean is untouched, so the Sharpe ratio is inflated by one over the root of that sum: one point six two here.

Undo it: fit the weights by maximum likelihood on five simulated funds of six hundred months. Each dot is a seed's estimate on the triangle of weights; the star is the truth. Every seed walks to the star in a few iterations; the moment estimator, grey, lands close too. On the smallest decile before 1990, the fit puts percent of the weight on the current month: Sharpe inflated times. Assume independent true returns are smoothed over two months: reported autocorrelation point four. Is true volatility higher or lower? Higher. If each month's return is spread over two months, the reported volatility is about three quarters of the truth, so the true one is a third higher, and the Sharpe ratio a quarter lower. Much of the buy side's money simply tracks an index. Next: what an index is, and what being in one does to a price.

15Benchmarks and indicesMaster's3 min

An index is a recipe for a portfolio. Most weight each member by the value of its shares that can trade, the float. A few old ones, like the Dow, add prices and divide by a divisor, which is reset at every split so the index doesn't jump. Put passive money behind the recipe: a fund tracking the index buys the same fraction of every member's float, its assets over the index's value. Classical finance says that buying shouldn't move prices, because demand for a stock is flat at its value. If demand slopes down, it does. Which is it?

The Russell indices give a sharp test. Rank American stocks by value. The top thousand form the Russell one thousand; the next two thousand, the Russell two thousand. Pour passive money onto both. Within each index, every member gets the same fraction of its float bought. But the stock ranked one thousand is the smallest member of a giant index, and the stock ranked one thousand and one is the largest member of a small one. If the same dollars tracked each, the buying per share would jump about -fold at the gate. Two almost identical companies, one rank apart, get very different index demand: a natural experiment, and the right tool for it is a regression discontinuity.

The evidence. Shleifer found that stocks added to the S and P five hundred jumped almost three percent on the announcement, in years when index funds were growing, and argued that demand curves for stocks slope down. Harris and Gurel found that much of the jump faded within weeks: price pressure, not news. Chang, Hong and Liskovich used the Russell gate: stocks that just make the Russell two thousand outperform those that just miss it. The frontier asks how much of the market is tied to benchmarks. Pavlova and Sikorskaya measure benchmarking intensity and find it lowers demand elasticities. And Greenwood and Sammon show the famous S and P inclusion effect has nearly disappeared: about seven percent in the 1990s, under one percent lately, as the market learned to anticipate the changes.

How a regression discontinuity works, on simulated data with a true one and a half percent jump at the cutoff: fit a line on each side and read the gap at the gate. The one choice is the bandwidth. Narrow is noisy; wide lets distant stocks in. Over eight seeds the estimate centres on the truth, its spread growing from to points as the bandwidth shrinks. A question: why does joining the smaller index bring more buying? Because weight is relative. The smallest member of the Russell 1000 is a sliver of a big index; the same company is among the largest in the Russell 2000, and the money tracking it must hold far more. Index rules differ by country, and so does everything else. Next: markets around the world.

16Markets around the worldIndustry3 min

The machine is built differently in each country, and the differences matter. The United States settles in a day, routes most retail orders to wholesalers, and splits trading across many venues. Europe and Britain move to one-day settlement together on the eleventh of October 2027. Japan's yen is the currency the world borrows in, which is why its carry trade, Part twenty-two, matters everywhere. India's National Stock Exchange has been the world's largest derivatives exchange by contracts since 2019, much of it weekly index options bought by individuals. Its regulator found ninety-three percent of them lost money over three years, and ninety-one percent in the year to March 2025, then made contracts bigger and cut weekly expiries to one per exchange. In China a share bought today can't be sold until tomorrow, prices may move at most ten percent a day, twenty on STAR and ChiNext, and in 2024 the regulator suspended lending shares for short sales and set rules for high-frequency trading.

Price limits change the statistics of Part one. Watch a stock hit by big news twice in forty days. The grey line is where the news says the price should be; the red line is the price that can trade, capped at ten percent a day. A spring ties them together. On a limit day the true price runs ahead and the spring stretches; the next day it drags the traded price up again, and again, until they meet. In symbols: the observed return is the true one plus yesterday's unexecuted remainder, clipped at the limit, and whatever is clipped rolls over to tomorrow. So consecutive observed returns share the remainder, their covariance is positive, and a limit day predicts more of the same.

Measure it. Simulate five thousand days of a stock with occasional big jumps, eight seeds, with no limit, with twenty percent limits, and with ten. Without limits the returns are uncorrelated, as they should be. With ten percent limits the autocorrelation is , from a stock that is at its limit on only percent of days; at twenty percent, . A backtest would see momentum. But on a limit-up day the buy queue doesn't clear, and an order joining its back may not fill. The House stores market rules beside prices and models execution. A question: in this carry-over model, a limit-up close with buyers queued. Tomorrow's expected return, and can you trade it? Positive in this model: some price adjustment is deferred. But don't assume a fill. Some orders can trade at the limit while later ones wait; a backtest needs execution evidence. Next: the firms running the machine.

17Industry: who runs the machineIndustry3 min

The money map: who pays whom. Retail orders go to a commission-free broker; the wholesaler that fills them pays for the flow. Exchange trades are novated to the clearing house and settled at the custodian. Hedge funds pay their prime broker, which funds itself in repo against their collateral. Every arrow is a revenue line. Open the boxes, using only what firms and regulators have published.

CME Group, the largest futures exchange, which clears what it trades, reported record 2024 revenue of billion dollars on about million contracts a day. Virtu, a wholesaler and market maker, earned about billion in revenue, up a quarter, and million of net income. Robinhood charges no commission; of its million dollars of transaction revenue in the last quarter of 2024, came from crypto, from options and only from stocks: payment for order flow is an options business. And Citadel Securities says it executes more than a third of American retail volume: the company's own claim.

Prime brokers' biggest recent trade is chapter two's carry on Treasuries: buy the bond, sell the future, fund it in repo, many times over. A Federal Reserve note puts it near billion dollars in September 2025, with hedge funds borrowing trillion in repo. Regulators set the rules. The SEC is moving Treasuries into central clearing, cash trades by the end of 2026 and repo by mid-2027. India's SEBI issued an interim order in July 2025 alleging that Jane Street manipulated index options around expiry days, and impounded about four thousand eight hundred crore rupees in escrow. Those are allegations in an interim order; Jane Street disputes them, and the case is pending.

Where do quants fit in this machine? Place the firms by how long they hold a position and what they trade. At microseconds, the high-frequency market makers and wholesalers. Options market makers a little slower. Statistical arbitrage over minutes to days; trend followers and systematic equity over weeks to months; the multi-manager platforms across all of it; and the banks' desks pricing and hedging for clients. Each has its parts later in the series. And the jobs: the researcher who finds and tests ideas, the trader who runs them and decides when to stop, the developer who builds the systems, the risk quant who asks what can go wrong, the desk quant who prices and hedges for a bank, and the structurer who designs products. Their interviews open with questions like this one: make me a market on the number of trading days in a year. The answer comes at the end of this part. First, the research still moving every number in it.

18Frontier, 2023 to 2026PhD2 min

Six pieces of recent research, placed on a timeline. Greenwood and Sammon show that the index-inclusion effect of chapter fifteen has nearly disappeared. Pavlova and Sikorskaya measure how much of each stock is tied to benchmarks, and find that the more it is, the less elastic its demand, and the lower its returns after the intensity rises. Bryzgalova, Pavlova and Sikorskaya document the rise of retail options trading, now over sixty percent of American options volume, with almost all of its payment for order flow coming from three wholesalers; retail buyers favour cheap weekly options with wide spreads, and lose on average. Schwarz, Barber, Huang, Jorion and Odean placed tens of thousands of identical orders at different brokers at the same moment and got different prices: the gap came from how wholesalers priced each broker's flow, not from payment for order flow. Federal Reserve economists have measured the Treasury basis trade, chapter two's carry on the safest asset: about eight hundred and thirty billion dollars by September 2025, roughly double its early-2020 peak. And Pinter's anatomy of the 2022 gilt crisis shows who sold, and why: pension funds' liability hedges meeting collateral calls, chapter nine's procyclical margin in another guise.

And the plumbing is being rebuilt as we watch. Filled dots are in force, hollow ones pending. American settlement went to T plus one in May 2024, and the clearing fund fell a fifth. The half-penny tick, adopted in 2024, was scheduled for the second of November 2026; in June 2026 the SEC moved it to November 2027. Treasuries, the market behind every repo in this part, move into central clearing: cash trades by the end of this year, repo by the middle of next. Duffie argued at Jackson Hole in 2023 for exactly that, with all-to-all trading, to make the market more resilient. New SEC rules on reporting short positions and securities loans were sent back to the agency by the courts and now start in 2028. Europe and Britain go to T plus one in October 2027. Every one of these changes a number in this part.

For the researcher: backtesting a margin modelPhD5 min

For the researcher: backtesting Chapter 9's margin model. It promises one breach in a hundred days. Can a count tell us whether it works?

The test is a likelihood ratio. Mark each day the margin was breached. If the model is right, the marks are independent coin flips that land heads one time in a hundred. Kupiec's statistic compares the likelihood of the promised rate with the likelihood of the rate observed. Expand it to second order and it is the squared standardised error of the breach rate. So by the central limit theorem it tends to a chi-squared with one degree of freedom: Wilks's theorem. Reject the model when it exceeds three point eight four.

But a year of trading is two hundred and fifty days, and a breach count is a small whole number. These are the exact chances of each count for a correct model. The chi-squared test rejects at zero breaches and at seven or more, and those counts together have probability nine and a half percent, almost twice the nominal five. There are two hundred and fifty-one possible counts, but most probability sits on just a few small ones. Discreteness still matters. At a thousand days the size is five and a half percent. The Basel traffic light, which counts breaches in a year, puts a correct model in its yellow zone or worse about one year in nine. That is a design choice, not an accident: a regulator prefers false alarms.

A count cannot see timing. A margin that is too thin in every crisis and too thick in every calm can have the right number of breaches, all in a few bad months. Christoffersen let the breaches follow a two-state Markov chain: the chance of a breach today given a breach yesterday, or given none. A correct model makes both equal to p. The independence test compares one transition probability with two, by counting each kind of transition: Wilks again, with one restriction. And the two tests add up to a test of conditional coverage, the right count with no memory, chi-squared with two degrees of freedom.

How well do the tests see? Simulate four years of daily returns with clustered volatility. The EWMA count test rejects about eight percent, above the nominal five. A constant margin with exactly the right long-run variance is breached one and a half percent of the time, because clustered volatility fattens the tails, and the count test catches it about half the time. But the independence test, built for exactly this failure, catches it only one time in four. A breach after a breach is six percent likely instead of one, and four years still hold too few breaches to show it. This low power is the test's well-known weakness.

Ninety-five years of the American market give a historical stress test. The constant margin uses the full sample's volatility, so it is a hindsight benchmark, not a tradable forecast. Its breaches pile into the 1930s and the 2000s: almost two hundred in one decade, six in another. EWMA reduces clustering, but the independence test still rejects. Both also fail the count: the EWMA margin is breached on two percent of days, not one, because a normal quantile is too thin for real tails, and breaches still cluster a little. The fix the industry uses is a fatter-tailed quantile or filtered historical simulation, and Part 40 returns to it.

Three open questions. First-order Markov tests miss breaches that cluster at longer lags. Duration tests and regression tests do better, but no test is best against every failure. Regulators now ask for expected shortfall, the average loss beyond the quantile, and expected shortfall cannot be scored on its own: it has no consistent scoring function, only one jointly with the quantile. How best to backtest it is still argued. And the margin's own parameters are estimated, so even under the model the breaches are not exactly coin flips.

Pause and predict. A one-percent margin model is breached on days forty, one hundred, one hundred and one, and one hundred and two, out of two hundred and fifty. Compute the count statistic and the transition counts. Which test, if any, rejects it?

The count is fine: four in two hundred and fifty gives a likelihood ratio of zero point seven seven. Of two hundred and forty-nine transitions, two enter a breach, two leave one, and two connect consecutive breaches. The next-day rate jumps from two in two hundred and forty-five to two in four. Independence rejects: twelve point two exceeds three point eight four. With four breaches, check against a simulated null distribution.

The funding desk; recap, desk questions, problemsAll tracks2 min

The House's second desk, treasury and funding, is built and tested. It maintains margin accounts and fits and backtests margin. It also handles netting, auctions, hedges, borrowing and fees. Rule 3: every backtest pays funding, margin and fees, with liquidation under its stated rules.

Part two in ten lines. Prices come with a mechanism and a cost: carry, spreads, collateral and fees. Netting shrinks obligations; clearing concentrates the remaining risk. A driftless Brownian log-price model gives benchmark liquidation odds. Margin calls can amplify stress. Borrowed shares can be recalled, haircuts can rise, and selling first can hurt everyone else. Smoothed returns flatter performance. Index demand and market rules change both prices and their measured statistics.

Three desk questions. The first is a classic of trading interviews, the market-making game: make me a market on the number of trading days in an American year. About two hundred and fifty-two: three hundred and sixty-five days, less a hundred and four weekend days, less nine or ten holidays. Quote it tight, and be ready to be hit on either side. A future at a hundred and two, spot at a hundred, six months, three percent rates: fair value is a hundred and one fifty-one, so sell the future, buy the spot with borrowed money, and lock in forty-nine cents. Short interest at a hundred and twenty percent of float: shares lent, sold and lent again; and every one of those shorts must one day buy from a float that may run out.

And seven problems: liquidation odds by the reflection principle, netting by hand, the deleveraging loop's fixed point, a hedge ratio, undoing smoothed returns, and two at the level of a qualifying exam: Wilks's theorem for Kupiec's test, and Christoffersen's independence test. Solutions, in English and Chinese, are in the notes.

Where this comes back: funding and margin in hedging and crises; books and auctions in execution; clearing in credit; and fees and smoothing in every backtest. The card gives the part numbers.

These are the textbook chapters, papers and primary reports behind this part. Computed examples use public market data or explicitly labelled simulations; disclosed firm figures come from the cited reports.

The House now has two desks: data and treasury. Next, Part three: value, accounting and the firm. What does a share claim, and what do company accounts reveal?

Where it goes next. Margin and funding return in every crisis of the series (Parts 21, 41); the auction and the book return as microstructure (Parts 35-38).

Key results

The part's results in one place, for revision.

Cost of carry\[F_0 = S_0\,e^{(r-q)T}\]
Liquidation price of a long\[P_{\text{liq}} = P_0\,\frac{1-1/L}{1-m}\]
Leverage and haircut\[L_{\max}=\frac1h\]
Minimum-variance hedge\[h^\ast=\rho\,\frac{\sigma_S}{\sigma_F}\]

Try it

Lab 2 · Margin, leverage and the liquidation price

Open the same long at 2x, 3x, 5x and 10x on one simulated path with a crash; let the House's margin account mark it to market bar by bar, and check the closed-form liquidation price and probability.

Figure produced by Lab 2: Margin, leverage and the liquidation price
Produced by the lab below, seed 0, in 0.1 s. Simulated data.
python -m videos.quant.labs 2 needs numpy, scipy, matplotlib, numba · download lab02.py · source on GitHub
2x                        liquidation price  50.25   survives; equity x0.44
3x                        liquidation price  67.00   survives; equity x0.15
5x                        liquidation price  80.40   liquidated at bar 161 (price 79.40); left -3.0% of margin
10x                       liquidation price  90.45   liquidated at bar 156 (price 88.60); left -14.0% of margin
P(liquidated in 10 days)  2x 0.0%  3x 0.0%  5x 4.9%  10x 36.5%

Driftless Brownian log price, reflection principle. Leverage chooses the distance to the barrier.
The code (50 lines; it asserts its own result)
"""Lab 2: one path, four leverages: who is liquidated, where, and what is left."""

import numpy as np

from videos.quant import labs
from explainer.quant.house import funding, paths

TITLE = "Margin, leverage and the liquidation price"
GOAL = ("Open the same long at 2x, 3x, 5x and 10x on one simulated path with a crash; let the House's margin "
        "account mark it to market bar by bar, and check the closed-form liquidation price and probability.")
TASKS = [
    "Make it a short (qty = -1) and move the crash to a squeeze. Which side has the bounded loss?",
    "Charge funding of 0.01% a bar (funding=np.full(n, 1e-4)): how much sooner does 10x go?",
    "Plot funding.liquidation_probability against leverage for 5, 20 and 60 days.",
]


def run(seed=0):
    n, sigma = 240, 0.035  # hourly bars over ten days; daily volatility 3.5%
    t, S = paths.gbm(100.0, 0.0, sigma * np.sqrt(365), 10 / 365, n, 1, seed=seed + 2)
    p = S[0].copy()
    p[150:] *= np.linspace(1.0, 0.72, 16).tolist() + [0.72] * (n + 1 - 166)  # an illustrative 28% slide
    lab, m = labs.Lab(), 0.005
    fig, ax = labs.figure(2, size=(11, 4.2))
    ax[0].plot(p, color=labs.SPOT)
    colors = [labs.GAIN, labs.P, labs.IMPLIED, labs.LOSS]
    for lev, c in zip((2, 3, 5, 10), colors):
        acct = funding.margin_account(p, qty=1.0, leverage=lev, maintenance=m)
        liq_px = funding.liquidation_price(p[0], lev, m)
        i = acct["liquidated_at"]
        ax[0].axhline(liq_px, color=c, lw=0.9, ls="--")
        ax[0].text(n, liq_px, f" {lev}x", color=c, va="center", fontsize=9)
        ax[1].plot(acct["equity"] / acct["initial_margin"], color=c, label=f"{lev}x")
        if i is None:
            lab.row(f"{lev}x", f"liquidation price {liq_px:6.2f}   survives; equity x{acct['left'] / acct['initial_margin']:.2f}")
            assert p.min() >= liq_px * (1 - 1e-9)
        else:
            ax[0].plot(i, p[i], "x", color=c, ms=8)
            lab.row(f"{lev}x", f"liquidation price {liq_px:6.2f}   liquidated at bar {i} (price {p[i]:.2f}); "
                               f"left {100 * acct['left'] / acct['initial_margin']:+.1f}% of margin")
            assert p[i] < liq_px <= p[:i].min() + 1e-9, "liquidated at the first bar below the liquidation price"
    prob = funding.liquidation_probability(np.array([2, 3, 5, 10]), 10, sigma, m)
    lab.row("P(liquidated in 10 days)", "  ".join(f"{lev}x {100 * q:.1f}%" for lev, q in zip((2, 3, 5, 10), prob)))
    lab.note = "Driftless Brownian log price, reflection principle. Leverage chooses the distance to the barrier."
    ax[0].set(title="One path, four liquidation prices", xlabel="hour", ylabel="price")
    ax[1].axhline(0, color=labs.MUTED, lw=0.8)
    ax[1].set(title="Equity as a multiple of the margin posted", xlabel="hour")
    ax[1].legend(ncols=4)
    lab.fig = fig
    return lab

Now change it

  1. Make it a short (qty = -1) and move the crash to a squeeze. Which side has the bounded loss?
  2. Charge funding of 0.01% a bar (funding=np.full(n, 1e-4)): how much sooner does 10x go?
  3. Plot funding.liquidation_probability against leverage for 5, 20 and 60 days.

Problems, with solutions

Try each problem before opening its solution; the last two of each set are at qualifying-exam level.

Desk questions, with solutions

  1. Make me a market on the number of trading days in a US year. 365 days less 104 weekend days is 261 weekdays; the NYSE closes for 9 or 10 holidays, so a year has about 250–252 trading days. A tight market, say 249 bid at 252 offered, shows you know the answer; the game is how you move the quote when you are hit.
  2. Future 102, spot 100, six months, 3%, no yield. Fair value is 100e^{0.03×0.5} = 101.51. The future is rich: borrow 100, buy spot, sell the future at 102; at expiry deliver, receive 102, repay 101.51: 0.49 locked in, less costs (and the margin the short future needs along the way).
  3. Short interest at 120% of float. Shares are lent, sold, and lent again by their buyers, so the same share is counted short more than once (SEC staff report, footnote 75). Every short is a future buyer of a float that may run out: the risk is a squeeze, plus recalls and rising borrow fees.

Problems, with worked solutions

  1. Liquidation odds. A long opened at \(P_0\) with leverage \(L\) is liquidated at \(P_0(1 - 1/L)/(1 - m)\). With \(m = 0.5\%\) and daily volatility 4%, use the reflection principle to find the chance that 5x and 10x longs are liquidated within 30 days.

    Solution

    d = −ln[(1 − 1/L)/(1 − m)]: 0.218 at 5×, 0.100 at 10×. With σ = 4% a day and H = 30, σ√H = 0.219, so P = 2Φ(−d/σ√H): 2Φ(−0.995) = 32% at 5×, 2Φ(−0.458) = 65% at 10×. Doubling leverage more than halves the distance (the maintenance margin eats into it) and doubles the odds.

  2. Netting. A owes B 10, B owes C 10, C owes A 10, and A owes C 5. Compute the gross, bilateral and multilateral obligations and check \(M \le B \le G\).

    Solution

    G = 10 + 10 + 10 + 5 = 35. Bilateral: A–B 10, B–C 10, C–A 10 against 5 leaves 5: B = 25. Net positions: A −5, B 0, C +5, so M = 5 ≤ 25 ≤ 35.

  3. The deleveraging loop. A fund at a 2% haircut's leverage limit sees the haircut rise to 4%. Each unit sold lowers the price by \(\lambda\). Write the deleveraging loop and find its fixed point; when does it wipe out the equity?

    Solution

    At the new haircut h′ the fund must cut assets to E/h′: a first sale s₀ = A(1 − h/h′). Each unit sold lowers the price by λ, which costs equity ≈ Aλ per unit and forces a further sale ≈ Aλ/h′ per unit: a loop with gain g = Aλ/h′. If g < 1 the sales converge to s₀/(1 − g); if g ≥ 1 there is no fixed point short of selling everything, and the equity is gone once the cumulative price fall exceeds E/A.

  4. Hedge ratio. Find the minimum-variance hedge ratio and its effectiveness when \(\rho = 0.8\) and \(\sigma_S/\sigma_F = 1.25\).

    Solution

    h* = ρσ_S/σ_F = 0.8 × 1.25 = 1.0; effectiveness ρ² = 0.64.

  5. Smoothing. A fund's returns are smoothed with \(\theta = (0.6, 0.3, 0.1)\) and its reported Sharpe ratio is 1.5. What is its true Sharpe ratio, and its reported lag-1 autocorrelation?

    Solution

    Σθ² = 0.36 + 0.09 + 0.01 = 0.46. True Sharpe = reported × √0.46 = 1.5 × 0.678 = 1.02. Reported ρ₁ = (θ₀θ₁ + θ₁θ₂)/Σθ² = (0.18 + 0.03)/0.46 = 0.46.

  6. (qual) Wilks for Kupiec. (qual) Show \(\text{LR}_{uc} = (\hat p - p)^2/(p(1 - p)/T) + o_p(1)\) under \(H_0\), and hence \(\text{LR}_{uc} \Rightarrow \chi^2_1\).

    Solution

    With \(\ell(q) = x\ln q + (T - x)\ln(1 - q)\), \(\text{LR}_{uc} = 2[\ell(\hat p) - \ell(p)]\). Taylor-expand \(\ell(p)\) around \(\hat p\): \(\ell'(\hat p) = 0\) and \(\ell''(\hat p) = -T/(\hat p(1 - \hat p))\), so \(\text{LR}_{uc} = T(\hat p - p)^2/(\hat p(1 - \hat p)) + O_p(T^{-1/2})\), and \(\hat p \to p\) makes the denominator \(p(1 - p)\). Under \(H_0\), \(\sqrt T(\hat p - p)/\sqrt{p(1 - p)} \Rightarrow N(0, 1)\) (the CLT for Bernoulli draws), so its square, and \(\text{LR}_{uc}\) by Slutsky, tends to \(\chi^2_1\).

  7. (qual) Christoffersen. (qual) Derive the Markov MLEs \(\hat\pi_{01}, \hat\pi_{11}\) and show \(\text{LR}_{ind} \Rightarrow \chi^2_1\); evaluate it for breaches on days 40, 100, 101 and 102 out of 250 days.

    Solution

    The Markov likelihood is \((1 - \pi_{01})^{n_{00}}\pi_{01}^{n_{01}}(1 - \pi_{11})^{n_{10}} \pi_{11}^{n_{11}}\); each factor is a Bernoulli likelihood, so \(\hat\pi_{01} = n_{01}/(n_{00} + n_{01})\) and \(\hat\pi_{11} = n_{11}/(n_{10} + n_{11})\). Independence is the one restriction \(\pi_{01} = \pi_{11}\), so Wilks gives \(\chi^2_1\) (with \(p\) interior, the chain ergodic and both rows' counts growing). For breaches on days 40, 100, 101 and 102 out of 250 days: \(n_{01} = 2\), \(n_{11} = 2\), \(n_{10} = 2\), \(n_{00} = 243\), \(\hat\pi_{01} = 0.008\), \(\hat\pi_{11} = 0.5\); \(\text{LR}_{uc} = 0.77\) (the count is fine), \(\text{LR}_{ind} = 12.2\), \(\text{LR}_{cc} = 13.0\) (\(p\) = 0.002): independence rejects. With so few breaches the \(\chi^2\) approximation is rough, and an exact or simulated \(p\)-value is better.

Reading and notes

The part's papers

from READING.md

  • Shleifer, A. (1986). "Do demand curves for stocks slope down?" Journal of Finance.
  • Chang, Y.-C., Hong, H., Liskovich, I. (2015). "Regression discontinuity and the price effects of stock market indexing." RFS.
  • D'Avolio, G. (2002). "The market for borrowing stock." JFE.
  • Duffie, D. (1996). "Special repo rates." Journal of Finance.
  • Duffie, D. (2010). "The failure mechanics of dealer banks." Journal of Economic Perspectives.
  • Copeland, A., Martin, A., Walker, M. (2014). "Repo runs: evidence from the tri-party repo market." Journal of Finance.
  • Battalio, R., Corwin, S., Jennings, R. (2016). "Can brokers have it all? On the relation between make-take fees and limit order execution quality." Journal of Finance.
  • Ernst, T., Spatt, C. (2022). "Payment for order flow and asset choice." NBER Working Paper 29883.
  • Fung, W., Hsieh, D. (1997). "Empirical characteristics of dynamic trading strategies: the case of hedge funds." RFS.
  • Getmansky, M., Lo, A. W., Makarov, I. (2004). "An econometric model of serial correlation and illiquidity in hedge fund returns." JFE.
  • SEC Staff (2021). Staff Report on Equity and Options Market Structure Conditions in Early 2021.
  • SEC (2024). Final rule on minimum pricing increments, access fees, and transparency (Rule 612 amendments), Release 34-101070; compliance moved to November 2026 (Release 34-104172, 2025) and to November 2027 (Release 34-105656, 11 June 2026).
  • SEBI (2023, 2024, 2025). Studies of profit and loss of individual traders in equity F&O (FY22–24: 93% lost; FY25: 91%).
  • Smith, E., Farmer, J. D., Gillemot, L., Krishnamurthy, S. (2003). "Statistical theory of the continuous double auction." Quantitative Finance 3(6).
  • Harris, L., Gurel, E. (1986). "Price and volume effects associated with changes in the S&P 500 list: new evidence for the existence of price pressures." Journal of Finance.
  • Duffie, D., Zhu, H. (2011). "Does a central clearing counterparty reduce counterparty risk?" Review of Asset Pricing Studies 1(1).
  • Brunnermeier, M., Pedersen, L. H. (2009). "Market liquidity and funding liquidity." RFS 22(6).
  • Afonso, G., Cipriani, M., Copeland, A., Kovner, A., La Spada, G., Martin, A. (2021). "The market events of mid-September 2019." FRBNY Economic Policy Review 27(2).
  • Bogousslavsky, V., Muravyev, D. (2023). "Who trades at the close? Implications for price discovery and liquidity." Journal of Financial Markets 66.
  • Frontier: Greenwood, R., Sammon, M. (2025). "The disappearing index effect." Journal of Finance 80(2); Pavlova, A., Sikorskaya, T. (2023). "Benchmarking intensity." RFS 36(3); Bryzgalova, S., Pavlova, A., Sikorskaya, T. (2023). "Retail trading in options and the rise of the big three wholesalers." Journal of Finance 78(6); Schwarz, C., Barber, B., Huang, X., Jorion, P., Odean, T. (2025). "The 'actual retail price' of equity trades." Journal of Finance 80(5); Glicoes, J., Iorio, B., Monin, P., Petrasek, L. (2024). "Quantifying Treasury cash-futures basis trades." FEDS Notes; Monin, P. (2026). "Decomposing hedge funds' U.S. Treasury exposures." FEDS Notes; Pinter, G. (2023). "An anatomy of the 2022 gilt market crisis." Bank of England Staff Working Paper 1019; Duffie, D. (2023). "Resilience redux in the US Treasury market." Jackson Hole symposium.
  • Industry and regulatory sources: DTCC/NSCC (netting; T+1 after-action report with SIFMA and ICI, September 2024); CME Group 2024 results; Virtu 2024 Form 10-K; Robinhood Q4 2024 results and 2024 Form 10-K; SEC press release 2022-70 (Archegos, allegations); FCA final notice to the LME (March 2025); SEBI interim order on Jane Street (3 July 2025; allegations); CME SPAN risk arrays; EMIR RTS 153/2013 Art. 28 and ESMA's APC guidelines.

Papers and sources

Every paper on this part's list in READING.md appears on screen: Shleifer (1986), Harris–Gurel (1986) and Chang–Hong–Liskovich (2015) in ch. 15; D'Avolio (2002) in ch. 10; Duffie (1996) and Copeland–Martin–Walker (2014) in ch. 11; Brunnermeier–Pedersen (2009) in ch. 11; Duffie (2010) in ch. 13; Battalio–Corwin–Jennings (2016) and Ernst–Spatt (2022, NBER WP 29883) in ch. 5; Fung–Hsieh (1997) and Getmansky–Lo–Makarov (2004) in ch. 14; Smith–Farmer–Gillemot–Krishnamurthy (2003) in ch. 3; Bogousslavsky–Muravyev (2023, Journal of Financial Markets) in ch. 4; Duffie–Zhu (2011) in ch. 6; Afonso et al. (2021) in ch. 12; the SEC staff report (2021) in the hook and ch. 5, 7, 10; Rule 612 (2024) in ch. 3 and 18; SEBI's studies in ch. 16; and the frontier papers (Greenwood–Sammon 2025, Pavlova–Sikorskaya 2023, Bryzgalova–Pavlova–Sikorskaya 2023, Schwarz et al. 2025, Glicoes et al. 2024 and Monin 2026, Pinter 2023, Duffie 2023) in ch. 18. Facts checked against primary sources for this edition: the SEC staff report's NSCC figures (section 3.5) and footnote 75; SEC exemptive order 34-105656 (11 June 2026: Rule 612 and the access-fee cap delayed to the first business day of November 2027); CME's SPAN risk arrays (16 scenarios, extremes at 3 scan ranges counting 30%); ESMA's guidelines on EMIR Art. 28 (25% buffer; 10-year look-back floor); NSCC's 98% netting; D'Avolio (2002), p. 271–272; the SIFMA–ICI–DTCC T+1 after-action report; the FCA's LME fine (£9.2 m, March 2025); SEC press release 2022-70; SEBI's interim order (allegations; the matter is pending).

For the researcher

  • The theorems. Wilks (1938) for both likelihood ratios; Kupiec (1995) and Christoffersen (1998) for the tests. Their asymptotics need many breaches: at \(p\) = 1% and \(T\) = 250 there are about 2.5, so exact binomial (or simulated Markov) distributions should replace \(\chi^2\) in practice.
  • Simplifications. The video ignores the estimation of the margin's parameters (Escanciano and Olmo 2010 show the test's size changes), and its GARCH simulation uses normal shocks; Student-\(t\) shocks raise the breach rate of any normal-quantile margin further.
  • Reading. Wilks (1938); Kupiec (1995); Christoffersen (1998); Christoffersen and Pelletier (2004); Engle and Manganelli (2004); Escanciano and Olmo (2010); Gneiting (2011); Fissler and Ziegel (2016); Acerbi and Szekely (2014); Basel Committee, Supervisory framework for the use of backtesting (1996).
  • Open problems. Tests with power against realistic, longer-lag clustering; backtesting expected shortfall; inference that accounts for an estimated margin.
Textbook audit
Book · section Where
Hull OFOD 1 (forwards, futures, options; types of traders) ch. 1, 2, 17
Hull 2 (futures markets: specs, convergence, daily settlement, margin, CCPs, delivery, forwards vs futures) ch. 1, 2, 6, 8
Hull 3 (hedging: basis risk, cross hedge, minimum-variance ratio, beta hedge, stack and roll) ch. 2
Hull 5 (forward and futures prices: carry, known yield, valuing forwards) ch. 2; FX and commodities → Part 22
Hull 5 (short selling) ch. 10
Hull 4, 6, 7 (interest rates, rate futures, swaps) quoting in ch. 1 → Part 18
Hull 10 (mechanics of options markets: specs, OCC, margin on written options) ch. 1, 9; strategies → Part 11
Harris 1–2 (introduction; the trading industry) ch. 14, 17
Harris 3 (orders: market, limit, stop; DAY/GTC/IOC/FOK; hidden, iceberg) ch. 3
Harris 4 (market structures: quote- and order-driven, brokered; continuous vs call; transparency) ch. 3, 4, 5
Harris 5 (order-driven markets: precedence rules; uniform vs discriminatory pricing) ch. 3, 4
Harris 6 (brokers: principal–agent, best execution) ch. 5
Harris 7–8 (why people trade; good markets) Part 1; Part 35
Tuckman–Serrat, repo (GC and special, specialness, tri-party, leverage) ch. 11, 12
Pedersen 1 (hedge funds, fees, high-water mark) ch. 14
Pedersen 5 (trading and financing: margin, funding liquidity, spirals) ch. 8, 9, 11, 13; Part 41
Pedersen 2–4 (performance measures, backtesting, portfolio construction) Parts 26, 30
Mishkin (the financial system, money markets) ch. 11, 12 (overview)
Data, scope and reproducibilityInterpretation boundaries
  • Market orders seek immediate execution; liquidity shortages and trading halts can prevent a complete fill. A limit order bounds the execution price rather than guaranteeing one price or a fill. Priority rules vary by venue.
  • Cash-and-carry equality is derived for frictionless forwards with fixed funding, shorting available and no default. Deterministic rates connect it to futures; stochastic rates, funding frictions and settlement details need additional care.
  • March 2020's hourly-close margin accounts are teaching simulations on real prices. Their negative balances do not reconstruct actual exchange liquidations or insurance-fund payouts. The reflection formula assumes a driftless Brownian log price, constant volatility and a fixed barrier, with no fees or funding changes.
  • In the historical margin backtest, constant volatility is estimated from the full research sample. It is a hindsight benchmark, not an out-of-sample trading rule.

Autocorrelation alone does not identify return smoothing or true volatility. The two-month worked inference assumes iid underlying returns and normalized nonnegative smoothing weights.

At a binding price limit, some orders can execute while the remaining queue waits. Backtests must establish queue priority and available liquidity rather than assume that every order fills, or that none can fill.

Data, scope and reproducibilityData and reproducibility
  • Binance's public archive (data.binance.vision), each file checked against Binance's SHA-256 and recorded in videos/quant/data/manifest.json: USD-M BTCUSDT perpetual hourly and daily candles and funding (2020); coin-margined BTCUSD_210326 hourly (December 2020 – March 2021), new in this edition; spot BTCUSDT hourly 2020–25 and daily 2018–25; spot ETHUSDT daily 2021–23.
  • FRED: SOFR, SOFR1, SOFR25, SOFR75, SOFR99 (new), DFF, IOER, IORB, WRESBAL; frozen windows through 2025.
  • Kenneth French: daily US market and size deciles, research window to 2020.
  • Simulations (seeded): the zero-intelligence book, the auction, RFQ and markouts, the netting day, Duffie–Zhu, the waterfall, the settlement belt, the squeeze, the spiral, the fire sale, GLM fits, the Russell RD, price limits.
  • The House's new functions (funding.py, tested in tests/test_quant_house.py): min_var_hedge, hedge_effectiveness, implied_carry, ewma_var, ewma_margin, ewma_loglik, fit_ewma_lambda, kupiec, liquidation_probability, ccp_waterfall, short_pnl, deleverage, fire_sale, glm_smooth, glm_fit.

Chapter notesChapters (about 65 minutes)
  • What happens when you press buy? A trade's life with a collateral clock; 27–28 January 2021 from the SEC staff report: NSCC's intraday calls of $6.9 bn on 36 members ($2.1 bn mark-to-market, $4.8 bn special charge), $25.5 bn required in all; the waived excess-capital-premium charge that would have been "more than double" one retail broker-dealer's $1.4 bn margin requirement; GameStop short interest 122.97% of float; the history strip (1602–2024).
  • 1. Instruments and how they are quoted. Six instruments; clean and dirty bond prices drawn live; contract specs (E-mini: $50 × index, 0.25-point tick; equity options: 100 shares, cleared by the OCC); notional, DV01, leverage.
  • 2. Futures: carry, basis and the hedge. F = Se^{(r−q)T} by cash-and-carry and reverse carry; Binance's coin-margined March-2021 BTC future against spot, hour by hour (10 Feb 2021: 5.09% over spot, 40.9% a year; mean 24.7%, max 57.2% with more than 10 days left); the minimum-variance hedge h* = ρσ_S/σ_F and effectiveness ρ²; 3D: hedge variance over (h, ρ); lab: ETH hedged with BTC, h* = 1.11 (bootstrap 1.01–1.22), 68% of variance removed in 2021–22, 65% out of sample in 2023.
  • 3. The order book. Order types, validity, hidden and iceberg orders, price–visibility–time precedence; a zero-intelligence book (Smith et al. 2003) running as queues; the cost of walking the book (half-spread plus walk) against simulated books (concave); spreads 2.0 / 3.1 / 5.4 ticks as the market-order rate rises; Rule 612 (2024), compliance moved to November 2027.
  • 4. Auctions: one price for everyone. 300 orders building the staircases live; proof that the crossing maximizes volume; a 2,000-share market-on-close buy moves the clearing price 100.07 → 100.14 (walking the book instead: average 100.13, last 100.17); closing auctions 7.5% of US volume in 2018 (Bogousslavsky–Muravyev); lab: call_auction.
  • 5. Dealers, RFQ and wholesalers. Best of n quotes (order statistics, √(2 ln n)) against leakage λ: n* = 4 at λ = 0.15σ; simulated markouts (retail against informed flow); wholesaler economics; GameStop internalization (SEC); Ernst–Spatt; Battalio–Corwin–Jennings.
  • 6. Clearing: novation, netting, the waterfall. The netting graph collapsing into the CCP ($11.0 bn → $3.1 bn → $1.0 bn, −91%); proof of M ≤ B ≤ G; NSCC's 98%; Duffie–Zhu (clearing one of K classes helps only if N − 1 > (√K − √(K−1))⁻²: N ≥ 39 for K = 10), Monte Carlo against the formula; a default waterfall under 10⁵ t-shocks (the worst-hit member's loss passes its margin on 9.3% of days, reaches survivors' money on 2.8%); cover-2; lab: netting.
  • 7. Settlement and the deposit. DVP, CNS, the clearing fund (99% parametric VaR, MTM, special charges, ECP); the settlement conveyor: a volatility spike to 400% multiplies the deposit 6.8×; T+2 → T+1 cuts it 50% for one-way flow but 30% for two-way flow; the real T+1 after-action numbers (clearing fund −$2.4 bn, −20%; affirmation 73% → ~95%).
  • 8. Margin and liquidation. IM/VM/maintenance; P_liq = P₀(1 − 1/L)/(1 − m); March 2020 run live hour by hour with three simulated accounts' equity (10× on 9 March, 3× on 12 March, 2× on 13 March at $4,063, $271 below zero); lab: margin_account; funding 17% a year in 2020; the reflection principle P = 2Φ(−d/σ√H); 3D: the empirical liquidation surface over leverage × horizon from BTC hourly lows 2020–25 against the formula (10×, 19 days: 37% in data, 50% by the formula; fat tails at short horizons, drift at long ones).
  • 9. How much margin? SPAN's 16 scenarios; EWMA VaR margin; 1987 as a breathing band (2-day margin 3.5% on 16 Oct → 11.7% on 20 Oct); λ fitted by likelihood, replayed (0.936 for the US market, 0.973 for BTC); breaches 2.09% vs 1% (Kupiec LR 226); procyclicality (×5.9 in 1987, ×4.0 in 2008, ×7.6 in 2020); EMIR anti-procyclicality tools; LME nickel 2022; UK LDI 2022; lab: ewma_margin.
  • 10. Short selling and the squeeze. Fee, rebate, dividends, specials (100 → 90: +14.84 at GC, −5.30 at a 20% fee); D'Avolio's numbers; short interest above 100% by relending; a squeeze against free float (runaway above about 1.1× the free float); Volkswagen, October 2008 (about 6% free float).
  • 11. Repo, lending and specials. Repo arithmetic, tri-party and bilateral (Copeland–Martin–Walker); the collateral tower (1/h) and its crumble (sales 50, 24.7, 6.1 … = 1.63× the first round); ten funds' spiral (Brunnermeier–Pedersen; 5.8×/2.6×/1.7× at 3/4/6% haircuts); specials (Duffie 1996); lab: deleverage.
  • 12. The day repo broke. The SOFR percentile fan (99th percentile 2.40% → 4.60% → 9.00% on 13/16/17 Sep 2019, median 5.25%); reserves; the reserve demand curve fitted by Gauss–Newton and replayed with bootstrap bands (+15.3 bp mean, +82.6 bp max below $1.5 tn; −9.6 bp above \(3.5 tn); Afonso et al. (2021). * **13. Prime brokers and the race to sell.** TRS economics; the race L_j = λq²(j − ½), the last seller losing (2K − 1)× the first; square-root impact with random orders (loss by rank, 8 seeds); the prisoner's dilemma; Archegos (SEC allegations; Credit Suisse ~\)5.5 bn, Nomura ~$2.9 bn as reported); Duffie (2010).
  • 14. Who earns what. Sell and buy side; 2 and 20 on 1927–2020 ($7,893 → $360, the investor keeps 4.5% of the profit); the performance fee as a call; Fung–Hsieh; Getmansky–Lo–Makarov smoothing (Sharpe ×1.62 for θ = (0.5, 0.3, 0.2)); smallest size decile AC1 0.40 (1963–89) vs 0.04 (1990–2020); the MLE fit replayed over five seeds against the moment estimator.
  • 15. Benchmarks and indices. Cap, float and price weights; inclusion demand; the Russell gate; Shleifer, Harris–Gurel, Chang–Hong–Liskovich, Pavlova–Sikorskaya, Greenwood–Sammon; a simulated regression discontinuity (true jump 1.5%, recovered at every bandwidth, s.d. 0.12 → 0.45 points as the bandwidth shrinks).
  • 16. Markets around the world. US, EU/UK T+1 (11 Oct 2027), Japan, India (SEBI: 93% FY22–24, 91% FY25), China (T+1, ±10%/±20%, 2024 rules); the price-limit spring (log returns clipped at \(\ln(1-L)\) and \(\ln(1+L)\)); simulated limits create AC1 0.12 at ±10% (0.03 at ±20%).
  • 17. Industry: who runs the machine. The money map; firm files (CME, Virtu, Robinhood, Citadel Securities), the basis trade, regulators (SEC, FCA, SEBI's Jane Street interim order: allegations); the quant map and roles.
  • 18. Frontier, 2023 to 2026. Six papers and the rule changes (T+1, Rule 612's delay, Treasury clearing, 13f-2 and 10c-1a, EU/UK T+1).
  • For the researcher: backtesting a margin model. Kupiec's likelihood ratio and Wilks's \(\chi^2_1\) limit, proved by a second-order expansion; at 250 days the exact size of the nominal 5% test is 9.5% (it rejects 0 and 7 or more breaches; 251 possible breach counts, concentrated near zero), 5.5% at 1,000 days; the Basel traffic light puts a correct model in yellow or red 10.8% of years. Christoffersen's Markov independence and conditional-coverage tests. Simulated GARCH(1,1): a constant margin with the right long-run variance is breached 1.5% of days and fails \(\text{LR}_{uc}\) 54% of the time but \(\text{LR}_{ind}\) only 26%; EWMA 8% and 6%. The US market 1926–2020 (24,876 days): EWMA breached 2.1% of days (\(\text{LR}_{ind}\) 34), the constant margin 1.9% with 195 breaches in the 1930s (\(\text{LR}_{ind}\) 94). Three open problems (duration tests; backtesting expected shortfall; estimation error).
  • The funding desk; recap, desk questions, problems.

Companion films in this repository

中文讲义

本讲的中文说明、交易台问题与习题解答(与英文版对应)。

导言量化金融,从零搭建 — 第2部分:市场的机器

本部分跟随一笔交易从按下按钮直到结算,并测量市场的“管道”对每个交易者做了什么:期货与持有成本、订单簿、集合竞价与交易商、清算与结算、 保证金(用真实崩盘价格模拟强平,以及确定保证金的模型)、卖空、回购与折扣率、主经纪商、费用与平滑收益、指数,以及世界各地市场的规则。 所有数字都由本系列自己的代码根据公开数据或注明模型的模拟算出;公司和事件取自公开记录,指控均注明为指控。

讲的是方法,不构成投资建议。

Chapter notes各章(约60分钟)

开场:一笔交易的生命周期,以及SEC工作人员报告中的2021年1月27–28日(NSCC对36家会员日内追缴69亿美元,总要求255亿美元; 被豁免的超额资本溢价对一家零售经纪商而言“超过其14亿美元保证金要求的两倍”;GameStop空头仓位达流通股的122.97%)。

  1. 金融工具及其报价(净价与全价、合约规格、名义本金)。2. 期货:持有成本、基差与对冲(比特币季度期货逐小时收敛;最小方差对冲比率, 三维方差曲面;以太坊用比特币对冲的实验)。3. 订单簿(零智能模型、吃单成本、612规则推迟到2027年11月)。4. 集合竞价(成交量最大化的证明、 收盘市价单)。5. 交易商、询价与批发商。6. 清算(净额结算图、M ≤ B ≤ G的证明、达菲–朱、违约瀑布)。7. 结算与保证金存款(传送带、 T+1的实际效果)。8. 保证金与强平(2020年3月逐小时、反射原理、三维强平概率曲面)。9. 保证金该收多少(SPAN、EWMA、似然拟合、 库皮耶克检验、顺周期性)。10. 卖空与轧空(大众汽车)。11. 回购、证券借贷与特殊券(抵押品之塔与螺旋)。12. 回购市场崩坏的那一天 (SOFR百分位扇形、准备金需求曲线)。13. 主经纪商与抛售竞赛(Archegos)。14. 谁赚什么钱(费用、平滑收益)。15. 基准与指数 (罗素断点回归)。16. 世界各地的市场(涨跌停弹簧)。17. 行业。18. 前沿。结尾:资金台、回顾、交易台问题与习题。
Desk questions, with solutions交易台问题与解答
  1. 给美国一年的交易日数报个价。 365天减去104个周末日是261个工作日;纽交所每年休市9到10天,所以约250到252个交易日。 报一个窄的价差,比如249买、252卖;这个游戏真正考的是被成交之后你如何调整报价。
  2. 期货102,现货100,六个月,利率3%,无收益。 公允价值100e^{0.015} = 101.51。期货偏贵:借100买入现货,以102卖出期货; 到期交割收102,还101.51:锁定0.49,扣除成本(以及期货空头途中所需的保证金)。
  3. 空头仓位是流通股的120%。 股票被借出、卖出,买方又再借出,同一股被重复计为空头(SEC工作人员报告脚注75)。 每个空头都是未来的买家,而可买的流通股可能耗尽:风险是轧空,以及召回和借券费上升。
Problems, with worked solutions习题与解答
  1. 强平概率。 以杠杆 \(L\) 在 \(P_0\) 开的多头,在 \(P_0(1 - 1/L)/(1 - m)\) 被强平。取 \(m = 0.5\%\)、日波动率4%,用反射原理求5倍和10倍多头在30天内被强平的概率。

    解答

    d = −ln[(1 − 1/L)/(1 − m)]:5倍为0.218,10倍为0.100。σ = 每天4%、H = 30时σ√H = 0.219, P = 2Φ(−d/σ√H):5倍为2Φ(−0.995) = 32%,10倍为2Φ(−0.458) = 65%。杠杆翻倍,距离缩短超过一半(维持保证金吃掉一部分),概率翻倍。

  2. 净额结算。 A欠B十,B欠C十,C欠A十,A再欠C五。计算总额、双边和多边净额债务,并验证 \(M \le B \le G\)。

    解答

    G = 10 + 10 + 10 + 5 = 35。双边:A–B 10,B–C 10,C–A 10与5相抵剩5:B = 25。净头寸:A −5,B 0,C +5, 所以M = 5 ≤ 25 ≤ 35。

  3. 降杠杆循环。 一只基金处在2%折扣率的杠杆上限,折扣率升到4%。每卖出一单位,价格下跌 \(\lambda\)。写出去杠杆循环并求其不动点;什么时候权益被清零?

    解答

    新折扣率h′下,基金必须把资产降到E/h′:第一轮卖出s₀ = A(1 − h/h′)。每卖一单位价格下跌λ,权益约损失Aλ, 又需多卖约Aλ/h′:循环增益g = Aλ/h′。g < 1时总卖出收敛到s₀/(1 − g);g ≥ 1时没有不动点,只能全部卖出, 累计跌幅超过E/A时权益归零。

  4. 对冲比率。 当 \(\rho = 0.8\)、\(\sigma_S/\sigma_F = 1.25\) 时,求最小方差对冲比率及其对冲效率。

    解答

    h* = ρσ_S/σ_F = 0.8 × 1.25 = 1.0;有效性ρ² = 0.64。

  5. 平滑。 一只基金的收益按 \(\theta = (0.6, 0.3, 0.1)\) 平滑,报告的夏普比率为1.5。真实夏普比率是多少?报告收益的一阶自相关是多少?

    解答

    Σθ² = 0.36 + 0.09 + 0.01 = 0.46。真实夏普 = 报告值 × √0.46 = 1.5 × 0.678 = 1.02。报告收益的一阶自相关 ρ₁ = (θ₀θ₁ + θ₁θ₂)/Σθ² = (0.18 + 0.03)/0.46 = 0.46。

  6. (资格考试)库皮耶克检验的威尔克斯定理。 (资格考试)在\(H_0\)下证明\(\text{LR}_{uc}=(\hat p-p)^2/(p(1-p)/T)+o_p(1)\),进而证明\(\text{LR}_{uc}\Rightarrow\chi^2_1\)。

    解答

    令\(\ell(q) = x\ln q + (T - x)\ln(1 - q)\),\(\text{LR}_{uc} = 2[\ell(\hat p) - \ell(p)]\)。在\(\hat p\)处泰勒展开,\(\ell'(\hat p) = 0\),\(\ell''(\hat p) = -T/(\hat p(1 - \hat p))\),所以\(\text{LR}_{uc} = T(\hat p - p)^2/(\hat p(1 - \hat p)) + O_p(T^{-1/2})\)。原假设下\(\sqrt T(\hat p - p)/\sqrt{p(1 - p)} \Rightarrow N(0, 1)\), 其平方以及\(\text{LR}_{uc}\)都趋于\(\chi^2_1\)。

  7. (资格考试)克里斯托弗森检验。 (资格考试)推导马尔可夫极大似然估计\(\hat\pi_{01},\hat\pi_{11}\),证明\(\text{LR}_{ind}\Rightarrow\chi^2_1\);计算250天中第40、100、101和102天击穿时的统计量。

    解答

    马尔可夫似然的每个因子都是伯努利似然,所以\(\hat\pi_{01} = n_{01}/(n_{00} + n_{01})\), \(\hat\pi_{11} = n_{11}/(n_{10} + n_{11})\);独立性是一个约束\(\pi_{01} = \pi_{11}\),由威尔克斯定理得\(\chi^2_1\)。250天内4次击穿、 设击穿发生在第40、100、101和102天:\(n_{01} = 2\),\(n_{11} = 2\),\(n_{10} = 2\),\(n_{00} = 243\);\(\text{LR}_{uc} = 0.77\),\(\text{LR}_{ind} = 12.2\), \(\text{LR}_{cc} = 13.0\)(\(p\) = 0.002):独立性检验拒绝。击穿这么少时卡方近似很粗糙,最好用精确或模拟的\(p\)值。

For the researcher写给研究者

两个似然比都依赖威尔克斯定理(1938);检验来自库皮耶克(1995)和克里斯托弗森(1998)。它们的渐近理论需要很多次击穿:\(p\) = 1%、 \(T\) = 250时只有约2.5次,所以实践中应改用精确的二项分布(或模拟的马尔可夫分布)。开放问题:对现实中更长滞后的聚集有功效的检验; 预期短缺的回测;考虑保证金参数估计误差的推断。

补充边界:市价单并不保证全部成交,限价单限定的是成交价格边界。持有成本等式先在固定融资利率、无摩擦、可卖空且无违约的远期模型下推导;利率确定时可联系到期货。2020年3月的逐小时收盘价模拟并非交易所实际强平或保险基金赔付的重建。反射公式要求无漂移、恒定波动率的布朗运动对数价格和固定边界。历史保证金回测中的固定波动率用全研究样本估计,是事后基准而非样本外交易规则。250天的击穿次数共有251个可能值;模拟样本只观察到其中一部分,不代表理论分布只有那些值。

自相关本身并不能确定收益被平滑,或确定真实波动率。两个月的推算要求真实收益独立同分布,且平滑权重非负、和为1。涨跌停价上可以有部分订单成交,剩余队伍继续等待;回测应结合排队优先级和可得流动性,不能假定全部成交,也不能一概认定无人能够成交。

Data, scope and reproducibility数据与复现

币安公开数据(逐文件SHA-256校验并记入videos/quant/data/manifest.json),其中本版新增币本位季度合约BTCUSD_210326; FRED(新增SOFR1、SOFR25、SOFR75、SOFR99);肯尼斯·弗伦奇数据库;所有模拟均固定随机种子。

Build the film

python -m videos.quant.quant2.compute      # the part's numbers, into .cache/quant2
python tools/make.py quant2                # the narrated film, English and Chinese
EXPLAINER_TTS=silent python tools/qa_scene.py quant2 Hook   # one chapter, silent, with a contact sheet

Scenes: videos/quant/quant2. Setup: see the course page. Source of these notes: the part's README and the scenes' narration.