BLOG

Behind the numbers.

Code examples, market analysis, and data quality deep-dives.

Does Skipping the Most Recent Month Improve Momentum? S&P 500 Decile Sorts in Python
Does Cointegration Survive Out of Sample? Pairs Trading Validation in Python
Which Dividends Are Not Covered by Cash? Free-Cash-Flow Coverage Screening in Python
GICS vs SIC vs NAICS: Which Industry Classification to Use
How Many Stocks Does It Take to Diversify? Random Portfolio Simulation in Python
How Many Days of Data Does a Volatility Estimate Need? Range-Based Estimators in Python
How Much of S&P 500 Cash Flow Is Stock Compensation? Cross-Sectional Analysis in Python
What Is a 13F Filing? Institutional Holdings Explained
Does Revenue Growth Explain Profit Growth? Cross-Sectional Decomposition in Python
How Much of the Nasdaq 100 Is Already in the S&P 500? Index Overlap Analysis in Python
How Often Does a 99% Value-at-Risk Limit Actually Break? VaR Backtesting in Python
Real-Time vs End-of-Day Market Data: Which Do You Need?
How Concentrated Are S&P 500 Earnings? Point-in-Time Index Analysis in Python
Does Volatility Scale With the Square Root of Time? Variance Ratio Test in Python
Does Goodwill Distort the Price-to-Book Screen? Goodwill-Adjusted Valuation in Python
How Are Shares Outstanding Reported (and Why They Disagree)
Do Low-Volatility Stocks Deliver Better Risk-Adjusted Returns? S&P 500 Quintile Sorts in Python
Does Trend Following Beat Buy and Hold? Time-Series Momentum in Python
Has the Stock-Bond Correlation Flipped? 60/40 Portfolio Risk in Python
What API to Use for a Stock Screener
Which Assets Hedge Inflation Shocks? Macro Factor Betas in Python
Does Covariance Shrinkage Beat the Sample Covariance? Minimum-Variance Portfolios in Python
Do Faster Inventory Turns Mean Thinner Margins? Gross Margin Return on Inventory in Python
SEC EDGAR API vs Fundamentals API: Which to Use
Does Fast Earnings Growth Persist? Rank Correlation Analysis in Python
Split Adjustment Explained: Adjusted Close vs Close
Which Trading Day of the Month Pays Best? Turn-of-the-Month Analysis in Python
Can You Use Yahoo Finance Data Commercially?
How Many Independent Bets Does a Nine-Sector Portfolio Give You? Eigenvalue Analysis in Python
Which Volatility Forecast Wins One Month Ahead? HAR vs EWMA in Python
How Concentrated Are Institutional Equity Portfolios? Form 13F Concentration Analysis in Python
Do Stocks Earn Their Returns Overnight or Intraday? Return Decomposition in Python
When Do Corporate Insiders Actually Trade? Form 4 Timing Analysis in Python
Data Requirements for Backtesting a Trading Strategy
What Is Survivorship Bias in Backtesting?
Do High Dividend Yields Come From Bigger Payouts or Falling Prices? Yield Decomposition in Python
Do Stocks Fall Harder Than They Rise? Downside Beta vs Upside Beta in Python
Does Volatility Targeting Improve Sharpe Ratios? Seven-Asset Backtest in Python
Free Stock Market Data APIs: What You Actually Get
How to Give an LLM Financial Data With an MCP Server
Does Post-Earnings Announcement Drift Survive Real Filing Dates? PEAD Event Study in Python
Do Insider Buying Clusters Predict Returns? Signal Testing in Python
Does the S&P 500 Index Effect Still Exist? Event Study in Python
Are Companies Leaving the S&P 500 Faster Than They Used To? Index Survival Analysis in Python
Does Gross Profitability Predict Stock Returns? Quintile Factor Test in Python
What Growth Rate Is the Market Pricing In? Reverse DCF in Python
Does a Strong Balance Sheet Cushion Drawdowns? Leverage and Downside Risk in Python
Does Ticker Recycling Corrupt a Mean-Reversion Backtest? Entity-Resolved Z-Scores in Python
How Much of a Growth Screen's Backtested Edge Is Survivorship Bias? Point-in-Time Index Testing in Python
Why Do Leveraged ETFs Decay? Measuring Volatility Drag in Python
Are Consumer Staples Margins Shrinking Under Inflation? Gross Margin Trend Analysis in Python
Do Weak Jobs Reports Predict Market Drawdowns? NFP Surprise Event Study in Python
Is the Rotation From Tech to Industrials Backed by Earnings? Relative EPS Growth Analysis in Python
Is the Semiconductor Rally Broadening Beyond NVIDIA? Return Dispersion Analysis in Python
Which Stocks Benefit Most When Oil Prices Fall? Oil Beta Screening in Python
Do Bond Returns Predict Stock Returns? Granger Causality Test in Python
Which Stocks Actually Drive Portfolio Returns? Shapley Value Attribution in Python
Does "Sell in May" Still Work? Calendar Anomaly Backtest in Python
How to Build Complete Price History Through Ticker Changes? Entity Resolution in Python
Are KO and PEP Cointegrated? Pairs Trading Signal Construction in Python
Which Commodities Have the Strongest Momentum? Rotation Backtest in Python
Which Commodity ETFs Have the Worst Tail Risk? Expected Shortfall in Python
Are Gold Miners Leveraged Gold Bets? Rolling Beta Analysis in Python
Does the Base-Metals-to-Gold Ratio Lead Cyclical Stocks? Signal Test in Python
Can Risk Parity Tame Commodity Volatility? Portfolio Optimization in Python
Are Power Stocks Becoming an AI Infrastructure Trade? Momentum Screening in Python
Which AI Chip Stocks Have Margin Momentum? Profitability Trend Analysis in Python
Which AI Stocks Are Cheapest Relative to Growth? Growth-Adjusted Valuation in Python
Does AI Stock Leadership Persist? Momentum Backtest in Python
Which AI Stocks Have the Cleanest Balance Sheets? Net Cash Screening in Python
Can Risk Parity Reduce Mega-Cap Drawdowns? Portfolio Optimization in Python
Which Growth Stocks Are Self-Funding? Cash-Flow Quality Screening in Python
Which Sectors Struggle When the Dollar Rallies? Sector Rotation Analysis in Python
Do Cheap Stocks Hold Up When Bonds Sell Off? Valuation Rotation in Python
Does the Nasdaq 100 Have Better Growth Quality Than the Dow? Index Constituent Analysis in Python
Do Healthcare Cash-Flow Margins Predict Returns? Signal Evaluation in Python
Which Dividend Stocks Survive a Cash-Flow Stress Test? Dividend Screening in Python
Does Heavy Insider Selling Predict Weak Returns? Insider Flow Test in Python
Can Quality Screens Reduce Small-Cap Balance-Sheet Risk? Russell 2000 Test in Python
Which Retailers Have Positive Operating Leverage? Margin Screening in Python
Is MSTR a Leveraged Bitcoin Proxy? Rolling Beta Analysis in Python
Is Micron's Memory Cycle Recovering? Inventory and Margin Forecasting in Python
Which Sectors Work When Bonds Rally? Rate-Sensitive Rotation in Python
Do One-Month Price Extremes Reverse? Signal Evaluation in Python
Do Low-Volatility S&P 500 Stocks Reduce Drawdowns? Factor Test in Python
Is AI Capex Paying Back Fast Enough? Revenue Hurdle Forecasting in Python
Could Shorter AI Asset Lives Hit Earnings? Depreciation Stress Test in Python
How Much AI Capex Risk Can a Portfolio Remove? Constrained Optimization in Python
Is the AI Capex Trade Crowded? Rolling Volatility and Sector Rotation in Python
Did the AI Boom Come From Existing S&P 500 Members? Point-in-Time Momentum Test in Python
Is AI Revenue Circular? Customer-Vendor Capex Loop Analysis in Python
Is the AI Trade Connected to Private Credit? Rolling Correlation Network in Python
Is Apollo More Balance-Sheet Sensitive Than Peers? Leverage Screen in Python
Are AI Earnings Supported by Cash Flow? Accrual and Capex Screen in Python
Can Defensive Stocks Hedge AI Drawdowns? Basket Regime Test in Python
How Fast Does the Market Price In Fed Decisions? FOMC Event Study in Python
How Much Are Options Sellers Overpaid? The Variance Risk Premium in Python
Which Companies Have the Worst Earnings Quality? Sloan Accrual Screen with Geographic Revenue Data in Python
Does the Oil-to-Gold Ratio Signal Recessions? XLE/GLD Backtest in Python
Is AI Spending Crowding Out Free Cash Flow? Capex Sustainability Across the Mag 7 in Python
Does a Long Energy / Short Bonds Portfolio Capture Inflation Surprises? Factor Construction in Python
Can a Hidden Markov Model Detect Oil Market Regimes? HMM Analysis in Python
Do Grain Prices Predict Food Inflation? Granger Causality Test in Python
Does the Corporate Credit Spread Predict Stock Market Crashes? BAA-AAA Spread Analysis in Python
Do Oil Stocks Hedge Inflation? Rolling Beta Analysis in Python
Which Stocks Are Most Rate-Sensitive? Equity Duration via Bond Beta in Python
Which Companies Have the Highest Accrual Ratios? Earnings Quality Screening in Python
Is Alpha Persistent or Decaying? Rolling Sharpe Ratio Analysis in Python
Are Markets Trending or Mean-Reverting? Hurst Exponent Analysis in Python
Is Consumer Discretionary vs Staples a Leading Indicator? XLY/XLP Ratio Analysis in Python
Does Heavy Capex Predict Future Stock Returns? Capital Expenditure Analysis in Python
How to Estimate Cost of Equity Using CAPM in Python
Is Volatility Predictable? Testing for Volatility Clustering in Python
Which Industrials Are Overleveraged? Net Debt to EBITDA Screening in Python
GM Before and After Bankruptcy: Why Entity Resolution Matters for Financial Data
What Is Adjusted Beta? Merrill Lynch Beta Shrinkage in Python
How Good Is a Stock Pick? Information Ratio and Tracking Error in Python
Do Stock Returns Follow a Normal Distribution? Testing for Fat Tails in Python
Which Large Caps Have the Highest Free Cash Flow Yield? FCF Screening in Python
Which Sectors Won Over 5 Years? Sector Rotation Analysis in Python
How to Forecast Stock Volatility with GARCH Models in Python
Are Stock Prices Mean-Reverting? Augmented Dickey-Fuller Test in Python
How to Calculate CAPM Alpha and Beta with Regression in Python
How to Compare Sector Sharpe Ratios and Sortino Ratios in Python
DELL: Why Stitching Historical Price Data Together Is Wrong
How to Analyze Drawdown and Recovery for Bank Stocks in Python
How to Screen SaaS Stocks by Revenue Growth and Cash Flow in Python
How to Screen REITs by Dividend Yield and Valuation in Python
How Correlated Are the Magnificent 7? Intra-Group Correlation in Python
AAPL vs XOM: Do Individual Stocks Have Seasonal Patterns?
How to Rank Large-Cap Stocks by Momentum in Python
How to Build a Multi-Endpoint Financial Dashboard in Python
How to Compare Volatility Across Energy Stocks in Python
How to Screen Healthcare Stocks by Valuation in Python
How to Build a Sector Correlation Matrix for Portfolio Diversification in Python
How to Find Oversold and Overbought Stocks Using Z-Scores in Python
How to Measure Earnings Quality: Cash Flow vs Net Income in Python
How to Build a Multi-Factor Stock Screen in Python (Value + Momentum + Quality)
How to Build a Simple DCF Model for Any Stock in Python
How to Screen Tech Stocks by Revenue Growth in Python
How to Screen Stocks by Balance Sheet Health in Python
Is "Sell in May" Real? SPY Monthly Seasonality Over 10 Years
How to Compare Sector Performance YTD Using Python
How to Screen Dividend Stocks by Yield and Quality in Python
How to Calculate Max Drawdown and Recovery Time for Any Stock in Python
How to Compare Profitability Across Mega-Cap Tech Stocks in Python
Why Ticker Symbols Are Unreliable: The Recycling Problem Every Quant Should Know
How to Calculate and Compare Stock Volatility in Python
How to Screen Blue-Chip Stocks by P/E Ratio in Python
How to Track Companies Through Ticker Changes, Bankruptcies, and Renames in Python
S&P 500 Turnover: How Much the Index Has Changed Since 2010
How to Calculate Stock Beta and Correlation in Python
← All articles

Does Skipping the Most Recent Month Improve Momentum? S&P 500 Decile Sorts in Python

What’s the question?

Cross-sectional momentum ranks stocks against one another on past return and holds the winners against the losers, betting the ranking persists. Almost every published version throws away the most recent month: the window runs from twelve months ago to one month ago, hence 12-1.

The reason is a second, opposite effect. Jegadeesh (1990) found that last month’s biggest gainers underperform over the following month, a reversal usually attributed to bid-ask bounce and to liquidity providers being paid to absorb one-sided flow. A twelve-month return that includes last month therefore mixes continuation with reversal, and skipping is meant to strip the reversal out. The Fama-French momentum factor uses months 2 to 12.

Two questions follow. What does the skip do to the decile spread in US large caps, and is the reversal that justifies it still there?

The approach

The universe is the S&P 500 as it stood at each formation date. Ranking today’s members over the past twenty years would rank the companies that survived, and momentum measured on survivors is not momentum.

  1. Pull index membership at each month end from December 2005 to June 2026, so a company removed in 2011 is ranked up to its removal and in none afterwards. The 247 snapshots cover 905 distinct companies.
  2. Pull monthly total returns from December 2004, keyed on entity identifier rather than ticker, so a series stays continuous through a rename and a recycled ticker cannot splice one company’s prices onto another’s.
  3. Screen the panel: duplicate rows and non-positive prices go, and a name whose monthly total return ever exceeds +200 percent or falls below −90 percent is set aside rather than winsorised.
  4. Rank every member twice, on months t-11 to t-1 (the standard 12-1 window) and on months t-11 to t (the same window with the last month left in), so the two rankings differ by one month of data and nothing else.
  5. Cut each ranking into ten equal-weighted deciles, hold for the following month, and repeat at the next month end. Around 479 names are ranked in a typical month.
  6. Rank the skipped month on its own, which measures the reversal the convention exists to remove.

Sharpe is mean return over volatility with no risk-free deduction. Drawdowns use month-end values.

Code

import numpy as np
import pandas as pd
import xfinlink as xfl

xfl.set_api_key("YOUR_API_KEY")  # free at https://xfinlink.com/signup

members = {}
for d in pd.date_range("2005-12-31", "2026-06-30", freq="ME").strftime("%Y-%m-%d"):
    ix = xfl.index("sp500", as_of=d)
    members[pd.Period(d, "M")] = sorted(int(e) for e in ix["entity_id"].dropna())

universe = sorted({e for ids in members.values() for e in ids})

px = pd.concat([xfl.prices(entity_id=universe[i:i + 20], start="2004-12-01",
                           end="2026-08-05", interval="1mo",
                           fields=["close", "return_daily"], max_rows=500000)
                for i in range(0, len(universe), 20)], ignore_index=True)

px = px.drop_duplicates(["entity_id", "date"]).dropna(subset=["return_daily"])
px = px[px["close"] > 0]
px["month"] = px["date"].dt.to_period("M")
rets = px.pivot_table(index="month", columns="entity_id", values="return_daily",
                      aggfunc="first")
rets = rets.drop(columns=[c for c in rets.columns
                          if (rets[c] > 2.0).any() or (rets[c] < -0.90).any()])

legs = {s: {k: {} for k in range(1, 11)} for s in ("skip", "noskip", "reversal")}
for T in sorted(members):
    H = T + 1                                     # the month the deciles are held
    window = rets.loc[(rets.index >= T - 11) & (rets.index <= T)]
    cols = [e for e in members[T] if e in rets.columns]
    window = window[cols]
    usable = window.notna().all() & rets.loc[H, cols].notna()
    window = window.loc[:, usable[usable].index]
    held = rets.loc[H, window.columns]

    signal = {"skip": (1 + window.iloc[:-1]).prod() - 1,   # months t-11 to t-1
              "noskip": (1 + window).prod() - 1,           # months t-11 to t
              "reversal": window.iloc[-1]}                 # month t on its own
    for name, s in signal.items():
        decile = pd.qcut(s.rank(method="first"), 10, labels=list(range(1, 11)))
        for k in range(1, 11):
            legs[name][k][H] = held[s.index[decile == k]].mean()

P = {name: pd.DataFrame({f"D{k}": pd.Series(v[k]).sort_index() for k in range(1, 11)})
     for name, v in legs.items()}
for name in P:
    P[name]["LS"] = P[name]["D10"] - P[name]["D1"]
    s = P[name]["LS"]
    print(f"{name:9} {(1 + s).prod() ** (12 / len(s)) - 1:7.2%} a year  "
          f"t = {s.mean() / (s.std() / np.sqrt(len(s))):5.2f}")

Full script with formatting and visualisation: momentum-12-1-skip-month-deciles-python.py

Output

S&P 500 momentum decile returns for the 12-1 and 12-0 constructions, with the growth of one dollar in each winners-minus-losers spread from 2006 to 2026
Cross-sectional momentum deciles on point-in-time S&P 500 membership, 2006-01 to 2026-07 (247 holding months)
Formation: cumulative total return over months t-11 to t-1 (12-1, most recent month skipped)
           and over months t-11 to t (12-0, most recent month kept)
Portfolios: ten equal-weighted deciles, re-formed at each month end, held one month

247 membership snapshots cover 905 distinct companies; 878 carry a monthly price history and 14 of those are set aside by the return-bound screen
Names ranked each month: 445 to 492, median 479

                         12-1 skip month           12-0 month kept
Decile             CAGR  Ann vol  Sharpe     CAGR  Ann vol  Sharpe
D1 losers         6.74%   29.55%    0.37    6.50%   30.57%    0.36
D2                8.85%   22.49%    0.49    8.36%   22.82%    0.47
D3               11.03%   19.23%    0.64   10.40%   19.85%    0.60
D4               10.77%   17.69%    0.67   10.32%   17.72%    0.65
D5               10.87%   15.98%    0.73   11.67%   15.88%    0.78
D6               11.91%   15.22%    0.82   11.35%   15.46%    0.78
D7               10.66%   15.21%    0.75   11.45%   14.78%    0.81
D8                9.97%   14.93%    0.71    9.91%   14.43%    0.73
D9               10.04%   15.07%    0.71    9.26%   14.65%    0.68
D10 winners       9.21%   18.95%    0.56   10.51%   18.57%    0.63

Winners minus losers, equal weighted, rebalanced monthly
                               12-1 skip   12-0 kept
Return a year                     -3.57%      -3.02%
Annualised volatility             24.84%      26.34%
Sharpe                             -0.01        0.03
t-statistic of monthly mean        -0.03        0.14
Worst drawdown                    -80.9%      -83.6%
Worst month                       -50.4%      -51.6%
Best month                         21.0%       26.2%
Months positive                    53.0%       53.8%
Return a year, 2009 removed        2.53%       3.08%
t-statistic, 2009 removed           0.99        1.10

How much the skip changes the ranking
  mean absolute move in percentile rank      6.2%
  names landing in the same decile           52.0%
  top decile shared by both constructions    81.1%
  bottom decile shared by both               82.7%
  correlation of the two spread series       0.979

The skipped month ranked on its own (highest minus lowest last-month return): 1.35% a year, t = 0.74
  its decile returns run 5.09% at D1 (worst last month) to 9.99% at D10 (best last month)

Winners minus losers, calendar year total return (%)
               12-1 skip         12-0 kept   last month only
2006                -8.5             -11.2              -0.7
2007                25.5              38.7              35.2
2008                 4.0              11.8              17.9
2009               -71.0             -70.6               1.9
2010                -4.6              -7.1             -15.1
2011                 5.9               9.8               5.3
2012                 4.8               0.3              -3.6
2013                 8.6              12.0               2.6
2014                 1.4               4.0              12.9
2015                42.3              38.0              -4.7
2016               -27.5             -31.6              -9.3
2017                 8.9               6.7               0.1
2018                10.5               2.4              -6.2
2019               -11.3             -16.3             -26.4
2020               -10.9             -11.5              -3.0
2021               -22.3             -23.8              -5.4
2022                17.5              19.1               3.7
2023               -18.3             -10.8               4.0
2024                27.2              28.7               6.1
2025                 2.2              12.1              26.2
2026                23.0              23.8               3.3

What this tells us

The skip changes the ranking without changing the portfolio. Dropping one month moves the median name 6.2 percentile points and leaves only 52.0% in the same decile, but that churn is in the middle of the distribution. At the ends, 81.1% of the top decile and 82.7% of the bottom are the same companies either way, and the two spread series correlate at 0.979.

The answer to the headline question is no, at least here. The 12-1 spread compounded at −3.57% a year against −3.02% for the version keeping the last month, and the 0.55 point gap sits inside the noise: t-statistics are −0.03 and 0.14. Compounded figures look worse than the averages because a long-short book pays for its own variance, and this one carries 24.84% annualised volatility.

Ranking on the skipped month alone explains why the skip is not paying. Were short-horizon reversal present, the stocks with the best return last month would lag this month. They do not. Highest minus lowest last-month return earned 1.35% a year, and the decile pattern runs upward, from 5.09% for the previous month’s worst performers to 9.99% for its best. Among S&P 500 members since 2006 the last month continues rather than reverses, so there is nothing for the skip to remove.

One year does most of the damage. In 2009 the spread lost 71.0% as the loser decile rebounded faster than any winner portfolio could follow, and the drawdown reached 80.9%. Strip 2009 out and both constructions turn positive, 2.53% and 3.08% a year, with t-statistics near 1.0.

So what?

Keep the skip. It costs nothing and protects against universes where short-horizon reversal is real, which is where it is strongest: small caps and less liquid names. What the numbers argue against is treating it as a source of return in large caps, where two decades put its contribution at half a point a year in the wrong direction.

Before tuning a formation window, rank the universe on the most recent month alone. If past-month winners lag, the correction is doing work; if they lead, as here, the convention is inherited rather than earned. What broke this strategy was the crash: a worst month of 50.4% needs a volatility target first.

For a long-only book the finding is narrower. Nothing here argues for buying the top decile, which returned less than the fifth and sixth with more volatility. Avoiding the bottom decile is the trade the data supports, 6.74% a year against roughly 10% for the rest.

Built with xfinlink — free financial data API for Python. pip install -U xfinlink

Built with xfinlink — free financial data API for Python. pip install -U xfinlink
← All articles