Skip to content

Chapter 19 — Reporting: PrintResults, LaTeX, figures

Part IV of the assayinganomalies tutorial. Prerequisite chapters: 1–18, especially 13 (SortResult, _matlab_prctile, run_univariate_sort), 15 (calc_gen_alpha, factor_matrix_for_gen_alpha), 16 (run_test_signal → make_res_to_print → print_tex_file), 17 (resBasicSorts, resAnoms, resCorrels, jitter), and 18 (resCloseFMB / resCloseSpan, Z, combStrats). Python modules covered: analytics/res_to_print.py, reporting/latex.py, reporting/tables.py, reporting/figures.py, analytics/plots.py, reporting/__init__.py, plus packaged reporting/bib/newSignalTestBib.bib.

What this chapter answers

  • How make_res_to_print turns a ProtocolResult into the print object (PrintResults / PrintText, stored as ProtocolResult.print_results) that the report writers read, field by field.
  • How the report code is split across tables.py, latex.py and figures.py (figure PDFs in figures.py, \includegraphics in latex.py).
  • How mat_to_tex decides whether to emit a t-stat row, and how the five table writers wrap it.
  • What semantic_tex_diff / strip_date_today normalize and compare, for checking a report against a reference .tex.
  • How the eight emit_* figure functions plus emit_all_figures produce the {Signal}_figure*.pdf files, including _matlab_linkage_to_scipy and plot_name_histogram.
  • How tab:closeAnomSpan depends on the tie-break seed, and how that shows in the compiled PDF.

Where this sits in the pipeline

Chapters 16–18 produce a ProtocolResult (ResStruct). This chapter is the last protocol stage: pack a print object, write Scratch/Assay/tex/{Signal}.tex, emit eight figure PDFs, copy the bibliography, and (outside Python) compile the PDF report. aa.test_signal / aa run-protocol turn this path on; aa.run_test_signal leaves it off (Ch 16).

flowchart TD
  RTS["run_test_signal  Ch 16"]
  MRTP["make_res_to_print"]
  PR["PrintResults / PrintText"]
  PTF["print_tex_file"]
  FIGS["emit_all_figures  8 PDFs"]
  TEX["{Signal}.tex + newSignalTestBib.bib"]
  DIFF["semantic_tex_diff vs reference .tex"]
  RTS --> MRTP
  MRTP --> PR
  PR --> PTF
  PTF --> FIGS
  PTF --> TEX
  TEX --> DIFF

run_test_signal in protocol.py calls the two writers in order: make_res_to_print when make_print_results=True, then print_tex_file when print_tex=True.

How the report code is organized

print_tex_file opens {signal}.tex and calls one helper per block of the paper. Each figure has two halves: a PDF emitter in reporting/figures.py and a \includegraphics wrapper in reporting/latex.py. Table bodies live in reporting/tables.py.

Python function Role
latex.print_tex_file assembler
latex.print_document_header preamble
latex.print_title_page title + abstract numbers
latex.print_intro_section §1
latex.print_signal_description_section §2 prose
latex.print_return_prediction_section §3 prose
latex.print_other_anomalies_section §4 prose
latex.print_close_anoms_section §5 prose
latex.print_comb_strats_section §6 prose
tables.print_basic_sort_table tab:tsRegs
tables.print_robustness_to_sorting_table tab:robustnessToSorting
tables.print_sub_sample_table tab:subSample (Python-only)
tables.print_cond_size_sort_table tab:doubleSortSize
tables.print_close_anoms_fmb_table tab:closeAnomFMB
tables.print_close_anoms_span_table tab:closeAnomSpan
figures.emit_signal_description_figure + latex.print_signal_description_figure Fig 1
figures.emit_sharpe_dist_figure + latex.print_sharpe_dist_figure Fig 2
figures.emit_ibbots_figure + latex.print_ibbots_plots_figure Fig 3
figures.emit_alpha_prctl_figure + latex.print_alpha_prctl_figure Fig 4
figures.emit_correl_figure + latex.print_correl_figure Fig 5
figures.emit_dendrogram_figure + latex.print_dendrogram_figure Fig 6
figures.emit_cond_strats_figure + latex.print_cond_strats_figure Fig 7
figures.emit_comb_strats_figure + latex.print_comb_strats_figure Fig 8
latex.print_end_of_paper_text \bibliography + \end{document}
latex.print_bibliography_file copy newSignalTestBib.bib
tables.add_comma thousands separators
tables.mat_to_tex matrix → LaTeX table body
tables.num_to_words small integers → English words (0–100)

make_res_to_print (in analytics/res_to_print.py) is this chapter's other half: it builds the PrintResults object all of the above read.


analytics/res_to_print.py — the print object

PrintText

Signature — dataclass fields. The camelCase names follow the original MATLAB toolkit's printResults struct, so pickled reports keep the same keys.

  • timePeriod — ndarray shape (2,), YYYYMM ints.
  • nAnoms — str, count of zoo names that had finite xret (the length of the Sharpe-ratio histogram).
  • signalChar — str, uppercased acronym.
  • sharpeChar / netSharpeChar — str, '%1.2f' of the baseline VW-NYSE quintile L/S Sharpe (gross / net).
  • nCloseAnoms — int, size of the close-anomaly set.
  • closeAnoms — str, comma-separated long names.
  • closeAnomLabels — list[str], the long names as a list.
  • tcostsType — str; defaults to AssayConfig.tcosts_type.
  • valuePeriod — first and last month of timePeriod in which the signal has values (YYYYMM pair, or None).
  • sortPeriod — first and last month in which the baseline sort has a return. The sorts ignore timePeriod, so this can be wider than it.
  • returnPeriod — the months of sortPeriod that lie in timePeriod.

The three periods are what the captions and sentences print as the sample of the signal's own numbers; a pickle from before them prints timePeriod.

Returns — to_dict() emits the same keys for the pickle payload (printResults.Text).

What it does — holds the prose scalars every section writer interpolates. No computation; make_res_to_print fills it at the end.

PrintResults

Signature — one dict field per report block, plus Text and signalInfo:

Field Contents
Fig_Cov signal percentiles + coverage vs ME
Tab_BasicSort Table 1 panels A/B/C
Tab_RobustSort Table 2 gross / net
Tab_SubSample Table 3, full sample + subperiods (Python-only)
Tab_CondSizeSort Table 4 5×5 + n/ME
Fig_SharpeDist zoo Sharpe histograms + test-signal line
Fig_CondAnoms three t-stat histograms
Fig_Correls Spearman/Pearson name-histogram x
Fig_Ibbots L/S return matrices for $1 plots
Fig_AlphaPrctl α percentile curves + test-signal dots
Fig_Dendrogram Z, labels, cutoff
Tab_CloseFMB Table 5
Tab_CloseSpan Table 6 (×100 coefficients)
Fig_CombStrat decile-VW L/S with/without the test signal
Text PrintText
signalInfo copied SignalInfo dict

Each Tab_* entry uses an {a, tA, h} layout (coefficients, t-stats, row headers; Tab_SubSample adds cols, periods and n_sub); figure panels use {x, y, xlim} or {Hist, Line}.

Returns — to_dict() is what ProtocolResult pickles under printResults. Missing blocks are empty dicts / None.

What it does — container only. make_res_to_print fills every field. ProtocolResult.print_results holds the object (ProtocolResult.printResults is an alias).

yyyymm_to_pdate(yyyymm)

Signature — yyyymm: int | float → float. 192601 → 1926.0, 192602 → 1926 + 1/12.

Returns — scalar plot date: year + (month - 1) / 12.

What it does — splits YYYYMM with divmod(v, 100) and returns a decimal year used as Fig_Cov's x-axis.

This is not the encoding figures._month_pdate uses for the Ibbotson plots, which is year + month/12 (January = year + 1/12). Both encodings come from the original MATLAB toolkit, which used one for its library pdates vector and the other inside ibbots.

dates_to_pdates(dates)

Signature — sequence of Timestamp / YYYYMM ints / plot-fraction floats → ndarray[float].

Returns — length-n plot dates. Values > 1e5 are treated as YYYYMM; smaller floats are passed through (already plot dates).

What it does — loop over the index; Timestamp → year + (month-1)/12. A vectorized yyyymm_to_pdate that also accepts month-end timestamps.

invprctile(x, xq, *, plot_pos="Hazen")

Signature

  • x — 1-D sample; non-finite dropped.
  • xq — query values (scalar or array).
  • plot_pos — "Hazen" (p1=0.5, p2=0) or "Weibull" (0, 1); anything else falls back to Hazen.

Returns — non-exceedance probabilities in percent (0–100). Empty x → all-NaN. xq below / above the sample → 0 / 100.

What it does — sort finite x; keep the last occurrence of each distinct value (np.unique first index + counts − 1); plotting positions (i - p1) / (n + p2) on the full sample, then subset to unique values; np.interp onto xq.

def invprctile(x: np.ndarray, xq: float | np.ndarray, *, plot_pos: str = "Hazen") -> np.ndarray:
    """Port of MATLAB ``invprctile`` (Hazen default) for a 1-D sample.
    # ...
    x_sorted = np.sort(x)
    n = x_sorted.size
    if n == 1:
        return np.where(xq_arr < x_sorted[0], 0.0, 100.0).astype(float)
    _, first_idx, counts = np.unique(x_sorted, return_index=True, return_counts=True)
    ind = first_idx + counts - 1  # last indices of each unique value
    xx = x_sorted[ind]
    pp = (np.arange(1, n + 1) - p1) / (n + p2)
    pp = pp[ind]
    p = np.interp(xq_arr, xx, pp, left=0.0, right=1.0) * 100.0
    return p.astype(float)

Used only for Fig_AlphaPrctl dx: the test-signal α's rank in the zoo α distribution. Only 1-D samples and the Hazen / Weibull plotting positions are supported.

Extraction helpers

These are the adapters between ProtocolResult attributes and the inputs make_res_to_print needs. Full template for the ones that do real work; the rest are grouped at the end of this module.

_unpack_res_struct(src)

Signature — ProtocolResult or a Mapping → flat dict with camelCase keys (resBasicSorts, testSignal, closeLabels, …).

Returns — that dict. TypeError if neither a ProtocolResult nor a mapping.

What it does — prefers ProtocolResult attributes (res_basic_sorts, test_signal, …) and maps them to the camelCase keys the rest of make_res_to_print uses. resCondMeSorts falls back to res_basic_sorts.conditional when the protocol did not store a separate object.

def _unpack_res_struct(src: Any) -> dict[str, Any]:
    """Normalize ProtocolResult / dict to a flat access map."""
    if hasattr(src, "to_res_struct_dict") and hasattr(src, "res_basic_sorts"):
        return {
            "signalInfo": src.signal_info,
            "signalLabel": src.signal_label,
            "testSignal": src.test_signal,
            "timePeriod": src.time_period,
            # ...
            "resCondMeSorts": src.res_cond_me_sorts
            if src.res_cond_me_sorts is not None
            else (src.res_basic_sorts.conditional if src.res_basic_sorts else None),

_wide_panel(s)

Signature — MultiIndex (date, permno) Series → date × permno DataFrame (unstack(level=1)). Same long-to-wide move as Ch 3.

_signal_info_dict(info)

Signature — SignalInfo / mapping / to_dict() object → plain dict.

_anom_results_dict(res_anoms, labels_short)

Signature — AnomStratResults / dict[str, SortResult] / None plus the short-label list → dict[str, SortResult | None] in label order, then extras.

What it does — AnomStratResults.results is already a name→SortResult dict (Ch 17). This fixes the label order used for the stats matrix and the Ibbotson columns.

_anom_tcosts_ts(sr, index=None)

Signature — SortResult | None → L/S tcost series, reindexed if index is given.

What it does — prefer sr.tcosts_ts; else metadata['tcosts_ts'] (older packs); else long_short - long_short_net. Needed for Fig_AlphaPrctl net gen-α.

_ls_return_series(sr)

Signature — SortResult | None → L/S Series (long_short, else last column of pret).

_factor_loadings_b_t(sr)

Signature — SortResult → (b, t, labels) with factors on rows.

What it does — SortResult.factor_loadings is a DataFrame (portfolios × factors); this transposes it to factors × portfolios for Table 1 Panel B. Mapping / .b/.t/.label structs are also accepted.

_gen_alpha_intercept(basic, label, f)

Signature — BasicSortsResults, sort label, factor-model int → (alpha0, t0).

What it does — basic.gen_alpha[(label, f)]["alpha_res"] is the calc_gen_alpha OLS (Ch 15). Returns the intercept.

_net_sharpe(netpret)

Signature — Series / ndarray → float: sqrt(12) * mean / std. Drops non-finite; sample std (ddof=1); < 2 obs or sd <= 0 → NaN.

make_res_to_print(res_struct, *, ...)

Signature

  • res_struct — ProtocolResult or ResStruct-like mapping.
  • returns, mcap — MultiIndex panels. Required for Fig_CombStrat and full Fig_Cov Panel B.
  • factors, factor_tcosts — for Fig_AlphaPrctl net gen-α. Loaded from DuckDB if omitted and compute_alpha_prctl.
  • tcosts_type — stored in Text.tcostsType.
  • convention — "dollar" (default) or "capital"; passed to the decile sorts on the combination signals run here. The protocol passes the convention of its run and then stores it in printResults.metadata["convention"] (Ch 16); it is not in Text.
  • dates — library month-end index. Inferred from mcap / returns / test_signal if omitted.
  • compute_alpha_prctl / compute_comb_sorts — set False to skip the two slow loops.
  • verbose — timing messages.

Returns — PrintResults.

What it does — one block per field, in this order.

1. Unpack and window. _unpack_res_struct, require timePeriod and a MultiIndex testSignal, take BASIC_SORT_LABELS[0] (vw_nyse_5) as the headline sort. Build yyyymm / pdates on the library date index.

2. Fig_Cov. Per month, the 25th / 50th / 75th cross-sectional percentiles of the signal (via _matlab_prctile, row-wise) plus the nanmean. Panel B is name coverage (isfinite(signal)/isfinite(me)) and ME coverage (nansum(me | signal finite) / nansum(me)). xlim is pdates at the first and last month of timePeriod in which the signal has values (Text.valuePeriod), so the axis is not empty before a signal that starts after the sample does.

    # ---- Figure coverage (Fig_Cov) ----------------------------------------
    # MATLAB: [prctile(testSignal, [25 50 75], 2) mean(testSignal, 2, 'omitnan')]
    sig_mat = sig_wide.to_numpy(dtype=float)
    quartiles = np.array([_matlab_prctile(row, [25.0, 50.0, 75.0]) for row in sig_mat])
    y_a = np.column_stack([quartiles, np.nanmean(sig_mat, axis=1)])
    # ...
    if me_wide is not None:
        # cover_n = finite_sig / finite_me; cover_me = nansum(me|sig) / nansum(me)
        results.Fig_Cov["PanelB"]["y"] = np.column_stack([cover_n, cover_me])

3. Tab_BasicSort. Panel A stacks xret then alpha for factor models (1,3,4,5,6). Panel B is FF6 (models[4]) factor loadings, transposed, headers $\beta_{\text{MKT}}$ etc. Panel C is nanmean(ptf_num_stocks[:, :5]) and nanmean(ptf_market_cap)/1e3 (the mean uses the full ME matrix, not only the five portfolio columns).

4. Tab_RobustSort. Five rows (BASIC_SORT_LABELS) × (1 + n_models) columns. Panel A: last xret / last alpha. Panel B: netxret then gen-α intercepts via _gen_alpha_intercept (so Panel B is net $r^e$ plus generalized α, not gross α). Row headers are strings like "Quintile & NYSE & VW" — they already contain & so mat_to_tex can drop them into a 9-column tabular.

4a. Tab_SubSample (Python-only). _sub_sample_table takes the long-short series of the Table 1 strategy (basic.basic[("vw_nyse_5", models[0])], decimal returns), cuts it to time_period (the basic sorts ignore it) and to its first and last valid month, and splits it with analytics/subsamples.py: with N = n_months // 12 years, n_subsamples(N) is min(4, N // 10) when N >= 20 and 2 otherwise (20–29 years give two subsamples, 30–39 three, 40 or more four), and subsample_bounds cuts the months into that many contiguous blocks whose lengths differ by at most one, the longer ones first (numpy.array_split). Rows are the full sample, then each block labelled "YYYYMM--YYYYMM". Each row is estimated like Table 1 (_matlab_style_sort_outputs, classical OLS t-stats, factors resolved once per model): column 0 the average excess return, column j+1 the alpha on models[j], both in % per month. A cell that cannot be estimated stays NaN and is listed in metadata["sub_sample"]["issues"]. The full-sample row equals Table 1's long-short column when time_period covers the whole series.

5. Tab_CondSizeSort. For each ME quintile i=1..5: xret[:-1], a NaN spacer, xret[-1], then each model's last alpha. Panel B: mean n in columns 1–5 and mean ME/1e3 in columns 7–11 (column 6 stays NaN).

6. Anomaly stats matrix. One row per zoo name with finite xret, seven columns: gross Sharpe, net Sharpe, cond-sort txret[-1], spanning-α t-stat (nanols of test L/S on [1, anom L/S]), Spearman, Pearson, and the FMB t-stat on the test signal. Feeds the Sharpe / cond / correlation figures.

7. Fig_SharpeDist / Fig_CondAnoms / Fig_Correls. Histograms and the test-signal vertical line (xlim = [-2, 2]). Fig_Correls stores 100 * rho with Panel A = Spearman (column 5) and Panel B = Pearson (column 6); emit_correl_figure labels the axes the same way.

8. Fig_Ibbots. The window is the signal's return months: from its first return in timePeriod, but not before the sample's second month, to its last. (For a signal with returns throughout this is the month after timePeriod[0] through timePeriod[-1]; the +1 month is taken on a month-end Timestamp, so 197512 rolls over to 197601.) Every strategy starts at \$1 in the month before the window. An anomaly gets the signal's return in each month of the window in which it has none of its own, and only there:

    miss_g = ~np.isfinite(pret_g_anoms)
    miss_n = ~np.isfinite(pret_n_anoms)
    pret_g_anoms = np.where(miss_g, pret_g_test[:, None], pret_g_anoms)
    pret_n_anoms = np.where(miss_n, pret_n_test[:, None], pret_n_anoms)

So an anomaly that starts after the signal, ends before it or has a gap holds the signal in those months and its own returns in all others, and no anomaly is dropped. nSignalMonths counts those months per anomaly. The original MATLAB toolkit replaced the column up to its last missing month, which turned an anomaly that ends early into a copy of the signal.

9. Fig_AlphaPrctl. Per anomaly, slice to the finite (ret + tcost) span, then for each factor model: gross α via nanols on [1, factors], net α via calc_gen_alpha. The L/S returns are scaled ×100 first so the intercept is %/month, the same units as Table 1 alpha and dy; this is what puts invprctile(alpha_gross, test_g) on the same axis as Table 1. Net-α NaNs are set to zero. Percentiles 0:99 via _matlab_prctile. dx is invprctile of the test-signal α in that zoo distribution (only the first five models).

10. Fig_Dendrogram. Pass-through of Z, dendrogramLabels, cutoff from Ch 18.

11. Tab_CloseFMB / Tab_CloseSpan. Close-set FM and spanning packs from Ch 18. Tab_CloseFMB is (n_close+4) × (n_close+2): column 0 is the regression on the test signal alone (intercept + slope), columns 1..n_close the bivariate regressions (intercept + test signal + that anomaly), the last column the joint one; rows are intercept, signal, the n_close anomalies (coefficients on percent returns), a \# months row with each regression's metadata["n_months"] (the monthly cross-sections averaged), and a last row with 100 * mean_r2 (the mean monthly adjusted R̄², in percent); the last two rows have tA NaN. Results saved before the signal-only regression existed still load: column 0 stays blank, a warning is logged and metadata["close_fmb_layout"] = "legacy"; results saved before the month count existed leave the months row blank. Tab_CloseSpan is (n_close+9) × (n_close+1): each of the six individual columns stores intercept + that anomaly's loading + the six factor loadings, with the joint regression in the last column, then a \# months row (each regression's n_obs) and a last row with the adjusted R̄² of each spanning regression in percent (tA NaN in both). Span coefficients are stored ×100; t-stats and the months row are not. That is why table cells read 0.40 and the abstract does 100 * a[0, -1] → 40 bps. The ×100 applies to every coefficient row, so the printed anomaly and factor loadings in Table 6 are 100× the regression loading (a loading of 1.03 prints as 102.81); only the intercept row, which is the one the prose quotes, is a percent/month figure.

12. Fig_CombStrat. Drop N/A methods; for each remaining forecast run a 10-bin name-break VW sort of eret and of eret_enh (time_period is passed here — unlike the Chapter 17 headline sorts). Store L/S series as columns of yWithout / yWith; x is YYYYMM from the sort index.

13. Text. Sharpe strings, comma-joined close names, nAnoms from the histogram length (kept names, not the raw zoo size).


reporting/tables.py — table emitters

Every writer returns its LaTeX as a string and, if given an open file handle fid, also writes it there (_write_or_return).

num_to_words(num)

Signature — number → English cardinal. Covers 0–19, tens, "one hundred"; larger values str(n).

Returns — str ("six", "twenty-five").

What it does — assay prose only needs small counts (close-set size, method count). Not a general number-to-words converter: 157 would be emitted as "157", and nAnoms is interpolated as the raw string, not spelled out.

add_comma(num)

Signature — finite number → f"{int(round(num)):,}"; non-finite → "".

mat_to_tex(coeffs, sigstats=None, row_headers=None, decimals=2, brackets_type="[", col_format_spec=None, sig_digits=None)

Signature

  • coeffs — 2-D (or 1-D promoted) float matrix.
  • sigstats — same shape (t-stats), or omitted.
  • row_headers — optional per-row TeX (already may contain &).
  • decimals — default 2; Panel C / cond-size Panel B use 0.
  • brackets_type — "[" / "(" / "{".
  • col_format_spec — optional per-column % specs; wins over decimals and sig_digits.
  • sig_digits — optional: coefficient cells with that many significant digits (2: 0.0073 → 0.0073, 0.11 → 0.11, 1.23 → 1.2, 12.3 → 12); t-stat cells keep decimals. No report table uses it at present (the close-anomaly FMB table did until its regressions moved to percent returns).

Returns — LaTeX body: leading \n\n, one coeff row per matrix row, optional t-stat row, trailing blank lines. NaN → " & " (empty cell).

What it does — t-stat rows are emitted only if nansum(coeffs - sigstats) is non-zero:

        # MATLAB: indSigStats = (nansum(nansum(coeffs - sigstats)) ~= 0).
        diff = np.where(
            np.isnan(coeffs) | np.isnan(sigstats),
            0.0,
            coeffs - sigstats,
        )
        ind_sig_stats = bool(np.nansum(diff) != 0)

So passing the coefficients themselves as sigstats (Panel C copies a into tA) suppresses the t-stat rows. Note this is a sum test, not an identity check. Coeff rows use \\[-1pt] when t-stats follow, else \\[2pt]. T-stat cells are [val].

build_basic_sort_panels(basic_sorts_res, row_label="vw_nyse_5")

Signature — BasicSortsResults → {PanelA, PanelB, PanelC} dicts.

Returns — same layout as PrintResults.Tab_BasicSort.

What it does — fallback when print_basic_sort_table is handed a BasicSortsResults instead of PrintResults. Duplicates the Table 1 assembly with hardcoded factor tuple (1, 3, 4, 5, 6). The protocol always goes through make_res_to_print instead.

Signature — panels may be PrintResults, a Tab_BasicSort dict, or BasicSortsResults. fid optional. signal_char / time_period default from Text.

Returns — LaTeX for tab:tsRegs.

What it does — caption (VW / quintile / NYSE, sample from Text.sortPeriod), \label{tab:tsRegs}, tabularx with quintile header (L) (2) (3) (4) (H) (H-L), then mat_to_tex on A (2 decimals + t-stats), B (FF6 loadings), C (decimals=0, sigstats=a so no t-stat rows).

How the report describes formation and holding. The wording is fixed and true for every signal, whether it has values every month or each June (Ch 13, When a sort trades):

  • The Table 1 caption: "In each month in which the signal is available, we sort stocks into five portfolios … The portfolios are held, without rebalancing, until the next such month."
  • The Table 2 paragraph (print_return_prediction_section): each portfolio is bought in a month in which the signal is available and held, without rebalancing, until the next such month, when the legs are resized (the clause follows printResults.metadata["convention"]: each leg back to one dollar, or both legs to the strategy's capital); net returns are gross returns less the cost of those trades, and "the cost of the initial purchase is not charged"; and the factors' trading costs are those of the 2×3 portfolios held between trades, each side brought back to equal shares every month, under the same convention (Ch 9b). Results saved before held legs have no convention in their metadata and keep the earlier sentence ("the cost of each month's rebalancing trades").
  • The conditional double sorts (the Table 3 caption, the text and the caption of the conditional-strategies figure): sorted "in each month in which the signal is available" (or "both signals are available"), and "the portfolios are value-weighted, with weights reset every month". These are bivariate sorts, which are not held legs: both the 25 size-by-signal portfolios of Table 3 (reweighted_sort) and the zoo's conditional strategies are weighted by last month's market capitalization every month.
    w("\\begin{table}[!htbp]\n")
    w("\\small\n")
    caption = (
        "\\caption{Basic sort: VW, quintile, NYSE-breaks\\\\\n"
        "\\small{This table reports average excess returns and alphas for "
        f"portfolios sorted on {sc}. "
        # ...
        f"T-statistics are in brackets. The sample period is {start} to {end}.}}}}\n"
    )
    w(caption)
    w("\\label{tab:tsRegs}\n")

Signature — PrintResults (needs Tab_RobustSort + Text).

Returns — LaTeX for tab:robustnessToSorting.

What it does — two panels (Panel B is net $r^e$ + generalized α), 9-column header (Portfolios & Breaks & Weights & $r^e$ & …). Row headers already contain those three &s. After mat_to_tex, t-stat rows are padded so they sit under columns 4–9:

    body = mat_to_tex(pa["a"], sigstats=pa["tA"], row_headers=pa["h"], decimals=2)
    # MATLAB: pad t-stat rows under the three construction-method columns
    body = body.replace("[-1pt]", "[-1pt] & &")

The replace keys on the coeff-row \\[-1pt] marker, which ends every coefficient row that is followed by a t-stat row.

tcost_wording(tcosts_type)

Signature — Text.tcostsType ('full', 'lf_combo' or 'gibbs') → dict with keys definition, short and caption.

What it does — the report's wording for the cost estimator. The report calls costs "trading costs" and names the estimator in three places: one defining sentence in the Table 2 paragraph (definition; for 'full', "Trading costs throughout this report are the Chen--Velikov (C-V) effective-spread costs of \citet{ChenVelikov2022}", followed by how they are built: TAQ/ISSM effective half-spreads where available, else the average of the four low-frequency estimators, else imputation on size and idiosyncratic volatility); the Table 2 Panel B sentence on net returns (short, "C-V effective spreads"); and every caption over net numbers — Table 2 and Figures 2–4 — which ends "net of" caption ("trading costs, measured as Chen--Velikov (C-V) effective spreads \citep{ChenVelikov2022}"). 'lf_combo' says "C-V low-frequency effective spreads" and drops TAQ; 'gibbs' names the Gibbs sampler of Hasbrouck (2009); any other value names no estimator. The cited estimator papers are in the packaged newSignalTestBib.bib.

Signature — PrintResults (reads Tab_SubSample + Text).

Returns — LaTeX for tab:subSample, or "" when Tab_SubSample is missing or empty (results saved before the table existed), so print_tex_file simply leaves the table out.

What it does — no MATLAB counterpart. One panel: a Sample label column and one column per entry of cols ($r^e$, then $\alpha_{\text{CAPM}}$ … $\alpha_{\text{FF6}}$), one mat_to_tex call with the t-stats in brackets and two decimals. The caption names the number of subsamples in words and the sample period.

Signature — PrintResults (Tab_CondSizeSort + Text).

Returns — LaTeX for tab:doubleSortSize, wrapped in landscape (the only landscape table in the report).

What it does — 14-ish column header (5 signal quintiles + spacer + H−L + 5 alphas). Rotated “Size quintiles” \multirow. Panel A body is passed through _pad_cond_size_panel_a so t-stat rows start with &&. Panel B is n and ME, decimals=0.

_pad_cond_size_panel_a(body)

Signature — mat_to_tex Panel A body → padded body.

What it does — two string passes: t-stat lines starting & [ get an extra & so they line up under the multirow size label.

Signature — PrintResults (Tab_CloseFMB + Text).

Returns — LaTeX for tab:closeAnomFMB. Caption interpolates num_to_words(nClose) and Text.closeAnoms, writes the regression with \sum_{k=1}^{n} (the numeral), says returns are in percent per month, explains how the anomalies were picked with close_anom_selection_sentence() (the same sentence as the section text: the combined rank of the absolute Spearman correlation and the spanning R²), and describes the first column (the signal alone), the \# months row and the R² row. The column spec follows a.shape[1]; the header row is column numbers only, & (1) & … & (n): (1) the signal alone, then one anomaly each, the last all of them (the spanning table is numbered the same way, without the signal-alone column). A slope row whose largest coefficient is below 0.01 in absolute value is multiplied by a power of ten that brings it to at least 0.1 (scale_small_slope_rows); its label says so (OCFI $\times 10^{2}$) and the caption gains "The slopes on OCFI are multiplied by $10^{2}$."; the t-statistics are not changed. The body is three mat_to_tex calls: the coefficient rows with their t-stats at two decimals, the months row at decimals=0, and the R² row at two decimals, the last two without t-stats, so no empty bracket line follows them.

Signature — PrintResults (Tab_CloseSpan + Text).

Returns — LaTeX for tab:closeAnomSpan. The caption uses num_to_words(n_close) throughout (MATLAB hard-coded "six" in one clause), the same selection sentence as the FMB caption, and ends by describing the \# months row and the adjusted-R² row. The body is three mat_to_tex calls: the coefficient rows with t-stats at two decimals, the months row at decimals=0, then the R² row at decimals=0 (integer percent).

The cells of this table are sensitive to the zoo tie-break seed; see How tab:closeAnomSpan appears in the PDF.


reporting/latex.py — document assembler

Signature

  • results — PrintResults.
  • out_dir — default Scratch/Assay/tex.
  • signal_acronym — filename stem; default Text.signalChar.
  • emit_figures — False skips drawing the PDFs but still writes the \includegraphics basenames.

Returns — absolute Path to {signal}.tex.

What it does — writes the blocks in paper order:

    with tex_path.open("w", encoding="utf-8", newline="\n") as fid:
        print_document_header(fid)
        print_title_page(results, fid)
        print_intro_section(results, fid)
        print_signal_description_section(results, fid)
        print_return_prediction_section(results, fid)
        print_other_anomalies_section(results, fid)
        print_close_anoms_section(results, fid)
        print_comb_strats_section(results, fid)

        print_signal_description_figure(results, fid)
        print_basic_sort_table(results, fid=fid)

Figures are emitted before the TeX write (emit_all_figures) so a failed plot does not leave a half-written .tex. The file is UTF-8 with \n newlines (not Windows \r\n), so semantic_tex_diff and text diffs are not fighting CRLF.

Signature — PrintResults → title / author / \date{\today} / abstract.

Returns — TeX string.

What it does — the title is three lines, "Assaying Anomalies Performance Report \ for Cross-Sectional Return Predictor \ {SignalName}" (a demo database adds a red banner line above them). signalInfo.PaperTitle is kept in the metadata but not printed. Splits signalInfo.Authors on " and " into \and blocks. Abstract numbers (example values from the MPE report of a full CIZ build in September 2026):

Abstract token Source
Sharpe 0.61 (0.48) Text.sharpeChar / netSharpeChar
FF6+mom α 43 (21) bps 100 * Tab_RobustSort.PanelA/B.a[0, 5]
those t-stats 4.73 (2.11) Tab_RobustSort t-matrix, same cell
spanning α 40 bps 100 * Tab_CloseSpan.a[0, -1]
spanning t 4.50 Tab_CloseSpan.tA[0, -1]
close names Text.closeAnoms
"six" num_to_words(nCloseAnoms)

Both 100 * factors here are the percent → bps conversion the prose promises, not a double scale. The span intercept reaches the abstract through two multiplications, but they are two different unit steps: make_res_to_print scales the raw regression coefficient (decimal, 0.0040) to percent/month for the table cells (0.40, the units Table 1 uses), and the abstract scales that to bps/month (40). The robust-sort α passes through only one, because sort alphas arrive in percent already (0.43 → 43 bps). Removing either would understate the headline by 100×.

\date{\today} makes the file change every calendar day; that is why strip_date_today exists.

Section writers with real interpolation

These five pull cells, format them, and drop them into a fixed prose template. They are not thin wrappers.

What it does — mask Fig_Cov Panel A/B by timePeriod converted to plot dates; interpolate mean / median / IQR / % names / % ME. The sample years in the sentence are those of Text.valuePeriod.

What it does — Table 1 H−L xret / min–max α / FF6 loadings / n and ME from Panel C; Table 2 net range and “how many of 25 gen-α t-stats exceed 1.65”; when Tab_SubSample has more than one row, a subsample paragraph: the number of subsamples, in how many the average return is positive, the lowest and highest return with their t-stats and periods, and the range of the last model's alpha and t-stats (the model name from cols[-1]); then the Table 4 (size) large-cap row. The Table 2 paragraph carries the trading-cost definition from tables.tcost_wording(Text.tcostsType). _re_between pulls the factor-model name out of $\alpha_{FF6}$.

What it does — Sharpe-rank of the test signal in the zoo histogram (100 * mean(line > hist)); Ibbotson terminal wealth via cumprod(1+r) - 1 with NaN→0 (no leading $1 row, unlike ibbots_cumret); α-percentile ranks from Fig_AlphaPrctl.dx.

What it does — the signal-alone t-stat from Tab_CloseFMB.tA[1, 0] (the sentence is dropped when that column is blank); FM min t-stat and label from Tab_CloseFMB.tA[1, 1:-1] (the bivariate columns), joint t-stat from tA[1, -1], and, when both are finite, the adjusted R² moving from a[-1, 0] (signal alone) to a[-1, -1] (joint), at two decimals; the selection sentence from tables.close_anom_selection_sentence; the joint spanning R² from Tab_CloseSpan.a[-1, -1]; span α range 100 * min/max of Tab_CloseSpan.a[0, :-1]; joint α 100 * a[0, -1]. The “which anomaly” label for the minimum spanning t-stat uses the spanning argmin (not the FMB one):

    min_ai = int(np.nanargmin(t0))
    min_at = f"{t0[min_ai]:.2f}"
    min_alab = close_labels[min_ai] if min_ai < len(close_labels) else f"Anomaly {min_ai + 1}"

Example §5 from the same MPE report: alphas “range from 37-43bps/month”, min t 4.09 “when controlling for Intangible return using BM”, joint “40bps/month with a t-statistic of 4.50”.

What it does — one paragraph per active method (Fig_CombStrat.ttl / .explanation); terminal $1 from cumprod(1 + y) on yWithout / yWith. N/A methods were already dropped in make_res_to_print, so a typical report has four panels (Avg / W-Avg / FMB / PLS), matching Ch 18.

Thin string-writers (grouped)

Function What it writes
print_document_header \documentclass + package list (amsfonts … natbib, hyperref, xcolor)
print_intro_section §1 + GitHub footnote naming the installed package version
print_end_of_paper_text \bibliographystyle{apalike} + \bibliography{newSignalTestBib} + \end{document}
_fig_includegraphics \hspace{-4mm} \includegraphics[width=…,keepaspectratio]{stem}
print_signal_description_figure fig:descriptiveStats
print_sharpe_dist_figure fig:distributionSharpeRatios
print_ibbots_plots_figure fig:dollarInvested
print_alpha_prctl_figure fig:alphaPercentiles
print_correl_figure fig:distributionCorrelations
print_dendrogram_figure fig:hierarchicalClusterPlot
print_cond_strats_figure fig:conditionalStrategies
print_comb_strats_figure fig:combStrat

Each print_*_figure writes only the TeX float (caption, label, \includegraphics); the PDF itself is drawn by the matching emit_* function in figures.py. _fig_includegraphics defaults to width=1.015\linewidth.

Signature — directory path → Path to newSignalTestBib.bib in that directory.

Returns — the destination path.

What it does — copy the first of: (1) AssayingAnomalies-MATLAB/Scratch/Assay/tex/newSignalTestBib.bib, if a source checkout has that reference-toolkit folder next to src/; (2) the packaged reporting/bib/newSignalTestBib.bib; (3) the _MINIMAL_BIB stub (Novy-Marx/Velikov 2026 only). The bib ships as package data, so an installed wheel uses (2).

strip_date_today(tex)

Signature — TeX string → TeX string.

Returns — same text with every \date{\today} replaced by \date{}.

def strip_date_today(tex: str) -> str:
    """Remove ``\\date{\\today}`` for cross-file comparison."""
    return re.sub(r"\\date\{\\today\}", r"\\date{}", tex)

What it does — the title page writes \date{\today}, so a raw file diff changes every calendar day. This is the only date normalization. It does not strip \maketitle, author blocks, or PDF timestamps.

semantic_tex_diff(produced, gold, *, keys=None)

Compares a produced report against a reference report (the gold argument) on the numbers that matter, ignoring layout.

Signature

  • produced, gold — full TeX strings (not paths).
  • keys — optional table-label list. Default:
    table_labels = keys or [
        "tab:tsRegs",
        "tab:robustnessToSorting",
        "tab:doubleSortSize",
        "tab:closeAnomFMB",
        "tab:closeAnomSpan",
    ]

Returns — dict:

Key Meaning
ok abstract_ok and figures_ok and tables_ok
abstract_ok Sharpe pair equal and present
sharpe_prod / sharpe_gold e.g. ("0.61", "0.48")
bps_prod / bps_gold (\d+) (\d+) bps/month and is (\d+) bps/month snippets (reported, not gated)
figures_ok \includegraphics[...]{basename} lists equal
figures_prod / figures_gold those basename lists
tables per-label {n_prod, n_gold, max_abs_prefix, max_rel_prefix, match}
abstract_prod / abstract_gold first 400 chars of collapsed abstract

What it does, in order:

  1. strip_date_today both sides. Calendar date is not a mismatch.
  2. Abstract. Regex \begin{abstract}...\end{abstract}, collapse whitespace, pull Sharpe ratio of ([0-9.]+) \(([0-9.]+)\). abstract_ok is that pair equal and non-None. It does not require the FF6 bps string or the spanning t-stat to match (those sit in bps_* for humans).
  3. Figures. All \includegraphics[opt]{stem} captures, compared as lists. Options (width= vs height=) are inside the [...] and are not compared — only the {stem} (MPE_figureIbbots, …).
  4. Tables. For each label, take the slice from \label{tab:...} to \end{table}, collapse whitespace, extract numbers with -?\d+\.\d+|-?\d+. Compare the common prefix of those sequences. A cell matches if abs_diff <= 0.02 or rel_diff <= 1e-3. The table match also requires |n_prod - n_gold| <= 5 (padding / extra & tokens can add a few integers). tables_ok is AND across labels.
        # Compare common prefix of numeric sequences with a magnitude-aware
        # tolerance: a cell matches if it is close in absolute terms (0.02,
        # i.e. the 2-decimal print resolution of small cells) OR in relative
        # terms (1e-3, so a large-magnitude cell like a coefficient of ~401
        # is not held to more precision than the print carries).
        n = min(np_p.size, np_g.size)
        # ...
            cells_ok = bool(np.all((diff <= 0.02) | (rel <= 1e-3)))
            match = cells_ok and abs(np_p.size - np_g.size) <= 5

The 0.02 floor is one printed hundredth (Table 1 cells are %.2f). The 1e-3 relative leg keeps large printed numbers (for example a tab:closeAnomFMB coefficient of about 401) from being held to more precision than the print carries. tab:closeAnomSpan can legitimately fail against a report produced with different zoo jitter (see the next section), so ok is False in that case even when everything else agrees.

What it does not compare: caption wording, \hline / tabularx padding, landscape, figure geometry, bibliography, section prose except via the abstract Sharpe pull, PDF pixels, \date after stripping.


How tab:closeAnomSpan appears in the PDF

Before the zoo quintile sorts, every zoo signal gets a tiny random jitter (randn * 1e-12) to break ties (Ch 17). This follows the original MATLAB toolkit, which draws that jitter unseeded; the Python package fixes the seed (_ANOM_NOISE_SEED), so a rerun reproduces the same report.

Most of the report does not move with the seed: the close-set identity and order, the abstract Sharpe ratios and FF6+mom α, the anomaly count, the eight figure files and Tables 1–5. The cells of Table 6 (\label{tab:closeAnomSpan}) do. In the MPE report of the September 2026 build the printed intercept row is

Intercept & 0.43 & 0.37 & 0.43 & 0.41 & 0.42 & 0.42 & 0.40
 & [4.76] & [4.09] & [4.76] & [4.58] & [4.63] & [4.65] & [4.50]

Columns 1–6 are the MPE α controlling for one close anomaly + FF6; column 7 is all six + FF6 (the 40 bps / t = 4.50 the abstract quotes). Sensitivity concentrates in columns whose zoo legs are tie-heavy (Price, Illiquidity, dollar volume): ties at the quintile breakpoints are broken by the jitter, so a different seed puts different stocks in the extreme portfolios. Across seeds the printed Table 6 cells moved by 0.09–0.57 (remember the table stores 100*beta, so a move on a loading row is 100× the change in the loading). Treat any one seed's Table 6 as one draw; there is no "correct" seed to search for.


reporting/figures.py — eight PDFs

Figures are drawn with matplotlib's Agg backend and saved with fig.savefig(..., format="pdf"). Basenames are {Signal}_figureSignalDescription.pdf, …SharpeDist, Ibbots, AlphaPrctl, Correl, Dendrogram, CondStrats, CombStrats.

FIGURE_SUFFIXES is the ordered (logical_key, basename) tuple listing the eight names.

ibbots_cumret(rets, dates=None)

Signature — rets month × series decimals; dates YYYYMM (or plot fractions).

Returns — (x, y) with y.shape == (T+1, K) and y[0] = 1.

What it does — NaN→0, prepend a zero-return row, cumprod(1+r); the x-axis gets one extra point 2*x[0] - x[1] before the sample dates. No plotting; emit_ibbots_figure / emit_comb_strats_figure draw.

    r = _as_2d(rets)
    r = np.nan_to_num(r, nan=0.0)
    t, k = r.shape
    y = np.cumprod(np.vstack([np.zeros((1, k)), r]) + 1.0, axis=0)
    # ...
            x0 = 2.0 * xd[0] - xd[1]
            x = np.concatenate([[x0], xd])
    return x, y

_month_pdate uses the encoding year + month/12, not yyyymm_to_pdate's year + (month-1)/12.

plot_name_histogram(x, labels, ax=None)

Signature — 1-D values (percent), string labels, optional Axes.

Returns — the Axes.

What it does — bins of width 20 from ±ceil(max|x|/20)*20; strip _ and cap labels at 10 chars; count per bin; in each bin, sort surviving labels alphabetically and write each with ax.text(i, j, lab) at font size 7; y-limit ceil(max_count/10)*10; x-limit [0.8, nBins+0.2]; xticklabels = bin edges.

_matlab_linkage_to_scipy(Z)

Converts a MATLAB-layout linkage matrix ((n-1)×3, 1-based cluster ids) to SciPy's ((n-1)×4, 0-based, with a count column). Ch 18 already emits SciPy Z from make_dendrogram_results, so on the live path this is a no-op; it lets a 3-column Z from an older saved result still be drawn.

Signature — ndarray → SciPy linkage.

Returns — (n-1)×4 float array.

What it does — if 4 columns and 1-based cluster ids (max >= n_leaf), subtract 1 from the first two columns. If 3 columns, subtract 1 from ids, rebuild counts by walking merged clusters. Transposes 3×N / 4×N.

    n = Z.shape[0] + 1
    left = Z[:, 0].astype(int) - 1
    right = Z[:, 1].astype(int) - 1
    dist = Z[:, 2]
    counts = np.zeros(Z.shape[0], dtype=float)
    for i in range(Z.shape[0]):
        cl = 1.0 if left[i] < n else counts[left[i] - n]
        cr = 1.0 if right[i] < n else counts[right[i] - n]
        counts[i] = cl + cr
    return np.column_stack([left.astype(float), right.astype(float), dist, counts])

emit_signal_description_figure(results, out_dir, *, signal_char=None)

Signature — PrintResults, output directory → Path | None.

Returns — {sc}_figureSignalDescription.pdf or None if Fig_Cov empty.

What it does — 2×1: Panel A plots four series (25th / median / 75th / mean) from Fig_Cov.PanelA; Panel B name% and ME% coverage. xlim from the panel when present.

emit_sharpe_dist_figure(results, out_dir, *, signal_char=None)

What it does — 2×1 histograms (bins="auto") of zoo Sharpes; red vertical line at Panel*.Line (the test signal). xlim [-2, 2].

emit_ibbots_figure(results, out_dir, *, signal_char=None)

What it does — 2×1 log $1 plots via _plot_ibbots_panel: gray lines for every anomaly column of pretGrossAnoms / pretNetAnoms, red line for the test signal. Transposes if the matrix arrived as anoms × months (h5 reload). Y-ticks $1 … $100,000,000.

emit_alpha_prctl_figure(results, out_dir, *, signal_char=None)

What it does — 1×2: percentile curves (one gray per factor model) and black diamonds at (dx, dy) for the test signal. Panel B y-label is the Novy-Marx / Velikov (RFS 2016) net generalized α. dy units are %/month because of the ×100 in make_res_to_print.

emit_correl_figure(results, out_dir, *, signal_char=None)

What it does — 2×1 plot_name_histogram. Panel A is labeled “Panel A: Spearman” and plots Fig_Correls.PanelA (Spearman); Panel B is “Panel B: Pearson” and plots Fig_Correls.PanelB (Pearson). See make_res_to_print step 7.

emit_dendrogram_figure(results, out_dir, *, signal_char=None)

What it does — _matlab_linkage_to_scipy, scipy.cluster.hierarchy.dendrogram with color_threshold=cutoff, leaf rotation 90. _strip_dendro_label pulls \color{red}{MPE} wrappers so the test-signal tick can be colored red. SciPy and matplotlib both come with the [analytics] extra.

emit_cond_strats_figure(results, out_dir, *, signal_char=None)

What it does — 3×1 histograms of Fig_CondAnoms Panels A/B/C (FMB t, spanning t, cond-sort t).

emit_comb_strats_figure(results, out_dir, *, signal_char=None)

What it does — 3×2 log $1 panels (unused axes hidden). Blue = without test signal, red = with. Titles Panel A: {ttl[i]}. ibbots_cumret on the two columns.

emit_all_figures(results, out_dir, *, signal_char=None)

Signature — PrintResults, directory → dict[str, Path] keyed by basename suffix.

Returns — only the figures that succeeded. _safe catches and logs an exception in any one emitter, so a failed figure is skipped rather than aborting the report.

    emitters = (
        ("figureSignalDescription", emit_signal_description_figure),
        ("figureSharpeDist", emit_sharpe_dist_figure),
        ("figureIbbots", emit_ibbots_figure),
        ("figureAlphaPrctl", emit_alpha_prctl_figure),
        ("figureCorrel", emit_correl_figure),
        ("figureDendrogram", emit_dendrogram_figure),
        ("figureCondStrats", emit_cond_strats_figure),
        ("figureCombStrats", emit_comb_strats_figure),
    )

analytics/plots.py — library ibbots / moving

These are user-facing plotting utilities. The assay report does not call them; figures.ibbots_cumret is the report path. SortResult.plot_results (Ch 13) draws the 4-panel strategy figure.

ibbots(rets, time_period=None, lin_plot_ind=False, legend_labels=None, ax=None, title=None)

Signature

  • rets — Series or DataFrame of decimal monthly returns, month-end index.
  • time_period — YYYYMM start or (start, end), via sorts._time_mask.
  • lin_plot_ind — linear cumulative gains instead of log $1.
  • legend_labels, ax, title — plot chrome.

Returns — DataFrame of cumulative $1 paths including the $1 starting row (index = min date minus one month-end).

What it does — fillna(0), (1+r).cumprod(), insert a leading 1.0 one month before the sample, semilogy with $1…$100,000,000 ticks and ylim = (0.8 min, 1.4 max).

    rets = rets.to_frame() if isinstance(rets, pd.Series) else rets.copy()
    rets = rets[_time_mask(rets.index, time_period)]
    y = (1 + rets.fillna(0)).cumprod()
    y.loc[y.index.min() - pd.offsets.MonthEnd(1)] = 1.0
    y = y.sort_index()
    # ...
        ax.semilogy(y.index, y.to_numpy(), linewidth=2.0)
        ticks = 10.0 ** np.arange(0, 9)
        ax.set_yticks(ticks)
        ax.set_yticklabels([f"${t:,.0f}" for t in ticks])
        ax.set_ylim(0.8 * float(np.nanmin(y.to_numpy())),
                    1.4 * float(np.nanmax(y.to_numpy())))

ibbots (interactive, DatetimeIndex) and figures.ibbots_cumret (report, YYYYMM) compound the same way: NaN→0, $1 start.

moving(x, m)

Signature — array-like x, window m → ndarray.

Returns — same length as x: a centered m-point moving average.

What it does — Series.rolling(m, center=True, min_periods=m).mean() then bfill().ffill(), so the edges repeat the first / last full-window value. Only the mean is supported (no custom reducer). Not called from the assay report (Fig 2 uses a raw histogram, not a moving average).


Packaged bibliography

src/assayinganomalies/reporting/bib/newSignalTestBib.bib holds the report's references (Fama–MacBeth 1973, FF 1993/2015/2018, Carhart 1997, Novy-Marx/Velikov 2016/2023, Chen–Zimmerman, Lewellen, …). print_bibliography_file copies it next to the .tex so \bibliography{newSignalTestBib} resolves; a run writes Scratch/Assay/tex/newSignalTestBib.bib. The file is listed under [tool.setuptools.package-data] in pyproject.toml, so it ships with the wheel.