Algorithm Search⌘K

Algorithmcore

Myerson's optimal auction

Also called Myerson auction, revenue-optimal auction.

Gives the item to the bidder with the highest nonnegative ironed virtual value and charges threshold prices. It maximizes expected revenue for independent private values.

Time
O(N + n K) worst
Space
O(N) extra
Where
K = the largest support size of one bidder; N = the total support size of the value distributions; n = the number of bidders
Properties
comparison baseddeterministiciterative
Origin
Roger B. Myerson, 1981

Myerson's optimal auction sells one item to bidders whose private values are drawn independently from known distributions, and it earns the largest expected revenue of all mechanisms in which bidders report truthfully and never lose by taking part. It maps each bid bib_i to its ironed virtual value φˉi(bi)\bar\varphi_i(b_i), gives the item to the bidder with the largest one if that value is nonnegative, and charges the winner the smallest bid with which it would still win. It is a revenue result built on Myerson's lemma. The lemma says which allocation rules can be made truthful in any single-parameter environment and fixes their payments. This auction uses the lemma and the prior to choose the rule that maximizes expected revenue.

In plain words

A seller has one item and several bidders. The seller does not know what the bidders will pay, but knows from past sales how likely each amount is for each bidder. Selling to the highest bidder is not always best for the seller. A bidder who is likely to bid low is worth less to the seller, because a higher price for that bidder would lose many sales but gain little. The auction corrects each bid for this effect and gets an adjusted bid. The item goes to the highest adjusted bid, and only if that adjusted bid is not negative, so sometimes the seller keeps the item. The winner pays the lowest bid with which it would still have won. So no bidder gains by lying about its value.

The problem

There are nn bidders and one item. Bidder ii has a private value viv_i drawn from a distribution FiF_i, and the draws are independent (independent private values). Utilities are quasilinear: a bidder who wins with probability xix_i and pays pip_i gets vixi−piv_i x_i - p_i. The seller knows F1,…,FnF_1, \ldots, F_n and wants a mechanism that is DSIC, or at least BIC, and individually rational, with the largest expected revenue E[∑ipi]\mathbb{E}[\sum_i p_i].

For a continuous FF with density ff the virtual value is φ(v)=v−(1−F(v))/f(v)\varphi(v) = v - (1 - F(v))/f(v). For a discrete FF on s1<⋯<sKs_1 < \cdots < s_K with probabilities fkf_k and qk=Pr⁡[v≥sk]q_k = \Pr[v \ge s_k], it is φ(sk)=(skqk−sk+1qk+1)/fk\varphi(s_k) = (s_k q_k - s_{k+1} q_{k+1})/f_k, with sK+1qK+1=0s_{K+1} q_{K+1} = 0. In both cases it is the slope of the revenue curve q↦q⋅F−1(1−q)q \mapsto q \cdot F^{-1}(1 - q), the revenue of a posted price that sells with probability qq. The ironed virtual value φˉ\bar\varphi is the slope of the concave hull of that curve (ironing). For a regular distribution the curve is already concave and φˉ=φ\bar\varphi = \varphi.

The algorithm

The implementation takes discrete distributions, so every value and payment is an exact fraction, and bids must lie in the bidder's support.

  1. MYERSON(F_1, ..., F_n, b_1, ..., b_n)
  2. 1for each bidder i: φ̄_i ← slopes of the concave hull of the revenue curve of F_i
  3. 2for each bidder i: c_i ← φ̄_i(b_i)
  4. 3if c_i < 0 for every i: return no sale, all payments 0
  5. 4w ← the smallest index i with c_i maximal
  6. 5p_w ← the smallest s in the support of F_w with which w would still win; p_i ← 0 for i ≠ w
  7. 6return w, p

Line L1 depends only on the distributions and can be done once for many auctions. Line L4 breaks ties by index, a fixed rule, which keeps the allocation monotone in each bid. In line L5, "would still win" means that φˉw(s)≥0\bar\varphi_w(s) \ge 0, that φˉw(s)>cj\bar\varphi_w(s) > c_j for each j<wj < w and that φˉw(s)≥cj\bar\varphi_w(s) \ge c_j for each j>wj > w, with the other bids fixed. For continuous regular distributions with strictly increasing φi\varphi_i, line L5 is pw=φw−1(max⁡(0,max⁡j≠wcj))p_w = \varphi_w^{-1}(\max(0, \max_{j \ne w} c_j)).

Example

Uniform values. For viv_i drawn from U[0,1]U[0, 1], φ(v)=2v−1\varphi(v) = 2v - 1, so the auction is the Vickrey auction with reserve price 1/21/2. One bidder faces the posted price 1/21/2 and the revenue is 1/41/4. With two bidders the revenue is E[max⁡(0,2max⁡(v1,v2)−1)]=5/12\mathbb{E}[\max(0, 2\max(v_1, v_2) - 1)] = 5/12, more than the 1/31/3 of the Vickrey auction without reserve. With bids (0.8,0.6)(0.8, 0.6) bidder 1 wins and pays 0.60.6, with bids (0.8,0.3)(0.8, 0.3) it pays the reserve 0.50.5, and with bids (0.4,0.3)(0.4, 0.3) the item is not sold.

An irregular distribution. Two bidders have values in {2,3,5}\{2, 3, 5\} with probabilities 1/2,1/6,1/31/2, 1/6, 1/3. Then q=(1,1/2,1/3)q = (1, 1/2, 1/3) and the revenue curve has the points (0,0)(0, 0), (1/3,5/3)(1/3, 5/3), (1/2,3/2)(1/2, 3/2) and (1,2)(1, 2). The virtual values are φ=(1,−1,5)\varphi = (1, -1, 5), which is not monotone, so the distribution is not regular. The point (1/2,3/2)(1/2, 3/2) lies below the chord from (1/3,5/3)(1/3, 5/3) to (1,2)(1, 2), whose slope is 1/21/2. So the ironed virtual values are φˉ=(1/2,1/2,5)\bar\varphi = (1/2, 1/2, 5): the values 2 and 3 are treated as equal.

bids (b1,b2)(b_1, b_2) (c1,c2)(c_1, c_2) winner payment
(2,2)(2, 2), (2,3)(2, 3), (3,2)(3, 2), (3,3)(3, 3) (1/2,1/2)(1/2, 1/2) 1 (tie) 2
(5,2)(5, 2) or (5,3)(5, 3) (5,1/2)(5, 1/2) 1 2
(2,5)(2, 5) or (3,5)(3, 5) (1/2,5)(1/2, 5) 2 5
(5,5)(5, 5) (5,5)(5, 5) 1 (tie) 5

With bids (2,3)(2, 3) the bidder with the lower bid wins, because both bids have the same ironed virtual value and the tie goes to bidder 1. With bids (5,3)(5, 3) bidder 1 pays only 2, since it would win the tie with the bid 2. Bidder 2 needs φˉ>1/2\bar\varphi > 1/2 to beat bidder 1, so it pays 5. The expected revenue is 33, which equals E[max⁡(0,φˉ1(v1),φˉ2(v2))]\mathbb{E}[\max(0, \bar\varphi_1(v_1), \bar\varphi_2(v_2))]. The Vickrey auction earns 89/36≈2.4789/36 \approx 2.47 here, and with reserve 5 it earns 25/9≈2.7825/9 \approx 2.78.

Correctness

The proof is in proofs/correctness.md. It has three parts.

  • Truthful. The ironed virtual value is nondecreasing in the bid, so the allocation is monotone, and the payment is the threshold bid. By Myerson's lemma this is DSIC, and a truthful bidder never pays more than its value, so it is ex post IR.
  • Revenue identity. For any monotone rule with threshold payments, an exchange of sums (or an integration by parts) gives E[pi]=E[xi(v)φi(vi)]\mathbb{E}[p_i] = \mathbb{E}[x_i(v) \varphi_i(v_i)]. Since the auction decides only through φˉ\bar\varphi, its allocation is constant where the revenue curve lies strictly below its hull, and then φ\varphi can be replaced by φˉ\bar\varphi. So the revenue is E[max⁡(0,max⁡iφˉi(vi))]\mathbb{E}[\max(0, \max_i \bar\varphi_i(v_i))].
  • Optimal. Any BIC and interim IR mechanism, randomized or not, has a nondecreasing interim allocation and payments at most the threshold sum. Its revenue is at most E[∑ixiφˉi]≤E[max⁡(0,max⁡iφˉi)]\mathbb{E}[\sum_i x_i \bar\varphi_i] \le \mathbb{E}[\max(0, \max_i \bar\varphi_i)], because Rˉ≥R\bar R \ge R and at most one bidder gets the item.
Proof: Correctness and optimality of Myerson's auctionfull

There are nn bidders with independent private values. Bidder ii has a discrete distribution on the values s1<s2<⋯<sKs_1 < s_2 < \cdots < s_K (the support and KK depend on ii, and we drop the index ii when only one bidder is in question) with probabilities f1,…,fK>0f_1, \ldots, f_K > 0. Write qk=∑j≥kfj=Pr⁡[v≥sk]q_k = \sum_{j \ge k} f_j = \Pr[v \ge s_k], so q1=1q_1 = 1, and put qK+1=0q_{K+1} = 0 and sK+1qK+1=0s_{K+1} q_{K+1} = 0. The revenue curve of the bidder is the list of points P0=(0,0)P_0 = (0, 0) and (qk,skqk)(q_k, s_k q_k) for k=K,K−1,…,1k = K, K-1, \ldots, 1, in increasing order of qq. The segment from (qk+1,sk+1qk+1)(q_{k+1}, s_{k+1} q_{k+1}) to (qk,skqk)(q_k, s_k q_k) has length fkf_k in qq and slope

φk=skqk−sk+1qk+1fk,\varphi_k = \frac{s_k q_k - s_{k+1} q_{k+1}}{f_k},

which is the discrete virtual value of sks_k. Let Rˉ\bar R be the least concave function on [0,1][0, 1] that lies on or above all the points, and let φˉk\bar\varphi_k be the slope of Rˉ\bar R on the segment of sks_k. This is the ironed virtual value. Utilities are quasilinear: a bidder with value vv who wins with probability xx and pays pp has utility vx−pv x - p.

Claim 1: line L1 computes the ironed virtual values, and they are nondecreasing in the value

The function upper_hull scans the points in increasing order of qq and keeps a stack. It removes the top of the stack while that point lies on or below the chord from the point under it to the new point. This is the monotone chain method for the upper hull, and at the end the stack holds the vertices of Rˉ\bar R, from P0P_0 to (1,s1)(1, s_1). Between two consecutive vertices Rˉ\bar R is linear, so each segment of a support value inside that range gets the slope of the chord. The slopes of a concave function do not increase as qq grows. Since qkq_k decreases as kk grows, φˉ1≤φˉ2≤⋯≤φˉK\bar\varphi_1 \le \bar\varphi_2 \le \cdots \le \bar\varphi_K. The slope of Rˉ\bar R changes only at a vertex, so if φˉk−1≠φˉk\bar\varphi_{k-1} \ne \bar\varphi_k, then the point (qk,skqk)(q_k, s_k q_k) is a vertex of Rˉ\bar R. The point (q1,s1q1)=(1,s1)(q_1, s_1 q_1) = (1, s_1) is always a vertex, since it is the last point.

Claim 2: the allocation rule is monotone

Fix the reports of all bidders except ii, and let cjc_j be their ironed virtual values (line L2). By lines L3 and L4, bidder ii with ironed virtual value cc wins exactly when c≥0c \ge 0, c>cjc > c_j for every j<ij < i with cj≥0c_j \ge 0, and c≥cjc \ge c_j for every j>ij > i with cj≥0c_j \ge 0. Each condition stays true when cc grows. By Claim 1, a higher report gives a value of cc at least as high. So if bidder ii wins with report sks_k, it wins with every report sk′>sks_{k'} > s_k. The method wins tests exactly these conditions.

Claim 3: truth telling is a dominant strategy and the auction is individually rational

Fix bidder ii, its true value vv in its support, and the reports of the others. Let tt be the smallest support value of bidder ii with which it wins, if there is one. By Claim 2, bidder ii wins with a report bb exactly when b≥tb \ge t. Line L5 is reached only for the winner ww, which wins with its own report, so the scan finds a value, and it is the smallest winning report, so the winner pays tt. The value tt depends only on the reports of the others.

If bidder ii reports vv, it gets v−t≥0v - t \ge 0 when v≥tv \ge t and 00 when v<tv < t, that is, max⁡(v−t,0)≥0\max(v - t, 0) \ge 0. This is individual rationality. With any other report it either wins and pays the same tt, for utility v−tv - t, or loses, for utility 00. Both are at most max⁡(v−t,0)\max(v - t, 0). If no report wins, bidder ii always gets 00.

Claim 4: the expected revenue equals the expected ironed virtual surplus

Fix bidder ii and the reports of the others. Let xk∈{0,1}x_k \in \{0, 1\} say whether bidder ii wins with report sks_k, and put x0=0x_0 = 0. By Claim 2, xx is nondecreasing, and by Claim 3 the payment with report sks_k is

pk=∑j≤ksj(xj−xj−1),p_k = \sum_{j \le k} s_j (x_j - x_{j-1}),

because the sum is sts_t when k≥tk \ge t and 00 otherwise. Exchange the order of summation:

∑kfkpk=∑jsj(xj−xj−1)qj=∑jxj(sjqj−sj+1qj+1)=∑jfjxjφj.(1)\sum_k f_k p_k = \sum_j s_j (x_j - x_{j-1}) q_j = \sum_j x_j \bigl(s_j q_j - s_{j+1} q_{j+1}\bigr) = \sum_j f_j x_j \varphi_j. \tag{1}

Now compare with φˉ\bar\varphi. Put Gk=∑j≥kfjφjG_k = \sum_{j \ge k} f_j \varphi_j and Gˉk=∑j≥kfjφˉj\bar G_k = \sum_{j \ge k} f_j \bar\varphi_j. The first sum telescopes to Gk=skqkG_k = s_k q_k, the height of the revenue curve at qkq_k. The second is the integral of the slope of Rˉ\bar R from 00 to qkq_k, so Gˉk=Rˉ(qk)\bar G_k = \bar R(q_k), since Rˉ(0)=0\bar R(0) = 0. Summation by parts gives, with GK+1=GˉK+1=0G_{K+1} = \bar G_{K+1} = 0,

∑kfkxk(φˉk−φk)=∑kxk((Gˉk−Gˉk+1)−(Gk−Gk+1))=∑k≥1(xk−xk−1)(Gˉk−Gk).(2)\sum_k f_k x_k (\bar\varphi_k - \varphi_k) = \sum_k x_k \bigl((\bar G_k - \bar G_{k+1}) - (G_k - G_{k+1})\bigr) = \sum_{k \ge 1} (x_k - x_{k-1}) (\bar G_k - G_k). \tag{2}

In (2), the term k=1k = 1 vanishes because (1,s1)(1, s_1) is a vertex of Rˉ\bar R. For k≥2k \ge 2, the auction decides through φˉ\bar\varphi only, so xk≠xk−1x_k \ne x_{k-1} implies φˉk≠φˉk−1\bar\varphi_k \ne \bar\varphi_{k-1}, and then (qk,skqk)(q_k, s_k q_k) is a vertex by Claim 1, so Gˉk=Gk\bar G_k = G_k. Hence (2) is zero, and ∑kfkpk=∑kfkxkφˉk\sum_k f_k p_k = \sum_k f_k x_k \bar\varphi_k.

Take the expectation over the independent reports of the others and sum over the bidders. The expected revenue is E[∑iXi(v)φˉi(vi)]\mathbb{E}[\sum_i X_i(v) \bar\varphi_i(v_i)], where Xi(v)=1X_i(v) = 1 if bidder ii wins at the profile vv. At each profile the winner has the largest ironed virtual value, which is nonnegative, and no one wins only when all of them are negative. So the expected revenue is E[max⁡(0,max⁡iφˉi(vi))]\mathbb{E}[\max(0, \max_i \bar\varphi_i(v_i))].

Claim 5: no Bayesian incentive compatible and individually rational mechanism earns more

Take any mechanism, perhaps randomized, in which truth telling is a Bayes-Nash equilibrium (BIC) and every type has nonnegative expected utility (interim IR). For bidder ii, let xkx_k be its probability to win and pkp_k its expected payment with report sks_k, both averaged over the values of the others, and put x0=p0=0x_0 = p_0 = 0.

Monotone. Type sks_k does not gain by reporting sk−1s_{k-1}, and type sk−1s_{k-1} does not gain by reporting sks_k. Adding the two inequalities gives (sk−sk−1)(xk−xk−1)≥0(s_k - s_{k-1})(x_k - x_{k-1}) \ge 0, so xx is nondecreasing.

Payment bound. IR for type s1s_1 gives p1≤s1x1p_1 \le s_1 x_1. The first of the two inequalities above is skxk−pk≥skxk−1−pk−1s_k x_k - p_k \ge s_k x_{k-1} - p_{k-1}, that is, pk≤pk−1+sk(xk−xk−1)p_k \le p_{k-1} + s_k (x_k - x_{k-1}). By induction, pk≤∑j≤ksj(xj−xj−1)p_k \le \sum_{j \le k} s_j (x_j - x_{j-1}) for every kk.

So, by the computation (1), ∑kfkpk≤∑kfkxkφk\sum_k f_k p_k \le \sum_k f_k x_k \varphi_k. In (2), every term is now nonnegative: xk−xk−1≥0x_k - x_{k-1} \ge 0 and Gˉk≥Gk\bar G_k \ge G_k because Rˉ\bar R lies above the curve, and the term k=1k = 1 is zero. Hence ∑kfkpk≤∑kfkxkφˉk\sum_k f_k p_k \le \sum_k f_k x_k \bar\varphi_k. Let Xi(v)X_i(v) be the probability that bidder ii gets the item at the profile vv. By independence, ∑kfkxkφˉk=E[Xi(v)φˉi(vi)]\sum_k f_k x_k \bar\varphi_k = \mathbb{E}[X_i(v) \bar\varphi_i(v_i)]. Summing over the bidders, and using Xi≥0X_i \ge 0 and ∑iXi≤1\sum_i X_i \le 1, the expected revenue is at most

E[∑iXi(v) φˉi(vi)]≤E[max⁡(0,max⁡iφˉi(vi))].\mathbb{E}\Bigl[\sum_i X_i(v)\, \bar\varphi_i(v_i)\Bigr] \le \mathbb{E}\Bigl[\max\bigl(0, \max_i \bar\varphi_i(v_i)\bigr)\Bigr].

By Claim 4, Myerson's auction attains this bound. A DSIC and ex post IR mechanism is also BIC and interim IR, so the auction is optimal in both classes.

The continuous regular case

For a distribution with density ff and a strictly increasing virtual valuation φ(v)=v−(1−F(v))/f(v)\varphi(v) = v - (1 - F(v))/f(v), the function myerson_regular gives the item to the bidder with the largest nonnegative virtual value and charges φw−1(max⁡(0,max⁡j≠wφj(bj)))\varphi_w^{-1}(\max(0, \max_{j \ne w} \varphi_j(b_j))). This is the smallest bid with which ww still wins, up to a tie, which has probability 00. The proofs of Claims 3 to 5 carry over with sums replaced by integrals: the payment identity is p(v)=vx(v)−∫0vx(z) dzp(v) = v x(v) - \int_0^v x(z)\, dz (Myerson's lemma), and integration by parts gives E[pi]=E[φi(vi)xi(vi)]\mathbb{E}[p_i] = \mathbb{E}[\varphi_i(v_i) x_i(v_i)]. No ironing is needed because φ\varphi is already monotone. For U[0,1]U[0, 1], φ(v)=2v−1\varphi(v) = 2v - 1, and with two bidders the revenue is E[max⁡(0,2max⁡(v1,v2)−1)]=∫1/21(2z−1) 2z dz=5/12\mathbb{E}[\max(0, 2\max(v_1, v_2) - 1)] = \int_{1/2}^1 (2z - 1)\, 2z\, dz = 5/12.

Running time

Line L1 builds one hull per bidder in time linear in its support size, since the points come sorted by qq and each point enters and leaves the stack at most once. One run of the auction does O(n)O(n) work in lines L2 to L4, and line L5 checks at most KwK_w support values with an O(n)O(n) test each. The implementation keeps that test simple. Computing the two maxima of the others once makes each test O(1)O(1), for O(n+Kw)O(n + K_w) per run.

Complexity

Line L1 builds one hull per bidder by the monotone chain method in time linear in its support size, so O(N)O(N) in total for supports given in sorted order, and stores O(N)O(N) slopes. One auction then takes O(n)O(n) for lines L2 to L4 and at most KK checks in line L5. With an O(n)O(n) check this is O(nK)O(nK). With the largest cjc_j of the bidders before ww and after ww computed once, each check is O(1)O(1) and the run takes O(n+K)O(n + K). For continuous regular distributions given by φi\varphi_i and its inverse, one run takes O(n)O(n) evaluations.

Properties

  • Optimal among BIC mechanisms, with a DSIC implementation. No mechanism with truthful Bayes-Nash equilibrium and interim IR earns more, and this one is DSIC and ex post IR.
  • Deterministic. The optimum needs no randomization in this single-item setting, unlike the multi-item case (selling separately or as a bundle).
  • Symmetric case. If all bidders have the same regular distribution, the auction is the Vickrey auction with the reserve φ−1(0)\varphi^{-1}(0), which does not depend on nn.
  • Asymmetric case. With different distributions the winner need not have the highest bid. For example, with v1v_1 from U[0,1]U[0, 1] and v2v_2 from U[0,2]U[0, 2], φ1(v)=2v−1\varphi_1(v) = 2v - 1 and φ2(v)=2v−2\varphi_2(v) = 2v - 2, so bids (0.9,1.3)(0.9, 1.3) give the item to bidder 1.
  • Not efficient. It keeps the item, or sells to a lower bidder, even when that loses welfare.

Variants and improvements

  • Single-parameter environments. The same proof applies whenever the feasible sets of winners are known: maximize the ironed virtual surplus ∑ixiφˉi(vi)\sum_i x_i \bar\varphi_i(v_i) over feasible xx at each profile. For kk identical items this sells to the up to kk highest nonnegative ironed virtual values.
  • Simple approximations. The Vickrey auction with one more bidder beats the optimal auction for i.i.d. regular values (Bulow-Klemperer theorem). Sequential posted pricing earns at least a 1−1/e1 - 1/e fraction of the optimum for any independent values.
  • Unknown distributions. When FiF_i is known only through samples, one runs the auction on an empirical estimate (sample complexity of revenue maximization).
  • Multiple items. For one buyer with additive values for two or more items, no comparably simple optimal mechanism is known, and the optimum may need randomization.

When to use it

Use it when one item, or a single-parameter allocation, must be sold for revenue, the values are independent, and the seller trusts its prior. It is the benchmark against which simpler auctions are measured. When the prior is unknown or doubtful, or when the bidders are asymmetric and an auction that sells to a lower bid would be unacceptable, a Vickrey auction with reserves or a posted price scheme is often preferred at a small loss.

Pitfalls

  • No ironing. Using the raw φ\varphi for an irregular distribution gives a rule that is not monotone. In the example above, a bidder with value 3 would have φ=−1\varphi = -1 and lose, but with the bid 2 it would have φ=1\varphi = 1 and win. It would gain by bidding lower.
  • The reserve for asymmetric bidders. Each bidder has its own reserve φˉi−1(0)\bar\varphi_i^{-1}(0), and a single reserve for all is in general not optimal.
  • Correlated values. With correlated values the optimal revenue can be much higher, up to the full welfare in the setting of the Crémer-McLean theorem, and this auction is no longer optimal.
  • The tie rule must be fixed. A tie rule that depends on the winner's own bid in other ways can break monotonicity. A random tie rule that does not depend on the bids gives the same expected revenue.
  • Exact arithmetic. The hull test and the comparisons with 00 decide the outcome, so they should be done in exact arithmetic for discrete distributions.

Implementations

Each implementation follows the pseudocode above. A comment @line links a line of code to a line of the pseudocode. Point at a line of the pseudocode to see the matching code. The build runs the native tests of each language.

myerson_optimal_auction.pyI0RawGitHub
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/myerson-optimal-auction/. The authors are listed in prov/VMDH3M.jsonl.

"""Myerson's revenue-optimal auction for one item and independent private values.

A distribution is a list of (value, probability) pairs with distinct values and positive
probabilities that sum to 1. Values and probabilities are ints or Fractions, and every
computation is exact. Bidder i reports a value in the support of its own distribution.

The virtual value of a support point is the slope of the revenue curve R(q) = q * F^{-1}(1 - q)
in quantile space. The ironed virtual value is the slope of its concave hull. The auction gives
the item to the bidder with the largest nonnegative ironed virtual value (the lowest index on
ties) and charges the winner the smallest value in its support with which it still wins.
"""

from fractions import Fraction
from itertools import product
from typing import Callable, Sequence

Dist = Sequence[tuple]


def normalize(dist: Dist):
    """Return (values, probs) sorted by value, as Fractions, after checking the input."""
    pairs = sorted((Fraction(v), Fraction(p)) for v, p in dist)
    values = [v for v, _ in pairs]
    probs = [p for _, p in pairs]
    if not pairs or len(set(values)) != len(values):
        raise ValueError("the support must be nonempty with distinct values")
    if any(p <= 0 for p in probs) or sum(probs) != 1:
        raise ValueError("the probabilities must be positive and sum to 1")
    return values, probs


def revenue_curve(values, probs):
    """Return the points (q, R) of the revenue curve, from (0, 0) up to q = 1.

    Point j (j >= 1) belongs to the j-th highest value s, with q = Pr[v >= s] and R = s * q.
    """
    pts = [(Fraction(0), Fraction(0))]
    q = Fraction(0)
    for s, f in zip(reversed(values), reversed(probs)):
        q += f
        pts.append((q, s * q))
    return pts


def upper_hull(pts):
    """Return the indices of the vertices of the concave (upper) hull of points sorted by q."""
    hull = []
    for k, (x, y) in enumerate(pts):
        while len(hull) >= 2:
            (x1, y1), (x2, y2) = pts[hull[-2]], pts[hull[-1]]
            # drop the middle point if it lies on or below the chord from hull[-2] to k
            if (y2 - y1) * (x - x1) <= (y - y1) * (x2 - x1):
                hull.pop()
            else:
                break
        hull.append(k)
    return hull


def virtual_values(dist: Dist):
    """Return the discrete virtual values phi(s_1), ..., phi(s_K) in increasing order of value."""
    values, probs = normalize(dist)
    pts = revenue_curve(values, probs)
    K = len(values)
    # the segment from point j - 1 to point j belongs to value index K - j
    slopes = [(pts[j][1] - pts[j - 1][1]) / (pts[j][0] - pts[j - 1][0]) for j in range(1, K + 1)]
    return list(reversed(slopes))


def ironed_virtual_values(dist: Dist):
    """Return the ironed virtual values in increasing order of value: slopes of the concave hull."""
    values, probs = normalize(dist)
    pts = revenue_curve(values, probs)
    K = len(values)
    hull = upper_hull(pts)
    slope = [None] * (K + 1)
    for a, b in zip(hull, hull[1:]):
        m = (pts[b][1] - pts[a][1]) / (pts[b][0] - pts[a][0])
        for j in range(a + 1, b + 1):
            slope[j] = m
    return list(reversed(slope[1:]))


class Auction:
    """Myerson's auction for a fixed list of bidder distributions."""

    def __init__(self, dists: Sequence[Dist]):
        if not dists:
            raise ValueError("there must be at least one bidder")
        self.supports = []
        self.ironed = []
        for d in dists:
            values, _ = normalize(d)
            self.supports.append(values)
            self.ironed.append(dict(zip(values, ironed_virtual_values(d))))  # @line L1

    def wins(self, i: int, c: Sequence[Fraction], ci: Fraction) -> bool:
        """True if bidder i wins with ironed virtual value ci against the others' values c."""
        if ci < 0:
            return False
        for j, cj in enumerate(c):
            if j == i or cj < 0:
                continue
            if cj > ci or (cj == ci and j < i):
                return False
        return True

    def run(self, bids: Sequence):
        """Return (winner, payments). The winner is None if the item is not sold."""
        n = len(self.supports)
        if len(bids) != n:
            raise ValueError("one bid per bidder is needed")
        bids = [Fraction(b) for b in bids]
        for i, b in enumerate(bids):
            if b not in self.ironed[i]:
                raise ValueError("a bid must lie in the bidder's support")
        c = [self.ironed[i][b] for i, b in enumerate(bids)]  # @line L2
        payments = [Fraction(0)] * n
        candidates = [i for i in range(n) if c[i] >= 0]  # @line L3
        if not candidates:
            return None, payments
        top = max(c[i] for i in candidates)
        w = min(i for i in candidates if c[i] == top)  # @line L4
        for s in self.supports[w]:  # @line L5
            if self.wins(w, c, self.ironed[w][s]):
                payments[w] = s
                break
        return w, payments  # @line L6


def myerson(dists: Sequence[Dist], bids: Sequence):
    """Run Myerson's auction once. Return (winner, payments)."""
    return Auction(dists).run(bids)


def profiles(dists: Sequence[Dist]):
    """Yield (bids, probability) over all value profiles of independent bidders."""
    supports = [list(zip(*normalize(d))) for d in dists]
    for combo in product(*supports):
        p = Fraction(1)
        for _, f in combo:
            p *= f
        yield [v for v, _ in combo], p


def expected_revenue(dists: Sequence[Dist]) -> Fraction:
    """Return the exact expected revenue of Myerson's auction, by enumeration of all profiles."""
    auction = Auction(dists)
    total = Fraction(0)
    for bids, p in profiles(dists):
        _, pay = auction.run(bids)
        total += p * sum(pay)
    return total


def expected_virtual_surplus(dists: Sequence[Dist]) -> Fraction:
    """Return E[max(0, max_i ironed phi_i(v_i))], the optimal revenue by Myerson's theorem."""
    ironed = [dict(zip(normalize(d)[0], ironed_virtual_values(d))) for d in dists]
    total = Fraction(0)
    for bids, p in profiles(dists):
        best = max([Fraction(0)] + [ironed[i][b] for i, b in enumerate(bids)])
        total += p * best
    return total


def myerson_regular(bids: Sequence, phis: Sequence[Callable], phi_invs: Sequence[Callable]):
    """Myerson's auction for regular continuous distributions.

    phis[i] is the virtual valuation of bidder i, a nondecreasing function, and phi_invs[i] is
    its inverse. The winner pays the smallest bid with which it still wins.
    """
    n = len(bids)
    c = [phis[i](bids[i]) for i in range(n)]
    payments = [0] * n
    candidates = [i for i in range(n) if c[i] >= 0]
    if not candidates:
        return None, payments
    top = max(c[i] for i in candidates)
    w = min(i for i in candidates if c[i] == top)
    rival = max([0] + [c[j] for j in range(n) if j != w])
    payments[w] = phi_invs[w](rival)
    return w, payments
test_myerson_optimal_auction.py 165 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/myerson-optimal-auction/. The authors are listed in prov/VMDH3M.jsonl.

import math
import random
import unittest
from fractions import Fraction as F
from itertools import product

from myerson_optimal_auction import (
    Auction,
    expected_revenue,
    expected_virtual_surplus,
    ironed_virtual_values,
    myerson,
    myerson_regular,
    profiles,
    virtual_values,
)

IRREGULAR = [(2, F(1, 2)), (3, F(1, 6)), (5, F(1, 3))]


def random_dist(rng, k, denom=6):
    """A distribution on k distinct values in 1..9 with probabilities that are multiples of 1/denom."""
    values = sorted(rng.sample(range(1, 10), k))
    cuts = sorted(rng.sample(range(1, denom), k - 1))
    parts = [b - a for a, b in zip([0] + cuts, cuts + [denom])]
    return [(v, F(p, denom)) for v, p in zip(values, parts)]


def brute_force_optimum(d1, d2):
    """The best revenue of a deterministic monotone rule with threshold payments, for two bidders."""
    s1, s2 = [v for v, _ in d1], [v for v, _ in d2]
    denom = 1
    for _, p in d1 + d2:
        denom = denom * p.denominator // math.gcd(denom, p.denominator)
    w1 = [int(p * denom) for _, p in d1]
    w2 = [int(p * denom) for _, p in d2]
    cells = list(product(range(len(s1)), range(len(s2))))
    best = None
    for rule in product((0, 1, 2), repeat=len(cells)):
        x = dict(zip(cells, rule))
        ok = True
        for a, b in cells:
            # monotone: a winner keeps winning when it raises its own bid
            if x[(a, b)] == 1 and a + 1 < len(s1) and x[(a + 1, b)] != 1:
                ok = False
                break
            if x[(a, b)] == 2 and b + 1 < len(s2) and x[(a, b + 1)] != 2:
                ok = False
                break
        if not ok:
            continue
        rev = 0
        for a, b in cells:
            if x[(a, b)] == 1:
                t = min(k for k in range(len(s1)) if x[(k, b)] == 1)
                rev += w1[a] * w2[b] * s1[t]
            elif x[(a, b)] == 2:
                t = min(k for k in range(len(s2)) if x[(a, k)] == 2)
                rev += w1[a] * w2[b] * s2[t]
        if best is None or rev > best:
            best = rev
    return F(best, denom * denom)


class TestVirtualValues(unittest.TestCase):
    def test_irregular_example(self):
        self.assertEqual(virtual_values(IRREGULAR), [1, -1, 5])
        self.assertEqual(ironed_virtual_values(IRREGULAR), [F(1, 2), F(1, 2), 5])

    def test_regular_needs_no_ironing(self):
        d = [(1, F(1, 3)), (2, F(1, 3)), (3, F(1, 3))]
        self.assertEqual(virtual_values(d), [-1, F(1), 3])
        self.assertEqual(ironed_virtual_values(d), virtual_values(d))

    def test_ironed_values_are_monotone(self):
        rng = random.Random(1)
        for _ in range(200):
            d = random_dist(rng, rng.randint(1, 5), denom=12)
            phi = virtual_values(d)
            bar = ironed_virtual_values(d)
            self.assertTrue(all(a <= b for a, b in zip(bar, bar[1:])))
            self.assertEqual(sum(phi[k] * p for k, (_, p) in enumerate(d)),
                             sum(bar[k] * p for k, (_, p) in enumerate(d)))


class TestAuction(unittest.TestCase):
    def test_worked_example(self):
        a = Auction([IRREGULAR, IRREGULAR])
        self.assertEqual(a.run([2, 3]), (0, [2, 0]))
        self.assertEqual(a.run([3, 5]), (1, [0, 5]))
        self.assertEqual(a.run([5, 3]), (0, [2, 0]))
        self.assertEqual(a.run([5, 5]), (0, [5, 0]))
        self.assertEqual(expected_revenue([IRREGULAR, IRREGULAR]), 3)

    def test_one_bidder_posts_the_monopoly_price(self):
        d = [(1, F(1, 2)), (2, F(1, 4)), (5, F(1, 4))]
        self.assertEqual(myerson([d], [1]), (None, [0]))
        self.assertEqual(myerson([d], [5]), (0, [5]))
        self.assertEqual(expected_revenue([d]), F(5, 4))

    def test_truthful_and_individually_rational(self):
        rng = random.Random(2)
        for _ in range(25):
            n = rng.randint(1, 3)
            dists = [random_dist(rng, rng.randint(1, 4)) for _ in range(n)]
            a = Auction(dists)
            for bids, _ in profiles(dists):
                winner, pay = a.run(bids)
                for i in range(n):
                    u = (bids[i] if winner == i else 0) - pay[i]
                    self.assertGreaterEqual(u, 0)
                    for lie, _ in dists[i]:
                        other = list(bids)
                        other[i] = F(lie)
                        w2, p2 = a.run(other)
                        self.assertGreaterEqual(u, (bids[i] if w2 == i else 0) - p2[i])

    def test_revenue_equals_virtual_surplus(self):
        rng = random.Random(3)
        for _ in range(30):
            n = rng.randint(1, 3)
            dists = [random_dist(rng, rng.randint(1, 4)) for _ in range(n)]
            self.assertEqual(expected_revenue(dists), expected_virtual_surplus(dists))

    def test_optimal_against_all_monotone_rules(self):
        rng = random.Random(4)
        cases = [(IRREGULAR, IRREGULAR), (random_dist(rng, 3), random_dist(rng, 3))]
        for d1, d2 in cases:
            self.assertEqual(expected_revenue([d1, d2]), brute_force_optimum(d1, d2))

    def test_bad_input(self):
        with self.assertRaises(ValueError):
            myerson([[(1, F(1, 2))]], [1])
        with self.assertRaises(ValueError):
            myerson([IRREGULAR], [4])
        with self.assertRaises(ValueError):
            Auction([])


class TestRegularContinuous(unittest.TestCase):
    def setUp(self):
        self.phi = lambda v: 2 * v - 1
        self.inv = lambda y: (y + 1) / 2

    def test_uniform_outcomes(self):
        two = ([self.phi] * 2, [self.inv] * 2)
        self.assertEqual(myerson_regular([F(4, 5), F(3, 5)], *two), (0, [F(3, 5), 0]))
        self.assertEqual(myerson_regular([F(4, 5), F(3, 10)], *two), (0, [F(1, 2), 0]))
        self.assertEqual(myerson_regular([F(2, 5), F(3, 10)], *two), (None, [0, 0]))

    def test_uniform_revenue_by_monte_carlo(self):
        rng = random.Random(5)
        for n, exact in ((1, 1 / 4), (2, 5 / 12)):
            trials, total = 40000, 0.0
            for _ in range(trials):
                bids = [rng.random() for _ in range(n)]
                total += sum(myerson_regular(bids, [self.phi] * n, [self.inv] * n)[1])
            self.assertAlmostEqual(total / trials, exact, delta=0.01)


if __name__ == "__main__":
    unittest.main()

History

Myerson (1981) wrote the revenue of any incentive compatible mechanism as the expected virtual surplus and so turned revenue maximization into a pointwise maximization. For distributions where φ\varphi is not monotone he introduced the ironing procedure. In the same year Riley and Samuelson showed that, for symmetric bidders, the standard auctions with the right reserve are optimal and that this reserve does not depend on the number of bidders. Bulow and Roberts (1989) explained the result through the revenue curve of a monopolist: the virtual value is a marginal revenue, and the auction sells to the bidder of highest marginal revenue. Myerson shared the 2007 Nobel Memorial Prize in Economic Sciences for the foundations of mechanism design.

References

  1. Roger B. Myerson, Optimal auction design, Mathematics of Operations Research 6(1) (1981), 58-73, the revenue of an incentive compatible mechanism as expected virtual surplus, the optimal auction for regular distributions, and the ironing of the virtual valuation in the general case
  2. John G. Riley and William F. Samuelson, Optimal auctions, American Economic Review 71(3) (1981), 381-392, the optimal reserve price for symmetric bidders and its independence of the number of bidders
  3. Jeremy Bulow and John Roberts, The simple economics of optimal auctions, Journal of Political Economy 97(5) (1989), 1060-1090, the virtual value as the marginal revenue of a monopolist, and the optimal auction as the sale to the bidder of highest marginal revenue
  4. Tim Roughgarden, Twenty Lectures on Algorithmic Game Theory, Cambridge University Press, 2016, Lecture 5, Revenue-maximizing auctions, Section 5.2 (expected revenue equals expected virtual welfare, and the optimal auction for regular distributions)
  5. Noam Nisan, Tim Roughgarden, Eva Tardos and Vijay V. Vazirani (eds.), Algorithmic Game Theory, Cambridge University Press, 2007, Chapter 13, Jason D. Hartline and Anna R. Karlin, Profit maximization in mechanism design (the Bayesian optimal mechanism and virtual values)
  6. Jason D. Hartline, Mechanism Design and Approximation, book draft, version with Chapters 1 to 7 revised in September 2021, https://jasonhartline.com/MDnA/, Chapter 3, Optimal mechanisms (revenue curves in quantile space, virtual values as their slopes, and ironing by the concave hull)

Where this leads

About this page

The build computes these levels from the evidence in the repository. Each row says what the next level needs. Read what the levels mean.

LadderLevelWhat the next level needs
Human proofH1 sketch
  • a full proof of time.worst
  • a full proof of space.extra
LeanL0 no Lean part
  • name a Lean module in the lean field (07)
Code (python)I0 not checked yet
  • the tests did not run in this build
VisualV0 none
  • add viz/scene.ts or a figure (10)
WritingW2 basic
  • a scene preset for the example