Chapter 9b — FF factor trading costs¶
Continuation of Chapter 9 — Transaction costs. Same module:
transforms/tcosts.py.
What this chapter answers¶
- How stock-level half-spreads (
tcost) roll up into Fama–French factor trading costs for the generalized alphas and the robustness tables: the factors are priced on held legs, as a test signal is (Ch 13), with one addition, a monthly re-split inside each side. - What the stored columns hold:
mkt_tc,smb_tc…umd_tc(convention="dollar", the default),smb_tc_capital…umd_tc_capital(convention="capital") andsmb_tc_capital_short…umd_tc_capital_short("capital", the factor held short), and the record inmetadatathat says so. - Why sorting machinery lives inside a transforms module instead
of calling
analytics/sorts.py. - Which accounting inputs must be June-only annual matrices (
be,at,revt, …) and howcompustat.build_june_annual_panelfeeds them.
Where this sits in the pipeline¶
After compute-tcosts, stage compute-ff-tcosts loads ccm_panel (ret,
me, momentum, NYSE flag, tcost), rebuilds June annual accounting via
compustat.build_june_annual_panel, and calls make_ff_tcosts_table. Sixteen
columns merge into ts_data, and the stage writes the key ff_tcosts to the
metadata table. The calculation is the held-leg core of
analytics/held.py, the same one run_univariate_sort uses
(Ch 13, Ch 15).
calc_tcosts is not called by this stage.
flowchart LR
TC["ccm_panel.tcost"]
PANEL["ret, me, R12_2, nyse_flag"]
ANN["June BE/AT/REVT/..."]
MAT["ff_tcosts_from_matrices"]
LEGS["held_legs per 2x3 sort"]
COMP["held_composite_long_short<br/>per factor and convention"]
TS[("ts_data: mkt_tc, smb_tc..umd_tc,<br/>smb_tc_capital..umd_tc_capital,<br/>smb_tc_capital_short..umd_tc_capital_short")]
META[("metadata.ff_tcosts")]
TC --> MAT
PANEL --> MAT
ANN --> MAT
MAT --> LEGS --> COMP --> TS
COMP --> META
Unlike the rest of the package, this path works on dense (month × stock)
matrices: make_ff_tcosts_table pivots the long panel to wide arrays and
ff_tcosts_from_matrices runs the sorts and the held-leg calculation on them.
How a factor is priced¶
The four 2×3 sorts (size × book-to-market, operating profitability, investment
and prior return, NYSE breakpoints) are those of the MATLAB toolkit's
makeFFTcosts.m and are unchanged. What is priced on them is this:
- Each 2×3 portfolio is a held leg. It is bought, value-weighted, in a
month in which its sort exists and left alone until the next such month:
each June for SMB, HML, RMW and CMA (their accounting inputs are June-only),
every month for UMD. Between trades a position grows with the stock's total
return
ret. - A side is the equal-share average of two or three of them. SMB is long the three small portfolios and short the three big ones; HML, RMW, CMA and UMD are long the two high portfolios and short the two low ones.
- Monthly re-split. At the end of every month that is not a trade month, a side brings its portfolios back to equal shares of its own value, and pays that month's half-spreads on the dollars moved. The size of the side does not change.
- A trade is one netted step. The side moves from what it holds, as the re-splits have left it, to the new portfolios, netted stock by stock within the side.
- The two sides are resized at trades only, to the size the convention
names: each back to $1 under
"dollar"(the default), both to the factor's capitalK = 1 + (long side's value − 1) − (short side's value − 1)under"capital". The re-split cost is the same under both. - A cost is the half-spreads paid, over the side's value entering the month; the factor's cost is the sum over its two sides.
- The first purchase is not in the cost series. Its cost, the same under
both conventions, is the factor's entry cost: one number per factor, written
to the build log and to the
metadatarecord. Every later trade is booked in its own month. K ≤ 0at a trade ("capital"only): the factor starts again with $1 in each side, as a test signal does. The trades at which this happened are counted per factor.- A factor held short is the same two sides exchanged. Under
"dollar"it costs what the factor costs. Under"capital"it has its own capital,2 − K, and its own cost at a trade; the re-split cost is the same. That cost is stored as well (smb_tc_capital_short…), and the generalized alpha charges it when its net mean-variance efficient portfolio is short a factor (Ch 15).
Why a side is re-split every month¶
The factor returns in ts_data are the published ones. A side's published
return is the average of its 2×3 portfolio returns, taken every month. For
HML:
HML = ½ (small-high + big-high) − ½ (small-low + big-low)
Averaging the returns each month means the side starts every month with equal dollars in each of its portfolios. After a month in which the portfolios earned different returns, that takes a trade. A cost computed on a side that is left alone from June to June would not charge for it, so the return and the cost would describe different portfolios.
One side with two portfolios, A and B, $0.50 each after the June trade; in each of the next two months A earns +10% and B earns −10%:
| A | B | Side | |
|---|---|---|---|
| After June | 0.50 | 0.50 | 1.00 |
| End of month 1, left alone | 0.55 | 0.45 | 1.00 |
| Month 2 return, published (equal shares again) | ½(+10%) + ½(−10%) = 0.0% | ||
| Month 2 return, side left alone | (0.055 − 0.045) / 1.00 = +1.0% |
To earn the published month-2 return the side moves $0.05 from A to B at the end of month 1: $0.10 traded, which costs 0.10 × the half-spread. UMD needs no re-split: its sort exists every month, so every month is a trade.
A consequence. SMB, HML, RMW and CMA carry a charge every month. A test signal with values each June does not: its return is that of legs left alone between trades, so it owes no such charge. Only the factor return assumes the re-split.
What the stored columns hold¶
| Column | Convention | Content |
|---|---|---|
mkt_tc |
both | 0 by construction |
smb_tc, hml_tc, rmw_tc, cma_tc, umd_tc |
"dollar" |
cost of the month, both sides, decimal; each side set back to $1 at a trade |
smb_tc_capital … umd_tc_capital |
"capital" |
the same with both sides set to the factor's capital at a trade |
smb_tc_capital_short … umd_tc_capital_short |
"capital" |
cost of the month of the factor held short (its sides exchanged) |
- SMB, HML, RMW, CMA: a cost in every month from the July after the factor's first June on. Each later June holds the netted trade; every other month, that first July included, holds the re-split. CMA's first sort is one June later than the others (it needs assets twelve months earlier).
- UMD: a cost in every month from the second month of the sample. The second month holds that month's own trade.
- 0, never NaN, before the first cost and in the rows of
ts_dataoutside the panel's months. - With a 1% half-spread on every stock the entry cost is 2% (1% per side), under both conventions. It is in none of the columns.
The stage records the calculation in the database:
metadata.ff_tcosts = {"calculation": "held", "version": 2,
"capital_restarts": {factor: count},
"entry_cost": {factor: cost}}
capital_restarts lists only the factors that restarted (empty when none
did). entry_cost is the cost of each factor's first purchase, a decimal for
both sides together. A protocol run reads the columns of its own convention
and checks this record first; a database without it, or whose record has no
"version": 2, is refused with FactorCostsError (Ch 16).
A record without the version is that of an earlier held-leg build, in which
the plain columns were the "capital" costs and the first purchase was inside
the series; aa setup-database --start-from compute-ff-tcosts rebuilds the
factor costs.
What the stage logs¶
Per factor, one line from ff_tcosts_from_matrices and one from the stage,
then one line with the entry costs of all five factors:
FF factor tcosts hml: mean=… max=… (capital: mean=…; monthly re-splits: mean=…; entry cost, not in the series: …)
FF factor HML: held sides … , ts_data … % a month over n months, correlation …; cost … % a month, of which monthly re-splits …
FF factor entry costs (the first purchase, % of a side; not in the cost series): SMB …, HML …, RMW …, CMA …, UMD …
The costs in the first two lines are those of the default convention,
"dollar".
The second line puts the long-minus-short return of the toolkit's held sides
beside the published factor in ts_data (same months): the two means and the
correlation say how close the toolkit's 2×3 portfolios are to the published
ones, and "of which monthly re-splits" is the part of the cost that comes from
the re-splits. A factor whose capital was zero or negative at a trade gets a
warning (FF factor trading costs: the capital of HML was zero or negative at
… trade(s)).
What this is not¶
- Not MATLAB's factor costs.
makeFFTcosts.mprices each side withcalcTcostson weights drifted with the market-cap ratio, on a constant $1, with no charge for the monthly re-split. The sorts are MATLAB's; the costs are not, and they do not reproduceff_tc.mat. - Two approximations remain. Between trades the 2×3 portfolios drift with
ret, where the published portfolios' value weights follow market cap. And the sorts are the toolkit's reconstruction of the published ones, not the published portfolios themselves. - Sizes on CRSP are not stated here. The average cost of each factor, the share paid in re-splits and the correlation of the held sides with the published factors are printed by the stage (above) for the database it builds.
Duplicated sorting machinery¶
The factor construction needs bivariate sorts, univariate sorts and bin
assignment on dense (month × stock) arrays. Rather than import the
pandas sort API in analytics/sorts.py, this module embeds minimal numpy
versions:
| Helper | Role |
|---|---|
_matlab_prctile_rows |
Row-wise breakpoints |
_assign_to_ptf |
Map values to bin indices |
_make_univ_sort_ind |
Univariate sort indices |
_make_biv_sort_ind |
Unconditional 2×3 product indices |
Why this is the clearest refactoring target: Ch 13 documents
run_univariate_sort / _get_breakpoints / _assign_bins as the canonical
sort path for assays. These matrix helpers reproduce only the unconditional
bivariate case with NYSE breakpoint filtering — a strict subset. They predate
the stable sort API, and the matrix form follows the original MATLAB toolkit's
factor-cost routine step for step.
Numerical identity: not byte-identical to sorts.py (different API: wide
numpy vs long MultiIndex; _assign_to_ptf uses numpy compares where sorts uses
pandas masks). A refactor onto sorts.py must check that the stored FF
trading-cost series are unchanged rather than assume API equivalence.
_matlab_prctile_rows vs sorts._matlab_prctile: on finite data they
agree (Ch 9). This path retains ±Inf in OpProf = OP/BE rows (~370
firm-years with BE == 0); sorts drops non-finite values. See Ch 9 callout.
Matrix helpers¶
_row_lag(x, n)¶
Lags a dense grid by n rows, padding with NaN.
Signature — x: 2-D float array (n_months, n_stocks).
Returns — lagged array, first n rows NaN.
_nanmatsum(x, y)¶
Element-wise sum treating NaN as 0 unless both inputs are NaN.
Returns — element-wise sum with NaN propagation only when both inputs NaN. Used for the operating-profit stack.
_matlab_prctile_rows(x, pcts)¶
Row-wise percentiles. Documented in Ch 9. Used here
by _make_univ_sort_ind.
_assign_to_ptf(x, bpts)¶
Signature
x: signal matrix(months, stocks).bpts:(months, n_breaks)breakpoint array.
Returns — int16 index matrix; 0 = unassigned (NaN comparisons yield 0).
What it does
Bin 1: x < bpts[:,0]; bin j+2: x >= bpts[:,j] — a value equal to a
breakpoint goes to the upper bin.
_make_univ_sort_ind(var, ptf_num_thresh, breaks_filter=None)¶
Univariate sort indices from name (equal-count) breakpoints; no cap weighting.
Signature
ptf_num_thresh: intn→ breakpoints at100/n, 200/n, …percent; or explicit percentile list (e.g.(30, 70)tertiles).breaks_filter: NYSE flag matrix; zeros masked to NaN before computing the percentiles.
Returns — portfolio index matrix 1…K (0 unassigned).
_make_biv_sort_ind(var1, thresh1, var2, thresh2, breaks_filter=None)¶
Unconditional (independent) bivariate sort.
Returns — combined index (ind1-1)*n2 + ind2 where both legs positive.
_month_rows(dates)¶
Returns — the row of each date on a complete monthly calendar that starts
at dates[0]. The held-leg core needs every calendar month as a row; a month
absent from dates becomes an empty row. Raises ValueError unless the dates
are increasing, one per calendar month.
_wide(panel, col, dates, permnos)¶
Returns — (len(dates), len(permnos)) float matrix from long/MultiIndex panel.
FF factor cost computation¶
ff_tc_columns(convention="dollar")¶
Returns — a mapping from stored column to canonical name (mkt_tc …
umd_tc) for convention: "dollar" reads smb_tc … umd_tc, "capital"
reads smb_tc_capital … umd_tc_capital; mkt_tc serves both. Any other
value raises ValueError. The protocol uses it to read the set of its run
(Ch 16).
ff_tc_short_columns(convention="dollar")¶
Returns — a mapping from stored column to smb_tc_short … umd_tc_short,
the costs of the factors held short: "capital" reads smb_tc_capital_short
… umd_tc_capital_short; "dollar" gives an empty mapping, since there a
factor held short costs its ordinary cost. Any other value raises
ValueError.
ff_tcosts_from_matrices(dates, *, tcosts, me, ret, be, at, revt, cogs, xsga, xint, mom, nyse)¶
Signature
All arrays dense (n_months, n_stocks) aligned with dates. Accounting matrices
are June-only, so the sorts built from them exist in June only.
ret is the monthly total return (held positions grow with it), mom the
monthly momentum signal, nyse the NYSE flag for the breakpoint filter.
Returns — DataFrame indexed by dates with
mkt_tc(0),smb_tc…umd_tc("dollar"),smb_tc_capital…umd_tc_capital("capital") andsmb_tc_capital_short… ("capital", the factor held short);- the two sides' turnover under each convention (
smb_to_short,smb_to_long,smb_to_short_capital, …); smb_tc_resplit…, the part of each cost that comes from the monthly re-splits (the same under both conventions);smb_held…, the long-minus-short return of the held sides.
Costs and turnover are 0, never NaN, in a month without a trade or a re-split.
attrs["capital_restarts"] counts, per factor, the trades at which the capital
was zero or negative ("capital" only). attrs["entry_cost"] is, per factor,
the cost of its first purchase (decimal, both sides, the same under both
conventions), which is in none of the cost columns.
What it does
- Signals:
btm = be/lag(me,6);OP = REVT - COGS - XSGA - XINTvia_nanmatsum;OpProf = OP/BE;inv = -AT/lag(AT,12). - Four 2×3 unconditional bivariate sorts with NYSE breaks, tertiles on second
variable.
±Infvalues ofOpProfstay in the breakpoint computation. Portfolios 1 to 3 are small (low, middle, high), 4 to 6 big. Each sort has six portfolios. - Each sort goes through
held_legs(ret, me, tcosts, ind, "v", n_ptfs=6, monthly_holdings=True)once: six value-weighted held legs, with each portfolio's month-end holdings kept for the re-splits. SMB and HML share the size × book-to-market legs. - Each factor goes through
held_composite_long_short(legs, short, long, convention=…)once per convention: SMB short (4, 5, 6) and long (1, 2, 3); HML, RMW, CMA and UMD short (1, 4) and long (3, 6) of their sort. mkt_tc = 0. A factor whose sort is empty in every month (no accounting data, or no momentum) gets zero costs.
A 2×3 portfolio with no stocks at a trade is left out until the next trade, and its side is split equally among the others, so the side stays fully invested.
_ff_tcosts_or_zeros(panel, tcost_series, annual, dates)¶
Guard rail around ff_tcosts_from_matrices.
What it does
Validate MultiIndex panel, tcost presence, ret, me, nyse_flag, momentum
column (aliases R12_2, r12_2, R, mom), and annual accounting columns.
On any failure, log a warning and return zeros for all FF_TC_STORED_COLS
(a panel without ret is one such failure; it does not raise). Check the log
when net-of-cost factor alphas look too good: zero non-market costs mean an
input was missing. Otherwise it pivots the inputs with _wide, calls
ff_tcosts_from_matrices, keeps the stored columns and carries the restart
counts, the entry costs, the held returns and the re-split costs in attrs.
make_ff_tcosts_table(panel, tcost_series, annual=None)¶
The entry point of the build. Inputs as in make_ff_tcosts.
Returns — date-indexed frame with FF_TC_STORED_COLS: mkt_tc,
smb_tc … umd_tc, smb_tc_capital … umd_tc_capital and
smb_tc_capital_short … umd_tc_capital_short.
attrs["capital_restarts"] is the per-factor count and attrs["entry_cost"]
each factor's entry cost; attrs["held_returns"]
and attrs["resplit_costs"] (not stored; None when the costs are zeros for
want of inputs) feed the stage's log lines.
make_ff_tcosts(panel, tcost_series, annual=None, *, convention="dollar")¶
User-facing entry point (also aa.make_ff_tcosts, which delegates to it).
Signature
panel: MultiIndex(date, permno)withret,me,nyse_flag, momentum (R12_2); the accounting columns too unless they are passed viaannual.tcost_series: stock half-spreads, same index.annual: optional June-only(date, permno)frame withFF_TC_ANNUAL_COLS. When omitted the columns are read frompaneland masked to June.convention:"dollar"(default) or"capital", the size of a factor's two sides after a trade; the same choice as inrun_univariate_sort.
Returns — date-indexed mkt_tc … umd_tc under convention (plain names
for both), plus stacked ff3_tc … ff6_tc sums. With "capital", the frame
also has smb_tc_short … umd_tc_short, the cost of each factor held short
(for calc_gen_alpha(..., factor_tcosts_short=)), and
attrs["capital_restarts"] has the per-factor counts.
What it does
- Call
make_ff_tcosts_table; keep the columnsff_tc_columns(convention)names and rename them to the plain names; add the columnsff_tc_short_columns(convention)names. - Stack combined FF tcost columns for downstream convenience.
A panel without ret (or any other missing input) gives zero non-market costs
with a warning.
FF_TC_COLS, FF_TC_CAPITAL_COLS, FF_TC_CAPITAL_SHORT_COLS, FF_TC_STORED_COLS, FF_TC_ANNUAL_COLS, FF_TC_RECORD_KEY¶
Tuple constants: the six canonical series (FF_TC_COLS, the "dollar"
costs), the five _capital columns, the five _capital_short columns, the
sixteen stored columns (the three together), and the required June accounting
columns. FF_TC_RECORD_KEY ("ff_tcosts") is the metadata key of the
stage's record, FF_TC_HELD ("held") its calculation value and
FF_TC_RECORD_VERSION (2) its version.