Panel data rules

From Alexander-M-Dickerson/ai-asset-pricing · View interactive version

Panel data rules is an AI agent skill from the GitHub repository Alexander-M-Dickerson/ai-asset-pricing. Rules and gotchas for CRSP, Compustat, and financial panel data: safe lagging/leading with date gap checks, look-ahead bias prevention, CCM linking, book equity construction, and missing value conventions. Auto-apply when working with CRSP, Compustat, or financial panel data.

How to use this skill

Skill file

Financial Panel Data Rules

Apply these rules whenever writing code that manipulates CRSP, Compustat, OptionMetrics, or any financial panel data. These are hard-won lessons — violating them causes silent data errors.

Rule 1: Safe Lagging/Leading (MANDATORY)

Every groupby().shift() and .diff() MUST be followed by a date gap check. Data is rarely contiguous — missing quarters, fiscal year changes, and delistings create gaps. A bare shift(1) will silently pair non-adjacent observations.

After any shift(k), auto-insert this validation:

df["_date_shifted"] = df.groupby(id_col)[date_col].shift(k)
day_gap = (df[date_col] - df["_date_shifted"]).dt.days
df.loc[(day_gap > max_gap) | (day_gap < min_gap), shifted_col] = np.nan
df.drop(columns=["_date_shifted"], inplace=True)

Thresholds by data source (validated against real WRDS data):

| Source | shift(1) max gap | shift(1) min gap | Notes |

|--------|------------------|------------------|-------|

| CRSP msf/msf_v2 (month-end normalized) | 31 days | 28 days | 2.26M obs: max gap = 31 days exactly (v2: mthcaldt) |

| CRSP msf/msf_v2 (raw trading dates) | 33 days | 28 days | Raw dates vary by last trading day |

| Compustat fundq | 100 days | 80 days | 99.89% in [90,92]; >100 = missing quarter |

| Compustat funda | 380 days | 350 days | <350 = FYE change (correctly flagged) |

| CRSP dsf/dsf_v2 | 5 days | 0 days | Weekends/holidays (v2: dlycaldt) |

For shift(k): max_gap = k * single_max, min_gap = k * single_min.

Infer frequency from data source (table name, column names). Columns ending in q (ibq, atq, seqq) → quarterly. If source unknown, ask the user.

CRSP month-end normalization (do this FIRST, before any gap checks or merges):

df["date"] = df["date"].dt.to_period("M").dt.to_timestamp("M")

This converts raw trading dates to calendar month-end. Required for: (1) gap checks to use the 31-day threshold, (2) matching CRSP to Compustat/JKP data, (3) consistent date joins across datasets.

Rule 2: Accounting Data Timing (Compustat Only)

Does NOT apply to JKP/Global Factor Data — JKP already has point-in-time alignment built in.

```python

# CORRECT — sort by ON key only (hard requirement)

left = left.sort_values('date').reset_index(drop=True)

right = right.sort_values('date').reset_index(drop=True)

pd.merge_asof(left, right, by='gvkey', on='date', direction='backward')

```

Sorting by [gvkey, date] raises ValueError: left keys must be sorted because dates restart at each new gvkey, breaking global monotonicity.

Rule 3: Panel Identifiers & CCM Linking

ID columns:

| Context | Primary ID | Group-by for shift/diff |

|---------|-----------|------------------------|

| CRSP only | permno | permno |

| Compustat only | gvkey | gvkey |

| Merged CRSP-Compustat | permno | permno |

CCM linking:

Always assert no duplicates after merge:

assert not df.duplicated(subset=['permno','date']).any()

Multi-class firms: Firms with multiple PERMNOs per GVKEY exist (2-4 share classes). For firm-level ME: groupby(['gvkey','date'])['me'].transform('sum').

Rule 4: Stock Universe Filters — ALWAYS ASK USER

Never apply filters by default. Present options:

v2 equivalents (string codes):

Rule 5: Missing Values (Compustat-Specific)

Fill with 0 (standard convention):

| Column | Table | Reason |

|--------|-------|--------|

| txditc, txditcq | funda/fundq | Deferred taxes — missing = zero |

| xrd | funda | R&D — missing = no R&D |

| drc, drlt | funda | Deferred revenue — missing = zero |

| dltt, dlc | funda | Debt — missing in ratio = no debt |

| dvpsxq | fundq | Dividends per share — missing = no dividend |

| rect, invt, xpp, ap, xacc | funda | Working capital — missing CHANGE = 0 |

Set to NaN: Ratios with AT ≤ 0 or BEQ ≤ 0 denominators.

Rule 6: Book Equity Hierarchies

Annual BE (Davis-Fama-French 2000):

SHE = SEQ → (CEQ + PSTK) → (AT - LT)
PS  = PSTKRV → PSTKL → PSTK
BE  = SHE + TXDITC(fillna 0) - PS(fillna 0)

Quarterly BEQ:

SHEQ = SEQQ → (CEQQ + PSTKQ) → (ATQ - LTQ)
PSQ  = PSTKRQ → PSTKQ          ← PSTKRQ first!
BEQ  = SHEQ + TXDITCQ(fillna 0) - PSQ(fillna 0)

Q4 supplement: If FQTR == 4 and BEQ missing, use annual BE from matching FYEARQ.

Rule 7: Winsorization — ASK USER FIRST

Do NOT winsorize by default. Confirm: whether to winsorize, which variables, cutoffs (1/99 standard), cross-sectional by month vs pooled.

Standard pattern when confirmed:

def winsorize_by_month(df, col, date_col="date", lo=0.01, hi=0.99):
    def _w(s):
        x = s.dropna()
        if x.empty: return s
        return s.clip(np.nanpercentile(x, lo*100), np.nanpercentile(x, hi*100))
    df[f"{col}_w"] = df.groupby(date_col)[col].transform(_w)

Rule 8: Quarterly Data Gotchas

Use this skill with your AI agent: Open on Skill Issue to copy, download, or add to your library. Works with Claude, ChatGPT, Gemini, Cursor, Windsurf and more.