The primary data source for the analysis in Bali et al. (2016) is CRSP. Bali et al. (2016) discuss several ways of obtaining CRSP data that applied in 2016 before indicating that they obtained CRSP data in form of SAS data accessed on WRDS servers using SSH (Bali et al. 2016, 104).
I store the WRDS tables used in this book as Parquet files.
1.1.1 WRDS tables
In 2016, when Bali et al. (2016) was published, the canonical form of WRDS data was SAS data files. For users with WRDS access, my wrds2pg package can be use to generate Parquet files from SAS data files. However, I recommend getting data from the WRDS PostgreSQL server instead.
Since 2017, WRDS has provided data through a PostgreSQL database server. As discussed in Gow and Ding (2024), the SAS data files and the PostgreSQL server can be viewed as canonical sources of WRDS data. For users with WRDS access, my db2pq package can be used to generate Parquet files from the PostgreSQL database. Because using db2pq is faster and more robust than using wrds2pg, I recommend that you use db2pq.
Some books and code repositories reduce the quantity of data retrieved from WRDS by taking subsets of observations or variables. For example, Tidy Finance (Scheuch et al. 2024) use a script to download a selection of variables from the CRSP daily stock file for subsets of firms in batches. In contrast, I download the full tables in each case.
While downloading the full WRDS data files used here can take several minutes even with a fast internet connection, I think this is a cost worth bearing for several reasons. First, many finance researchers will only have access to annual updates and will use the data on a near-daily basis. So the fixed cost of downloading the data can be amortized over many uses.
Second, managing vintages of data is much easier with the approach used here. The core db2pq function wrds_update_pq() used below retains information about the vintage of the data on WRDS and this avoids downloading data that is of the same vintage as the user already has. Other functions offered by db2pq allow the user to retain older vintages and swap them easily if one wants to reproduce data using a specific vintage.
It seems not uncommon for researchers to get a certain set of variables in initial analysis, then need to go back to retrieve additional variables later on when the vintage of the data might be different. In such cases, a research is confronted with a choice of updating all variables, potentially losing finely balanced results in the process, or just getting data for the additional variables, which introduces potential inconsitencies in the data. By getting all variables at the outset, this issue is avoided.
Another reason to get the full data files relates to reproducibility. If your results are generated on a specific subset of a WRDS data file, then I need to get that specific subset to reproduce them. Because researchers often do not include the code to produce the WRDS data files they use, additional frictions are introduce to reproducibiliy in practice. In contrast, using crsp.dsf produced using db2pq will produce exactly the same results as I’d get from using crsp.dsf in the PostgreSQL database.
A third approach to managing data avoids storing local data at all. For example, Gow and Ding (2024) provide code to run analyses in their book using direct connections to the WRDS PostgreSQL server with little or no persistence of data locally. While this does reduce the initial set-up costs, it introduces issues of performance and even reproducibility that do not seem worth forgoing the modest initial setup costs of the approach used here.1
1.1.1.1 Compustat (comp)
Compustat is the most common source of financial-statement data for academic research, particulary for US firms. Academic researchers generally get Compustat data through WRDS.
While Compustat is a rich source of data from income statement, balance sheets, and cash flow statements, its direct use by Bali et al. (2016) is limited to calculating the book value of common equity. The table from Compustat needed for this purpose is comp.funda, which supplies annual data.
While Bali et al. (2016) make little use of Compustat data, many studies of the cross-section of stock returns go deeper into financial statements. Chapter 14 of Gow and Ding (2024) covers Bernard and Thomas (1989), which uses quarterly income before extraordinary items (ibq in comp.fundq) to measure earnings surprises, then compare abnormal returns across earnings-surprise deciles after the announcements. Chapter 15 of Gow and Ding (2024) focuses on Sloan (1996), which uses annual financial statements (comp.funda) to separate earnings into accrual and cash-flow components, then compares subsequent returns across portfolios sorted on accruals.
1.1.1.2 CRSP (crsp)
The primary source of data in Bali et al. (2016) is the CRSP database. According to its website, “the Center for Research in Security Prices, LLC (CRSP) maintains the most comprehensive collection of security price, return, and volume data for the NYSE, AMEX and NASDAQ stock markets. Additional CRSP files provide stock indices, beta-based and cap-based portfolios, treasury bond and risk-free rates, mutual funds, and real estate data. [CRSP] maintains the most comprehensive collection of security price, return, and volume data for the NYSE, AMEX and NASDAQ stock markets. Additional CRSP files provide stock indices, beta-based and cap-based portfolios, treasury bond and risk-free rates, mutual funds, and real estate data.”
According to WRDS, “CRSP contains end-of-day and month-end prices on all listed NYSE, Amex, and NASDAQ common stocks along with basic market indices, and includes the most comprehensive distribution information available, with the most accurate total return calculations.”
In 2022, CRSP introduced a new data format called CIZ.2 The CIZ format replaced the SIZ format available when Bali et al. (2016) was written. CRSP stopped releasing SIZ format data in early 2025, so no data on returns and stock prices are available in the SIZ format for periods after 2024.
One major change with CIZ was to the layout of the tables, with CIZ tables often being much larger because they contain data from what were multiple tables in SIZ.3
A second change with CIZ affected the calculation of monthly returns. With SIZ, monthly returns are calculated from month-end to month-end, with dividends reinvested at month-end. In contrast, CIZ compounds daily returns over the month, with dividends reinvested on their ex-dividend dates.4
A third change with CIZ was the incorporation of any applicable delisting returns into the reported monthly return. In contrast, the SIZ data available to Bali et al. (2016) placed delisting returns in a separate table and researchers bore the burden of incorporating delisting returns, which were often missing from that table. See CRSP’s comparison of the formats.
Because my focus here is on providing a reader’s companion to Bali et al. (2016), I use the final vintage of the SIZ data throughout this version of the book. Because the SIZ files I use come from a later CRSP vintage than used in BEM, the underlying data can still differ, though in practice not by much. A later edition of this book may instead use CIZ data or provide a guide to how the analyses could be conducted using CIZ data.
Daily returns come from crsp.dsf and monthly returns from crsp.msf. We use crsp.msenames for data on industries and the exchanges on which stocks are traded. Delisting returns come from crsp.msedelist and index data from crsp.msi.
The final CRSP table we use is crsp.ccmxpf_lnkused. CRSP provides PERMNO, its own “permanent identifier” for each security in its database. Additionally, CRSP provides a company-level identifier, PERMCO, for each company. WRDS tells us that CRSP’s goals in creating these identifiers are to allow “for clean and accurate backtesting, time-series and event studies, measurement of performance, accurate benchmarking, and securities analysis.” Howver, the firm identifier on Compustat is GVKEY and crsp.ccmxpf_lnkused provides a way to link CRSP data with the relevant Compustat records. Chapter 7 of Gow and Ding (2024) explains how to link CRSP and Compustat.5
1.1.1.3 Fama–French factors
Throughout the book I use the June 2014 releases from Kenneth French’s Data Library for the daily and monthly Fama–French factors, risk-free returns, and momentum factors, and for the monthly short-term reversal factor. This vintage is closer to the data available when BEM prepared their book. For example, estimating beta with the June 2014 daily market factor improves the match to the annual beta portfolio returns in BEM Table 5.3. eap_pl.get_ff_factors() downloads the archives and keeps checksum-verified local copies for later renders.
WRDS distributes the French series in separate daily and monthly tables. The ff.factors_daily extract I compared reports an update on June 16, 2026, with data through April 2026. The ff.factors_monthly extract reports an update on May 23, 2026, with data through March 2026. These dates are consistent with the two tables being refreshed separately. WRDS data description
get_ff_factors("daily", vintage="202604") matches mktrf, smb, hml, and rf in all 26,233 WRDS daily observations at published precision. get_ff_factors("monthly", vintage="202512") matches those four columns over 1988–2012, with differences elsewhere in the WRDS history. The full monthly history and the umd momentum column at both frequencies remain unmatched in the archives I checked.
To approximate monthly mktrf from the daily data, add back the daily risk-free return, compound the total market return and the risk-free return separately, then subtract the two monthly returns. For smb, hml, and momentum, compounding the underlying portfolio returns before taking their differences improves on compounding the daily factor spreads.6 French publishes monthly returns for the portfolios used to construct these factors. Fama–French factor definitions. French sorts stocks into momentum portfolios each trading day for the daily factor and once a month for the monthly factor. Daily momentum definition and monthly momentum definition.
1.1.1.4 Source vintages
Table 1.1 lists the WRDS inputs used in this build. The source update date comes from the metadata embedded in each Parquet file, read with db2pq. It is not the sample end date or the date the file was downloaded.
Code
import refrom db2pq import pq_last_modifiedfrom IPython.display import Markdown, displaytables = [ ("comp", "funda", "Compustat","Annual fundamentals for book equity."), ("crsp", "dsf", "CRSP legacy (SIZ)","Daily returns for beta estimation in @sec-bem-beta and daily prices, returns, and volume for @sec-liquidity-replication."), ("crsp", "msf", "CRSP legacy (SIZ)","Legacy prices, shares outstanding, and monthly returns."), ("crsp", "msenames", "CRSP legacy (SIZ)","Historical share codes, exchanges, and industries."), ("crsp", "msedelist", "CRSP legacy (SIZ)","Delisting returns and codes for monthly holding-period returns."), ("crsp", "msi", "CRSP legacy (SIZ)","CRSP value-weighted index for the market factor comparison."), ("crsp", "ccmxpf_lnkused", "CRSP/Compustat Merged","Historical links from Compustat firms to CRSP securities."),]rows = ["| WRDS table | Dataset | Used for | Source updated |","|:---|:---|:---|:---|",]for schema, name, dataset, purpose in tables: metadata = pq_last_modified(name, schema) or"" match = re.search(r"Updated (\d{4}-\d{2}-\d{2})", metadata) updated = match[1] if match else"Not recorded" rows.append(f"| `{schema}.{name}` | {dataset} | {purpose} | {updated} |")display(Markdown("\n".join(rows)))
Table 1.1: WRDS inputs and source update dates
WRDS table
Dataset
Used for
Source updated
comp.funda
Compustat
Annual fundamentals for book equity.
2026-06-16
crsp.dsf
CRSP legacy (SIZ)
Daily returns for beta estimation in Chapter 8 and daily prices, returns, and volume for Chapter 13.
2025-02-08
crsp.msf
CRSP legacy (SIZ)
Legacy prices, shares outstanding, and monthly returns.
2025-02-08
crsp.msenames
CRSP legacy (SIZ)
Historical share codes, exchanges, and industries.
2025-02-08
crsp.msedelist
CRSP legacy (SIZ)
Delisting returns and codes for monthly holding-period returns.
2025-02-08
crsp.msi
CRSP legacy (SIZ)
CRSP value-weighted index for the market factor comparison.
2025-02-08
crsp.ccmxpf_lnkused
CRSP/Compustat Merged
Historical links from Compustat firms to CRSP securities.
2026-02-06
1.1.1.5 Create the Parquet repository
Copy .env.example to .env in the book checkout and set DATA_DIR to your Parquet root and WRDS_ID to your WRDS username. After uv sync, run the setup script from that checkout. If you already have the source files there, you can skip this step. If your WRDS account lacks access to the legacy CRSP tables, use licensed SIZ extracts at the corresponding paths. eap_pl.load_parquet() reads these files from DATA_DIR/schema/table.parquet.
uv run scripts/download_wrds_tables.py
The following Python example shows how the script uses db2pq.wrds_update_pq() to export the WRDS tables to DATA_DIR.
from db2pq import wrds_update_pqfrom dotenv import load_dotenvload_dotenv()tables = {"crsp": ["msf", "dsf", "msenames", "msedelist", "msi", "ccmxpf_lnkused"],"comp": ["funda"],}for schema, names in tables.items():for name in names: wrds_update_pq(name, schema)
1.1.2 Other data sources
The annual methods chapters construct December betas, size, and book-to-market from the local source data when needed. See Chapters 8, 9, and 10 for how each measure is constructed. The monthly replications estimate the 12-month daily beta on demand with eap_pl.load_monthly_betas(). See the render instructions.
Chapter 13 uses the December 2013 Pástor–Stambaugh liquidity release bundled with eap_pl.
1.2 Winsorization and Truncation
Winsorization caps values outside chosen percentile cutoffs at the corresponding cutoff. Truncation sets those values to missing, so analyses that require the variable exclude those observations. In Section 1.2, Bali et al. (2016) describe both methods as ways to limit the influence of extreme values. They suggest capping observations that still convey information about genuinely high or low values, and consider truncation when the extremes appear to come from a different process. They urge caution when the conclusions depend on which treatment is used.
BEM compute the cutoffs separately for each year or month because they analyze each period’s cross-section before summarizing the results over time. Their 0.5% rule uses the 0.5th and 99.5th percentiles. In Chapter 3, both variables are winsorized for Pearson correlations, and Spearman correlations use ranks of the original values. In Chapter 6, the regressors are winsorized and the excess-return outcome is used as observed.
I compute the winsorization cutoffs by linear interpolation with .eap.winsorize(prob=0.005, quantile_method="linear"). The eap_pl.winsorized_corr() helper applies this rule to each variable after keeping pairs with two finite values. In Chapter 8, .over("month") computes cutoffs separately for each month’s beta estimates. I then fit the Fama–MacBeth regressions with statspai.fama_macbeth().
In Section 1.3, Bali et al. (2016) explain why inference on a time-series mean can be sensitive to changing variance and correlation across periods. Regressing a series on a constant gives its sample mean as the intercept. The adjustment of Newey and West (1987) estimates the standard error using covariances across periods, with less weight on more distant lags. Depending on the pattern of autocorrelation, the adjustment can increase or decrease the standard error. In Chapter 5, BEM use the adjustment for average portfolio returns and spreads, and in time-series factor regressions for portfolio alphas.
For Fama–MacBeth regressions, BEM apply the adjustment to the sequence of estimated coefficients, with one estimate per cross-section. BEM motivate six lags with a rule of thumb for a series of about 600 monthly observations and also use six lags in their annual example, which has only 24 coefficient estimates. Gow et al. (2010) call this procedure FM-NW and find that its standard errors can remain too small when the underlying panel has both cross-sectional and time-series dependence. A short coefficient series provides limited information about persistence in the underlying data (Gow et al. 2010, 488).
The annual, beta, size, and book-to-market regressions replicated here use realized excess returns over nonoverlapping holding periods. This resembles the return-based application in Gow et al. (2010, sec. V), where shared shocks across stocks are the main concern. For slope inference, the relevant serial dependence involves the joint behavior of regressors and residuals. Size is highly persistent in my replications. Across specifications, the pooled lag-one correlations between residuals for the same stock range from about \(-0.05\) to \(-0.01\).
For every slope in the monthly replications, the ordinary and six-lag tests agree at the 5% level. Section 6.2 shows how the adjustment changes inference on size in the annual example.
For more on Newey–West, Fama–MacBeth, and clustering, see Section 5.6 of Empirical Research in Accounting in the StatsPAI edition or the Polars edition.
1.4 Python packages
1.4.1 Polars
I use Polars, imported as pl, to filter, join, and summarize the data throughout the book. A DataFrame holds the data in memory, and a LazyFrame describes a query that runs when I call .collect(). Expressions such as pl.col("ret") refer to columns, and .over("month") applies a calculation separately within each month. See the Polars user guide.
1.4.2eap_pl
Here eap stands for “Empirical Asset Pricing” and pl is the standard abbreviation for Polars. The eap_pl package was created specifically for this reader’s companion and streamlines work that recurs across chapters, including reading local Parquet tables, constructing stock-level variables, and forming portfolios.
Importing eap_pl also registers the .eap namespace for Polars expressions and DataFrames. For example, .eap.winsorize() clips an expression at quantile cutoffs. For more details, see the eap_pl function reference.
1.4.3 Great Tables
I use Great Tables to format the book’s tables, usually through .eap.show_table() on a Polars DataFrame. For tables that need grouped rows or spanning column headings, I use Great Tables methods through .style, as in the table of beta portfolio alphas and factor loadings. See the Great Tables documentation.
1.4.4plotnine_polars
I use plotnine_polars for all figures in the book. The figures build on the grammar of graphics popularized in R by Hadley Wickham’s ggplot2. Hassan Kibirige and the other contributors have done an excellent job bringing that approach to Python with plotnine.
I wrote plotnine_polars to give plotnine a more fluent interface for use with Polars. It adds .ggplot() to Polars DataFrames so I can build a figure by chaining methods for aesthetics, layers, scales, and labels. The figures on the composition of the CRSP sample show how this works with time series grouped by exchange or industry. I first explored this style in my note Making plotnine more ‘Pythonic’. See the plotnine_polars documentation.
I use StatsPAI (statspai) to estimate regressions and calculate standard errors. For example, statspai.fama_macbeth() fits a cross-sectional regression in each period, averages the coefficients over time, and can apply a Newey–West adjustment to the standard errors of those averages. The Fama–MacBeth chapter shows this for annual data. See the StatsPAI project page.
Bernard, Victor L., and Jacob K. Thomas. 1989. “Post-Earnings-Announcement Drift: Delayed Price Response or Risk Premium?”Journal of Accounting Research 27: 1–36. https://doi.org/10.2307/2491062.
Gow, Ian D., and Tongqing Ding. 2024. Empirical Research in Accounting: Tools and Methods. Chapman; Hall/CRC. https://doi.org/10.1201/9781003456230.
Gow, Ian D., Gaizka Ormazabal, and Daniel J. Taylor. 2010. “Correcting for Cross-Sectional and Time-Series Dependence in Accounting Research.”The Accounting Review 85 (2): 483–512. https://doi.org/10.2308/accr.2010.85.2.483.
Newey, Whitney K., and Kenneth D. West. 1987. “A Simple, Positive Semi-Definite, Heteroskedasticity and Autocorrelation Consistent Covariance Matrix.”Econometrica 55 (3): 703–8. https://doi.org/10.2307/1913610.
Scheuch, Christoph, Stefan Voigt, Patrick Weiss, and Christoph Frey. 2024. Tidy Finance with Python. 1st ed. Chapman; Hall/CRC. https://doi.org/10.1201/9781032684307.
Sloan, Richard G. 1996. “Do Stock Prices Fully Reflect Information in Accruals and Cash Flows about Future Earnings?”The Accounting Review 71 (3): 289–315. https://www.jstor.org/stable/248290.
In addition, Gow and Ding (2024) rely on features of the R packages they use have no exact equivalents in Python.↩︎
My local Parquet extract of the CIZ table crsp.dsf_v2 is 4.63 GB, about 2.1 times the size of the 2.21 GB extract of the SIZ table crsp.dsf. The CIZ extract has 50 columns and the SIZ extract has 20.↩︎
Of course, this is not necessary more “correct”, as dividends can only be reinvested once they are received, which would be long after the ex-dividend date. To be sure, one could pledge one’s claim to dividends to raise cash for reinvestment on the ex-dividend date, but there would be transaction costs and interest associated with this approach that the CRSP calculation ignores. Any calculation of returns that assumes that you can buy at the month-end price in one month and sell at the month-end price in another will always be an approximation of the returns that a hypothetical investor could actually earn.↩︎
The chapter’s worked example uses crsp.ccmxpf_lnkhist. This comparison of the CRSP–Compustat link tables shows how to reconstruct crsp.ccmxpf_lnkused from crsp.ccmxpf_lnkhist apart from the ulinkid field.↩︎
Over 1988–2012, compounding the April 2026 daily market and risk-free series separately gives a mean absolute difference of 0.015 percentage points from WRDS monthly mktrf. Using the September 2026 French files, compounding the underlying portfolios reduces the gap from 0.107 to 0.022 percentage points for smb, from 0.119 to 0.026 for hml, and from 0.712 to 0.611 for momentum.↩︎