BLOG

Behind the numbers.

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

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

When Do Corporate Insiders Actually Trade? Form 4 Timing Analysis in Python

What’s the question?

Corporate insiders do not pick their trading dates freely. Almost every large US company closes an internal trading window some weeks before the fiscal quarter ends and reopens it a day or two after results are published. While management knows the quarter’s numbers and the market does not, any trade invites a claim of dealing on material non-public information. Rule 10b5-1 supplies the standard exemption: an insider who adopts a written plan while the window is open, fixing amounts and dates in advance, may keep trading after it shuts.

Those policies are private, but the outcome is public. Form 4 requires an insider to report a transaction within two business days, including the date it was placed, so the policy can be recovered from behaviour. If windows work the way company handbooks describe, the distribution of open-market transactions across the quarter should be far from flat.

The approach

The sample is the 499 current S&P 500 constituents and every open-market buy and sell dated between 1 July 2021 and 30 June 2026. Grants, option exercises, tax withholding and gifts are excluded, since none is a decision about when to be in the market.

  1. Pull Form 4 transactions in batches of 25 tickers, then quarterly period ends for the same batches.
  2. Anchor each transaction to the most recent fiscal quarter end of its own filer, not the calendar quarter. A January-ending retailer sits five weeks out of phase with a December filer, and a shared calendar would blur the effect being measured.
  3. Record the days between that quarter end and the transaction, keeping the following 91 days.
  4. Take the median gap between period end and filing date as the mark for when results reach the market, using Q1 through Q3, since the fourth quarter is reported on the annual 10-K under its own deadline.
  5. Compare transactions per day across three stretches of the quarter, separately for buys and sells.

Code

import pandas as pd
import xfinlink as xfl

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

START, END, BATCH = "2021-07-01", "2026-06-30", 25

tickers = sorted(xfl.index("sp500")["ticker"].dropna().unique().tolist())
batches = [tickers[i:i + BATCH] for i in range(0, len(tickers), BATCH)]

trades, quarters = [], []
for b in batches:
    trades.append(xfl.insiders(b, start=START, end=END,
                               transaction_type=["open_market_buy", "open_market_sell"],
                               fields=["ticker", "transaction_date", "transaction_type",
                                       "insider_role", "insider_name"],
                               max_rows=200000))
    q = xfl.fundamentals(b, start="2021-01-01", end="2026-07-28",
                         period_type="quarterly", max_rows=200000)
    quarters.append(q[["ticker", "period_end", "fiscal_period", "filing_date"]])

trades = pd.concat(trades, ignore_index=True)
quarters = pd.concat(quarters, ignore_index=True)

# typical interim reporting lag (the fourth quarter is reported on the annual 10-K)
q13 = quarters[quarters["fiscal_period"].isin(["Q1", "Q2", "Q3"])].copy()
q13["lag"] = (pd.to_datetime(q13["filing_date"]).dt.tz_localize(None)
              - pd.to_datetime(q13["period_end"])).dt.days
report_day = int(q13.loc[q13["lag"].between(1, 120), "lag"].median())

qe = (quarters[["ticker", "period_end"]].drop_duplicates()
      .assign(period_end=lambda d: pd.to_datetime(d["period_end"]))
      .sort_values("period_end"))
trades["transaction_date"] = pd.to_datetime(trades["transaction_date"]).dt.tz_localize(None)

m = pd.merge_asof(trades.sort_values("transaction_date"), qe,
                  left_on="transaction_date", right_on="period_end",
                  by="ticker", direction="backward")
m["day"] = (m["transaction_date"] - m["period_end"]).dt.days
m = m[m["day"].between(0, 91)]

sells = m[m["transaction_type"] == "open_market_sell"]
buys = m[m["transaction_type"] == "open_market_buy"]

for lo, hi in [(0, report_day - 1), (report_day, report_day + 29), (report_day + 30, 91)]:
    n = hi - lo + 1
    print(f"days {lo:>2}-{hi:<2}  "
          f"sells/day {sells['day'].between(lo, hi).sum() / n:7.1f}  "
          f"buys/day {buys['day'].between(lo, hi).sum() / n:6.1f}")

Full script with formatting and visualisation: when-do-insiders-trade-form-4-timing-python.py

Output

Two bar charts of S&P 500 open-market insider transactions by day of the fiscal quarter, showing selling that rises sharply after the typical day-32 report and collapses in the final fortnight, with buying far flatter apart from a spike on day 0.
S&P 500 open-market insider transactions, 2021-07-01 to 2026-06-30
Universe: 499 tickers   Transactions placed in a mapped quarter: 74,511
Median 10-Q reporting lag: 32 days after fiscal quarter end (n=7,629, IQR 27-36)

Days after quarter end                   Sells     /day    Buys    /day
 0-31  quarter closed, report not out   17,158    536.2   1,376    43.0
32-61  first month after the report     33,891   1129.7   1,636    54.5
62-91  run-up to the next quarter end   19,177    639.2   1,273    42.4

Busiest selling day: day 51 (1,626 transactions)
Quietest stretch: days 80-91 at 253.1 sells/day, 22% of the post-report rate
Median transaction day: sells 46, buys 43
Sells per buy: 16.4
Officers: 48,632 sells, median day 47, 75.7% on or after day 32
Directors: 11,446 sells, median day 43, 78.6% on or after day 32

Sells on days 0-2: 2,508 (3.6% of sells) from 363 insiders; top 3 account for 409

What this tells us

Selling runs at 536 transactions per day while the quarter is closed and results are unpublished, then jumps to 1,130 per day in the month after the typical filing date, 2.1 times higher. The busiest day of the cycle is day 51, roughly three weeks after a median filer reports.

Across days 80 to 91, the fortnight in which the next period is closing, selling falls to 253 per day, 22% of the post-report rate. Nothing in market microstructure explains a collapse of that size on those dates. It matches policies that shut the window before the period ends, when management can already estimate the quarter it is about to report.

Buying traces the same shape with much weaker amplitude: 43.0, 54.5 and 42.4 transactions per day across the three stretches, a peak-to-trough ratio of 1.3 against 2.1 for sales. Purchases are rare, at one buy for every 16.4 sells, and mostly discretionary. Routine selling is what pre-arranged plans automate, so it inherits the calendar those plans are built around.

The spike at the start of the quarter belongs to that automation. Days 0 to 2 hold 3.6% of all sales and 3.8% of purchases land on day 0 alone, concentrated in 363 insiders of whom three account for 409 of the 2,508 early sales. Plans dated to the first trading day of a quarter execute whether or not the window is open. Role barely matters: officers place 75.7% of sales on or after day 32, directors 78.6%.

So what?

Any signal built on insider transactions inherits this calendar, and the naive versions confuse it with information. A screen that flags a company because insider selling rose sharply this week will fire on the mechanical post-earnings surge for hundreds of names at once; a screen hunting unusual quiet will fire on the fortnight before period close.

The correction is to standardise against day of quarter first. Compute the expected count for each day from 0 to 91, from the curve above or from the company’s own history, and score observed activity against that baseline instead of a flat prior. The anchor has to be the filer’s own fiscal quarter end.

Two refinements repay the effort: treat the day 0 to 2 cluster as its own series, since pre-arranged plans dominate it and carry no view on price, then weight what remains by how unusual it is. A purchase on day 85, when the aggregate rate sits at its floor, required an exception to the policy that stops everyone else.

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

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