Quant interview toolkit · sampling algorithms

How to keep one uniformly random trade from a stream

A feed handler sees trades one at a time. At the closing bell it must produce one trade chosen uniformly from the day. It can store one record and a counter. The opening trade has to go into the empty slot. When the second trade arrives, a fair coin decides whether it takes the slot. What should happen on the third?

One reservoir slot stays fair

Chance first item is retained (%)

One-slot reservoir sampling retains each item with probability 1/N after N arrivals.

Give the new arrival its fair share

At trade ii, draw an integer uniformly from 1 through ii. Replace the stored record if the draw is 1. That gives the newcomer its required 1/i1/i chance. Each older record had probability 1/(i−1)1/(i-1) of holding the slot and keeps it with probability (i−1)/i(i-1)/i. Its new chance is also 1/i1/i.

You can follow one record all the way to the close. Trade 3 gets in with probability 1/31/3. At a fixed closing count n≥3n\ge3 its chance of surviving is

133445⋯n−1n=1n.\frac13\frac34\frac45\cdots\frac{n-1}{n}=\frac1n.

No estimate of the eventual trade count enters the rule. Running the same argument conditional on a fixed input sequence works even if the trade sizes and prices are strongly dependent. The random draws used by the sampler must be independent of that sequence.

Keep a whole sample

For capacity kk, copy the first kk records. For record i>ki>k, draw a slot index uniformly from 0,…,i−10,\ldots,i-1. If the index falls inside the reservoir, overwrite that slot. Every resident now faces the same 1/i1/i eviction probability.

from random import Random

def reservoir(records, k, rng):
    if k < 1:
        raise ValueError("capacity must be positive")
    sample = []
    for count, record in enumerate(records, start=1):
        if count <= k:
            sample.append(record)
        else:
            slot = rng.randrange(count)
            if slot < k:
                sample[slot] = record
    return sample

sample = reservoir(range(1, 101), 5, Random(17))

If the stream ends early you get every observed record. Otherwise the output is a uniform subset of size kk. Treat repeated values as distinct records by position. The positions inside the returned list need not be randomly ordered.

Why every subset has the same probability

Equal inclusion probabilities alone leave room for bias. For four trades, a sampler that flips between pairs {1,2}\{1,2\} and {3,4}\{3,4\} gives everyone a half chance while missing four possible pairs.

For the reservoir, assume each size-kk subset of the first i−1i-1 records is equally likely. Fix a particular target subset among the first ii. If it excludes the newcomer, the reservoir must already equal the target and reject the newcomer. Its probability is

1(i−1k)i−ki=1(ik).\frac{1}{\binom{i-1}{k}}\frac{i-k}{i}=\frac{1}{\binom{i}{k}}.

If the target includes the newcomer, its other k−1k-1 members must already be present. There are i−ki-k choices for the extra resident. For each predecessor set the draw must evict exactly that extra record, a 1/i1/i event. The result is the same fraction. The first kk records form the only possible initial set, which starts the induction.

When the closing bell depends on the sample

Suppose you always observe two trades. Stop after trade 2 if trade 1 still holds the slot. Otherwise process one final trade and stop. Among runs ending at two, trade 1 occupies the slot every time. Conditioning on the stopping count has exposed information about the sampler’s private coin flip.

An externally determined close avoids that selection effect. Also pin down the desired sampling unit. A uniformly sampled trade gives a one-share execution the same chance as a thousand-share execution. Its expected price estimates the trade-count average.

For streams where random draws are expensive, Vitter also analyzes how many arrivals a sampler can skip before its next replacement. Jeffrey Vitter, Random Sampling with a Reservoir

Practice

MergeTwo servers sampled one trade each from disjoint streams of 40 and 60 trades. Can you combine the samples without replaying the feeds?
Show answer

Choose the first server with probability 0.4 and the second with probability 0.6, independently of their samples. Any trade on the first server has probability 0.4/40=1/1000.4/40=1/100 of being returned. The same calculation holds on the second. Choosing servers by fair coin would overweight the smaller feed.

CostHow many slot writes do you expect over n records with capacity one?
Show answer

Trade ii causes a write with probability 1/i1/i, including the opening trade. Summing gives the harmonic number HnH_n. A million records require about 14.4 writes on average, although the handler still processes every record.