Chapter 16 — The assay protocol orchestrator¶
Part IV of the assayinganomalies tutorial. Prerequisite chapters: 1–15, especially 2 (entry-point map), 11 (
check_fill_anomalies/fill_var), and 12 (SignalInfo,get_anomaly_signals). Python modules covered:analytics/protocol.py,signal_tester.py.
What this chapter answers¶
- What
run_test_signaldoes, step by step, and whichmake_*builder fills eachResStructfield. - How
test_signaldiffers fromrun_test_signal(defaults, not algorithm). - Why
ProtocolResultkeeps camelCase accessors (signalInfo,testSignal,timePeriod,printResults) andto_res_struct_dict. - How the twelve results builders hang off this orchestrator — six called
directly, six nested inside
make_comb_strats. - Why the
1e-12tie-break jitter in the anomaly sorts is seeded, and what that means fortab:closeAnomSpan(see also Known limitations).
Where this sits in the pipeline¶
Chapters 3–11 build DuckDB. Chapters 12–15 are the analytics primitives the
protocol calls. This chapter is the driver that loads a candidate signal, loads
the Chen–Zimmerman zoo, runs the builders in a fixed order, packs a
ResStruct-like object, and (optionally) hands it to reporting (Ch 19).
The four user-facing entries all land on run_test_signal:
| Entry | Defaults |
|---|---|
aa.run_test_signal(...) |
no pickle, no printResults, no TeX |
aa.test_signal(...) |
pickle + printResults + TeX + figures |
aa run-protocol (Ch 1) |
same as test_signal |
SignalTester.run |
same as run_test_signal; injects db_path from AssayClient |
Each call tests one signal. run_test_signal loads the CZ zoo itself when
anoms= is omitted; pass anoms= (and labels=) to reuse a loaded zoo
across several signals.
flowchart TD
TS["test_signal / aa run-protocol / SignalTester.run"] --> RTS["run_test_signal"]
RTS --> FILL["check_fill_anomalies Ch 11"]
RTS --> S1["1 make_anom_strat_results Ch 17"]
RTS --> S2["2 make_basic_sorts_results Ch 17"]
RTS --> S3["3 make_anom_benchmark_results Ch 17"]
RTS --> S4["4 make_dendrogram_results Ch 18"]
RTS --> S5["5 make_close_anom_results Ch 18"]
RTS --> S6["6 make_comb_strats Ch 18"]
S6 --> C1["6a make_avg_rank"]
S6 --> C2["6b make_weighted_avg_rank"]
S6 --> C3["6c make_fmb_res"]
S6 --> C4["6d make_pls_res"]
S6 --> C5["6e make_ipca_res"]
S6 --> C6["6f make_lasso_res"]
S1 --> PACK["ProtocolResult / ResStruct"]
S2 --> PACK
S3 --> PACK
S4 --> PACK
S5 --> PACK
S6 --> PACK
PACK --> PRT["make_res_to_print Ch 19"]
PRT --> TEX["print_tex_file Ch 19"]
make_fmb_res is the combination-strategy Fama–MacBeth, not the per-anomaly
FMs stored in resFMBs by make_anom_benchmark_results.
The result object¶
ProtocolResult¶
Signature — a @dataclass. Fields the protocol fills:
| Field | Type | to_res_struct_dict key |
|---|---|---|
signal_info |
SignalInfo |
signalInfo |
signal_label |
str |
signalLabel |
test_signal |
pd.Series MultiIndex (date, permno) |
testSignal |
time_period |
tuple[int, int] YYYYMM |
timePeriod |
labels |
dict with "short" / "long" |
labels |
res_basic_sorts |
BasicSortsResults \| None |
resBasicSorts |
res_cond_me_sorts |
dict \| None |
resCondMeSorts (also on res_basic_sorts.conditional) |
res_anoms |
AnomStratResults \| None |
resAnoms |
res_correls |
pd.DataFrame \| None |
resCorrels |
res_cond_sort |
dict \| None |
resCondSort |
res_fmbs |
dict \| None |
resFMBs |
Z |
np.ndarray \| None |
Z |
dendrogram_labels |
list[str] \| None |
dendrogramLabels |
cutoff |
float \| None |
cutoff |
res_close_fmb |
list \| None |
resCloseFMB |
res_close_span |
list \| None |
resCloseSpan |
close_labels |
dict \| None |
closeLabels |
comb_strats |
CombStratsResults \| None |
combStrats |
print_results |
PrintResults \| None |
not a key; saved beside ResStruct in the pickle as printResults |
filled_anoms / keep_anoms / keep_roll_anoms |
fill outputs | not included |
stage_log / summary |
Python bookkeeping | stage_log / summary |
path / tex_path |
output paths | not included |
Returns — the object run_test_signal returns. Nested values are the
make_* result dataclasses (BasicSortsResults, …).
What it does — holds the assay. Snake_case is the Python API.
Four read-only @property aliases provide camelCase names:
# ---- aliases matching MATLAB field casing (read-only convenience) ----
@property
def signalInfo(self) -> SignalInfo:
return self.signal_info
@property
def testSignal(self) -> pd.Series:
return self.test_signal
@property
def timePeriod(self) -> tuple[int, int]:
return self.time_period
@property
def printResults(self) -> PrintResults | None:
return self.print_results
The camelCase names follow the original MATLAB toolkit, whose result struct
ResStruct used them; the properties let code written as res.signalInfo
keep working without storing every field twice.
to_res_struct_dict is the second half of that surface: a dict keyed like
ResStruct, which is what gets pickled under the "ResStruct" key.
def to_res_struct_dict(self) -> dict[str, Any]:
"""Flatten to a dict keyed like MATLAB ``ResStruct`` for pickling/inspection."""
return {
"signalInfo": self.signal_info.to_dict(),
"signalLabel": self.signal_label,
"testSignal": self.test_signal,
"timePeriod": np.asarray(self.time_period, dtype=int),
"labels": self.labels,
"resBasicSorts": self.res_basic_sorts,
"resCondMeSorts": self.res_cond_me_sorts,
"resAnoms": self.res_anoms,
"resCorrels": self.res_correls,
"resCondSort": self.res_cond_sort,
"resFMBs": self.res_fmbs,
"Z": self.Z,
"dendrogramLabels": self.dendrogram_labels,
"cutoff": self.cutoff,
"resCloseFMB": self.res_close_fmb,
"resCloseSpan": self.res_close_span,
"closeLabels": self.close_labels,
"combStrats": self.comb_strats,
"stage_log": list(self.stage_log),
"summary": dict(self.summary),
}
When save=True, the pickle payload is
{"ResStruct": result.to_res_struct_dict(), "ProtocolResult": result, "printResults": ...}.
printResults sits beside ResStruct in the pickle, not inside the dict.
ResStruct fields × builder × chapter¶
ResStruct key |
Filled by | Tutorial |
|---|---|---|
signalInfo |
get_signal_info (Ch 12), stored here |
12, 16 |
signalLabel |
SignalAcronym |
16 |
testSignal |
_resolve_test_signal |
12, 16 |
timePeriod |
_infer_time_period or time_period= |
16 |
labels |
_load_cz_zoo then _filter_labels |
5, 16 |
resAnoms |
make_anom_strat_results |
17 |
resBasicSorts |
make_basic_sorts_results |
17 |
resCondMeSorts |
same (.conditional) |
17 |
resCorrels |
make_anom_benchmark_results |
17 |
resCondSort |
same | 17 |
resFMBs |
same (per-anomaly FM of 100*ret; not make_fmb_res) |
17 |
Z |
make_dendrogram_results |
18 |
dendrogramLabels |
same | 18 |
cutoff |
same | 18 |
resCloseFMB |
make_close_anom_results |
18 |
resCloseSpan |
same | 18 |
closeLabels |
same | 18 |
combStrats |
make_comb_strats → avg rank, weighted avg rank, make_fmb_res, PLS, IPCA, LASSO |
18 |
(sibling) printResults |
make_res_to_print |
19 |
Support helpers¶
_log_stage(stage_log, msg, *, verbose)¶
Signature — stage_log: list[str] is mutated in place. verbose gates
stdout / LOGGER.info.
Returns — None. Appends [{YYYY-mm-dd HH:MM:SS}] {msg}.
What it does — keeps every stage line on the result object, so a 5-hour
run is inspectable after the fact (result.stage_log). When verbose=True it
also prints msg without the timestamp prefix and logs it via
LOGGER.info. No log file is written, and warnings are not globally
disabled.
def _log_stage(stage_log: list[str], msg: str, *, verbose: bool) -> None:
stamp = datetime.now().strftime("%Y-%m-%d %H:%M:%S")
line = f"[{stamp}] {msg}"
stage_log.append(line)
if verbose:
# Match MATLAB fprintf to stdout as well as logging
print(msg, flush=True)
LOGGER.info("%s", msg)
_coerce_series(obj, name)¶
Signature — obj is a Series or DataFrame; name is the column to
pick ("ret", "me", "nyse_flag", "tcost").
Returns — pd.Series. Renames an unnamed Series; if given a DataFrame,
takes name or the sole column.
What it does — aa.load(..., panel=True) returns a DataFrame. The
orchestrator wants four Series. A one-column frame is accepted; a wide frame
without name raises ValueError.
_resolve_test_signal(signal, signal_info, *, panel_index, signal_column)¶
Signature
signal—Series,DataFrame, CSVPath/str, orNone(thensignal_info.fileLink).signal_info—SignalInfo(Ch 12).panel_index— optional library MultiIndex to reindex onto (passed asmcap.indexfrom the caller).signal_column— optional column name whensignalis a DataFrame or CSV.
Returns — float Series, MultiIndex named (date, permno).
What it does — three input shapes:
- Series — must already be MultiIndex; names forced to
date/permno. - DataFrame — column =
signal_column, elseSignalAcronym, else the sole column. - Path or empty —
get_anomaly_signals(Ch 12). The CSV must havepermnoanddatescolumns; dates become month-end timestamps. If the path is missing, triesAssayingAnomalies-MATLAB/{filename}relative to the working directory (where the bundledmpe.csvusually sits). Prefers the acronym column when it is in the CSV header.
# path or null → fileLink
path: Path | None = None
if isinstance(signal, (str, Path)):
path = Path(signal)
elif signal_info.fileLink:
path = Path(signal_info.fileLink)
if path is None:
raise ValueError("no test signal provided and signalInfo.fileLink is empty")
if not path.is_file():
# try relative to cwd; common MATLAB layout
alt = Path("AssayingAnomalies-MATLAB") / path.name
if alt.is_file():
path = alt
else:
raise FileNotFoundError(
f"signal CSV not found: {path} (also tried {alt})"
)
The caller then reindexes onto mcap and masks stock-months with missing
me.
_infer_time_period(test_signal)¶
Signature — one MultiIndex Series.
Returns — (start_yyyymm, end_yyyymm) as int.
What it does — the first date on which the signal has at least one finite
observation, and the last date of the panel (the signal is on the panel's index
when this is called), converted with month_end_to_yyyymm (Ch 12). Raises
ValueError if no observation is finite.
The window does not end with the signal's last value: the positions formed in that month still earn returns (for a year, if the signal has values each June), and the parts of the report that are cut to the window would lose them. A signal that stops early has no returns after one trading interval past its last trade (Ch 13, "When a sort trades"), and the report's captions state the months its numbers use.
def _infer_time_period(test_signal: pd.Series) -> tuple[int, int]:
arr = pd.to_numeric(test_signal, errors="coerce").to_numpy(dtype=float)
finite = test_signal[np.isfinite(arr)]
if finite.empty:
raise ValueError("test signal has no finite observations")
first = finite.index.get_level_values(0).min()
last = test_signal.index.get_level_values(0).max()
return month_end_to_yyyymm(first), month_end_to_yyyymm(last)
For MPE the window starts in 197501 and ends in the panel's last month.
Override with time_period=(start, end) (YYYYMM ints or timestamps).
_load_library_stock_panel(db_path) and _load_library_panel(db_path)¶
Signature — db_path optional; None → load_config().database_path.
Returns — _load_library_stock_panel: (ret, me, nyse_flag, tcost);
nyse / tcost may be None if the DB is incomplete. _load_library_panel
(a diagnostic helper; the orchestrator does not call it) adds
(factors, factor_tcosts) from _resolve_factor_bundle.
What it does — loads the stock panel once; the orchestrator then passes these objects to every builder.
- Probe DuckDB
information_schemaforccm_panel.tcost(ortcost_gibbs, unused except as a presence check). Includetcostin theaa.loadfield list only if the column exists, so incomplete DBs still load. load(["ret","me","nyse_flag", maybe "tcost"], panel=True), coerce Series.
An exception in the tcost probe is logged and swallowed: tcost stays None
and later stages run without costs. Callers can skip DuckDB entirely by
passing returns= / mcap= / ….
_resolve_factor_bundle(factors, factor_tcosts, db_path, convention="dollar")¶
Returns — FactorBundle(factors, factor_tcosts, source), resolved once
per run and handed to every stage that uses factors.
What it does
- Explicit
factors=win and open no database;factor_tcosts=is then taken as given (source="explicit"). Nothing is checked. - Otherwise factors come from one database (
db_path, else the configured one) throughload_factors. - If
factor_tcostswas not passed, the factor costs come from the same database'sts_data, the set stored for the run'sconvention(ff_tc_columns, Ch 9b):mkt_tc,smb_tc…umd_tcfor"dollar";mkt_tc,smb_tc_capital…umd_tc_capitalfor"capital". They are returned under the plain namesmkt_tc…umd_tc. Under"capital"the costs of the factors held short (smb_tc_capital_short…,ff_tc_short_columns) come with them, assmb_tc_short…umd_tc_short; the generalized alpha charges them on a short position in a factor (Ch 15). An explicitfactor_tcosts=frame may carry such columns too. - Before reading them,
require_held_factor_costschecks the database (below). If the record lists factors whose capital was zero or negative at a trade, a warning names them.
A failure to read the cost columns is logged and the run goes on with zero
factor costs (Ch 15 documents the zero-fill). FactorCostsError is not
swallowed: run_test_signal re-raises it.
require_held_factor_costs(db_path, convention="dollar") and FactorCostsError¶
The stage compute-ff-tcosts prices the factors on held legs, stores the
costs under both conventions and writes the metadata key ff_tcosts
({"calculation": "held", "version": 2, "capital_restarts": {…},
"entry_cost": {…}}, Ch 9b). A database built before that
holds factor costs computed another way and has no record. A database whose
record has no "version": 2 is an earlier held-leg build: its plain columns
are the "capital" costs and the first purchase is inside the series. Pairing
either with a held-leg test signal would price the two sides of a generalized
alpha differently, so:
| Database | Result |
|---|---|
has the record, with "version": 2 |
passes; returns the recorded restart counts per factor ("capital"; empty for "dollar") |
ts_data has no factor-cost column at all |
passes; the run uses zero factor costs, with a warning |
has factor-cost columns and no record, or a record without "version": 2 |
raises FactorCostsError (exported as aa.FactorCostsError) |
The message names the rebuild: aa setup-database --start-from
compute-ff-tcosts, or --start-from transform-compustat when the database
also lacks the June-only annual-layout record (Ch 7),
because the stages after compute-ff-tcosts refuse such a panel. Passing
factors= and factor_tcosts= explicitly avoids the check.
The check runs for every run that reads factor costs from
a database, including a run whose stages use no factor. And a factor's
restarts appear in the build log, in the metadata record and in a logger
warning of the protocol run; they are not written to the run's stage log or
manifest (the restarts of the test signal and of the zoo strategies are, see
run_test_signal).
_load_cz_zoo(db_path, *, max_anoms, dates)¶
Signature — dates is forwarded to load_cz_anomalies but the orchestrator
passes dates=None (full table). max_anoms is a development cap (for
smoke runs): the first N columns after the sort described below.
Returns — (cz_df, labels) where labels = {"short": [...], "long": [...]}.
What it does — load cz_anomalies, drop all-null columns, map DuckDB’s
lowercased names back to SignalDoc acronym_cased, sort columns by
CamelCase code-point order, then attach LongDescription as labels.long.
# The DuckDB columns are lowercased; restore SignalDoc's acronym casing and
# order the zoo the way MATLAB does (`[labels, I] = sort(labels)` in
# getChenZimmermanAnomalies, i.e. a code-point sort of the CamelCase
# acronyms). Every downstream leaf that is indexed by anomaly position --
# resCorrels, the dendrogram linkage, Fig_Ibbots columns -- inherits this
# order, so it has to match the reference run.
cz = cz.rename(columns={c: acr_to_cased.get(str(c).lower(), str(c)) for c in cz.columns})
cz = cz[sorted(str(c) for c in cz.columns)]
This order matters. Position in resCorrels / dendrogram Z / Ibbotson
columns is “the i-th kept anomaly,” not an acronym lookup. (The tie-break
draws do not depend on it: each anomaly's stream is keyed by its name.)
The code-point sort of the CamelCase acronyms follows the original MATLAB
toolkit; because DuckDB lowercases column names, the casing must be restored
before sorting. The March-2022 cz_signal_info path is Ch 5. An empty
cz_anomalies table raises RuntimeError (pass anoms= for smoke runs); a
missing one (the build's C-Z stage did not complete) raises
MissingCZAnomaliesError, which names
aa setup-database --start-from fetch-cz-anomalies (Ch 12).
_filter_labels(labels, kept_names)¶
Signature — labels is the {"short","long"} dict; kept_names is the
post-coverage acronym list in keep order.
Returns — a new {"short","long"} dict aligned to kept_names. Unknown
names are echoed into both lists.
What it does — looks up each kept name in short. Coverage-screen order
is the original zoo order with drops removed, so the positional identity of
the 157 kept columns is preserved. Wrong alignment here would scramble every
positionally indexed output.
The orchestrator¶
Held legs and convention¶
Every long/short strategy the protocol costs (the test signal's sorts, the zoo strategies, the decile sorts on the combination signals) is a pair of held legs: bought in a month in which the signal has values, left alone until the next such month, and charged for the trades that move the legs from what they hold to the new targets (Ch 13). The first purchase is not charged: its cost is reported as one number per strategy, the entry cost. The data decide when a strategy trades (Ch 13): a signal with values each June trades each June, a signal with values every month trades every month. There is no option that turns this off.
convention is the size of the two legs after a trade:
"dollar"(default): each leg goes back to $1;"capital": both legs are set to the strategy's capital, 1 plus the long leg's gain minus the short leg's since the last trade.
Gross returns are the same under both; trading costs and turnover differ.
Under "dollar" a strategy costs the same whichever leg is long. Under
"capital" it does not, and the run passes the generalized alpha the cost of
each strategy and each factor held short
(Ch 15); under
"dollar" it passes nothing.
The factor costs follow the same choice (_resolve_factor_bundle). On the
command line it is aa run-protocol --convention capital|dollar. The earlier
names "held" and "rebalanced" are not accepted.
Where a run records it:
| Place | Content |
|---|---|
| stage log | timePeriod = […]; n_jobs=…; convention=dollar |
result.summary["convention"] |
the string |
run manifest, scientific.settings.convention |
the string; it enters the scientific_id, so runs under the two conventions have different ids |
printResults.metadata["convention"] |
the string (the report text reads it from here; it is not in printResults.Text) |
Capital restarts. Under "capital", a strategy whose capital is zero or
negative at a trade starts again with $1 in each leg at that trade. After the
zoo-strategy stage (label anomaly strategy) and after the basic sorts
(label <signal> sort) the stage log gets one line per
such strategy (WARNING: anomaly strategy <name>: capital zero or negative at
<k> trade(s); the strategy restarted there with $1 in each leg.) and one
total (Capital restarts (anomaly strategy): n strategies, k trade(s).).
result.summary["capital_restarts"] maps each strategy to its count, and the
manifest keeps the summary under execution.summary. Under "dollar" there is no
capital and no restart.
Entry costs. result.summary["entry_cost"] maps each of the test signal's
sorts to the cost of its first purchase (a decimal), taken from
res_basic_sorts.metadata["entry_cost"]; the zoo strategies have theirs in
res_anoms.metadata["entry_cost"]. Net returns do not charge it.
run_test_signal(signal=None, metadata=None, **kwargs)¶
Signature
| Parameter | Shape / dtype / default |
|---|---|
signal |
Series / DataFrame / path / None (then signalInfo.fileLink) |
metadata |
SignalInfo, mapping, or {"info": ...} |
returns, mcap, nyse_flag, tcosts |
MultiIndex Series |
factors, factor_tcosts |
date-indexed DataFrames |
anoms, labels |
DataFrame or dict[str, Series]; {"short","long"} |
db_path |
DuckDB path |
max_anoms |
int or None (development cap) |
time_period |
(YYYYMM, YYYYMM) or timestamps; inferred if omitted |
compute_gen_alpha |
bool, default True |
factor_models |
tuple, default FACTOR_MODELS (1,3,4,5,6) |
n_close |
int or None → min(6, n) |
mcap_thresh |
float, default 0.40 |
n_roll |
int, default 120 |
out_dir, save |
path; save default False |
verbose |
bool, default True |
signal_column |
str; CSV column, default = acronym |
make_print_results |
bool, default False |
print_tex / emit_tex |
bool, default False; implies make_print_results |
emit_figures |
bool, default True when printing TeX |
tex_dir |
path, default {out_dir}/tex or Scratch/Assay/tex |
compute_alpha_prctl, compute_comb_sorts |
printResults options |
tcosts_type |
str stored in printResults.Text |
convention |
"dollar" (default) or "capital": the size of the two legs of a long/short strategy after a trade; any other value raises ValueError |
stages |
iterable subset of fill, anom_strats, basic_sorts, benchmarks, dendrogram, close, comb; default all |
Legacy kwarg signal_df= is accepted if signal is None. Unknown kwargs
are debug-logged, not errors.
Returns — ProtocolResult. If save=True, also
{out_dir}/{SignalAcronym}_Results.pkl. If print_tex=True, tex_path is
the .tex file.
What it does — in execution order:
1. Normalize kwargs and start the log.
_log_stage(
stage_log,
f"Starting runTestSignal for {signal_info.SignalAcronym or 'signal'} "
f"at {datetime.now():%Y-%m-%d %H:%M:%S}.",
verbose=verbose,
)
2. Library panel and factor bundle. If returns or mcap is missing,
_load_library_stock_panel. The factors and factor costs are resolved once by
_resolve_factor_bundle(factors, factor_tcosts, db_path, convention). Then coerce Series. Passing both returns and
mcap skips DuckDB, which is why synthetic tests do not need a warehouse.
3. Test signal + me mask + timePeriod.
test_signal = _resolve_test_signal(
signal,
signal_info,
panel_index=mcap.index if isinstance(mcap.index, pd.MultiIndex) else None,
signal_column=signal_column,
)
# Align to me panel and mask stock-months without market cap (runTestSignal.m)
test_signal = test_signal.reindex(mcap.index)
test_signal = test_signal.where(mcap.notna())
Series.where(mcap.notna()) sets the signal to NaN for stock-months with
missing me, so they never enter a sort. The sample window is then
_infer_time_period unless time_period= is given.
4. CZ zoo. Loaded with _load_cz_zoo if anoms is None. A DataFrame is
turned into dict[str, Series] for fill. max_anoms slices columns and
labels lists.
5. Construct the result shell with signal_info, test_signal,
time_period, labels. Remaining fields start None.
6. Stage fill — check_fill_anomalies. Python calls
check_fill_anomalies (Ch 11; default mcap_thresh=0.40, n_roll=120),
keeps only the anomalies that pass the coverage screen (signals, filled
signals, rolling-keep flags), then _filter_labels. On MPE 197501–202112
this keeps 157 / 212.
Smoke fallback: if the coverage screen keeps zero anomalies
(placeholder CZ / tiny panel), the orchestrator logs a WARNING, fill_vars
the raw signals, and continues, so a CI smoke can still exercise the make_*
stages. On a full zoo it never triggers.
If "fill" is omitted from stages, every anomaly is still fill_var’d
(needed by combination strategies) but the 40% screen is skipped.
7. Stage anom_strats — make_anom_strat_results. VW NYSE-quintile
extreme-leg sorts of every kept anomaly, with the tie-breaking jitter
discussed below. Output → result.res_anoms.
8. Stage basic_sorts — make_basic_sorts_results. Five sort variants ×
five factor models, plus conditional-on-size sorts, plus gen-α when
compute_gen_alpha=True. Output → res_basic_sorts and res_cond_me_sorts
(res_basic.conditional).
9. Stage benchmarks — make_anom_benchmark_results. Panel
correlations, 5×5 conditional sorts, per-anomaly Fama–MacBeth. Unpacked onto
res_correls / res_cond_sort / res_fmbs.
10. Stage dendrogram — make_dendrogram_results. Requires res_anoms
and res_basic. Wrapped in try/except: failure is logged, Z stays
None, and the rest of the run continues.
11. Stage close — make_close_anom_results. Requires strat + basic +
benchmark results and len(anoms_dict) > 0. n_close defaults to
min(6, n). Same try/except pattern.
12. Stage comb — fill_var + make_comb_strats. Python
fill_var(test_signal, mcap) then make_comb_strats(...). Inside
make_comb_strats (Ch 18) the six helpers run in COMB_STRAT_LABELS order:
make_avg_rank, make_weighted_avg_rank, make_fmb_res, make_pls_res,
make_ipca_res, make_lasso_res. Each helper is itself try/except’d to an
N/A NaN panel, independently of the orchestrator’s outer guard.
13. Summary. Headline Sharpe / xret from the ("vw_nyse_5", first
factor model) cell when present, stored on result.summary.
14. make_res_to_print. Only if make_print_results and basic sorts
exist. Failure is logged; has_print_results=False.
15. print_tex_file. Only if print_tex and print_results is packed.
print_tex_file (Ch 19) writes {acronym}.tex and optionally eight figure
PDFs.
16. Save. Pickles to {out_dir}/{SignalAcronym}_Results.pkl only when
save=True.
The protocol ends at the pickle, TeX and figure PDFs; zipping or sending the results is left to the user.
Default stages is all seven names. Dendrogram / close / comb also require
their upstream results to be non-None, so stages=("dendrogram",) alone is a
no-op, and stages=("fill", "basic_sorts") leaves res_anoms as None.
Because of the inner try/except guards, a late failure still returns a
partial ProtocolResult.
End-to-end numbers. A full MPE run on a fresh WRDS pull (August 2026) gives Sharpe 0.61 / 0.48, FF6+mom α 43 (21) bps, spanning 38 bps, 157 anomalies, close set Size / Amihud illiquidity / Past trading volume / Price / Intangible return using BM / Sales-to-price, 8 figure PDFs, and a 24-page PDF. Wall-clock for the protocol phase: 5 h 09 m.
tab:closeAnomSpan and the seeded jitter¶
make_anom_strat_results adds 1e-12 Gaussian noise to each anomaly signal
before sorting, so that tied signal values are split at random. Among tied
values, which name lands in the extreme NYSE quintile is decided by that
draw. Python seeds it (_ANOM_NOISE_SEED = 20231201 in results.py; details
in Ch 17), so a run is reproducible. This follows the original MATLAB
toolkit, which adds the same jitter without a seed.
The seed therefore matters for tie-heavy signals. Binary event signals and
tie-heavy close anomalies (Price, Illiquidity, DolVol) move with the seed,
while tie-free ones (Size, IntanBM, SP) do not; changing the seed moves
tab:closeAnomSpan and the close L/S series used in spanning (max cell
difference across seeds around 0.2–0.8). See
Known limitations.
test_signal(signal=None, metadata=None, *, out_dir=None, save=True, make_print_results=True, print_tex=True, emit_figures=True, **kwargs)¶
Signature — same signal / metadata as run_test_signal. Keyword-only
defaults flip the three artifact flags on. out_dir defaults to
Scratch/Assay in the project folder (config.scratch_dir()). Remaining kwargs go straight to run_test_signal.
Returns — ProtocolResult (and writes pickle + TeX when those flags stay
True).
What it does — get_signal_info(metadata) (the default MPE signal info
if metadata is None), then:
info = get_signal_info(metadata)
if out_dir is None:
out_dir = scratch_dir()
return run_test_signal(
signal,
info,
out_dir=out_dir,
save=save,
make_print_results=make_print_results,
print_tex=print_tex,
emit_figures=emit_figures,
**kwargs,
)
That is the whole difference: defaults, not a second algorithm. Pass a
signal path or SignalInfo directly; there is no interactive form.
CLI aa run-protocol calls test_signal, not run_test_signal
(Ch 1). If you call it from a pytest module,
import the module rather than the name: a bare from … import test_signal
is collected as a test.
SignalTester.run(signal, info, **kwargs)¶
Signature — constructed with AssayClient | None (from_config() if
omitted). run takes the same signal / info / kwargs as
run_test_signal.
Returns — ProtocolResult.
What it does — get_signal_info(info), then setdefault("db_path",
self.client.db_path) if the caller did not pass db_path, then
run_test_signal. It does not turn on save / make_print_results /
print_tex; those stay run_test_signal defaults (off). For a full paper
build use aa.test_signal or the CLI.
def run(
self,
signal: pd.Series | pd.DataFrame | str | Path | None = None,
info: SignalInfo | dict[str, Any] | None = None,
**kwargs: Any,
) -> ProtocolResult:
...
metadata = get_signal_info(info)
if "db_path" not in kwargs and self.client is not None:
kwargs.setdefault("db_path", self.client.db_path)
return run_test_signal(signal, metadata, **kwargs)
signal_tester.py re-exports SignalInfo, default_mpe_signal_info,
get_signal_info for a one-stop import; those names are owned by Ch 12.
AssayClient is covered in Ch 1.