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/alphaoutputs are in percent per month (MATLABestFactorRegsconvention); Sharpe/information ratios are annualized.time_periodarguments accept a MATLAB-styleYYYYMMinteger (sample start), a(YYYYMM, YYYYMM)pair, or Timestamps. Malformed values (e.g.1963) raiseValueError.
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.
-
conventionis the size of the two legs after a trade:"dollar"(the default) sets each back to $1;"capital"sets both to the strategy's capitalK = 1 + long P&L - short P&Lsince 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 raisesValueError. -
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 innyse_flag— any boolean filter works, e.g.exchcd == 3for NASDAQ breaks), or"cap"(equal total market cap per bin, mass fromportfolio_mass, defaultmcap).weighting:'v'/'V'value-weighted or'e'/'E'equal-weighted; anything else raisesValueError(MATLABrunUnivSortinput check).factor_model:1/3/4/5/6or a user-supplied factor DataFrame (include anrfcolumn so excess returns are formed the same way). Models 5-6 use the five-factorsmb2, neversmbin its place. Other integers raiseValueError. MATLAB-style stats are computed whenever a factor model is given, including withadd_long_short=False.factors: optional explicit factor store for integer models (e.g. the output ofload_factors(db_path)). The model's columns andrfare 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_resultsandmake_close_anom_resultstake 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. thetcostortcost_gibbscolumns): priced on the trades of the two extreme legs, populating theSortResulttrading-cost block (below). At a trade a leg of sizesmoves from its holdingsDtos × target weights, and payssum(|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. Needsadd_long_short=Trueand at least two portfolios; otherwise no cost block is returned.
- scalar: subtracted from the long-short return (
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 lastholding_periodformations (calc_ptf_rets). Gross returns only: a per-stocktcostspanel withholding_period > 1raisesValueError.- Under
"capital", ifKis 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 noKand 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 propertiespret(legs +long_shortcolumn) anddates. - MATLAB-style stats (
%/mo where applicable):xret,txret,alpha,talpha,sharpe,info,resid,r2_adj, plusfactor_loadings/factor_loading_tstatsand legacy raw-unitalphas/tstats. - trading-cost block (per-stock
tcostsinput 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, sonetpret == long_short - tcosts_tswherever 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 ofptf_costsadd up totcosts_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 oftcosts_ts, whose legs are both set toK.to_tsis 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_costshas 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 capitalK' = 1 + short P&L - long P&L).Noneunder"dollar", where that cost istcosts_ts.calc_gen_alphatakes it asanom_tcosts_short.tcosts,turnover: averages over the months in which the long-short portfolio has a return. The mean gross return less100 × tcostsisnetxret.turnoveris 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(): MATLABprtSortResults-style summary DataFrame (xret, alphas, loadings, t-stats, Sharpe/info, n stocks, net rows when costs are present).print_results(): printstable()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 ofplotStrategyFigs.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:SortResultover then1*n2portfolios;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 behindrun_univariate_sort, for portfolio assignments you made yourself.(date, permno)Series in; leg returns, stock counts and market caps out, and withtcoststhe cost and turnover oflongminusshort(costs, withcost_exchangedfor the pair held short), itsentry_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.weightsalso takes a grid of custom weights (scaled to sum to 1 within each portfolio; negative weights raise).monthly_holdings=Truealso returns each portfolio's month-end dollars in stocks, whichheld_composite_long_shortneeds. The result ofheld_long_shorthasentry_cost(andentry_cost_short,entry_cost_long), andcost_exchanged,turnover_exchangedandcapital_exchanged: the cost, turnover and capital of the same pair with its legs exchanged, equal tocostandturnoverunder"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 (shortandlongare 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 mostmonthscalendar months (MATLABFillMonths).xis a numeric Series or DataFrame on a(date, permno)index. Annual Compustat columns are stored in the June they become available only;fill_monthsof 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"): MATLABcalcPtfRets.m— lagged membership/weights, annual-rebalance carry-forward, overlapping holding periods. Every month each portfolio earns the return of fresh target weights.run_univariate_sortuses it only forholding_period > 1;run_bivariate_sortuses it throughout.est_factor_regs(pret, *, factor_model, add_long_short=False, ...): MATLABestFactorRegs.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.xmay be a DataFrame, Series, list of Series, or{name: Series}dict; passlabels=[...]for named printed rows.analytics.ols.nanols(y, x, labels=None) -> OlsRes: port ofnanols.m— OLS after dropping rows with any NaN in[y x]; result carriesbeta/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 ofcalcTcosts.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 withcalc_ptf_rets.tcostsholds decimal effective half-spreads, not full spreads. The cost of a portfolio-month issum |dw| × half-spreadover 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 raiseValueError.ptf_retsis read by date and by portfolio ids1..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 > 1prices the union of the lastholding_periodformations (thecalc_ptf_retsmembership). It raises for custom weight matrices and for assignments that skip calendar months.- Constant-base convention. With
ptf_rets=Nonethe strategy runs on a constant $1 base, as MATLABcalcTcostsdoes. 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. Passingptf_retscompounds the base instead, leaving only the dividend component. meproxies 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) movemewithout moving the value of a position already held, and the function sees onlyme, so it cannot separate them.
make_ff_tcosts(panel, tcost_series, annual=None, *, convention="dollar")(delegates totransforms.tcosts): trading costs of SMB, HML, RMW, CMA and UMD. The 2×3 sorts are those ofmakeFFTcosts.m; the costs are not. Each 2×3 portfolio is a held leg (June trades; monthly for UMD) and each side is priced withheld_composite_long_short. The panel must carryret,me,nyse_flagandR12_2; if an input is missing the non-market costs are zero, with a warning. Returnsmkt_tc(zero),smb_tc…umd_tcunderconvention, and the sumsff3_tc…ff6_tc; under"capital"alsosmb_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_alphaandestimate_gen_alpha(analytics.gen_alpha) take two optional arguments,anom_tcosts_shortandfactor_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 ofibbots.m— cumulative performance of $1 (log scale by default); returns the growth paths.moving(x, m): port ofmoving.m— centered m-point moving average with edge padding.
Anomaly helpers¶
transforms.anomaly_fill.fill_var(var, mcap): port offillVar.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 ofcheckFillAnomalies.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 theuse_library.msection-11 decay loop over the Chen-Zimmerman signals (rebalancing frequency, documentation screens, sample windows, weighting), expressed onrun_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=Truepasses each one throughfill_months. On a database built before annual columns were stored this way, a load of an annual column raisesAnnualLayoutErrorwith 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.