Sort stocks into deciles with qcut, compare them with fixed size groups from cut, handle stocks of identical size with rank, and form new deciles on each date with groupby transform.
After this lesson, you can sort the stocks of each date into ten portfolios from the smallest to the largest.
How do I sort stocks into deciles?
pd.qcut(sizes, q=10, labels=list(range(1, 11))) computes the size boundaries that split the stocks into ten groups of equal count, so with 20 stocks each decile holds two, decile 1 the smallest and decile 10 the largest. AAA and BBB, the two smallest, form decile 1.
The made-up panel holds 20 companies, AAA to TTT, on 2 and 3 March 2026, one row per stock and date, with the market capitalisation in millions of dollars. pd.cut uses boundaries you choose instead, here 0, 50, 100 and 200 for Small, Mid and Large, so its groups hold 5, 5 and 10 stocks. Each interval includes its right edge, so EEE’s size of 50 counts as Small.
The following box builds the panel and puts both groupings beside the sizes of 2 March.
date ticker size fixed_group decile
2026-03-02 AAA 10 Small 1
2026-03-02 BBB 20 Small 1
2026-03-02 CCC 30 Small 2
2026-03-02 DDD 40 Small 2
2026-03-02 EEE 50 Small 3
2026-03-02 FFF 60 Mid 3
2026-03-02 GGG 70 Mid 4
2026-03-02 HHH 80 Mid 4
2026-03-02 III 90 Mid 5
2026-03-02 JJJ 100 Mid 5
2026-03-02 KKK 110 Large 6
2026-03-02 LLL 120 Large 6
2026-03-02 MMM 130 Large 7
2026-03-02 NNN 140 Large 7
2026-03-02 OOO 150 Large 8
2026-03-02 PPP 160 Large 8
2026-03-02 QQQ 170 Large 9
2026-03-02 RRR 180 Large 9
2026-03-02 SSS 190 Large 10
2026-03-02 TTT 200 Large 10
What if several stocks have the same size?
When many stocks share a size, several decile boundaries coincide and pd.qcut raises a ValueError. On 3 March, the ten stocks AAA to JJJ all have a size of 30. Ranking first with .rank(method="first") gives the tied stocks the ranks 1 to 10 in table order, so ten deciles of two stocks remain, while duplicates="drop" keeps the tied stocks together and leaves six groups.
The ranks of tied stocks follow their order in the table, here alphabetical, so a different order can move a tied stock to another decile. labels=False numbers the groups from 0.
The following box tries the plain deciles and compares both fixes on 3 March.
panel.groupby("date")["size"].transform(size_decile) sorts the stocks of each date into deciles separately and returns one decile per row. TTT, the largest stock on both dates, is in decile 10 on both, while deciles from both dates pooled put TTT’s 3 March size of 130 in decile 9.
size_decile ranks the sizes and splits the ranks into ten groups. In a backtest, the sizes must also be known on the date the portfolios are formed.
The following box computes the deciles per date and pooled.