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
One-slot reservoir sampling retains each item with probability 1/N after N arrivals.
Give the new arrival its fair share
At trade , draw an integer uniformly from 1 through . Replace the stored record if the draw is 1. That gives the newcomer its required chance. Each older record had probability of holding the slot and keeps it with probability . Its new chance is also .
You can follow one record all the way to the close. Trade 3 gets in with probability . At a fixed closing count its chance of surviving is
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 , copy the first records. For record , draw a slot index uniformly from . If the index falls inside the reservoir, overwrite that slot. Every resident now faces the same 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 . 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 and gives everyone a half chance while missing four possible pairs.
For the reservoir, assume each size- subset of the first records is equally likely. Fix a particular target subset among the first . If it excludes the newcomer, the reservoir must already equal the target and reject the newcomer. Its probability is
If the target includes the newcomer, its other members must already be present. There are choices for the extra resident. For each predecessor set the draw must evict exactly that extra record, a event. The result is the same fraction. The first 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 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 causes a write with probability , including the opening trade. Summing gives the harmonic number . A million records require about 14.4 writes on average, although the handler still processes every record.