Skip to content

Assaying Anomalies: quickstart

This page is the package's quickstart notebook, shown without its outputs.

Download the notebook

It walks through the steps of Get started:

  1. set the project's parameters,
  2. build the research database from CRSP and Compustat,
  3. load data and run a univariate portfolio sort and a Fama–MacBeth regression,
  4. run the full anomaly-testing protocol on a signal of your own.

Before you start. Install the package with its analytics extra (see the README). The database and its settings live in Data/aa.duckdb under your project folder. Set that folder once, in a terminal with aa set-params --project-dir <folder> or in the first cell below, and every notebook, script and terminal finds it from any folder (see The project folder). If you have not set one, the first cell falls back to the folder holding Data/: the notebook's folder, or the one above it. The signal CSV and the outputs below are written under the project folder too. Building the database needs a WRDS subscription; without one, set DEMO = True in step 2 to build a small synthetic database (fine for trying the API, never for research).

Conventions used throughout: returns are decimals, dates are month-ends, and panels are pandas objects indexed by (date, permno).

import os
from pathlib import Path

import pandas as pd

import assayinganomalies as aa
from assayinganomalies.config import scratch_dir, set_params
from assayinganomalies.analytics.regressions import run_fama_macbeth

# The project folder holds Data/aa.duckdb (the database and its settings) and the
# outputs. Set it once, here or with `aa set-params --project-dir <folder>` in a
# terminal, and every later session finds it from any folder:
# aa.set_project_dir(Path.home() / "research" / "my-project")

# Fallback when none is set: Jupyter runs a notebook in its own folder, so use the
# folder above when that one holds Data/.
PROJECT_DIR, source = aa.resolve_project_dir()
if (
    source == "current folder"
    and not (PROJECT_DIR / "Data").is_dir()
    and (PROJECT_DIR.parent / "Data").is_dir()
):
    PROJECT_DIR = PROJECT_DIR.parent
    os.environ["AA_PROJECT_DIR"] = str(PROJECT_DIR)  # this session only
    source = "the folder above this notebook"
print(f"Project folder: {PROJECT_DIR} (from {source})")

1. Set parameters

set_params changes only the settings you pass and saves them with the project (inside Data/aa.duckdb in the project folder, or in the JSON file named by the AA_CONFIG_PATH environment variable if you set one). It is the Python twin of aa set-params --sample-start 1963 --sample-end 2024. The sample window controls what the build pulls from WRDS; changing it after a build needs a rebuild.

cfg = set_params(sample_start=1963, sample_end=2024)
print(cfg.database_path)

2. Build the database

This is the long step: a from-scratch build takes a few hours and downloads about 10 GB (CRSP, Compustat and the Chen–Zimmerman anomaly zoo). It reads your WRDS credentials from WRDS_USERNAME / WRDS_PASSWORD, ~/.pgpass or your keyring.

The cell is guarded by RUN_BUILD so that re-running the notebook never starts a build by accident. Set it to True once, run the cell, then set it back. Many people prefer to run aa setup-database in a terminal instead, which does the same.

RUN_BUILD = False   # set to True to (re)build the database
DEMO = False        # True: synthetic data, no WRDS needed (not for research)

if RUN_BUILD:
    db = aa.setup_database(demo=DEMO)
    print(f"Built {db}")
else:
    print("Skipping the build; using the existing database at", cfg.database_path)

3. Check the settings and load data

aa show-config lists every setting with its value and the aa set-params flag that changes it. The ! prefix runs a shell command from the notebook; this needs the environment where you installed the package to be the one Jupyter runs in.

!aa show-config

aa.load pulls columns from the monthly stock panel. With panel=True you get a DataFrame indexed by (date, permno): here monthly returns ret, market equity me (in millions) and a flag for NYSE listing, used for NYSE breakpoints. The full list of columns is in the panel column dictionary.

panel = aa.load({"ret", "me", "nyse_flag"}, panel=True).sort_index()
dates = panel.index.get_level_values("date")
print(f"{len(panel):,} stock-months, {dates.min():%Y-%m} to {dates.max():%Y-%m}")
panel.head()

4. A univariate portfolio sort

Each month, sort stocks into size quintiles on NYSE breakpoints and hold value-weighted portfolios for the next month. print_results=True prints the average excess return of each portfolio and of the long-short spread (top minus bottom quintile), with t-statistics and factor-model alphas.

res = aa.run_univariate_sort(
    returns=panel["ret"],
    signal=panel["me"],
    mcap=panel["me"],
    n_bins=5,
    breaks="NYSE",
    nyse_flag=panel["nyse_flag"],
    weighting="v",
    print_results=True,
)

The long-short portfolio buys the top quintile and sells the bottom one, so with size as the signal it is big minus small: its negative average is the size premium. The result object keeps the time series as well as the summary; res.long_short is the monthly long-short return (decimal).

ls = res.long_short.dropna()
print(f"Size long-short: {100 * ls.mean():.2f}%/month over {len(ls)} months")
(1 + ls).cumprod().plot(logy=True, title="Size quintile spread, growth of $1");

5. A Fama–MacBeth regression

Each month, regress the cross-section of returns (in percent) on log size and momentum (R12_2, the return from month t−12 to t−2), then average the monthly slopes and report Newey–West t-statistics. time_period=196307 starts the regressions in July 1963. In the printout, var 1 is log size and var 2 is momentum, in the order they were passed.

df = aa.load({"ret", "me", "R12_2"}, panel=True).sort_index()
fm = run_fama_macbeth(100 * df["ret"], [aa.log(df["me"]), df["R12_2"]], time_period=196307)
fm.print_results()

6. Test a signal with the full protocol

aa.test_signal runs the battery of tests from Novy-Marx and Velikov (2026) on a candidate predictor: portfolio sorts, factor-model alphas, trading-cost-adjusted performance, Fama–MacBeth regressions and comparisons with about 160 published anomalies. It writes a LaTeX report with figures.

The signal goes in as a long CSV with columns permno, dates (YYYYMM) and one column named after the signal's acronym. Here we write one from a column the database already has, book-to-market (bm). Since value is itself a well-known anomaly, the report should tell us this "new" signal is not new.

sig = aa.load({"bm"}, panel=True)["bm"].dropna()
sig = sig.rename("BM").reset_index()
sig["dates"] = sig["date"].dt.year * 100 + sig["date"].dt.month   # month-end -> YYYYMM
sig = sig[["permno", "dates", "BM"]]

signal_csv = PROJECT_DIR / "bm_signal.csv"
sig.to_csv(signal_csv, index=False)
print(f"Wrote {len(sig):,} rows to {signal_csv}")
sig.head()

The full protocol takes about two hours on a 16-core machine. QUICK = True cuts that to about 40 minutes by comparing the signal with only the first 25 zoo anomalies and skipping the generalized-alpha step; the output is then a smoke test, not a result. Set QUICK = False for the real thing (the same run as aa run-protocol). The evaluation window is inferred from the signal; pass time_period=(197501, 202112) to fix it.

QUICK = True

info = {
    "authors": "Your Name",
    "paper_title": "Your Paper",
    "signal_name": "Book-to-market",
    "acronym": "BM",
}
quick = {"max_anoms": 25, "compute_gen_alpha": False} if QUICK else {}
OUT_DIR = scratch_dir()  # Scratch/Assay in the project folder
result = aa.test_signal(signal_csv, info, out_dir=OUT_DIR, **quick)
print(result.tex_path)

The run writes, under Scratch/Assay/ in the project folder, BM_Results.pkl (every number in the report), BM_manifest.json (code version, data, settings and seeds, so the run can be reproduced) and the report under tex/. Compile it with latexmk -pdf BM.tex in that folder.

sorted(p.name for p in OUT_DIR.rglob("*") if p.is_file())

Where next

The tutorial covers each step in depth, starting with the end-to-end tour; the analytics API reference lists the public functions.