Skip to content

Chapter 7 — COMPUSTAT derived variables and the CCM merge

Part II of the assayinganomalies tutorial. Prerequisite chapters: 1, 2, 3, 4, 5, 6. Python modules covered: transforms/compustat.py.

What this chapter answers

  • How annual COMPUSTAT becomes June-aligned BE/BM (and the other annual columns), stored on the June row of the monthly CRSP panel only, and how aa.fill_months / aa.load(..., fill_annual=True) give monthly values.
  • Why the quarterly variables are computed on a forward-filled monthly grid, not on raw fundq rows.
  • How _nansum treats missing values — including “all-NaN → NaN, not 0”.

Where this sits in the pipeline

Stage transform-compustat (Ch 4) loads linked funda / fundq / CCM link history, calls merge_compustat_crsp, and writes COMPUSTAT columns onto the existing ccm_panel from Ch 6. Downstream stages (tcosts, betas, NMV, assay) read be, bm, fin_firm, and the quarterly signals from that panel.

flowchart LR
  FUNDA["funda"]
  FUNDQ["fundq"]
  LINK["ccmxpf_lnkhist"]
  CCM0["ccm_panel CRSP"]
  MERGE["merge_compustat_crsp"]
  CCM1["ccm_panel + COMPUSTAT"]
  FUNDA --> MERGE
  FUNDQ --> MERGE
  LINK --> MERGE
  CCM0 --> MERGE
  MERGE --> CCM1

Linking, alignment, derived variables and the quarterly grid all run under one orchestrator on one long panel.

Schema: the panel column dictionary. The eight quarterly items derive from the forward-filled monthly grid built by build_quarterly_monthly_panel, not from the quarterly fundq rows.


Three things to keep straight

1. June alignment and the accounting lag

Fiscal year ending in calendar year Y lands at June of Y+1:

    # Align to June of the following year (YYYYMM format then convert to month-end)
    # E.g., FY2020 data (ending Dec 2020) → available June 2021
    df["date"] = pd.to_datetime(
        (df["fyear"] + 1).astype(str) + "-06-30"
    ) + pd.offsets.MonthEnd(0)

Then BM is be / me_dec where me_dec is December ME for fyear — at the June row, the ME six months earlier.

The record is stored on its June row and nowhere else. attach_annual_records joins each record to the panel row with the same permno and the same June month-end. The annual value columns (ANNUAL_VALUE_COLS, and columns added with aa add-compustat-vars --annual) and the four provenance columns (comp_datadate, comp_avail_date, be_source, be_avail_date) are NaN on the other eleven rows of the year. Nothing is carried forward in the build. This is MATLAB's June-only annual matrix. The stage records the layout in the database (metadata.annual_layout = "june").

Monthly values are made when they are needed, with one function:

d = aa.load(["gp", "at"])                    # June only, as stored
m = aa.load(["gp", "at"], fill_annual=True)  # June through the following May
m2 = aa.fill_months(d)                       # the same fill, on any (date, permno) frame

aa.fill_months(x, months=11) carries each stock's last value forward for at most 11 calendar months (MATLAB's FillMonths), so a June value reaches the following May and never stands in for a later year without a filing. It fills rows that exist and adds none. What aa.load(..., fill_annual=True) does and does not fill is in Ch 12. Which of the two you sort on decides how often the sort trades: a signal with June-only values trades each June, a filled one every month (Ch 13).

A stock with no panel row in the June has no values from that record, also after a fill, until its next June. This is rare: it needs a stock that has a linked filing but no ccm_panel row in that June and rows later in the year (for example one that enters the panel a few months after the June). MATLAB, and versions of this package that stored the columns filled June to May, gave such a stock the record's values from its first month.

A database built before this layout holds the columns filled June to May and has no layout record. aa.load of an annual column and aa add-compustat-vars --annual refuse it with aa.AnnualLayoutError, and the stages compute-nmv-anomalies and validate-bm-hml stop with an error that names the same command; rebuild with aa setup-database --start-from transform-compustat (the staged extracts are reused; no WRDS login). SQL written by hand against ccm_panel is not checked.

Davis–Fama–French historical BE is different. The DFF file’s column BE_YYYY is stored at June YYYY (same year as the label), not June YYYY+1. Do not apply the Compustat FY→June+1 rule to it.

2. Quarterly variables live on the monthly grid

Do not derive beq / roa / sue / … on quarterly rows and then fill. Each raw input (SEQQ, ATQ, IBQ, …) is first placed at its RDQ month and forward-filled per column up to two months past the last announcement. Derived formulas then run on that monthly grid. Independent fills mix vintages: a month can pair a new ATQ with a stale SEQQ. Lags are in months. Computing per quarter and filling outputs gives different numbers. This follows the original MATLAB toolkit, which built these variables on dense months×stocks matrices filled column by column.

3. _nansum and missing values

_nansum treats NaN as 0 in a sum, but if every operand is NaN the cell stays NaN (not 0):

def _nansum(*arrays: pd.Series) -> pd.Series:
    """Sum arrays treating NaN as 0 (like MATLAB nanmatsum)."""
    result = arrays[0].copy()
    for arr in arrays[1:]:
        # Where both are NaN, result stays NaN; otherwise sum ignoring NaN
        both_nan = result.isna() & arr.isna()
        result = result.fillna(0) + arr.fillna(0)
        result[both_nan] = np.nan
    return result

Partial sums must stay in one _nansum call. Splitting into two groups and subtracting poisons finite partials when the subtracted group is all-NaN. Plain + / - (WCAP, GPQ) is intentional where a missing operand should make the result missing.


Module constants

Name Value / contents Meaning
QUARTERLY_FFILL_VARS seqq, ceqq, pstkq, atq, ltq, txditcq, revtq, cogsq, ibq, epspxq, niq, cheq, mibq, xrdq Raw quarterly inputs filled onto the monthly grid
QUARTERLY_DERIVED_COLS beq…amonth + ibq, niq, ltq, cheq, mibq, xrdq Derived + raw quarterly columns written to the panel (ibq/niq/ltq/cheq needed by NMV; mibq/xrdq carried for user signals)
ANNUAL_VALUE_COLS be, bm, at, lt, …, wcap, cfo, mib Annual columns, stored on the row of the June their filing becomes available (mib carried for user signals)
ANNUAL_PROVENANCE_COLS comp_datadate, comp_avail_date, be_source, be_avail_date Where the June row's record came from; June row only
ANNUAL_VALIDITY_MONTHS 12 Length of a record's window; fill_annual=True carries a value 11 months
ANNUAL_LAYOUT_KEY / ANNUAL_LAYOUT_JUNE "annual_layout" / "june" The metadata record transform-compustat writes
QUARTERLY_FILL_HORIZON 2 Months a quarterly value persists past the last announcement
QUARTERLY_LAG_WINDOW 60 Max months back when looking for prior report months (SUE/dROE)
SUE_MIN_OBS 6 Minimum seasonal differences for the SUE standard deviation
QUARTERLY_START 1971-01-31 First month quarterly signals are produced
FF_TCOST_RAW_COLS at, revt, cogs, xsga, xint June inputs for FF tcosts (Ch 9)

_nansum(*arrays)

Signature

  • *arrays: pd.Series — same index; each is one operand.

Returns — pd.Series, NaN-tolerant sum with all-NaN → NaN (unlike np.nansum, which returns 0).

What it does — pairwise fold: fillna(0), add, restore NaN where both were NaN. Order matters for floating-point only in long chains; the semantics that matter are the all-NaN rule and collapsing signed terms into one reduction.

Used by be, oc, d, inv_capital, fcf, div, cfo, beq.


Annual derived helpers

compute_book_equity(funda)

Signature

  • funda: pd.DataFrame — annual fundamentals (seq, ceq, pstk, at, lt, pstkrv, pstkl, txditc, txdb, itcb, …).

Returns — pd.Series BE = nansum(SE, DT, -PS).

What it does

  1. SE = SEQ; fill from CEQ+PSTK (plain +, NaN propagates); then AT−LT.
  2. PS = PSTKRV → PSTKL → PSTK.
  3. DT = TXDITC; else _nansum(TXDB, ITCB).
  4. BE = _nansum(se, dt, -ps).
    se = funda.get("seq", pd.Series(np.nan, index=idx))
    if "ceq" in funda.columns and "pstk" in funda.columns:
        alt_se = funda["ceq"] + funda["pstk"]
        se = se.fillna(alt_se)
    # ...
    return _nansum(se, dt, -ps)

Critical: do not fillna(0) on CEQ+PSTK. If both are NaN, the sum must be NaN so SE falls through to AT−LT. Zero-filling would set SE=0 and block that fallback (documented in the function docstring; matters for early Compustat coverage).

Davis–Fama–French historical BE overwrites this value later, in the merge (see below).

compute_operating_costs / compute_total_debt / compute_investment

Signature — each takes funda; returns a Series.

Function Formula Panel column
compute_operating_costs _nansum(cogs, xsga) oc
compute_total_debt _nansum(dlc, dltt) d
compute_investment _nansum(ppegt, invt) inv_capital

compute_free_cash_flow(funda)

Signature — funda with ni, dp, wcapch, capx.

Returns — FCF Series.

What it does — single _nansum(ni, dp, -wcapch, -capx). The four signed terms must be one reduction: _nansum(ni, dp) - _nansum(wcapch, capx) would return NaN whenever WCAPCH and CAPX are both missing, even though NI/DP is finite.

compute_dividends(funda)

Signature — funda with dvc, prstkcc, optional prstkc/prstkpc.

Returns — DIV Series: primary dvc.fillna(0)+prstkcc; where prstkcc is NaN, fallback _nansum(dvc, prstkc.fillna(0)-prstkpc.fillna(0)) (net repurchases stand in for missing PRSTKCC).

compute_working_capital(funda)

Returns — plain act - lct (NaN if either missing). This is deliberately not a _nansum: a missing LCT must not be treated as zero.

compute_cfo(funda)

Signature — twelve components + optional oancf fallback.

What it does — _nansum of IB, XIDO, DP, TXDC, ESUBC, −SPPIV, FOPO, RECCH, INVCH, APALCH, TXACH, AOLOCH; then fillna(oancf). SPPIV (gain on sale of property and investments) is non-operating, so it enters with a minus sign.

    components = _nansum(
        _col("ib"),
        _col("xido"),
        _col("dp"),
        _col("txdc"),
        _col("esubc"),
        -_col("sppiv"),  # MATLAB line 112: nanmatsum(temp, -SPPIV)
        _col("fopo"),
        # ...
    )
    oancf = _col("oancf")
    result = components.copy()
    result = result.fillna(oancf)

compute_derived_variables(df)

Signature — annual frame (typically post-align); returns copy with be, oc, d, inv_capital, fcf, div, wcap, cfo.

What it does — calls the helpers above. fin_firm is not computed here: it comes from CRSP sic inside merge_compustat_crsp, not from Compustat SICH.

bm and fin_firm are finished in the merge.


FF historical book equity

fetch_ff_historical_be(config)

Signature

  • config: AssayConfig — sample_start / sample_end filter years.

Returns — DataFrame permno, date (June month-end), be. Prefers a local AssayingAnomalies-MATLAB/Data/FF/DFF_BE_With_Nonindust.txt (or Data/FF/…) over downloading Ken French’s zip, so rebuilds use a fixed vintage of the file. If the local file is absent, the download is tried three times (5 and 15 seconds apart). If every attempt fails it raises HistoricalBookEquityError, which names the URL, and the build stops: it does not go on without the file.

What it does — parse wide BE_1926…BE_2001; skip −99.99 / −999; map column year yr → Timestamp(f"{yr}-06-30") (BE_1926 → 1926-06-30, not 1927).

                if pd.notna(val) and abs(float(val) - (-99.99)) > 0.01 and val != -999:
                    # DFF's "BE_YYYY" column stores BE available at June YYYY.
                    # Matches MATLAB: ffDates = (100 * (1926:2001) + 6)'.
                    date = pd.Timestamp(f"{yr}-06-30")
                    rows.append({"permno": perm, "date": date, "be": float(val)})

In the merge, the DFF value overwrites Compustat BE wherever DFF has a value — it does not merely fill missing Compustat BE.


The link is cleaned once and stored: transform-compustat writes the cleaned link as the ccm_link table before it merges anything (even when the Compustat extract or ccm_panel is missing), and compute-car3 and compute-ff-tcosts read that table rather than the staging parquet. A database built before ccm_link existed falls back to cleaning the raw ccmxpf_lnkhist table (then the staged extract) with a warning to rebuild transform-compustat.

clean_ccm_link(raw, config=None)

Signature

  • raw — ccmxpf_lnkhist (gvkey, lpermno, linkdt, linkenddt, and usually linktype, lpermco, linkprim), any column-name case.
  • config — sample_end closes open links (default config when omitted); "latest" means the year the database's last build resolved it to (AssayConfig.resolved_sample_end), and raises SampleEndUnresolvedError when no build has recorded one.

Returns — the columns of CCM_LINK_COLUMNS (gvkey, permno, permco, linkdt, linkenddt, linktype, linkprim), one row per usable link: LC/LU only (when linktype is present), lpermno/lpermco renamed to permno/permco, dates parsed, a missing linkenddt set to {sample_end}-12-31, rows without a permno dropped, permno int64. Cleaning a cleaned link returns it unchanged. An empty or unusable input gives an empty frame with typed columns (so the demo build still writes a typed table).

Signature — any gvkey-keyed frame and a cleaned link (ccm_link or clean_ccm_link output).

Returns — the rows of df whose date falls in a link window (linkdt ≤ date ≤ linkenddt, inclusive), with an int permno; unlinked rows dropped, the link's own columns left out, your columns untouched. Public as aa.merge_on_link (Ch 12 shows it on your own data).

merge_on_link(funda, clean_ccm_link(link, config)): takes a raw or clean link. merge_compustat_crsp cleans once and passes the clean link to the annual and quarterly merges; build_june_annual_panel goes through this wrapper.

align_annual_to_monthly(funda_linked, config)

Signature — linked annual frame; config unused for the date math (kept for API symmetry).

Returns — date = June of fyear+1; duplicates on (permno, date) keep latest datadate (fiscal-year-end moves). Non-December fiscal year-ends use the same simplified rule (June of the year after the FYE year).

Signature — link+align; keep columns (default FF_TCOST_RAW_COLS); optional Compustat+FF be; filter date.month == 6; MultiIndex (date, permno).

What it does — June rows built from the filings themselves, not read from ccm_panel. Firm-year gaps stay NaN so stale priors do not re-enter 2×3 sorts (documented in the docstring). Every record is kept, including that of a stock with no panel row in the June, which ccm_panel does not hold. Used by the FF transaction-cost estimator (Ch 9).


Quarterly monthly panel and helpers

build_quarterly_monthly_panel(fundq_linked, panel_dates, *, permnos=None, variables=QUARTERLY_FFILL_VARS)

Signature

  • fundq_linked — quarterly rows with permno, rdq, datadate, raw fields.
  • panel_dates — CRSP calendar (unique month-ends from ccm_panel).
  • permnos — optional restrict.
  • variables — the raw columns to fill (default QUARTERLY_FFILL_VARS; merge_compustat_crsp adds the columns added with aa add-compustat-vars, and align_extra_quarterly passes only those). The grid depends on the announcement dates only, so the choice of columns never changes it.

Returns — contiguous monthly grid per permno with independently forward-filled variables.

What it does

  1. Drop missing RDQ; date = RDQ month-end; drop dates outside CRSP calendar.
  2. Sort (permno, rdq, datadate); keep last per (permno, date).
  3. Expand each permno from first to last announcement + 2 months.
  4. Cast to float64 (nullable dtypes break != — see amonth).
  5. Per column: ffill within permno; blank past last_pos + 2.
    for col in value_cols:
        announced = grid.loc[grid[col].notna()]
        last_pos = announced.groupby("permno")["pos"].max()
        series = grid.groupby("permno", sort=False)[col].ffill()
        cap = grid["permno"].map(last_pos)
        filled[col] = series.where(grid["pos"] <= cap + QUARTERLY_FILL_HORIZON)

Each variable is filled independently, so one month can mix vintages across columns (see "Three things to keep straight").

_month_index / _fill_months / _scatter / _report_lag_frame / _nan_moments

Helper Role
_month_index year*12+month, so gaps are measured in months
_fill_months ffill + cap at last finite + persist months
_scatter report-month values onto the full index, blanking non-report cells
_report_lag_frame values at the k-th prior report month; gap ≤ 60 months
_nan_moments sequential count/mean/std (ddof=1)

_nan_moments quirk: the moments are accumulated sequentially rather than with NumPy’s pairwise sum. On a constant window the pairwise sum gives a std of exactly 0 → 0/0 = NaN, while sequential accumulation gives std ~1e-17 → SUE2 = 0. This follows the original MATLAB toolkit, whose std(...,'omitnan') accumulates in that order; it changes roughly 12,000 sue2 cells from NaN to 0.


Quarterly derived variables

All of these expect the monthly frame from build_quarterly_monthly_panel (or equivalent), not raw fundq.

compute_quarterly_book_equity / compute_quarterly_gross_profit

Function Formula Notes
BEQ SEQQ → CEQQ+PSTKQ → ATQ−LTQ; DT=TXDITCQ; PS=PSTKQ; _nansum(SE,DT,-PS) No PSTKRQ / TXDBQ fallbacks (unlike annual)
GPQ revtq - cogsq Plain subtraction

On the monthly grid, BEQ/GPQ mix input vintages across quarters.

compute_quarterly_roa(monthly)

Returns — ibq / groupby(permno).atq.shift(3) — three months, so ROA moves within a quarter as lagged ATQ rolls. No zero guard (ATQ==0 → Inf).

compute_quarterly_report_month / compute_amonth

A month is a report month when IBQ is finite and differs from the previous month’s IBQ.

    ibq = monthly["ibq"]
    prev = monthly.groupby("permno", sort=False)["ibq"].shift(1)
    changed = (ibq != prev).fillna(True)
    return (ibq.notna() & changed).fillna(False).astype(bool)

.fillna(True) makes the first month (prev NaN) count as changed. Without it, pandas nullable x != NA is NA, which would silently drop every firm’s first announcement and shift the SUE/dROE lag chains. amonth is dense 0/1 (astype(float)); the merge fills it with 0.

compute_sue(monthly, *, report_month=None)

What it does — at report months only: eight seasonal EPS diffs lag_j − lag_{j+4} (j=1..8) via _report_lag_frame (12 lags, 60-month cap); std with qmin=6, std==0 → NaN; numerator EPSPXQ − lag_4; gate ≥ 1971-01; _scatter + _fill_months(persist=2).

compute_droe(monthly, beq=None, *, report_month=None)

What it does — report-month (ibq − ibq_l4) / beq_l1; no BE zero guard; spread with _fill_months.

compute_sue2(monthly) / compute_droa(monthly)

SUE2 dROA
Indexing Pure monthly rows Pure monthly rows
Numerator IBQ[i]−IBQ[i−12] IBQ[i]−mean(IBQ[i−12:i−1])
Denom / scale std(IBQ[i−24:3:i−3]) contemporaneous ATQ
Guards none (no qmin, no std==0) none on ATQ
Start ≥ 1971-01 ≥ 1971-01

dROA’s twelve-month mean spans ~four quarterly vintages each repeated three times on the filled grid.

compute_quarterly_derived(monthly)

Returns — input plus beq, gpq, roa, sue, droe, sue2, droa, amonth.


Merge orchestrator

Signature

  • funda, link, ccm_panel (must include me, preferably sic), config.
  • fundq optional — if present, quarterly path runs.
  • extra_annual, extra_quarterly — raw funda / fundq columns added with aa add-compustat-vars (Ch 5). They join ANNUAL_VALUE_COLS and the raw quarterly columns (QUARTERLY_FFILL_VARS / QUARTERLY_DERIVED_COLS), so they are carried, and replaced on every run, exactly like at and ibq. Empty (the default) builds the panel exactly as without them. _stage_transform_compustat passes the names recorded in the database.

Returns — updated ccm_panel with annual + quarterly COMPUSTAT columns.

What it does (execution order)

  1. link_compustat_to_crsp → align_annual_to_monthly → compute_derived_variables.
  2. FF BE: left-merge overwrite where FF finite; append DFF-only (permno, date) rows (fyear = date.year - 1 for BM).
  3. BM: December ME for fyear; bm = be / me_dec (keeps negative BM).
  4. Drop stale Compustat columns on the panel (left-merge would otherwise keep old be/bm); attach_annual_records left-joins each record, whole, on the panel row of its availability June. The other months stay NaN; nothing is carried forward. The log line Attached … of … annual records to their June rows counts the records of stocks with no panel row in that June, which are not on the panel.
  5. fin_firm from CRSP sic ∈ [6000, 6999], NaN SIC → 0.
  6. If fundq: link → build_quarterly_monthly_panel → compute_quarterly_derived → reindex onto panel; amonth.fillna(0).
    # Step 6: each record goes, whole, on the panel row of its availability
    # June. The other months are NaN; nothing is carried forward here.
    result = attach_annual_records(panel, records)

Called from the pipeline by _stage_transform_compustat in pipeline.py, which writes the panel and then the layout record (metadata.annual_layout = "june").

Returns — permno, date and columns (float64), one row per row of panel_keys (the permno, date of ccm_panel), in its order.

What they do — what merge_compustat_crsp does for its own columns, for a few raw columns of an extract that holds only those and the identifiers (aa add-compustat-vars). Annual: link_compustat_to_crsp → align_annual_to_monthly → attach_annual_records (whole records on their June rows; NaN in the other months). Quarterly: link_compustat_to_crsp → build_quarterly_monthly_panel(variables=columns) → reindex onto the panel keys. A test checks that an added column equal to at (or xrdq) at WRDS lands on the panel exactly where at (xrdq) is.

build_placeholder_panel(config)

Returns — empty frame with date, permno, gvkey, at, be, bm, the legacy empty schema for placeholder mode. Free to delete once the placeholder path is gone.