Quant interview toolkit · weighted sampling

Draw trades by size without drawing the same trade twice

3 min readalgorithmsprobabilitysampling

Three trades contain one, two and three lots. Pick two distinct trades for review. On each draw the chance of choosing a remaining trade should be proportional to its lot count. The three-lot trade has a half chance of going first. What chance does it have of appearing anywhere in the final pair?

Weight increases first-draw chance

First-draw chance (%)

Exponential race with the other trades’ total weight fixed at 100.

Give each trade a clock

For a trade of positive weight wiw_i, generate an independent exponential time TiT_i with rate wiw_i. Take the trades in order of increasing times. Write W=∑iwiW=\sum_i w_i. The probability that clock ii rings first is obtained by integrating its density at time tt against the probability that everyone else is still waiting:

P(i first)=∫0∞wie−wit∏j≠ie−wjt dt=∫0∞wie−Wt dt=wiW.P(i\text{ first})=\int_0^\infty w_i e^{-w_it} \prod_{j\ne i}e^{-w_jt}\,dt=\int_0^\infty w_i e^{-Wt}\,dt =\frac{w_i}{W}.

Conditional on the first ring’s time and identity, each remaining clock has survived to that time. Exponential memorylessness gives each residual clock its original distribution, independently. The second winner therefore comes from the remaining weights in the desired proportions. Repeating the argument proves the entire ordered sampling rule.

Why doubling a first-draw probability fails

The three-lot trade can enter the pair in exactly three ways. It can win immediately, follow the one-lot trade, or follow the two-lot trade. Adding these disjoint probabilities gives

36+1635+2634=1720=85%.\frac36+\frac16\frac35+\frac26\frac34 =\frac{17}{20}=85\%.

Doubling its first-draw chance would give 100%. The other two trades really can win both slots. In fact, one then two has probability (1/6)(2/5)=1/15(1/6)(2/5)=1/15, while two then one has probability (2/6)(1/4)=1/12(2/6)(1/4)=1/12. Together these outcomes explain the missing 15%.

This distinction matters when reconstructing totals from a weighted audit. An estimator that sees an unordered set of included trades needs each trade’s final inclusion probability to apply inverse-probability weighting. The weight share wi/Ww_i/W supplies the first-draw probability. Estimating a total from a thinned log

Keep only the earliest clocks

The clocks are random priorities and can be generated as records arrive. A trade that already has kk earlier clocks ahead of it can never make the final top kk. Keep the kk smallest priorities seen so far and discard the rest. A heap maintains these candidates using memory proportional to kk. Exponential times also avoid raising a uniform random number to a power very close to zero, which can make many priorities round to one. Efraimidis and Spirakis, Weighted random sampling with a reservoir

from heapq import nsmallest
from math import isfinite
from random import Random

def weighted_sample(records, k, rng):
    if k < 1:
        raise ValueError("sample size must be positive")

    def clocks():
        for position, (record, weight) in enumerate(records):
            if not isfinite(weight) or weight < 0:
                raise ValueError("weights must be finite and nonnegative")
            if weight > 0:
                yield rng.expovariate(weight), position, record

    return [record for _, _, record in nsmallest(k, clocks())]

print(weighted_sample([("A", 1), ("B", 2), ("C", 3)], 2, Random(7)))

Zero-weight records never enter. If fewer than kk records have positive weight, this implementation returns all eligible records. The position breaks finite-precision ties consistently and avoids comparing arbitrary record payloads.

Practice

UnitsWould recording trade size in shares instead of lots change the sampling law if every lot contains 100 shares?
Show answer

Multiplying all rates by 100 divides all clock times by 100 in distribution. The ordering has the same law. Equivalently, the common factor cancels from every sequential draw probability.

Distributed feedTwo machines process disjoint records. Which information must they send to recover the global sample?
Show answer

Each sends its local kk earliest clock values and their record identifiers, or all eligible records if fewer exist. Select the kk smallest from their union, preserving the original priorities and using a globally consistent tie rule. A locally discarded record already lost to at least kk records on its own machine. The machines need independent clock draws across the full stream.