Cross-sectional momentum in Python (2026)

Introduction
Cross-sectional momentum ranks assets by their trailing 12-1 return, skipping the most recent month, then holds a portfolio of relative winners against relative losers. This post shows how to build that signal in pandas on a price panel, form decile long/short portfolios with a rebalance loop, and audit the result for look-ahead, survivorship and crash risk before trusting any output.
About this article (E-E-A-T disclosure): This post is desk research based on the published academic literature cited inline; no backtest was run and no performance figures are claimed for the code shown. The code is illustrative and runnable on a synthetic seeded panel. Sources: Jegadeesh & Titman (1993), Journal of Finance; Moskowitz, Ooi & Pedersen (2012), JFE; Daniel & Moskowitz (2016), NBER WP 20439. Verify all claims against the linked papers before relying on them.
Momentum has been documented since at least Jegadeesh and Titman (1993), and it is easy to fake in code by accident. A few lines of pandas can produce a beautiful equity curve that is entirely an artifact of a shifted index or a survivorship-biased panel. This post is a build-it-then-audit-it guide, not a signal pitch.
What you will be able to do after reading:
- Construct a 12-1 momentum signal on a wide monthly price panel using pandas and numpy only.
- Form decile or tercile portfolios, long-only or long-short, equal-weighted, inside an explicit rebalance loop with correct lag alignment.
- Place the construction against the canonical evidence base and its documented failure modes.
- Run a verification checklist before believing any backtest output, including your own.
The six sections that follow map one-to-one onto that process: the evidence, the signal, the portfolio loop, the risks, the verification checklist, and a short FAQ.
What the evidence says
Three papers anchor the topic. Jegadeesh and Titman documented that buying past winners and selling past losers earned significant returns over three- to twelve-month holds on NYSE and AMEX stocks from 1965 to 1989. Moskowitz, Ooi and Pedersen separate cross-sectional from time-series momentum, and Daniel and Moskowitz document momentum crashes.
Jegadeesh & Titman (1993), Journal of Finance 48(1), 65-91. Strategies that buy past winners and sell past losers generate significant positive returns over 3- to 12-month holding periods, and the profitability is not due to systematic risk or to delayed price reactions to common factors. The sample is NYSE and AMEX stocks, 1965-1989. The paper’s own worked example matters for anyone tempted to extrapolate: a portfolio formed on the past six months’ returns generates an average cumulative return of 9.5% over the next 12 months, then loses more than half of that return over the following 24 months (Jegadeesh & Titman 1993). Part of the first-year abnormal return dissipates.
Moskowitz, Ooi & Pedersen (2012), Journal of Financial Economics 104(2), 228-250. Time-series momentum — an instrument’s own past 12-month excess return predicting its own future return — is positive for every one of the 58 liquid futures contracts the authors consider, with returns persisting one to 12 months and partially reversing over longer horizons. The paper is explicit that this is related to but different from cross-sectional momentum, which focuses on relative performance of securities in the cross-section: outperformers over 3-12 months continue to outperform peers on average over the next month (Moskowitz, Ooi & Pedersen 2012; DOI 10.1016/j.jfineco.2011.11.003). The decomposition in that paper attributes most of the momentum profit to positive auto-covariance in futures returns.
Daniel & Moskowitz (2016), Journal of Financial Economics 122(2), 221-247 / NBER WP 20439. Momentum strategies can experience infrequent, persistent strings of negative returns. Those crashes are partly forecastable: they occur in panic states, following market declines and when market volatility is high, and are contemporaneous with market rebounds. The authors report that an implementable dynamic momentum strategy based on forecasts of momentum’s mean and variance approximately doubles the alpha and Sharpe ratio of a static momentum strategy, and that the result is robust across multiple periods, international equity markets and other asset classes (Daniel & Moskowitz 2016; DOI 10.1016/j.jfineco.2015.12.002).
The practical takeaway: the anomaly is real in the literature, but it ships with a documented crash signature. That signature is what shapes the verification checklist in Section 6.
Building the signal in pandas
The 12-1 convention measures the cumulative return from month t-12 to month t-1, deliberately skipping the most recent month to sidestep short-term reversal effects. On each rebalance date every asset is ranked cross-sectionally on that signal. Implementation is a shifted-panel computation: two shift calls, a ratio of prices, and a per-date rank along the column axis.
The convention, precisely. The signal at formation date t is P(t-1) / P(t-12) - 1. The skip month exists so that the medium-term signal is not contaminated by short-term reversal, which points the other way. It is a definitional convention, not a tuned parameter, and you should treat it as fixed until you have a reason to vary it out of sample.
Data layout. A wide monthly panel: DatetimeIndex at month-end, one column per ticker, adjusted close prices. Missing data is the first design decision. An asset with fewer than twelve months of history has no 12-1 signal; it must drop out of that date’s cross-section rather than being scored as zero momentum, because zero is a real value that would sit in the middle of the ranking and quietly dilute both legs.
import numpy as np
import pandas as pd
# ---------------------------------------------------------------
# 1. Synthetic monthly price panel (illustrative data only)
# numpy + pandas, fixed seed, no external data required.
# ---------------------------------------------------------------
rng = np.random.default_rng(42)
n_months, n_tickers = 180, 40
dates = pd.date_range("2010-01-31", periods=n_months, freq="ME") # pandas >= 2.2
tickers = [f"S{i:02d}" for i in range(n_tickers)]
# monthly log-returns: common drift plus name-level noise
log_rets = rng.normal(loc=0.005, scale=0.06, size=(n_months, n_tickers))
prices = pd.DataFrame(
np.exp(np.cumsum(log_rets, axis=0)) * 100.0,
index=dates,
columns=tickers,
)
# deliberate holes, so the NaN policy below is visible
prices.iloc[:14, 0:3] = np.nan # three names with short history
prices.iloc[60:63, 10] = np.nan # one mid-sample data gap
# ---------------------------------------------------------------
# 2. The 12-1 signal: cumulative return from month t-12 to month t-1
# prices.shift(1) -> price at t-1 (end of the previous month)
# prices.shift(12) -> price at t-12
# The most recent month is skipped by construction.
# At index t the signal uses prices through t-1 only: no look-ahead.
# ---------------------------------------------------------------
mom_12_1 = prices.shift(1) / prices.shift(12) - 1.0
# ---------------------------------------------------------------
# 3. Cross-sectional ranking, computed per rebalance date
# na_option="keep" leaves assets without enough history as NaN,
# so they are excluded from the cross-section rather than scored 0.
# ---------------------------------------------------------------
pct_ranks = mom_12_1.rank(axis=1, ascending=True, pct=True, na_option="keep") # highest signal -> pct 1.0 (winners land in the top bucket)
latest = pct_ranks.iloc[-1].dropna().sort_values(ascending=False)
print(latest.head())
Reading the shift semantics. shift(1) is the price at the end of last month, shift(12) is the price twelve months back. Their ratio is the eleven-month cumulative gross return from t-12 to t-1. If you port this to a daily panel, resample to month-end first; do not compute the ratio on daily data and then sample, because the endpoints will not line up.
A convention worth stating. The rank is relative to the universe available on that date, not to the universe available today. That single sentence is the difference between a usable signal and a survivorship-biased one.
Forming the portfolio and the rebalance loop
Ranked assets are grouped into deciles, or terciles for narrow universes, on each rebalance date. The classic construction is long the top decile and short the bottom decile, equal-weighted within each leg; long-only on the top bucket is the deployable variant for equities. A loop steps through dates, holds weights, and applies the following period’s returns.
Bucket assignment. Convert the percentile rank into an integer bucket with np.ceil(pct * n_buckets), clipped to [1, n_buckets]. This is more robust than pd.qcut on a row with gaps, because you control exactly what happens to NaN names. Use n_buckets=3 for terciles when the cross-section is too narrow for decile legs to hold more than a handful of names.
Long-only versus long-short. These are structurally different products, not two settings of the same one. A long-short decile book is roughly market-neutral by construction, needs a borrow market for the short leg, and absorbs borrow fees and short-squeeze risk. A long-only top-bucket book is cheap to run but carries full market beta, so a large part of its return may simply be the market. Name the variant your code implements; never let a reader guess.
Equal weighting. Within each leg, weight is 1/n over the names with a valid signal on that date, normalised so that a long-short book sums to ±1 across the two legs and a long-only book sums to +1. Weights are set at the rebalance and held until the next one.
# ---------------------------------------------------------------
# 4. Bucket weights from percentile ranks
# long_short=True -> +1/n on the top bucket, -1/n on the bottom
# long_short=False -> +1/n on the top bucket only (long-only)
# ---------------------------------------------------------------
def bucket_weights(row, n_buckets=10, long_short=True):
row = row.dropna() # names with a valid signal only
if row.empty:
return pd.Series(dtype=float)
bucket = np.ceil(row * n_buckets).clip(1, n_buckets)
top = bucket[bucket == n_buckets].index
bottom = bucket[bucket == 1].index
w = pd.Series(0.0, index=row.index)
if len(top):
w[top] = 1.0 / len(top) # long leg, equal weight
if long_short and len(bottom):
w[bottom] = -1.0 / len(bottom) # short leg, equal weight
return w
# ---------------------------------------------------------------
# 5. Rebalance loop with explicit lag alignment
# Signal at date t uses data through t-1 only.
# The weight set at t earns the return realised in the month
# AFTER t. Using the same-date return would be look-ahead.
# ---------------------------------------------------------------
asset_rets = prices.pct_change(fill_method=None)
rebal_dates = pct_ranks.dropna(how="all").index
port_rets, weight_history = [], []
for i, dt in enumerate(rebal_dates[:-1]):
w = bucket_weights(pct_ranks.loc[dt], n_buckets=10, long_short=True)
next_dt = rebal_dates[i + 1]
fwd = asset_rets.loc[next_dt].reindex(w.index)
ok = fwd.notna() # drop names with no forward return; never zero-fill
port_rets.append(float((w[ok] * fwd[ok]).sum()))
weight_history.append(w.rename(dt))
port_rets = pd.Series(port_rets, index=rebal_dates[1:], name="portfolio_return")
weights = pd.DataFrame(weight_history)
# Deliberately no Sharpe, CAGR or hit-rate here: the series is returned
# for the verification work in Section 6, not for reporting.
print(weights.shape, port_rets.shape)
Turnover is a first-order concern, not a footnote. Monthly rebalancing of decile portfolios churns the book every period: names cross bucket boundaries, and the composition of both legs changes even when the signal is stable. Transaction costs on the long leg and borrow fees on the short leg arrive every month, so any cost-blind evaluation of the loop above is incomplete. Section 5 treats this as a risk in its own right.
Risks that matter
Five failure modes dominate. Momentum crashes cluster in panic states that follow market declines and high volatility, and land during rebounds. Turnover drives cost. Survivorship bias inflates a panel built from today’s tickers. Look-ahead leaks signal information into returns. Data-snooping accumulates through repeated tuning on the same history, so apparent edges rarely survive out of sample.
- Momentum crashes. Daniel & Moskowitz (2016) describe infrequent, persistent strings of negative returns that occur in panic states after market declines when volatility is high, and that land contemporaneously with market rebounds. Their dynamic variant, which forecasts momentum’s mean and variance, approximately doubles static momentum’s alpha and Sharpe ratio per the paper’s abstract. That is cited as a published finding, not reproduced here.
- Turnover and implementation cost. Monthly decile rebalancing generates material turnover. Jegadeesh & Titman (1993) report 84.8% semiannual turnover for their strategy and a 9.29% risk-adjusted return after a 0.5% one-way transaction cost. Their rebalance frequency differs from this loop’s monthly one, and the cited sources do not cover short-borrow fees, so borrow cost is an assumption you must state. There is no costless version of this strategy; the cost model is part of the strategy definition.
- Survivorship. A panel assembled from today’s index membership embeds the absence of every delisted and acquired name. Jegadeesh & Titman (1993) studied NYSE and AMEX stocks over 1965-1989. A survivorship-free panel as the benchmark for your own data is an author’s inference, not a finding of that paper.
- Look-ahead. Off-by-one errors between signal date and return date are the single most common way a momentum backtest becomes fiction. The skip-month convention itself exists partly to keep short-term reversal out of the signal, and the loop in Section 4 makes the alignment explicit by construction — but only if you keep it that way when you edit it.
- Data-snooping. Sweeping formation windows, ranking schemes and portfolio cuts over one history can produce an impressive in-sample artifact. Jegadeesh & Titman (1993) discuss Levy’s (1967) relative-strength rule, and Jensen and Bennington’s (1970) finding that the rule was produced after examining 68 different trading rules: the same selection problem a parameter sweep reproduces.
What to verify before trusting it
Before trusting any momentum backtest, verify data integrity, signal timing and construction logic rather than headline statistics. Check universe completeness, the NaN policy, lag alignment, weight normalisation, decile balance, turnover, behaviour in crash windows, and robustness to convention changes. The checklist below is process only; it makes no claim about what results you should obtain.
- Universe: does the panel include delisted names, and does the cross-section on each date match the assets actually tradable on that date?
- Signal timing: does the signal at date t use only information through t-1 (the 12-1 window with the skip month honoured), and is the return applied the next period’s return?
- NaN policy: are assets with insufficient history excluded from the ranks rather than zero-filled, and does the equal-weight denominator count only valid names?
- Weights: do the legs sum to ±1 (long-short) or +1 (long-only), and are weights set at the rebalance and held until the next one?
- Decile balance: are bucket sizes reasonable relative to the universe width on every date, with no degenerate single-name deciles?
- Turnover: what fraction of the book turns over per rebalance, and are transaction costs and borrow assumptions stated explicitly?
- Crash windows: how does the strategy behave under the panic-state conditions described by Daniel & Moskowitz (2016) — high volatility after market declines, during rebounds?
- Sensitivity: do results survive changes to formation window, skip month, decile versus tercile and rebalance frequency, checked out of sample rather than tuned on the full history?
- Reconciliation: does the vectorised pandas computation match an independent loop-based reimplementation on a small panel?
FAQ
The FAQ covers the three questions practitioners ask first: why the most recent month is skipped, how cross-sectional momentum differs from the time-series variant, and whether long-only is a legitimate substitute for long-short. Each answer is definitional, sourced from the cited papers, and carries no performance claim.
Why skip the most recent month in the 12-1 momentum signal?
The 12-1 convention measures the cumulative return from t-12 to t-1. The skip month keeps short-term reversal from contaminating the medium-term signal. It is a definitional convention, stated as such, not a parameter to be optimised — and if you change it, that change belongs in the out-of-sample sensitivity check rather than in the base case.
How is cross-sectional momentum different from time-series momentum?
Moskowitz, Ooi & Pedersen (2012) define time-series momentum as an asset’s own 12-month excess return predicting its own future return, positive in all 58 liquid futures contracts they studied. Cross-sectional momentum instead ranks assets relative to their peers over 3-12 months and bets on the spread between relative winners and relative losers.
Can I run this long-only instead of long-short?
Yes. Long-only on the top tercile, or top decile, is a standard construction and the one most deployable for equities, since it removes short-leg borrow constraints. It also leaves the portfolio carrying market beta, which the long-short book is designed to minimise. The choice is structural, and no return difference between the two is claimed here.
← Back to all posts

