Skip to content

Analytics API

Public analytical surface of assayinganomalies. Everything documented here is importable from assayinganomalies (top level) or the listed submodule. The quickstart notebook, the quickstart, walks through the main entry points end to end.

Conventions:

  • Panels are (date, permno)-indexed pandas Series/DataFrames; monthly dates are month-end Timestamps; returns are decimals.
  • xret/alpha outputs are in percent per month (MATLAB estFactorRegs convention); Sharpe/information ratios are annualized.
  • time_period arguments accept a MATLAB-style YYYYMM integer (sample start), a (YYYYMM, YYYYMM) pair, or Timestamps. Malformed values (e.g. 1963) raise ValueError.

Sorts (analytics.sorts)

run_univariate_sort(returns, signal, mcap, *, n_bins=5, breaks="name", nyse_flag=None, portfolio_mass=None, weighting="v", holding_period=1, time_period=None, add_long_short=True, factor_model=None, tcosts=None, robust_se=False, print_results=False, plot_results=False, convention="dollar") -> SortResult

The sort of MATLAB makeUnivSortInd + runUnivSort (same inputs, breakpoints and statistics) on held legs. Each portfolio is bought in a month in which the signal has values and left alone until the next such month. Returns, costs and turnover describe that one portfolio. The definitions are in the module docstring of analytics/held.py and in Ch 13, Held legs.

  • The data decide when the sort trades. A trade month is a month in which any stock has a portfolio assignment, i.e. a signal value. A signal with values every month is sorted and traded every month, and its gross returns are those of monthly rebalanced portfolios. A signal with values each June is traded each June and held for the year. There is no argument for the schedule; see Ch 13, When a sort trades.
  • Between trades a position grows with the stock's total return (ret): a dividend is reinvested in the stock that paid it, and that purchase is not charged. A return of -100% or less makes the position worthless. The value of a stock that loses its market cap waits in cash until the next trade.
  • The long-short return is the long leg's return minus the short leg's, each on its own value.
  • convention is the size of the two legs after a trade: "dollar" (the default) sets each back to $1; "capital" sets both to the strategy's capital K = 1 + long P&L - short P&L since the previous trade. It changes costs and turnover, not gross returns. Under "dollar" the cost is the same whichever leg is long; under "capital" it is not. Any other value raises ValueError.

  • n_bins: portfolio count (5) or explicit percentile cutoffs ([30, 70] for tertiles, [10, 90] for an extreme-decile-legs sort — the middle bin is inert and the long/short return is top bin minus bottom bin).

  • breaks: "name" (all stocks), "NYSE" (breakpoints from stocks flagged in nyse_flag — any boolean filter works, e.g. exchcd == 3 for NASDAQ breaks), or "cap" (equal total market cap per bin, mass from portfolio_mass, default mcap).
  • weighting: 'v'/'V' value-weighted or 'e'/'E' equal-weighted; anything else raises ValueError (MATLAB runUnivSort input check).
  • factor_model: 1/3/4/5/6 or a user-supplied factor DataFrame (include an rf column so excess returns are formed the same way). Models 5-6 use the five-factor smb2, never smb in its place. Other integers raise ValueError. MATLAB-style stats are computed whenever a factor model is given, including with add_long_short=False.
  • factors: optional explicit factor store for integer models (e.g. the output of load_factors(db_path)). The model's columns and rf are selected from it by name and no database is opened. Without it, integer models load factors from the configured database. run_bivariate_sort, est_factor_regs, make_basic_sorts_results and make_close_anom_results take the same argument.
  • tcosts: three forms —
    • scalar: subtracted from the long-short return (long_short_net);
    • date-indexed Series: aligned and subtracted from the long-short return;
    • per-stock panel ((date, permno)-indexed Series of decimal effective half-spreads, e.g. the tcost or tcost_gibbs columns): priced on the trades of the two extreme legs, populating the SortResult trading-cost block (below). At a trade a leg of size s moves from its holdings D to s × target weights, and pays sum(|s × target - D| × half-spread) over its value entering the month. The first purchase (sum(target × half-spread) per leg, the same under both conventions) is not in the cost series: it is reported as one number, entry_cost, and net returns do not charge it. Every later trade is booked in its own month. A stock without a market cap in the trade month is not traded; a stock without a half-spread is traded for free. Needs add_long_short=True and at least two portfolios; otherwise no cost block is returned.
  • holding_period: with a value above 1 the portfolios are not held legs: every month each leg earns the return of fresh target weights over the union of the last holding_period formations (calc_ptf_rets). Gross returns only: a per-stock tcosts panel with holding_period > 1 raises ValueError.
  • Under "capital", if K is zero or negative at a trade (the pair lost at least everything since the previous trade), the strategy starts again with $1 legs, that trade is charged as the move from what is held to those legs, and a warning is logged. metadata["capital_restarts"] counts such trades. "dollar" has no K and no restart.

SortResult

Dataclass mirroring the MATLAB Res struct:

  • core: leg_returns, long_short, long_short_net, metadata, ptf_num_stocks, ptf_market_cap; convenience properties pret (legs + long_short column) and dates.
  • MATLAB-style stats (%/mo where applicable): xret, txret, alpha, talpha, sharpe, info, resid, r2_adj, plus factor_loadings / factor_loading_tstats and legacy raw-unit alphas/tstats.
  • trading-cost block (per-stock tcosts input only):
    • tcosts_ts: the cost of the two extreme legs' trades in each month, in decimals, the first purchase excluded. 0, never NaN, in a month without a trade, so netpret == long_short - tcosts_ts wherever there is a return.
    • netpret, netxret, tnetxret: the net long-short return, its mean in percent per month and the t-statistic of the mean.
    • ptf_costs, ptf_to: every portfolio's own cost and traded dollars over its value, as a portfolio held by itself (0 in a month without a trade). Under "dollar" each portfolio goes back to $1 at a trade, and the two extreme columns of ptf_costs add up to tcosts_ts. Under "capital" each portfolio rolls its own value over (1 plus its P&L since the previous trade; nothing is put in or taken out), and the two extreme columns are not the parts of tcosts_ts, whose legs are both set to K. to_ts is the turnover of the two extreme legs as legs of the pair.
    • entry_cost: the cost of the first purchase of the two extreme legs, a decimal per $1 in each leg. ptf_entry_costs has it for every portfolio. It is in none of the series or averages of this block.
    • tcosts_ts_short: under "capital", the cost per month of the strategy held short (the same two portfolios with the legs exchanged, with its own capital K' = 1 + short P&L - long P&L). None under "dollar", where that cost is tcosts_ts. calc_gen_alpha takes it as anom_tcosts_short.
    • tcosts, turnover: averages over the months in which the long-short portfolio has a return. The mean gross return less 100 × tcosts is netxret. turnover is both legs' traded dollars over leg value, divided by 4. For a signal traded once a year the average runs over all twelve months, so it is about a twelfth of the turnover of the trade month.
    • metadata["convention"], metadata["capital_restarts"].
  • table(): MATLAB prtSortResults-style summary DataFrame (xret, alphas, loadings, t-stats, Sharpe/info, n stocks, net rows when costs are present).
  • print_results(): prints table() with a MATLAB-style header (plus a turnover/tcosts line when costs are present); falls back to a plain raw return summary if no factor model was used.
  • plot_results(): 4-panel strategy figure (port of plotStrategyFigs.m).

run_bivariate_sort(returns, signal1, signal2, mcap, *, n_bins1=5, n_bins2=5, sort_type="unconditional", ...) -> BivariateSortResult

Mirror of makeBivSortInd + runBivSort. Portfolio ids are MATLAB-style row-major ((i-1)*n2 + j). The result bundles:

  • flat: SortResult over the n1*n2 portfolios;
  • cell_returns: the same returns with (bin1, bin2) MultiIndex columns;
  • cond_var1_given_var2, cond_var2_given_var1: conditional long/short strategies;
  • print_grid(label, name1, name2): prints the average-return grid and the conditional var2-within-var1 strategy table, returning the grid DataFrame.

Building blocks

  • calc_held_ptfs(returns, ind, mcap, tcosts=None, *, weighting="v", n_ptfs=None, short=1, long=None, convention="dollar", label=None): the held-leg calculation behind run_univariate_sort, for portfolio assignments you made yourself. (date, permno) Series in; leg returns, stock counts and market caps out, and with tcosts the cost and turnover of long minus short (costs, with cost_exchanged for the pair held short), its entry_cost, and every portfolio's own cost, turnover and entry cost (ptf_costs, ptf_turnover, entry_costs).
  • held_legs(ret, me, tcost, ind, weights="v", *, growth=None, n_ptfs=None, monthly_holdings=False), held_long_short(legs, short=1, long=None, *, convention="dollar", label=None): the core, on dense months × stocks numpy grids over a complete monthly calendar. weights also takes a grid of custom weights (scaled to sum to 1 within each portfolio; negative weights raise). monthly_holdings=True also returns each portfolio's month-end dollars in stocks, which held_composite_long_short needs. The result of held_long_short has entry_cost (and entry_cost_short, entry_cost_long), and cost_exchanged, turnover_exchanged and capital_exchanged: the cost, turnover and capital of the same pair with its legs exchanged, equal to cost and turnover under "dollar".
  • held_portfolio_costs(legs, *, convention="dollar"): the cost, turnover and entry cost of every portfolio held on its own. Under "dollar" a portfolio goes back to $1 at a trade; under "capital" it rolls its own value over.
  • held_composite_long_short(legs, short, long, *, convention="dollar", label=None): a long/short pair in which each side is the equal-share average of several held portfolios (short and long are sequences of portfolio ids). At the end of every month without a trade each side brings its portfolios back to equal shares of its own value and pays that month's half-spreads; a trade is one netted step; the sides are resized at trades only. This is how the Fama-French factors are priced (Ch 9b).
  • fill_months(x, months=11): carries each stock's last value forward for at most months calendar months (MATLAB FillMonths). x is a numeric Series or DataFrame on a (date, permno) index. Annual Compustat columns are stored in the June they become available only; fill_months of such a column, or of a signal computed from such columns, has values from June through the next May, and a sort on it trades every month.
  • calc_ptf_rets(returns, ind, mcap, *, holding_period=1, weighting="v"): MATLAB calcPtfRets.m — lagged membership/weights, annual-rebalance carry-forward, overlapping holding periods. Every month each portfolio earns the return of fresh target weights. run_univariate_sort uses it only for holding_period > 1; run_bivariate_sort uses it throughout.
  • est_factor_regs(pret, *, factor_model, add_long_short=False, ...): MATLAB estFactorRegs.m-style factor regressions.
  • load_factors(db_path=None): month-end-indexed factor DataFrame (mkt, smb, smb2, hml, rf, mom, rmw, cma).

Regressions

  • analytics.regressions.run_fama_macbeth(y, x, ...): monthly cross-sectional OLS/WLS with winsorize/trim, min_obs, Newey-West lags, no_const, time_period; RHS is lagged one month by default. x may be a DataFrame, Series, list of Series, or {name: Series} dict; pass labels=[...] for named printed rows.
  • analytics.ols.nanols(y, x, labels=None) -> OlsRes: port of nanols.m — OLS after dropping rows with any NaN in [y x]; result carries beta/tstat/bstd/resid/yhat/sige/rsqr/rbar/nobs/nvar.
  • analytics.ols.prt(res, title=...): jplv7-style coefficient table print.

Trading costs (analytics.costs)

  • calc_tcosts(tcosts, ind, me, weighting="v", ptf_rets=None, compute_dw=True, holding_period=1): port of calcTcosts.m; returns per-portfolio costs, turnover, and net weight changes. Nothing in the package calls it any more: run_univariate_sort, the protocol and the factor costs price held legs (above). It stays as a function for the MATLAB calculation, which pairs with calc_ptf_rets.
    • tcosts holds decimal effective half-spreads, not full spreads. The cost of a portfolio-month is sum |dw| × half-spread over two-sided weight changes, so a full replacement pays one half-spread to sell and one to buy.
    • Inputs are read by their (date, permno) labels, never by position. They may be long, MultiIndexed or wide, in any order, but must cover the same month-end dates and permnos. Duplicate keys or differing label sets raise ValueError. ptf_rets is read by date and by portfolio ids 1..n_ptfs.
    • Lags run in calendar months. A month absent from the inputs is an empty row, so the next month has no prior weights.
    • holding_period > 1 prices the union of the last holding_period formations (the calc_ptf_rets membership). It raises for custom weight matrices and for assignments that skip calendar months.
    • Constant-base convention. With ptf_rets=None the strategy runs on a constant $1 base, as MATLAB calcTcosts does. Reported turnover therefore includes the notional rebalance: a portfolio needing no trades still books |1 - R_p| of turnover, the appreciation withdrawn to restore the $1 base. That is a real trade under this convention, not an artifact. Passing ptf_rets compounds the base instead, leaving only the dividend component.
    • me proxies the ex-dividend return. Weight drift uses cap growth, me(t) / me(t - reb_freq), as a shortcut for the gross ex-dividend return on a fixed holding. Share-count changes (issuance, buybacks, splits) move me without moving the value of a position already held, and the function sees only me, so it cannot separate them.
  • make_ff_tcosts(panel, tcost_series, annual=None, *, convention="dollar") (delegates to transforms.tcosts): trading costs of SMB, HML, RMW, CMA and UMD. The 2×3 sorts are those of makeFFTcosts.m; the costs are not. Each 2×3 portfolio is a held leg (June trades; monthly for UMD) and each side is priced with held_composite_long_short. The panel must carry ret, me, nyse_flag and R12_2; if an input is missing the non-market costs are zero, with a warning. Returns mkt_tc (zero), smb_tc … umd_tc under convention, and the sums ff3_tc … ff6_tc; under "capital" also smb_tc_short … umd_tc_short, the cost of each factor held short. The first purchase is not in these series. The database stores both conventions (smb_tc … for "dollar", smb_tc_capital … for "capital") and, for "capital", the factors held short (smb_tc_capital_short …). See Ch 9b.
  • calc_gen_alpha and estimate_gen_alpha (analytics.gen_alpha) take two optional arguments, anom_tcosts_short and factor_tcosts_short: the costs charged on a short position in the net mean-variance efficient portfolio. They matter under "capital" only; see Ch 15.

Plot helpers (analytics.plots)

  • ibbots(rets, time_period=None, lin_plot_ind=False, legend_labels=None, ax=None, title=None): port of ibbots.m — cumulative performance of $1 (log scale by default); returns the growth paths.
  • moving(x, m): port of moving.m — centered m-point moving average with edge padding.

Anomaly helpers

  • transforms.anomaly_fill.fill_var(var, mcap): port of fillVar.m — cross-sectional rank in [-0.5, 0.5]; stocks with market cap but no signal get the median rank; low-frequency signals are carried forward first.
  • transforms.anomaly_fill.check_fill_anomalies(anoms, mcap, time_period, mcap_thresh=0.40, n_roll=120, seed=0): port of checkFillAnomalies.m — returns (filled, keep, keep_roll).
  • analytics.anomaly_decay.run_anomaly_decay(anoms_panel, summary, *, returns, mcap, prc=None, exchcd=None, nyse_flag=None, verbose=True): port of the use_library.m section-11 decay loop over the Chen-Zimmerman signals (rebalancing frequency, documentation screens, sample windows, weighting), expressed on run_univariate_sort.
  • analytics.anomaly_decay.plot_anomaly_decay(results, summary, all_dates): lines the strategies up on publication date and plots the average decay.

Data loaders

  • load(fields, ..., fill_annual=False): see Ch 12. Annual Compustat columns come back as stored, in the June they become available only; fill_annual=True passes each one through fill_months. On a database built before annual columns were stored this way, a load of an annual column raises AnnualLayoutError with the rebuild command.

  • ingest.ken_french.load_ff25(url=FF25_URL, cache=None): downloads/parses the monthly value-weighted block of Ken French's 25 size/book-to-market portfolios (decimals, missing codes masked).

Combination strategies (analytics.results)

make_lasso_res(filled_anoms, ret, time_period=..., verbose=...) runs the rolling 120-month LASSO (5-fold CV, random_state=0) over filled anomaly signals and returns a LassoRes with the expected-return signal (eret) and monthly coefficient paths (betas). See analytics/results.py for the rest of the protocol result builders (make_*) and their dataclasses.

Session facade

AssayClient exposes thin wrappers (run_univariate_sort, run_fama_macbeth, ...) over the functional API; SignalTester drives the anomaly protocol (analytics.protocol.run_test_signal).

run_test_signal(..., convention="dollar") passes its convention to every sort it runs (the test signal's and the zoo strategies') and records it in summary["convention"], the run manifest and printResults.metadata. summary["entry_cost"] has the cost of the first purchase of each of the test signal's sorts.

run_test_signal resolves one factor bundle before any stage runs: the explicit factors/factor_tcosts when given, otherwise factors and factor costs from db_path (or the configured database), where it reads the factor-cost columns of the run's convention. A database whose factor costs were computed by an earlier version raises FactorCostsError with the rebuild command. Every stage, including the process-pool workers, uses that bundle, and summary["factor_source"] records where it came from.