from datetime import date
import polars as pl
from plotnine_polars import aes, guide_legend
from eap_pl import get_ff_factors, load_parquet, plot_cumulative_returns7 The CRSP Sample and Market Factor
This chapter is an early draft and I have not yet carefully reviewed it. Also the APIs used in the examples may change as I continue working on the book.
This chapter reconstructs the figures and tables in Chapter 7 of Bali et al. (2016). I use a later snapshot of legacy CRSP (SIZ), the same data format used by the authors. See Table 1.1 for source update dates.
7.1 The US Stock Market
7.1.1 The CRSP US-Based Common Stock Sample
For market capitalization, use the absolute alternate price times shares outstanding. Dividing by 1,000 gives millions of dollars because CRSP reports shares in thousands.
first = pl.date(1925, 12, 1)
last = pl.date(2012, 12, 1)
msf = (
load_parquet("msf", "crsp")
.with_columns(month=pl.col("date").dt.month_start())
.filter(pl.col("month").is_between(first, last))
.select(
"permno", "month", "date", "altprc", "prc", "ret",
cap=pl.when((pl.col("altprc") != 0) & (pl.col("shrout") > 0))
.then((pl.col("altprc") * pl.col("shrout")).abs() / 1000),
)
)At each calendar month-end, keep securities with a historical share code of 10 or 11. The names records define the universe, so the left join retains eligible stocks across exchanges and when price is missing.
names = (
load_parquet("msenames", "crsp")
.filter(
pl.col("shrcd").is_in([10, 11]),
pl.col("namedt") <= last.dt.month_end(),
pl.col("nameendt") >= first,
)
.with_columns(
month=pl.date_ranges(
pl.max_horizontal(pl.col("namedt").dt.month_start(), first),
pl.min_horizontal(pl.col("nameendt").dt.month_start(), last),
interval="1mo",
)
)
.explode("month")
.filter(pl.col("month").dt.month_end().is_between("namedt", "nameendt"))
.select("permno", "month", "exchcd", "siccd")
)
universe = names.join(msf, on=["permno", "month"], how="left", validate="1:1")I use the June 2014 Fama–French archive, with the same month-start dates as the stock data for the later return comparisons.
vintage = "201406"
factors = (
get_ff_factors("monthly", vintage=vintage).lazy()
.select(pl.col("date").alias("month"), "mktrf", "rf")
.filter(pl.col("month").is_between(first, last))
)For the market-value figures, I load the monthly CPI and take December 2012 as the base month.
cpi = (
pl.read_csv("data/cpi-aucns.csv", try_parse_dates=True)
.rename({"observation_date": "month", "CPIAUCNS": "cpi"})
)
if cpi.filter(pl.col("month").is_between(first, last))["month"].n_unique() != 1045:
raise ValueError("Refresh the CPI file for December 1925–December 2012; see README.")
cpi_2012 = cpi.filter(pl.col("month") == last)["cpi"].item()7.1.2 Composition of the CRSP Sample
Figures 7.1–7.4 of Bali et al. (2016) decompose the sample by exchange and industry from December 1925 to December 2012. Count every stock in the month-end universe, even if market capitalization is missing. For market value, sum only observed capitalization. Convert nominal millions to billions of December 2012 dollars using the ratio of December 2012 CPI to that month’s CPI.
Stock Exchange Composition of CRSP Sample
The book groups exchange codes 1 and 31 as NYSE, 2 and 32 as AMEX, and 3 and 33 as Nasdaq. All remaining codes go into Other.
exchange = (
pl.when(pl.col("exchcd").is_in([1, 31])).then(pl.lit("NYSE"))
.when(pl.col("exchcd").is_in([2, 32])).then(pl.lit("AMEX"))
.when(pl.col("exchcd").is_in([3, 33])).then(pl.lit("Nasdaq"))
.otherwise(pl.lit("Other"))
)
composition = (
universe
.filter(pl.col("month").is_between(pl.date(1925, 12, 1), pl.date(2012, 12, 1)))
.select("month", "cap", "siccd", exchange=exchange)
.join(cpi.lazy(), on="month", how="left", validate="m:1")
.with_columns(real_cap=pl.col("cap") * cpi_2012 / pl.col("cpi") / 1000)
.collect()
)
assert composition["cpi"].is_not_null().all()
assert composition["cpi"].gt(0).all()
assert composition["month"].n_unique() == 1045For each month and exchange, count stocks and sum their real market capitalization. The grid includes months in which an exchange has no stocks, so those groups get a zero.
def summarize_composition(sample, group, labels):
summary = sample.group_by("month", group).agg(
stocks=pl.len(),
value=pl.col("real_cap").sum(),
)
grid = sample.select("month").unique().join(
pl.DataFrame({group: labels}), how="cross"
)
return (
grid
.join(summary, on=["month", group], how="left", validate="1:1")
.with_columns(pl.col("stocks", "value").fill_null(0))
.sort("month")
)
exchange_labels = ["NYSE", "AMEX", "Nasdaq", "Other"]
by_exchange = summarize_composition(composition, "exchange", exchange_labels)
total = (
by_exchange
.group_by("month")
.agg(pl.col("stocks", "value").sum())
.with_columns(exchange=pl.lit("Total"))
.select(by_exchange.columns)
)
by_exchange = pl.concat([total, by_exchange])I use the same plotting function for the count and market-value series, with the total shown in black.
Code
def plot_composition(data, group, labels, measure, y_label):
colors = [
"#1f77b4", "#ff7f0e", "#2ca02c", "#d62728", "#9467bd", "#8c564b",
"#e377c2", "#7f7f7f", "#bcbd22", "#17becf", "#aec7e8", "#ffbb78",
]
palette = dict(zip(labels, colors))
if "Total" in palette:
palette["Total"] = "black"
return (
data
.ggplot(aes(x="month", y=measure, color=group))
.geom_line()
.scale_x_date(date_breaks="10 years", date_labels="%Y")
.scale_y_continuous(limits=(0, None), expand=(0, 0, 0.05, 0))
.scale_color_manual(values=palette, breaks=labels, guide=guide_legend(ncol=3))
.labs(x="Month", y=y_label, color="")
.theme_minimal()
.add_theme(figure_size=(9, 4.5), legend_position="bottom")
)
plot_composition(by_exchange, "exchange", ["Total", *exchange_labels],
"stocks", "Number of stocks")
Code
plot_composition(by_exchange, "exchange", ["Total", *exchange_labels],
"value", "Market value ($ billions, December 2012)")
AMEX enters the data in July 1962. Most Nasdaq coverage starts in December 1972. The value series jumps much less than the count series at those dates: market coverage can change substantially without much change in market value. Keep that distinction in mind when comparing equal- and value-weighted results across time.
The December 2012 stock count includes 86 stocks in the Other category, of which 85 have no usable capitalization.1
Industry Composition of CRSP Sample
I use the security’s current SIC code rather than a code carried back from a later date. OSHA’s SIC manual describes the divisions. The table uses the intervals in BEM Table 7.1, with shortened labels. Keep zero and null codes separate from nonmissing codes that do not fall in a listed interval.
Code
sic_divisions = pl.DataFrame({
"first_sic": [1, 1000, 1500, 2000, 4000, 5000, 5200, 6000, 7000, 9000],
"last_sic": [999, 1499, 1799, 3999, 4999, 5199, 5999, 6799, 8999, 9999],
"industry": ["Agriculture", "Mining", "Construction", "Manufacturing",
"Transport and utilities", "Wholesale", "Retail",
"Finance", "Services", "Public administration"],
})
with pl.Config(tbl_rows=12):
display(sic_divisions)| first_sic | last_sic | industry |
|---|---|---|
| i64 | i64 | str |
| 1 | 999 | "Agriculture" |
| 1000 | 1499 | "Mining" |
| 1500 | 1799 | "Construction" |
| 2000 | 3999 | "Manufacturing" |
| 4000 | 4999 | "Transport and utilities" |
| 5000 | 5199 | "Wholesale" |
| 5200 | 5999 | "Retail" |
| 6000 | 6799 | "Finance" |
| 7000 | 8999 | "Services" |
| 9000 | 9999 | "Public administration" |
industry = pl.coalesce([
pl.when(pl.col("siccd").is_between(lo, hi)).then(pl.lit(name))
for lo, hi, name in sic_divisions.iter_rows()
])
classified = composition.with_columns(
industry=pl.when(pl.col("siccd").fill_null(0) == 0).then(pl.lit("Missing"))
.otherwise(industry.fill_null("Unclassified"))
)
industry_labels = [*sic_divisions["industry"].to_list(), "Missing"]
if classified["industry"].eq("Unclassified").any():
industry_labels.append("Unclassified")
by_industry = summarize_composition(classified, "industry", industry_labels)Code
plot_composition(by_industry, "industry", industry_labels,
"stocks", "Number of stocks")
Code
plot_composition(by_industry, "industry", industry_labels,
"value", "Market value ($ billions, December 2012)")
7.2 Stock Returns and Excess Returns
Start with eligible common stocks at the end of month \(t\) and look up the return for the same security in month \(t+1\). Do not require it to remain in the common-stock universe in the holding month: that would screen out delistings.
Chapter 7 uses the legacy CRSP delisting return in place of the regular monthly return if the stock delists. If no delisting return is recorded, it imputes a loss of 30% for the codes listed below and a loss of 100% for other delistings. This is the book’s convention for legacy data, not a reason to adjust the reported returns from CRSP CIZ a second time.
first_return = pl.date(1926, 7, 1)
first_return_late = pl.date(1963, 7, 1)
hold_month = pl.col("month").dt.offset_by("1mo")
delist = (
load_parquet("msedelist", "crsp")
.with_columns(month=pl.col("dlstdt").dt.month_start())
.filter(pl.col("month").is_between(first_return, last))
.select("permno", "month", "dlret", "dlstcd")
)
poor_performance = (
pl.col("dlstcd").is_in([500, 520, 580, 584])
| pl.col("dlstcd").is_between(551, 574)
)
imputed_delist = pl.when(poor_performance).then(-0.30).otherwise(-1.00)I join the regular and delisting returns to the formation universe by holding month. Subtracting that month’s risk-free return gives the two excess-return series.
return_panel = (
universe
.with_columns(formation_month="month")
.with_columns(month=hold_month)
.filter(pl.col("month").is_between(first_return, last))
.drop("ret")
.join(
msf.select("permno", "month", ret_raw="ret"),
on=["permno", "month"], how="left", validate="1:1",
)
.join(delist, on=["permno", "month"], how="left", validate="1:1")
.join(factors.select("month", "rf"), on="month", how="left", validate="m:1")
.with_columns(
ret_adj=pl.when(pl.col("dlstcd").is_not_null())
.then(pl.coalesce("dlret", imputed_delist))
.otherwise(pl.col("ret_raw"))
)
.with_columns(
excess_raw=pl.col("ret_raw") - pl.col("rf"),
excess_adj=pl.col("ret_adj") - pl.col("rf"),
)
)I first calculate the statistics across stocks for each return month, then average those monthly statistics. In particular, the means give each month equal weight, irrespective of the number of stocks in that month. I use sample standard deviations, bias-adjusted skewness and excess kurtosis, and linearly interpolated quantiles.
def summarize_returns(start):
x = pl.col("return_pct")
return (
return_panel
.filter(pl.col("month") >= start)
.select("month", "excess_adj", "ret_adj", "excess_raw", "ret_raw")
.unpivot(index="month", variable_name="series", value_name="return_pct")
.with_columns(return_pct=100 * x)
.group_by("month", "series")
.agg(
n=x.count(),
mean=x.mean(),
sd=x.std(),
skew=x.skew(bias=False),
excess_kurtosis=x.kurtosis(fisher=True, bias=False),
min=x.min(),
p05=x.quantile(0.05, interpolation="linear"),
p25=x.quantile(0.25, interpolation="linear"),
median=x.median(),
p75=x.quantile(0.75, interpolation="linear"),
p95=x.quantile(0.95, interpolation="linear"),
max=x.max(),
)
.group_by("series")
.agg(pl.exclude("month", "series").mean())
.collect()
)I arrange the four return series as columns and calculate the summary for each of the two sample periods.
table_7_2 = summarize_returns(first_return)
table_7_3 = summarize_returns(first_return_late)July 1926–December 2012 (Table 7.2)
Code
def display_returns(table):
labels = {
"excess_adj": "Adjusted excess",
"ret_adj": "Adjusted total",
"excess_raw": "Unadjusted excess",
"ret_raw": "Unadjusted total",
}
return (
table
.with_columns(series=pl.col("series").replace_strict(labels))
.unpivot(index="series", variable_name="statistic", value_name="value")
.pivot(on="series", index="statistic", values="value")
.select("statistic", *labels.values())
.with_columns(pl.exclude("statistic").round(2))
)
with pl.Config(tbl_rows=12):
display(display_returns(table_7_2))| statistic | Adjusted excess | Adjusted total | Unadjusted excess | Unadjusted total |
|---|---|---|---|---|
| str | f64 | f64 | f64 | f64 |
| "n" | 3110.72 | 3110.72 | 3094.05 | 3094.05 |
| "mean" | 0.96 | 1.25 | 0.99 | 1.28 |
| "sd" | 13.44 | 13.44 | 13.27 | 13.27 |
| "skew" | 2.33 | 2.33 | 2.38 | 2.38 |
| "excess_kurtosis" | 43.85 | 43.85 | 39.42 | 39.42 |
| "min" | -65.13 | -64.84 | -54.42 | -54.13 |
| "p05" | -16.44 | -16.15 | -16.33 | -16.04 |
| "p25" | -5.76 | -5.47 | -5.75 | -5.46 |
| "median" | -0.08 | 0.21 | -0.08 | 0.21 |
| "p75" | 6.17 | 6.46 | 6.18 | 6.47 |
| "p95" | 21.13 | 21.42 | 21.13 | 21.42 |
| "max" | 191.1 | 191.39 | 186.78 | 187.07 |
7.2.1 CRSP Sample (1963–2012)
Code
with pl.Config(tbl_rows=12):
display(display_returns(table_7_3))| statistic | Adjusted excess | Adjusted total | Unadjusted excess | Unadjusted total |
|---|---|---|---|---|
| str | f64 | f64 | f64 | f64 |
| "n" | 4780.04 | 4780.04 | 4751.69 | 4751.69 |
| "mean" | 0.74 | 1.17 | 0.8 | 1.22 |
| "sd" | 15.71 | 15.71 | 15.5 | 15.5 |
| "skew" | 3.09 | 3.09 | 3.12 | 3.12 |
| "excess_kurtosis" | 66.33 | 66.33 | 59.81 | 59.81 |
| "min" | -82.41 | -81.99 | -67.87 | -67.45 |
| "p05" | -19.52 | -19.1 | -19.36 | -18.93 |
| "p25" | -6.7 | -6.27 | -6.69 | -6.26 |
| "median" | -0.36 | 0.06 | -0.36 | 0.06 |
| "p75" | 6.49 | 6.91 | 6.5 | 6.93 |
| "p95" | 23.77 | 24.2 | 23.79 | 24.21 |
| "max" | 273.12 | 273.54 | 266.66 | 267.08 |
The delisting adjustment raises the average monthly maximum excess return in both samples.2
7.3 The Market Factor
The Fama–French market factor (mkt) is the excess return on a broad value-weighted portfolio of US common stocks. CRSP’s value-weighted market index (vwretd) has a broader set of eligible securities. I put both measures on an excess-return basis by subtracting the risk-free rate (rf) from vwretd. mkt already has the risk-free rate subtracted.
market = (
factors
.rename({"mktrf": "mkt"})
.filter(pl.col("month").is_between(pl.date(1926, 7, 1), pl.date(2012, 12, 1)))
.join(
load_parquet("msi", "crsp")
.select(month=pl.col("date").dt.month_start(), vwretd=pl.col("vwretd")),
on="month", how="left", validate="1:1",
)
.with_columns(
vw_excess=pl.col("vwretd") - pl.col("rf"),
log_excess=pl.col("mkt").log1p(),
)
.sort("month")
.collect()
)The monthly correlation between mkt and the adjusted CRSP return (vw_excess) is 0.9995 in this data vintage. Following Bali et al. (2016, sec. 7.3), I summarize the monthly returns from July 1926 through December 2012. The annualized Sharpe ratio uses \(\sqrt{12}\) times the ratio of the monthly mean to the monthly standard deviation, as in the book.
Code
series_labels = {
"mkt": "`mkt`",
"vw_excess": "`vwretd` less `rf`",
"log_excess": "Log `mkt`",
}
returns = pl.col(*series_labels)
market_summary = (
market
.select(
pl.lit(list(series_labels.values())).alias("Series"),
pl.concat_list(returns.mean() * 100).alias("Monthly mean (%)"),
pl.concat_list(returns.std() * 100).alias("Monthly SD (%)"),
pl.concat_list(returns.mean() * 12**0.5 / returns.std())
.alias("Annualized Sharpe"),
)
.explode(pl.all())
.with_columns(pl.col(pl.Float64).round(3))
)
market_summary.with_columns(pl.col(pl.Float64).cast(pl.String)).eap.show_table()| Series | Monthly mean (%) | Monthly SD (%) | Annualized Sharpe |
|---|---|---|---|
mkt |
0.628 | 5.434 | 0.4 |
vwretd less rf |
0.626 | 5.46 | 0.397 |
Log mkt |
0.479 | 5.444 | 0.305 |
Cumulative market excess returns
For comparison with BEM Figure 7.5, I compound the monthly market factor, \(\prod_{s\leq t}(1+\mathrm{MKT}_s)-1\), and sum its log transformation, \(\sum_{s\leq t}\log(1+\mathrm{MKT}_s)\). Both are transformations of the same underlying series. The panels share a month-end date axis and use separate percentage scales.
Compounding the market factor is not the same as subtracting the compounded risk-free return from the compounded market return. Here I follow the book’s definition.
market_path = market.with_columns(
date=pl.col("month").dt.month_end(),
compounded=(1 + pl.col("mkt")).cum_prod() - 1,
cumulative_log=pl.col("log_excess").cum_sum(),
)Code
plot_cumulative_returns(market_path, y_label="Cumulative market excess return")
Drawdowns
The compounded line makes early losses look small compared with later ones. To measure a drawdown, divide the value at the trough by the value at the preceding peak, then subtract one. Use the peak and trough months described in BEM; the recovery month is the first later month back at or above the old peak. Month names here refer to end-of-month values, so an episode that begins in September uses the August close as its reference.
Code
episodes = [
("1929 crash", date(1929, 8, 1), date(1932, 6, 1)),
("1968–1974 decline", date(1968, 11, 1), date(1974, 9, 1)),
("Dot-com bust and financial crisis", date(2000, 3, 1), date(2009, 2, 1)),
("1987 crash", date(1987, 8, 1), date(1987, 11, 1)),
]
wealth = market_path.select("month", wealth=1 + pl.col("compounded"))
def measure_drawdown(episode, peak, trough):
peak_value = wealth.filter(pl.col("month") == peak)["wealth"].item()
trough_value = wealth.filter(pl.col("month") == trough)["wealth"].item()
recovery = wealth.filter(
(pl.col("month") > trough) & (pl.col("wealth") >= peak_value)
)["month"].first()
return {
"Episode": episode,
"Peak": peak.strftime("%Y-%m"),
"Trough": trough.strftime("%Y-%m"),
"Drawdown (%)": round(100 * (trough_value / peak_value - 1), 1),
"Recovery": recovery.strftime("%Y-%m") if recovery else "Not by 2012-12",
}
pl.DataFrame([measure_drawdown(*episode) for episode in episodes])| Episode | Peak | Trough | Drawdown (%) | Recovery |
|---|---|---|---|---|
| str | str | str | f64 | str |
| "1929 crash" | "1929-08" | "1932-06" | -84.7 | "1945-04" |
| "1968–1974 decline" | "1968-11" | "1974-09" | -55.7 | "1983-04" |
| "Dot-com bust and financial cri… | "2000-03" | "2009-02" | -54.4 | "Not by 2012-12" |
| "1987 crash" | "1987-08" | "1987-11" | -31.0 | "1991-05" |
The daily Fama–French file shows the individual crash-day returns in October 1929 and October 1987.3
Code
daily_market = get_ff_factors("daily", vintage=vintage)
(
daily_market
.filter(pl.col("date").is_in([date(1929, 10, 28), date(1929, 10, 29), date(1987, 10, 19)]))
.select("date", market_excess_pct=(100 * pl.col("mktrf")).round(2))
.sort("date")
)| date | market_excess_pct |
|---|---|
| date | f64 |
| 1929-10-28 | -11.25 |
| 1929-10-29 | -11.97 |
| 1987-10-19 | -17.44 |
7.4 The CAPM Risk Model
BEM §7.4 introduces the specification rather than reporting another empirical table. To adjust a portfolio for its market exposure, regress its excess return \(r_{p,t}\) on the market excess return:
\[ r_{p,t} = \alpha_p + \beta_p\mathrm{MKT}_t + \varepsilon_{p,t}. \]
The intercept \(\alpha_p\) is the average monthly abnormal return under this model; \(\beta_p\) is the sensitivity to the market. A portfolio long one group and short another is already a difference in returns, so subtracting the risk-free rate from both legs cancels out. Chapter 9 applies this logic and also considers the Fama–French three-factor model.
BEM §7.1.2 reports two stocks in the Other category at the end of 2012. The cause of the difference is unclear.↩︎
The adjusted maxima average 191.10% and 273.12% here, compared with 208.10% and 302.74% in BEM Tables 7.2 and 7.3. The unadjusted maxima are within 0.02 percentage points of BEM in both samples, suggesting the difference is concentrated in the delisting observations.↩︎
Compounding the October 28 and 29, 1929 returns gives a loss of 21.9%. BEM §7.3 reports a loss of more than 23% for those two days.↩︎