Appendix — Coming from the MATLAB toolkit¶
Part V of the assayinganomalies tutorial. Read this if you used the original MATLAB toolkit of Novy-Marx and Velikov (2026) and want to know where its functions went and what behaves differently. Nothing else in the tutorial depends on it.
The package began as a port of that MATLAB toolkit. The MATLAB code remains
available, unmaintained, on the
matlab-legacy branch
of the repository.
The workflow in one table¶
| MATLAB | Python |
|---|---|
addpath(genpath(...)), setAssayPath.m |
pip install the package (Ch 1) |
Edit the Params struct in setup_library.m |
aa set-params --sample-start 1925 ... or aa.set_params(...); settings persist in the database (Ch 1) |
Run setup_library.m |
aa setup-database or aa.setup_database(); restartable with --start-from (Ch 4) |
load ret me NYSE from Data/*.mat |
aa.load(["ret", "me", "nyse_flag"]), from one DuckDB file (Ch 12) |
use_library.m |
aa.load plus the analytics calls; the quickstart walks through them (Ch 2) |
Run test_signal.m |
aa run-protocol --signal my_signal.csv or aa.test_signal(...) (Ch 16) |
MPE_Results.mat |
MPE_Results.pkl (results and the report struct in one pickle) plus MPE_manifest.json (Ch 20) |
Function-to-function mapping¶
aa is import assayinganomalies as aa. Names without aa. live in the module
the chapter documents. Build steps that have no Python function you call
directly are named by their pipeline stage (aa setup-database runs them all).
Setup and configuration¶
| MATLAB | Python | Chapter |
|---|---|---|
setup_library.m (the Params block) |
AssayConfig, aa.set_params, aa set-params, aa show-config |
1 |
setup_library.m (the build) |
aa.setup_database, aa setup-database |
2, 4 |
setAssayPath.m |
package install; outputs default to Scratch/Assay in the project folder |
1 |
usernameUI.m, passwordUI.m, setupWRDSConn.m, callWRDSConnection.m, getWRDSTable.m |
WRDSClient (credentials from environment variables, ~/.pgpass, the keyring or a prompt) |
5 |
checkJavaHeapMemory.m |
not needed (no JDBC) | — |
startLogFile.m |
standard logging; the protocol's stage log is ProtocolResult.stage_log |
4, 16 |
Library build¶
| MATLAB | Python | Chapter |
|---|---|---|
getCRSPData.m, getCRSPMonthlyData.m |
stages fetch-crsp-monthly, fetch-crsp-aux (fetch_crsp_monthly) |
5 |
getCRSPDailyData.m |
stage fetch-crsp-daily (fetch_crsp_daily) |
5 |
getCOMPUSTATData.m, getCOMPUSTATAdditionalData.m, getCOMPUSTATQuery.m |
stages fetch-compustat-annual, fetch-compustat-quarterly |
5 |
getFFFactors.m, getFFDailyFactors.m |
stages fetch-ff-factors, fetch-ff-daily (from WRDS) |
5 |
getChenZimmermanAnomalies.m, downloadChenZimmermanFiles.m, getGoogleDriveData.m |
stage fetch-cz-anomalies (write_cz_anomalies_table); aa.load_cz_anomalies to read |
5, 12 |
makeCRSPMonthlyData.m, makeCRSPDerivedVariables.m |
transform_monthly (stage transform-crsp-monthly) |
6 |
makeIndustryClassifications.m, makeFF10Indus.m, makeFF17Indus.m, makeFF49Indus.m |
columns ff10, ff17, ff49 (FF10_RANGES, ...) |
6 |
makePastPerformance.m |
momentum columns R12_2, R6_1, R60_13 |
6 |
makeCOMPUSTATVariables.m, makeCOMPUSTATDerivedVariables.m, mergeCRSPCOMP.m |
stage transform-compustat (merge_compustat_crsp and the compute_* helpers) |
7 |
testCRSPData.m |
stage validate-bm-hml |
4 |
makeCRSPDailyData.m, makeCRSPDailyDerivedVariables.m |
transform_daily, aggregate_daily_to_monthly (stages transform-crsp-daily, compute-car3) |
8 |
makeTradingCosts.m |
make_trading_costs (stage compute-tcosts) |
9 |
makeCorwinSchultz.m, makeAbdiRanaldi.m, makeKyleObizhaeva.m |
compute_corwin_schultz, compute_abdi_ranaldi, compute_kyle_obizhaeva |
9 |
makeGibbs.m, makeHighFreqEffSpreads.m |
load_gibbs, load_hf_spreads |
9 |
fillMissingTcosts.m |
fill_missing_tcosts |
9 |
makeFFTcosts.m |
make_ff_tcosts (stage compute-ff-tcosts); aa.make_ff_tcosts. Same 2×3 sorts, different costs (held legs; see below) |
9b, 15 |
makeBetas.m |
compute_betas, compute_fp_beta, compute_ols_betas (stage compute-betas) |
10 |
makeNovyMarxVelikovAnomalies.m |
compute_nmv_anomalies (stage compute-nmv-anomalies); aa.load_nmv_anomalies to read |
11 |
Data access and signals¶
| MATLAB | Python | Chapter |
|---|---|---|
load <var> |
aa.load([...]) (long panel; wide=True for a months × stocks frame) |
3, 12 |
getAnomalySignals.m |
aa.get_anomaly_signals, aa.load_signal_csv |
12 |
getSignalInfo.m |
aa.get_signal_info, SignalInfo |
12 |
lag.m |
AssayClient.lag (row shift within each permno); the sorts and signal builders lag by calendar month internally |
1 |
fillVar.m, checkFillAnomalies.m |
aa.fill_var, aa.check_fill_anomalies |
11, 16 |
Analytics¶
| MATLAB | Python | Chapter |
|---|---|---|
makeUnivSortInd.m + runUnivSort.m |
aa.run_univariate_sort → SortResult |
13 |
makeBivSortInd.m + runBivSort.m |
aa.run_bivariate_sort → BivariateSortResult |
13 |
assignToPtf.m |
binning inside the sort functions | 13 |
calcPtfRets.m |
aa.calc_ptf_rets |
13 |
estFactorRegs.m, GRStest_p.m |
aa.est_factor_regs, aa.load_factors |
13 |
prtSortResults.m, plotStrategyFigs.m |
SortResult.print_results, SortResult.plot_results |
13 |
runFamaMacBeth.m, prtFMBResults.m |
aa.run_fama_macbeth → RegressionResult (.print_results) |
14 |
nanols.m, ols.m, prt.m, prt_reg.m |
aa.nanols, aa.prt |
14 |
winsorize.m, trim.m, nwest.m |
options of aa.run_fama_macbeth (winsor_trim_pct, trim_indicator, newey_west_lags) |
14 |
calcTcosts.m |
aa.calc_tcosts (kept as a function; run_univariate_sort no longer uses it, see below) |
15 |
calcGenAlpha.m, calcMve.m, calcNetMve.m |
calc_gen_alpha, calc_mve, calc_net_mve |
15 |
anomaly-decay section of use_library.m |
aa.run_anomaly_decay, aa.plot_anomaly_decay |
15 |
ibbots.m, moving.m |
aa.ibbots, aa.moving |
15, 19 |
The assay protocol¶
| MATLAB | Python | Chapter |
|---|---|---|
test_signal.m |
aa.test_signal, aa run-protocol, aa.default_mpe_signal_info |
16 |
runTestSignal.m |
aa.run_test_signal → ProtocolResult |
16 |
makeBasicSortsResults.m |
make_basic_sorts_results |
17 |
makeAnomBenchmarkResults.m, calcPanelCorrels.m |
make_anom_benchmark_results |
17 |
makeAnomStratResults.m |
make_anom_strat_results |
17 |
makeFMBRes.m |
make_fmb_res |
17 |
makeCloseAnomResults.m |
make_close_anom_results |
18 |
makeDendrogramResults.m |
make_dendrogram_results |
18 |
makeCombStrats.m |
make_comb_strats |
18 |
makeLassoRes.m, makePLSRes.m, makeIPCARes.m, runIPCAforMonth.m |
make_lasso_res, make_pls_res, make_ipca_res |
18 |
makeAverageRank.m, makeWeightedAverageRank.m |
make_avg_rank, make_weighted_avg_rank |
18 |
Reporting¶
| MATLAB | Python | Chapter |
|---|---|---|
makeResToPrint.m |
aa.make_res_to_print → PrintResults |
19 |
printTexFile.m |
aa.print_tex_file (draws every figure, then writes the .tex) |
19 |
print*Table.m, print*Section.m, printTitlePage.m, printDocumentHeader.m, printEndOfPaperText.m, printBibliographyFile.m |
the same names in snake case (printBasicSortTable.m → print_basic_sort_table), returning LaTeX strings |
19 |
print*Figure.m |
split in two: emit_*_figure draws the PDF, print_*_figure writes the TeX that includes it |
19 |
plotNameHistogram.m |
plot_name_histogram |
19 |
invprctile.m, addComma.m |
invprctile, add_comma |
19 |
Not ported¶
makeUniverses.m (no universe column), make_sS.m (S-s rebalancing bands),
sendUserResults.m (e-mailing results), the daily RMW/CMA factors from
getFFDailyFactors.m, and the downloaders with no role in the build
(getFOMCDates.m, getFredData.m, getMarketDataViaYahoo.m).
Differences that matter¶
Most functions compute what their MATLAB counterparts did. These are the differences that change your numbers or your workflow.
Data layout and defaults¶
- Long panels, not matrices. Every variable is a long table keyed by
(date, permno), holding only stock-months that exist; MATLAB'snMonths × nStocksmatrices padded the rest with NaN.aa.load(..., wide=True)returns the matrix shape. Lags are calendar-month lags within each permno, so they match a matrixlag. - Dates are month-end timestamps (
1963-07-31, not196307). Arguments such asdates=(196307, 201212)and the signal CSV'sdatescolumn still accept YYYYMM. Returns are decimals, as before. - Names.
NYSEis the booleannyse_flag(aa.loadaccepts the old name); MATLAB'sRisR12_2andR62isR6_1;dretmaxismaxret; the market factor ismktrf. aa.loadreturns common shares only (shrcd10 or 11) by default; passcommon_shares_only=Falsefor everything the database holds.- Different defaults.
sample_startis 1963 (MATLAB: 1925) andtcosts_typeis"lf_combo", which needs no high-frequency spreads (MATLAB:"full"). To rebuild the MATLAB reference library, setaa set-params --sample-start 1925 --tcosts-type fulland supplyhf_monthly.csv(trading-cost inputs). - The CRSP tape. New builds use CRSP's current CIZ format; the MATLAB
toolkit reads only the legacy SIZ format, which CRSP froze in December 2024.
Numbers differ slightly between the two (returns are compounded differently
and already include delisting payoffs), but the research conclusions do not. Use
aa set-params --crsp-format sizto build on the legacy tape. - External data. Fama–French factors come from WRDS rather than Ken
French's website (they agree to rounding; WRDS can lag by a few months at the
end of the sample). Chen–Zimmerman signals come from the newest release by
default (
cz_release_versionpins one), and a failed download stops the build instead of continuing without it.
Corrected MATLAB behaviour (numbers differ on purpose)¶
maxretis the largest daily return. MATLAB'sdretmaxtook the maximum of daily volume.- NASDAQ trading costs. A typo in
makeTradingCosts.m(1982212for198212) dropped every NASDAQ Gibbs and VoV estimate; Python applies the intended December 1982 cutoff, so NASDAQ costs are somewhat higher. - Piotroski F-score tiebreaker ranks book-to-market within each month; MATLAB ranked each stock against its own history.
- Pearson correlations are Pearson. MATLAB's
calcPanelCorrelscall stored Spearman twice. Python stores both, ranks close anomalies on Pearson and sorts missing values last, so the six "closely related" anomalies can differ, and Figure 5's Panel B is a real Pearson correlation. - The close-anomalies section names the anomaly with the lowest spanning t-statistic (MATLAB reused the Fama–MacBeth index).
Held legs: returns and trading costs of sorts and factors¶
The univariate sort, the zoo strategies, the protocol and the factor costs do not reproduce MATLAB here, by design.
- A sort holds its legs.
runUnivSortearns the return of fresh target weights every month and chargescalcTcostson weights drifted with the market-cap ratio, each leg on a constant $1.aa.run_univariate_sortbuys each portfolio in a month in which the signal has values and leaves it alone until the next such month; positions grow withret; the cost is that of the trades that move the two legs from what they hold to the new targets; the first purchase is reported as one number and is not charged (Ch 13). The data decide when it trades (Ch 13). For a signal with values every month the gross returns are those of monthly rebalanced portfolios, as in MATLAB; for a signal with values once a year they are not. Trading costs differ from MATLAB's for every signal, under both settings ofconvention("dollar", the default: each leg back to $1 at a trade;"capital": both legs set to the strategy's capital). - Factor trading costs.
makeFFTcosts.mprices each side of a factor withcalcTcosts.compute-ff-tcostskeeps its 2×3 sorts and prices them on held legs, with each side brought back to equal shares of its 2×3 portfolios every month, under both conventions (Ch 9b). The stored factor costs do not matchff_tc.mat. Two approximations remain: the 2×3 portfolios drift withretwhere the published value weights follow market cap, and the sorts are the toolkit's reconstruction of the published ones. calc_ptf_retsandcalc_tcostsremain as functions and still followcalcPtfRets.mandcalcTcosts.m. Bivariate sorts, the 5×5 benchmark portfolios and the FF49 industry returns stay on monthly value weights and carry no cost.
The protocol¶
- Tie-break noise is seeded. MATLAB adds unseeded
randn*1e-12noise before sorting the anomaly zoo, so no two MATLAB runs agree exactly. Python seeds it, so its runs reproduce, but the tie-heavy cells — chiefly the close-anomaly spanning table (tab:closeAnomSpan) — will not match any particular MATLAB run (seed). - LASSO and IPCA combination strategies run. MATLAB reported them as N/A
because the dense three-dimensional array ran out of memory. LASSO uses
scikit-learn's
LassoCV(different penalty grid, seeded folds), so it is not a replica of the Statistics Toolboxlasso. - A test signal enters the combination strategies when it has data. The average rank uses it from its first month of data, the other five methods once it has 120 months of data, and in each panel the strategies with and without the signal start in the same month. MATLAB hands every method the signal from the start of the sample and keeps it in IPCA in every month, so for a signal that starts late the IPCA windows without data cannot be solved and the two lines of that panel cover different periods.
- Benchmark conditional sorts use NYSE breakpoints on the anomaly leg when NYSE flags are supplied (the protocol always supplies them); MATLAB used all-stock breakpoints on both legs.
- Holding periods above one month give gross returns only:
run_univariate_sort(..., holding_period=h)withh > 1and a per-stock cost panel raisesValueError(known limitations). - Quieter, partial-failure-tolerant functions. The sorts and Fama–MacBeth
regressions do not print or plot unless asked (
print_results=True,factor_model=4for alphas). A failing late stage of the protocol (dendrogram, close anomalies, combination strategies) is logged and returns a partialProtocolResultrather than aborting. One exception: a test signal that cannot be placed in the cluster plot stops the run (DendrogramSignalError). - Dendrograms use SciPy's linkage format (
(n-1) × 4, 0-based cluster ids); distances agree with MATLAB, cluster numbers do not.
How the port was checked¶
Every database computation and protocol builder was compared number by number with the MATLAB toolkit's output on the same SIZ extract; apart from the intended differences above, they agreed to floating-point tolerance. That comparison predates the held-leg calculation: sort returns of annual signals, all sort costs and the factor costs no longer match MATLAB, on purpose. See Ch 20.