Chapter 1 — Architecture, install, config, CLI¶
Part I of the assayinganomalies tutorial. Prerequisite chapters: none. Python modules covered:
__init__.py,config.py,cli.py,client.py; alsopyproject.toml.
What this chapter answers¶
- How the installable package is laid out under
src/, and what installing it actually exposes. - What the 43 names in
__all__are, and which later chapter owns each one. - What each
AssayConfigfield controls and what its default is. - How the project folder (and so the database) is found, and when config lives in DuckDB's
configtable versus a JSON file behindAA_CONFIG_PATH. - What the four
aaCLI commands do, and howAssayClientrelates to the module-level API.
Where this sits in the pipeline¶
This chapter is the front door. Everything downstream — WRDS ingest, the DuckDB panel, sorts, the assay protocol — reads AssayConfig (or an explicit db_path) and assumes the package was installed so that import assayinganomalies as aa and the aa console script both resolve.
flowchart LR
subgraph entry [Entry points]
CLI["aa CLI<br/>cli.py"]
API["import aa<br/>__init__.py"]
Client["AssayClient<br/>client.py"]
end
CFG["AssayConfig<br/>config.py"]
DB[("DuckDB<br/><project>/Data/aa.duckdb")]
PIPE["setup_database<br/>Ch 4+"]
AN["analytics / protocol<br/>Ch 12+"]
CLI --> CFG
API --> CFG
Client --> CFG
CFG --> DB
CLI --> PIPE
API --> PIPE
PIPE --> DB
Client --> AN
API --> AN
DB --> AN
Installing the package makes it importable; the only path to set up is the project folder (aa set-params --project-dir), which holds the one DuckDB file, and settings live in AssayConfig.
Packaging: pyproject.toml and the src/ layout¶
Why src/¶
[tool.setuptools]
package-dir = {"" = "src"}
setuptools is told that importable packages live under src/, not the repo root. That means pip install -e . puts src/assayinganomalies/ on sys.path as the package assayinganomalies. Tests and scripts that do import assayinganomalies therefore hit the installed (editable) copy, not an accidental shadow from a loose folder named the same way at the repo root.
Installing¶
The package is on PyPI as assayinganomalies (releases start at 0.9.0). The README has the full instructions; the three environment managers are equivalent:
# conda
conda create -n assaying-anomalies python=3.11
conda activate assaying-anomalies
pip install "assayinganomalies[analytics]"
# python -m venv
python3 -m venv .venv # Windows: py -3.11 -m venv .venv
source .venv/bin/activate # Windows: .venv\Scripts\activate
python -m pip install --upgrade pip
python -m pip install "assayinganomalies[analytics]"
# uv (a uv environment has no pip of its own: always `uv pip`)
uv venv --python 3.11 .venv
source .venv/bin/activate # Windows: .venv\Scripts\activate
uv pip install "assayinganomalies[analytics]"
Pin a version to reproduce a result ("assayinganomalies[analytics]==0.9.0"). assayinganomalies.__version__ and aa --version print the installed version; database builds and protocol runs record it in their manifests (code.package_version) and the report prints it in its first footnote. For a development state, pip install "assayinganomalies[analytics] @ git+https://github.com/velikov-mihail/AssayingAnomalies" installs from the repository. To work on the code itself, clone it and install it editable from inside the source folder: pip install -e ".[analytics]".
Then check that aa is the one you just installed: which aa (macOS/Linux), where aa (Command Prompt) or Get-Command aa (PowerShell). zsh, the macOS default, caches command locations, so if you ran aa before installing into an environment that was already active, run rehash (bash: hash -r) and check again. See Check which aa you are running.
Runtime dependencies and extras¶
Core deps (click, duckdb, pandas, wrds, …) install with the package. The [analytics] extra adds what the protocol needs for its figures, its TeX templating (Ch 19) and the combination strategies: matplotlib, seaborn, jinja2, scipy and scikit-learn.
Console script¶
[project.scripts]
aa = "assayinganomalies.cli:main"
After install, the shell command aa invokes cli.main (a Click group). Equivalent: python -m assayinganomalies only if a __main__.py exists — today the supported entry is the aa script.
py.typed¶
[tool.setuptools.package-data]
assayinganomalies = ["py.typed"]
src/assayinganomalies/py.typed is an empty PEP 561 marker shipped as package data. Its presence tells type checkers (mypy, pyright) that the installed distribution is typed and that they may trust inline annotations on public APIs. It does not change runtime behavior.
Public surface: __init__.py¶
"""
Public entry points for the Assaying Anomalies Python toolkit.
"""
from __future__ import annotations
from pathlib import Path
from typing import Iterable, Mapping, MutableMapping, Sequence
from .client import AssayClient
from .config import AssayConfig, load_config, save_config, set_params
from .data_access import (
load,
load_cz_anomalies,
load_nmv_anomalies,
list_cz_signals,
get_cz_signal_info,
describe_cz_signal,
)
from .analytics import (
calc_ptf_rets,
calc_tcosts,
est_factor_regs,
ibbots,
load_factors,
make_ff_tcosts,
moving,
nanols,
plot_anomaly_decay,
prt,
run_anomaly_decay,
run_bivariate_sort,
run_fama_macbeth,
run_univariate_sort,
)
# ... also ingest, transforms, ops, pipeline, protocol, signal_io, reporting ...
The module does one job: re-export the names a day-to-day user should type as aa.<name>. Implementation lives in the submodules; this file is the index. __all__ lists 43 exports (verified at import time). Two small wrappers (set_params_cli, load_fields) sit below __all__ and are not part of the advertised public surface.
Tutorial index — every name in __all__¶
| Export | One-line role | Chapter |
|---|---|---|
AssayClient |
Stateful session wrapper around config + load + a few analytics methods |
1 |
AssayConfig |
Persisted parameters (sample window, tcosts type, WRDS user, …) | 1 |
load_config / save_config / set_params |
Read / write / update config | 1 |
setup_database |
Run the ordered DuckDB build pipeline | 4 |
load_ff25 |
Load FF 25 portfolios (ingest helper) | 5 |
fill_var / check_fill_anomalies |
Anomaly panel fill / QA | 11 |
load / load_cz_anomalies / load_nmv_anomalies / list_cz_signals / get_cz_signal_info / describe_cz_signal |
Panel and anomaly I/O | 12 |
get_anomaly_signals / load_signal_csv / get_signal_info / default_mpe_signal_info |
User-signal I/O for the protocol | 12 |
run_univariate_sort / run_bivariate_sort / calc_ptf_rets / est_factor_regs / load_factors |
Portfolio sorts and factor regressions | 13 |
run_fama_macbeth / nanols / prt / log |
Cross-sectional FM, OLS utility, safe log | 14 |
calc_tcosts / make_ff_tcosts / run_anomaly_decay / plot_anomaly_decay |
Portfolio costs and anomaly decay | 15 |
SignalTester / SignalInfo / ProtocolResult / run_test_signal / test_signal |
Assay protocol entry points | 16 |
PrintResults / make_res_to_print / print_tex_file / semantic_tex_diff |
Packed printResults + TeX + TeX comparison | 19 |
ibbots / moving |
Cumret / moving-average plot helpers | 19 |
set_params_cli(**kwargs)¶
Signature
**kwargs— forwarded unchanged toset_params.
Returns — an AssayConfig (whatever set_params returned).
What it does — one-line passthrough:
def set_params_cli(**kwargs: object) -> AssayConfig:
"""
Convenience wrapper used by the CLI to update parameters.
"""
return set_params(**kwargs)
The docstring claims CLI use; cli.py actually imports set_params directly. Dead indirection today (candidate for deletion).
load_fields(fields, *, path=None, **kwargs)¶
Signature
fields: Iterable[str] | Mapping[str, str]— column names (or rename map) passed toload.path: str | Path | None— DuckDB path;None→ config default.**kwargs— forwarded toload(panel,wide,filters, …).
Returns — whatever load returns (typically a (date, permno) MultiIndex DataFrame for panel loads).
What it does — swaps argument order so fields is positional, for scripts that lead with the field list; no numeric effect:
def load_fields(
fields: Iterable[str] | Mapping[str, str],
*,
path: str | Path | None = None,
**kwargs: object,
):
"""
Thin wrapper around :func:`load` for parity with MATLAB-style scripts.
"""
return load(path=path, fields=fields, **kwargs)
Not listed in __all__; still importable as aa.load_fields because it is defined on the package module. Detail of load itself is Ch 12.
Configuration: config.py¶
A @dataclass is a class whose __init__, __repr__, and field storage are generated from annotated class attributes. AssayConfig is one: constructing AssayConfig(sample_start=1975) fills the other fields from their defaults.
The fields at a glance¶
AssayConfig field |
Default | Notes |
|---|---|---|
database_path |
<project folder>/Data/aa.duckdb |
One DuckDB file; path is not written into the DB config table. See Finding the project folder |
sample_start |
1963 |
Start of the common CRSP/Compustat research window; set 1925 for the full CRSP history |
sample_end |
"latest" |
The last complete calendar year on the WRDS tapes when setup-database runs, or a year such as 2024; see below |
dom_com_eq |
True |
Share codes 10/11 filter |
compustat_variables |
"compustat_variables.csv" (packaged) |
CSV with columns Annual,Quarterly (file name or path) or 'All'; see Ch 5 |
tcosts_type |
"lf_combo" |
Gibbs + three low-frequency spreads, so a fresh machine needs no high-frequency TAQ file; 'full' adds the HF effective spreads |
wrds_username |
None |
Password is not stored; see WRDS client (Ch 5) |
cz_release_version |
None (= the newest on Hugging Face when the build runs; 2026.10 today) |
Chen–Zimmerman release label, e.g. "2024.10" (legacy "2022-03" also parses); pin one to reproduce a zoo; see Ch 5 |
cz_signal_doc_path |
None |
Local SignalDoc.csv override (default: the release's own) |
cz_signals_path |
None |
Local signal panel (signed_predictors_dl_wide .parquet/.csv/.zip) read instead of staging or a download |
crsp_format |
"ciz" |
Which CRSP tape to build from ("siz" | "ciz"). See below |
Credentials live in env vars / the OS keyring / a prompt, never in AssayConfig.
AssayConfig¶
Signature — dataclass fields as in the table above. database_path uses field(default_factory=_default_database_path) so each instance snapshots <project folder>/Data/aa.duckdb (via resolve_project_dir) at construction time rather than sharing one mutable Path object.
@dataclass
class AssayConfig:
"""Container for persisted configuration values."""
# database_path is special: derived from the project folder (see
# resolve_project_dir), not stored in the database
database_path: Path = field(default_factory=_default_database_path)
sample_start: int = 1963
sample_end: int | str = LATEST_SAMPLE_END # "latest", or a year
dom_com_eq: bool = True
compustat_variables: str = "compustat_variables.csv"
# Default lf_combo: Gibbs + 3 LF spreads; no HF TAQ required (safer on new machines).
# For numeric parity with reference tcosts.mat (built with Params.tcostsType='full'),
# set tcosts_type='full' and ensure hf_monthly.csv is discoverable — MATLAB must match.
tcosts_type: str = "lf_combo"
wrds_username: str | None = None
# ...
crsp_format: str = DEFAULT_CRSP_FORMAT # "ciz"
_DB_FIELDS = (
"sample_start",
"sample_end",
"dom_com_eq",
"compustat_variables",
"tcosts_type",
"wrds_username",
"cz_release_version",
"cz_signal_doc_path",
"cz_signals_path",
"protocol_n_jobs",
"memory_budget_gb",
"crsp_format",
)
def __post_init__(self) -> None:
fmt = str(self.crsp_format or "").strip().lower()
if fmt not in VALID_CRSP_FORMATS:
raise ValueError(...)
self.crsp_format = fmt
__post_init__ is the dataclass hook that runs right after the generated
__init__ finishes; it is where a dataclass validates or normalizes what it was
handed. Here it lower-cases and strips crsp_format and rejects anything that
is not "siz" or "ciz", so a typo fails at construction rather than three
hours into a build.
Returns — N/A (container type).
What it does
to_dict()— full payload includingdatabase_pathas a string (JSON path).to_db_dict()— only_DB_FIELDS(what the DuckDBconfigtable stores).from_dict(payload)— rebuild from JSON; coercesdatabase_pathtoPath; drops deprecatedcz_data_path.from_db_dict(payload, database_path)— rebuild from DB rows, injecting the path explicitly; filters unknown keys so older DBs with stray columns still load.
crsp_format — which CRSP tape the database is built from¶
CRSP froze the legacy stock tape in January 2025. That tape — Flat File
Format 1.0, called SIZ — is crsp.msf, crsp.dsf, msedelist,
dsedelist, mseexchdates, stocknames, msfhdr, and it stops at December
- Everything after that exists only on Flat File Format 2.0, CIZ:
crsp.msf_v2,crsp.dsf_v2,stkdelists,stksecurityinfohist,stocknames_v2.crsp_formatpicks one:
aa set-params --crsp-format siz # only to go back to the legacy tape
aa setup-database --full-refresh
The dataclass default is "ciz" (DEFAULT_CRSP_FORMAT), so a fresh
install builds from the live tape without passing the flag at all.
Three rules govern the field, and each exists to stop a silent mistake:
- Validation at construction.
__post_init__rejects anything outsideVALID_CRSP_FORMATS = ("siz", "ciz"). - The legacy rule. A persisted config with no
crsp_formatkey was necessarily built from SIZ — it predates the CIZ option — so_load_config_from_db(and_load_config_from_file, for theAA_CONFIG_PATHJSON) fills inLEGACY_CRSP_FORMAT = "siz"and logs an INFO line, rather than adopting whatever the current dataclass default happens to be. This is the one place where "the default" and "what an old build gets" are deliberately decoupled, so making CIZ the default did not retroactively reinterpret a single existing database. Two constants, on purpose:DEFAULT_CRSP_FORMAT = "ciz"is what a new build reads;LEGACY_CRSP_FORMAT = "siz"is what an old one keeps. - No mixing.
setup_databasecompares the requested format against thecrsp_formatkey in the database'smetadatatable and refuses to proceed if they differ, unless you pass--full-refresh. The chunked daily fetch stamps its source into the resume manifest for the same reason, so an interrupted pull cannot be resumed against the other tape.
The two tapes disagree about more than table names — units, the sign of prc,
how share and exchange codes are encoded, and whether the monthly return already
contains the delisting payoff. All of that lives behind CRSPSource (Ch 5); no
code outside ingest/crsp_source.py branches on crsp_format.
Which one should you use? CIZ — it is the default. Choose SIZ only to reproduce results built from the legacy tape through December 2024, such as output from the original MATLAB toolkit, which reads only SIZ.
sample_end — latest or a year¶
sample_end is either a year (2024) or the sentinel "latest"
(LATEST_SAMPLE_END), the default. "latest" means the last complete
calendar year on the WRDS tapes when setup-database runs:
- Right after the WRDS login (
_preflight_credentials), the preflight_preflight_sample_endasks, on the same session, for the last month and the last December month on the tape's monthly stock file (CRSPSource.monthly_table:crsp.msf_v2.mthcaldtfor CIZ,crsp.msf.datefor SIZ;CRSPSource.tape_end_sql()), and the same on Compustatcomp.funda(datadate, with the standardindfmt/datafmt/consol/popsrcfilters). - Complete-year rule: the year is the earlier of the two last-December
years (
ingest/sample_end.py: resolve_latest_sample_end). A year whose December is not on both tapes yet is incomplete and left out: a build in March 2026 resolves to 2025 even though CRSP already has January 2026. - SIZ clamp: CRSP froze SIZ in January 2025, so
SIZSource.frozen_end_yearis 2024 (SIZ_FROZEN_END_YEAR) and"latest"on SIZ resolves to at most- An explicit year past it (
--sample-end 2025with--crsp-format siz) is lowered to 2024 with a warning before anything else runs (_clamp_sample_end_for_tape). CIZ is never clamped.
- An explicit year past it (
- Demo builds have no tape to ask and use
DEMO_SAMPLE_END(2024), so they do not depend on the date. - Runs that fetch nothing (
--start-froma stage after the WRDS fetches, arebuildwithout refetch) do not log in: they reuse the year the last build recorded, so the transforms see the window the staged extracts were fetched with. A database with no recorded year raisesSampleEndUnresolvedError, whose message names both fixes.
The config keeps "latest"; the build works on a copy holding the year
(AssayConfig.with_sample_end), so every stage still sees an int. Because the
memory check needs the year, it runs after the login when sample_end is
"latest" and before it (as always) for an explicit year.
Where the year is recorded. The database's metadata table keeps
sample_end (the resolved int, as before) and adds sample_end_requested
(latest or the year), sample_end_resolved, sample_end_source
(wrds, metadata, demo, explicit or clamped-siz), crsp_tape_max_date,
crsp_tape_last_december, compustat_max_datadate and
compustat_last_december. aa show-config prints latest (resolved to 2025 by
the last build); AssayConfig.resolved_sample_end() returns the year (an
explicit year as is, else the recorded one). The run manifest's identity carries
the year only (scientific.sample.end_year, settings.sample_end), so a
latest build and one pinned to the same year have the same scientific_id;
data_vintage says what was requested and the tapes' last dates
(Ch 4).
Pin a year for a paper. "latest" moves when CRSP publishes another
December, so a rebuild a year later covers a longer window and changes every
number. For results you will publish, pin the year:
aa set-params --sample-end 2025 # any year the tape covers
aa setup-database --full-refresh # a sample change requires a full rebuild
A persisted year is kept as it is: a database whose settings already store
2025 keeps building through 2025 after this default changed.
The package's regression snapshots come from reference builds that end at
December 2024 (sample_start=1925, sample_end=2024), and a comparison of SIZ with CIZ
only isolates the tape when both builds cover the same window; pin
--sample-end 2024 to reproduce either
(Ch 20, Golden snapshots).
Dual persistence: DuckDB config table vs AA_CONFIG_PATH JSON¶
Resolution order for load:
- Explicit
path=argument toload_config/set_params→ that JSON file. - Else env
AA_CONFIG_PATH(or legacyASSAYINGANOMALIES_CONFIG_PATH) → JSON file (if the env value is a directory, appendconfig.json). - Else DuckDB at
<project folder>/Data/aa.duckdb, tableconfig(key TEXT PRIMARY KEY,value TEXTholding JSON-encoded scalars).
Save follows the same fork. Default mode is per-project: config rides inside the project folder's database, so two projects do not share settings. Set AA_CONFIG_PATH when you want one JSON file shared across projects or checked into version control.
Finding the project folder¶
resolve_project_dir(project_dir=None) -> (folder, source) picks the project folder, first match wins:
- The
project_dir=argument (load_config(project_dir=...),set_params(project_dir=...)): this call only, not saved. Source"argument". - The
AA_PROJECT_DIRenv var: one terminal session. Source"AA_PROJECT_DIR". - The folder saved by
set_project_dir(path)/aa set-params --project-dir, kept inplatformdirs.user_config_dir("assayinganomalies")/settings.jsonas{"project_dir": "..."}. That file holds only the pointer; research settings stay in the database. Source"saved in <file>". - The current folder. Source
"current folder".
A folder from step 2 or 3 that does not exist raises ProjectDirError rather than falling back silently. scratch_dir() is <folder>/Scratch/Assay, the default output root. set_project_dir creates the folder if needed and writes the settings file atomically (temp file, then os.replace).
require_database(cfg_or_path=None) is the guard for readers: it raises DatabaseNotFoundError when the database is missing or holds nothing but the config table (only set-params has run), naming the path, where the folder came from, and the two fixes. Every data_access reader and aa run-protocol call it, so a wrong folder fails loudly instead of DuckDB creating an empty file. The user-facing guide is The project folder.
Either way, settings persist between sessions: set_params saves immediately, and every later command reads the saved values.
load_config(path=None, *, project_dir=None)¶
Signature
path: Path | None— optional JSON path override.project_dir: str | Path | None— project folder for this call only (see Finding the project folder).
Returns — AssayConfig. If the DuckDB file or config table is missing, returns defaults with database_path set to the project folder's database. Corrupt DB reads also fall back to defaults, with a logged warning naming the file.
What it does — implements the three-way resolution above via _get_config_file_path, _load_config_from_file, _load_config_from_db.
def load_config(
path: Path | None = None, *, project_dir: str | Path | None = None
) -> AssayConfig:
"""
Load configuration.
Resolution order:
1. If `path` argument is provided → use that JSON file
2. If AA_CONFIG_PATH env var is set → use that JSON file
3. Otherwise → load from the database, <project>/Data/aa.duckdb, where
the project folder is `project_dir` (this call only) or as found by
:func:`resolve_project_dir`
"""
if path is not None:
return _load_config_from_file(Path(path).expanduser())
cfg_file = _get_config_file_path()
if cfg_file is not None:
return _load_config_from_file(cfg_file)
# Default: load from database
return _load_config_from_db(_database_path_for(project_dir))
save_config(config, path=None, *, project_dir=None)¶
Signature
config: AssayConfig— values to persist.path: Path | None— optional JSON override; same env-var fork as load.project_dir: str | Path | None— save into this project folder's database instead ofconfig.database_path.
Returns — None.
What it does — JSON dump of to_dict(), or INSERT OR REPLACE of each _DB_FIELDS entry as json.dumps(value) into DuckDB. Ensures parent directories / the config table exist.
set_params(*, path=None, project_dir=None, **kwargs)¶
Signature
path: Path | None— optional JSON override.project_dir: str | Path | None— write to this project folder's database (this call only;set_project_dirsaves a folder).**kwargs— must be existingAssayConfigattribute names (sample_start,tcosts_type, …); unknown keys raiseAttributeError.
Returns — the updated AssayConfig after save.
What it does — load_config → setattr each kwarg → save_config. Both the functional API (aa.set_params(sample_start=1975)) and aa set-params --sample-start 1975 go through this.
def set_params(*, path: Path | None = None, **kwargs: Any) -> AssayConfig:
"""
Update configuration values programmatically.
...
"""
cfg = load_config(path)
for key, value in kwargs.items():
if not hasattr(cfg, key):
raise AttributeError(f"Unknown config field: {key}")
setattr(cfg, key, value)
save_config(cfg, path)
return cfg
The change persists immediately; there is no separate save step.
ensure_config_dir(path=DEFAULT_CONFIG_DIR)¶
Signature
path: Path = Path.home() / ".assayinganomalies"— legacy home-dir config location.
Returns — None. Creates path with mkdir(parents=True, exist_ok=True).
What it does — leftover from when config defaulted to ~/.assayinganomalies/config.json. Default persistence no longer uses that directory; the constants DEFAULT_CONFIG_DIR / DEFAULT_CONFIG_PATH remain exported for backwards compatibility. Likely dead for new workflows.
Small helpers (config.py)¶
| Name | Role |
|---|---|
_default_database_path() |
resolve_project_dir()[0] / "Data" / "aa.duckdb" |
_user_settings_path() |
platformdirs.user_config_dir("assayinganomalies") / "settings.json"; a function so tests can redirect it |
_get_config_file_path() |
Read AA_CONFIG_PATH / legacy env; append config.json if a directory |
_ensure_config_table(con) |
CREATE TABLE IF NOT EXISTS config (key, value) |
_load_config_from_db(db_path) |
Open DuckDB, JSON-decode rows, from_db_dict; defaults on missing/unreadable DB |
_save_config_to_db(config) |
Upsert _DB_FIELDS as JSON strings |
_load_config_from_file(cfg_path) |
Load JSON, or auto-create defaults (with resolved absolute database_path) if missing |
_save_config_to_file(config, cfg_path) |
Pretty-printed JSON dump |
CONFIG_PATH_ENV / LEGACY_CONFIG_PATH_ENV |
"AA_CONFIG_PATH" / "ASSAYINGANOMALIES_CONFIG_PATH" |
PROJECT_DIR_ENV |
"AA_PROJECT_DIR" |
DEFAULT_CONFIG_DIR / DEFAULT_CONFIG_PATH |
Legacy ~/.assayinganomalies[/config.json] |
CLI: cli.py¶
Click builds a command group. @click.group() on main makes aa a dispatcher; each @main.command("…") is a subcommand. Options become kwargs; missing optional flags arrive as None and are filtered out before set_params.
main¶
Signature — Click group; no user parameters.
Returns — N/A.
What it does — registers subcommands; docstring becomes aa --help text. The group class (_Group) turns ProjectDirError / DatabaseNotFoundError into a plain Error: message, and its command class (_Command) prints Using database: <path> (project folder: <dir>, from <source>) on stderr before each command runs. That happens in invoke, after option parsing, so --help prints nothing extra.
set-params (set_params_cmd)¶
Signature (Click options → kwargs) — one option per AssayConfig field, in
field order, each under both spellings: --sample-start and --sample_start both
set sample_start. The type comes from the field's annotation:
| Field type | Option | Example |
|---|---|---|
int / float (or … \| None) |
typed value | --sample-start 1975, --memory-budget-gb 48 |
bool |
on/off pair | --dom-com-eq / --no-dom-com-eq |
crsp_format, tcosts_type |
click.Choice |
--crsp-format [siz\|ciz], --tcosts-type [full\|lf_combo\|gibbs] |
Path, or a name ending in _path |
path, stored absolute; '' clears |
--gibbs-path '' |
| anything else | text | --wrds-username me |
--cz-release-version is checked against the known releases (latest clears it).
--project-dir is the one option that is not a config field: it saves the project
folder (set_project_dir), then applies any other flags to that project's database.
--database-path only works with AA_CONFIG_PATH set, where the JSON stores it;
without it, the database is always <project folder>/Data/aa.duckdb, so the option is
an error pointing at --project-dir. With no project folder set, set-params warns
that it is using the current folder.
Only options the user actually passed (is not None) are forwarded to set_params.
Returns — prints Config saved (database: …).
What it does
def _config_option(fld: dataclasses.Field, hint):
"""One click option for one AssayConfig field, both spellings accepted."""
name = fld.name
dashed, underscored = config_flag(name), "--" + name
kind = _base_type(hint)
... # bool -> "--x/--no-x"; Choice / int / float / Path picked from the hint
return click.option(*decls, name, **kw)
def _with_config_options(func):
"""Attach one option per AssayConfig field to the command ``func``."""
hints = typing.get_type_hints(AssayConfig)
for fld in reversed(dataclasses.fields(AssayConfig)):
func = _config_option(fld, hints[fld.name])(func)
return func
@main.command("set-params")
@_with_config_options
def set_params_cmd(**kwargs):
# None = flag not given; the _CLEAR sentinel = "set this back to None".
updates = {
k: (None if v is _CLEAR else v) for k, v in kwargs.items() if v is not None
}
cfg = set_params(**updates)
click.echo(f"Config saved (database: {cfg.database_path})")
The options are generated, not written out. @click.option(...) above a function is
shorthand for f = click.option(...)(f), so the decorators can be applied in a loop
over dataclasses.fields(AssayConfig) instead of writing each call by hand. A
new config field therefore gets a flag with no CLI change; help
text, choices and validators the annotation cannot express sit in three small tables
in cli.py (_FIELD_HELP, _FIELD_CHOICES, _FIELD_CALLBACKS).
click.Choice(..., case_sensitive=False) rejects a bad tape name at the CLI
boundary with a usage message, before AssayConfig.__post_init__ ever sees it;
the dataclass check is the backstop for callers coming in from Python.
There is no password option: the CLI never accepts a WRDS password.
show-config (show_config_cmd)¶
Signature — --json prints the raw load_config().to_dict() instead (plus
project_dir when no AA_CONFIG_PATH is set).
Returns — the project folder and where it came from, then one line per field:
the set-params flag that changes it (from the same config_flag function that
names the options) and its current value, e.g.
--project-dir /home/you/research/aa (from saved in /home/you/.config/assayinganomalies/settings.json)
--sample-start 1963
--gibbs-path (not set)
setup-database (setup_database_cmd)¶
Signature
--full-refresh— rebuild all tables from scratch.--verbose— verbose pipeline logging.--start-from STAGE— skip stages beforeSTAGE(e.g.transform-crsp-daily); earlier stages must already have succeeded.
Returns — prints Database ready at {path}.
What it does — delegates to pipeline.setup_database (Ch 4). This chapter only owns the Click wiring:
@main.command("setup-database")
@click.option("--full-refresh", is_flag=True, help="Rebuild all tables from scratch.")
@click.option("--verbose", is_flag=True, help="Enable verbose setup logging.")
@click.option(
"--start-from",
type=str,
default=None,
help="Skip stages before this one (e.g. 'transform-crsp-daily'). "
"Earlier stages must have already completed successfully.",
)
def setup_database_cmd(full_refresh: bool, verbose: bool, start_from: str | None):
path = setup_database(full_refresh=full_refresh, verbose=verbose, start_from=start_from)
click.echo(f"Database ready at {path}")
The build is a staged pipeline, so an interrupted run restarts from the failed stage with --start-from instead of starting over.
run-protocol (run_protocol_cmd)¶
Signature (selected options)
| Option | Role |
|---|---|
--signal PATH |
Signal CSV; default prefers AssayingAnomalies-MATLAB/mpe.csv (a source checkout that includes the original toolkit), else ./mpe.csv |
--out-dir PATH |
Assay root (default Scratch/Assay in the project folder, the output location of the original MATLAB toolkit) |
--tex-dir PATH |
TeX/PDF dir (default {out-dir}/tex) |
--max-anoms N |
Cap CZ zoo size (dev smoke) |
--time-period YYYYMM YYYYMM |
Sample window |
--tcosts-type |
Label stored in printResults text |
--no-tex / --no-figures / --no-print-results / --no-save |
Skip artifacts |
--db-path (or --database-path) |
DuckDB override |
--n-jobs (or --protocol-n-jobs) |
Process-pool size |
--quiet |
Less stage logging |
Returns — echoes a JSON summary (minus stage_log), plus paths to the results pickle and TeX when present.
What it does — checks the database with require_database (a missing or settings-only database stops here, before any work), builds MPE signalInfo via default_mpe_signal_info, then calls test_signal(...) (Ch 16).
repo_mpe = Path("AssayingAnomalies-MATLAB") / "mpe.csv"
if signal_path is None:
if repo_mpe.is_file():
signal_path = repo_mpe.resolve()
else:
signal_path = Path("mpe.csv")
info = default_mpe_signal_info(file_link=signal_path)
if out_dir is None:
out_dir = scratch_dir()
# ... flag → kwargs ...
result = test_signal(signal_path, info, **kwargs)
Session class: client.py¶
Why both module-level functions and AssayClient?¶
Day-to-day scripts can stay fully functional (aa.set_params, aa.load, aa.run_univariate_sort). AssayClient is for workflows that want a small object holding config + db_path so every load does not re-resolve paths. It is intentionally thin: only load, lag, run_univariate_sort, and run_fama_macbeth are methods today. Everything else stays on the aa module (or is imported from subpackages).
@dataclass(slots=True) means instances get a fixed attribute set (config, db_path) without a per-instance __dict__ — slightly leaner, and assigning a typo attribute raises AttributeError instead of silently creating a new field.
AssayClient¶
Signature
- Fields:
config: AssayConfig,db_path: Path. AssayClient.from_config(cfg=None)— classmethod; loads config if omitted, setsdb_path=config.database_path.load(fields, **kwargs)—data_access.load(..., path=self.db_path, **kwargs).lag(series, periods=1)— ifserieshas a MultiIndex,groupbythepermnolevel (or level 0) andshift; else plainshift. This is the pandas spelling of lagging a firm panel without peeking across permnos — the long-panel equivalent of shifting a months × stocks matrix down one row.run_univariate_sort/run_fama_macbeth— pure forwards to the analytics functions (no extra binding ofdb_path).
@dataclass(slots=True)
class AssayClient:
"""Stateful helper exposing ergonomic methods for everyday analysis."""
config: AssayConfig
db_path: Path
@classmethod
def from_config(cls, cfg: AssayConfig | None = None) -> "AssayClient":
config = cfg or load_config()
return cls(config=config, db_path=config.database_path)
def load(self, fields: Iterable[str] | Mapping[str, str], **kwargs: Any) -> pd.DataFrame:
return data_access.load(fields, path=self.db_path, **kwargs)
def lag(self, series: pd.Series, periods: int = 1) -> pd.Series:
if isinstance(series.index, pd.MultiIndex):
level = series.index.names.index("permno") if "permno" in series.index.names else 0
return series.groupby(level=level).shift(periods)
return series.shift(periods)
# ... run_univariate_sort / run_fama_macbeth forwards ...
Returns — methods return DataFrames / analytics result objects from the underlying functions.
The method surface is a subset of __all__: bivariate sorts, the protocol and the CZ helpers are module-level only.
Path setup: install + project folder¶
An editable or regular install (src/ layout + aa script) makes the package importable everywhere, without mutating sys.path. Everything else is relative to the project folder: data lives in one DuckDB file at <project folder>/Data/aa.duckdb, and aa run-protocol writes assay outputs under <project folder>/Scratch/Assay (creating directories as writers need them). Save the folder once with aa set-params --project-dir <folder> and every command, notebook or IDE finds it from any working directory; see Finding the project folder.