How do I compute 12-2 momentum with log returns in pandas?
Compute each stock’s 12-2 momentum in a long pandas panel with np.log1p, a rolling sum, a shift and np.expm1, and see which months enter the signal and when it is NaN.
After this lesson, you can compute each stock’s 12-2 momentum in a panel and tell which months enter it.
How do I compute 12-2 momentum?
At a month-end, 12-2 momentum is the stock’s compounded return over the eleven months before that month-end. At the end of December 2024, it compounds January to November 2024 and skips December, because the winners of the latest month tend to fall back in the next month.
Here \(r_{t-k}\) is the stock’s return \(k\) months before month \(t\). The sum of the logs gives the same result as the product, and pandas has a rolling sum.
np.log1p gives \(\log(1+r)\) for each return, .rolling(months).sum() adds the last eleven, .shift(1) moves each sum one month down so that it skips the month itself, and np.expm1 turns the sum back into a return.
The example is a long panel, as in the lesson on long and wide panels, of two made-up stocks over 14 month-ends. AAA earns 1% every month, so its momentum is \(1.01^{11} - 1 = 0.1157\). BBB earns nothing except 10% in February 2024 and 10% in February 2025.
groupby("ticker") runs momentum on each stock separately, and .transform(momentum) returns one value per row, in the panel’s order. .tail(3) on the grouped panel keeps each stock’s last three months.
The following box builds the panel and computes the momentum.
BBB’s momentum is 0.10 at the end of December 2024 and January 2025, while February 2024 is in the window. At the end of February 2025 it is 0, because February 2024 has left the window and February 2025 is skipped.
When is momentum NaN?
Momentum is NaN until a stock has eleven months before the month-end, and for every month-end whose window holds a missing return. min_periods=min_months lowers the number of months a window needs.
In the example, BBB’s return for June 2024 is missing, and all three printed windows contain June.
With the default, a window needs all eleven months, so BBB has no momentum at the three month-ends.
With min_months=10, each window compounds its ten observed months.
panel_gap.loc[19, "stock_return"] = np.nan removes BBB’s June return, because BBB’s rows start at row 14. by_stock holds the grouped returns, so each setting is one .transform().
The following box computes the momentum with eleven and with ten required months.
AAA keeps its momentum of 0.1157 in both columns, because its returns are complete.
Your turn
Compute 12-1 momentum, which compounds the twelve months up to and including the month-end, with months=12 and skip=0, and print each stock’s last three months. You should see 0.1268 for AAA and 0.10 for BBB at the end of February 2025, because February 2025’s 10% now enters.
TipShow answer
.transform() passes months=12 and skip=0 on to momentum.