Coming from Alphalens
Map an Alphalens or Alphalens Reloaded workflow onto Lacuna, convert a pandas factor Series to long form, and see where the numbers and the guarantees differ.
Alphalens, and its maintained fork Alphalens Reloaded, answer one question well: does a factor sort assets into groups whose later returns differ? Its inputs are a factor Series and a price DataFrame, and its outputs are tables and tear-sheet plots. Lacuna asks the same question and then keeps going: what did the study assume about timing, what did it drop, and what evidence is missing?
That difference shapes the migration. Most of Alphalens’s computations have a Lacuna counterpart, but the two tools disagree on where decisions are made. Alphalens takes several decisions from the shape of your data. Lacuna gives each one a parameter and records the answer. It does not force you to answer all of them, and only some leave a visible UNKNOWN when you do not. This page maps the workflow, converts the data, and lists the places where the same inputs can give different numbers, or different certainty.
Alphalens is not installed in the environment that runs this page, so its snippets are shown, not run, and are labelled as such. Everything marked as Lacuna behaviour is run. Alphalens behaviour is described only where its public API makes it well known; check your installed version’s documentation before relying on a detail.
What changes in the data
Alphalens works from two pandas objects: a factor Series indexed by a (date, asset) MultiIndex, and a prices DataFrame with dates down the index and assets across the columns. It joins them into a factor_data frame that carries the forward returns as columns:
import alphalens as al
factor_data = al.utils.get_clean_factor_and_forward_returns(
factor, # Series, MultiIndex (date, asset)
prices, # DataFrame, dates by assets
quantiles=5,
periods=(1, 5),
max_loss=0.35,
)
information_coefficient = al.performance.factor_information_coefficient(factor_data)
mean_returns, _ = al.performance.mean_return_by_quantile(factor_data) Lacuna keeps the two inputs apart and long. A signal table has one row per instrument per observation, and so does a price table. Forward returns are not a column you carry around; they are built from the prices, with the timing you declare, when the study needs them. Preparing your data covers the table shapes in general.
Convert the factor and the prices
The next block builds a synthetic version of Alphalens’s inputs: a price DataFrame, and a 5-day momentum factor in a (date, asset) Series. The factor uses prices through the day before, so it is known at the open of each date.
import lacuna as lc
import numpy as np
import pandas as pd
import polars as pl
rng = np.random.default_rng(2024)
dates = pd.bdate_range("2025-01-06", periods=80, name="date")
assets = pd.Index([f"S{n:02d}" for n in range(10)], name="asset")
log_returns = rng.normal(0.0004, 0.012, size=(len(dates), len(assets)))
prices = pd.DataFrame(100 * np.exp(log_returns.cumsum(axis=0)), index=dates, columns=assets)
momentum = prices.pct_change(5).shift(1)
factor = momentum.stack(future_stack=True).rename("factor")
print(factor.index.names, len(factor), int(factor.isna().sum())) ['date', 'asset'] 800 60 Convert the factor Series with to_polars. The (date, asset) index is where the identities live, and to_polars drops a pandas index unless you ask for it. Without the flag, you would be left with a bare column of values and no way to tell which asset or date each belongs to:
print(lc.adapters.to_polars(factor).columns) ['factor'] With include_pandas_index=True the index levels become columns, and a rename gives Lacuna’s default names:
signal = lc.adapters.to_polars(factor, include_pandas_index=True).rename(
{"date": "time", "asset": "instrument", "factor": "signal"}
)
print(signal.head(3)) shape: (3, 3)
┌─────────────────────┬────────────┬────────┐
│ time ┆ instrument ┆ signal │
│ --- ┆ --- ┆ --- │
│ datetime[μs] ┆ str ┆ f64 │
╞═════════════════════╪════════════╪════════╡
│ 2025-01-06 00:00:00 ┆ S00 ┆ null │
│ 2025-01-06 00:00:00 ┆ S01 ┆ null │
│ 2025-01-06 00:00:00 ┆ S02 ┆ null │
└─────────────────────┴────────────┴────────┘ The warm-up rows are null, not NaN: Polars treats a pandas NaN as a missing value. Lacuna will drop them and count them, as the output below shows.
The wide price frame needs one more step, from dates by assets to one row per date and asset:
def prices_to_long(wide: pd.DataFrame) -> pl.DataFrame:
frame = lc.adapters.to_polars(wide, include_pandas_index=True)
return frame.unpivot(index="date", variable_name="instrument", value_name="close").rename(
{"date": "time"}
)
long_prices = prices_to_long(prices)
print(long_prices.schema) Schema({'time': Datetime(time_unit='us', time_zone=None), 'instrument': String, 'close': Float64}) Both tables use the same Datetime type for time, which matters: Lacuna refuses to join key columns whose dtypes differ at all, whether Date against Datetime, a different Datetime unit (ms against us) or a different time zone. Both come from the same pandas index here, so they agree.
Run the same analyses
A SignalStudy holds the two tables and the declarations. The declarations are the part Alphalens leaves implicit. They are optional: signal_observed_at and entry default to None, which enters on the signal’s own row with no error and no finding. This study says the factor is known at the open of its date, that the position is entered at that date’s close, and that the prices include dividends and splits.
study = lc.SignalStudy(
signal=signal,
prices=long_prices,
horizons=("1D", "5D"),
signal_observed_at="open",
entry="current_close",
price_adjustment="total_return_adjusted",
quantiles=5,
)
ic = study.ic()
print(pl.DataFrame(ic.table("ic_by_horizon")).select("horizon", "mean_ic", "std_ic", "n_periods"))
print(ic.metadata.parameters["headline_horizon"], round(ic.metrics["mean_ic"], 6)) shape: (2, 4)
┌─────────┬───────────┬──────────┬───────────┐
│ horizon ┆ mean_ic ┆ std_ic ┆ n_periods │
│ --- ┆ --- ┆ --- ┆ --- │
│ str ┆ f64 ┆ f64 ┆ i64 │
╞═════════╪═══════════╪══════════╪═══════════╡
│ 1D ┆ -0.0401 ┆ 0.32854 ┆ 73 │
│ 5D ┆ -0.115854 ┆ 0.328603 ┆ 69 │
└─────────┴───────────┴──────────┴───────────┘
1D -0.0401 ic_by_horizon is the counterpart of Alphalens’s mean IC table, with one row per horizon. The per-date values are in the ic_by_period table of the same result. The headline metrics, such as ic.metrics["mean_ic"], are not an average over horizons: they describe one horizon, the first in horizons, recorded as headline_horizon. Read ic_by_horizon when you want every horizon. Rank (Spearman) correlation is the default, with average ranks for ties, on each date’s cross-section. Alphalens’s IC is also a Spearman correlation per date, so the mean IC on matching inputs is a useful first sanity check before comparing anything else.
The rows dropped on the way are in the result too:
attrition = pl.DataFrame(ic.table("data_attrition"))
print(attrition.select("reason", "input_rows", "excluded_rows")) shape: (2, 3)
┌─────────────────────────────┬────────────┬───────────────┐
│ reason ┆ input_rows ┆ excluded_rows │
│ --- ┆ --- ┆ --- │
│ str ┆ i64 ┆ i64 │
╞═════════════════════════════╪════════════╪═══════════════╡
│ null_or_nan_signal_or_label ┆ 1540 ┆ 120 │
│ below_minimum_observations ┆ 1420 ┆ 0 │
└─────────────────────────────┴────────────┴───────────────┘ The 60 null factor values (six warm-up dates times ten assets) were counted once for each of the two horizons, which is why 120 rows were excluded. SignalStudy methods always drop them and say so. The functional API, such as lc.signal.ic(..., null_policy="raise"), can refuse them instead; SignalStudy.ic, quantiles and turnover have no null_policy parameter.
Quantile returns and turnover come from the same study:
quantiles = study.quantiles()
five_day = pl.DataFrame(quantiles.table("quantile_returns")).filter(pl.col("horizon") == "5D")
print(five_day.select("quantile", "mean_return", "n_observations"))
turnover = study.turnover(lags=(1,))
print(pl.DataFrame(turnover.table("turnover_by_lag")).select("lag", "mean_rank_turnover", "mean_signal_autocorrelation")) shape: (5, 3)
┌──────────┬─────────────┬────────────────┐
│ quantile ┆ mean_return ┆ n_observations │
│ --- ┆ --- ┆ --- │
│ i64 ┆ f64 ┆ i64 │
╞══════════╪═════════════╪════════════════╡
│ 1 ┆ 0.005663 ┆ 138 │
│ 2 ┆ 0.001702 ┆ 138 │
│ 3 ┆ 0.006573 ┆ 138 │
│ 4 ┆ -0.002404 ┆ 138 │
│ 5 ┆ -0.00488 ┆ 138 │
└──────────┴─────────────┴────────────────┘
shape: (1, 3)
┌─────┬────────────────────┬─────────────────────────────┐
│ lag ┆ mean_rank_turnover ┆ mean_signal_autocorrelation │
│ --- ┆ --- ┆ --- │
│ i64 ┆ f64 ┆ f64 │
╞═════╪════════════════════╪═════════════════════════════╡
│ 1 ┆ 0.181735 ┆ 0.752095 │
└─────┴────────────────────┴─────────────────────────────┘ The synthetic momentum factor has no skill, so these values are noise. What matters here is the shape of the results and what each column means, which the sections below cover.
Concept mapping
| Alphalens | Lacuna | Notes |
|---|---|---|
get_clean_factor_and_forward_returns | lc.SignalStudy, built on lc.labels.forward_returns | Factor and prices stay separate. Quantile assignment happens in the analysis (bucketize, quantiles), not in the join. |
factor_information_coefficient | lc.signal.ic, SignalStudy.ic | Table ic_by_period; summary in ic_by_horizon. Spearman by default. |
mean_information_coefficient | ic_by_horizon, or aggregate ic_by_period yourself | Lacuna does not resample by calendar period. by= chooses the grouping keys, such as a group column. |
mean_return_by_quantile | lc.signal.quantiles, SignalStudy.quantiles | Table quantile_returns. Raw means, not demeaned, averaged over dates. See below. |
compute_mean_returns_spread | Table spread_by_period | Top bucket mean minus bottom bucket mean, per observation. |
factor_rank_autocorrelation | lc.signal.turnover: signal_autocorrelation and rank_turnover | Not the same statistic. See below. |
quantile_turnover | lc.signal.turnover: membership_turnover_by_period_lag | Different denominator. See below. |
factor_returns, factor_weights | lc.signal.portfolio_projection | A diagnostic projection of a bucketed signal. Not a backtest. |
create_full_tear_sheet | SignalStudy.audit, then AuditReport.to_html | The report renders stored evidence. renderer="plotly" draws charts. |
groupby, by_group | by= with a group column, group_available_time | Grouping works without an availability time but is marked UNKNOWN. See below. |
filter_zscore, max_loss | None | Lacuna records attrition instead of filtering or gating on it. No built-in audit rule checks attrition. |
| Event-returns tear sheet | lc.events.event_windows, lc.events.event_response | See Event studies. |
The SignalStudy constructor takes the inputs Alphalens takes from function arguments:
| Parameter | Meaning |
|---|---|
signal, prices | The two long tables. They are separate, unlike factor_data. |
horizons | Forward horizons as observations per instrument, like "5D". Counterpart of periods, which Alphalens counts along one date index shared by all assets. |
signal_schema, price_schema | Column names for NumPy input. Rarely needed. |
signal_time, price_time, instrument, signal_value, price | Names of your columns, so you do not have to rename them. instrument is the identifier column of both tables. |
signal_observed_at | When the signal is known within its observation: "open" or "close". Alphalens has no counterpart. |
entry, exit | Where a position starts and ends. Defaults: the signal’s own observation, at its close. |
price_adjustment | What the prices include. Recorded and audited; there is no counterpart. |
delisting_return | A column giving the return to use at an exit row whose price is null. See below. |
missing | "drop" (default) or "raise" for labels with missing prices. |
allow_same_close | Allow a close-observed signal to trade at that same close. |
quantiles | Number of buckets, default 5. SignalStudy.quantiles can override per call. The functional lc.signal.quantiles defaults to 10. |
Differences that change the numbers
Horizons count observations
Alphalens measures periods along the one date index that all assets share, the rows of your prices frame. Lacuna’s "5D" means five observations per instrument, whatever the dates are. A weekend, a holiday or a missing session never stretches a horizon, and Lacuna never infers a calendar. The two agree when every instrument has a row on every date. When instruments have their own gaps or start dates, check which date each label ends on. Forward-return labels has the rule in full.
Timing is declared
Alphalens pairs each factor value with the price on its own date. Whether the factor was known in time to trade at that price depends on how you built and lagged the inputs, and nothing records it. Lacuna gives you parameters to record it, signal_observed_at and entry, but does not demand them. Once you declare a factor computed from a session’s close, it cannot also trade at that same close, and Lacuna refuses the combination:
lc.SignalStudy(
signal=signal,
prices=long_prices,
signal_observed_at="close",
entry="current_close",
price_adjustment="total_return_adjusted",
).ic() MethodContractError: a close-observed signal cannot use the same close; use entry='next_open' or entry='next_close' (horizons of at least 2D), or explicitly set allow_same_close=True Pick entry="next_open" (needs an open column) or entry="next_close" with horizons of at least two observations. The choice is stored in the labels’ metadata, where a reviewer will find it.
Nothing is filled
SignalStudy and forward_returns never forward-fill a price or a signal. (Point-in-time joins such as lc.bias.asof_join do look backward by design; that is their purpose.) A missing price keeps its place in the sequence as an observation with no price, and every label whose entry or exit lands on it is dropped and counted. Put a missing price in the wide frame to see it:
gappy = prices.copy()
gappy.iloc[40, 3] = np.nan
gappy_study = lc.SignalStudy(
signal=signal,
prices=prices_to_long(gappy),
horizons=("1D", "5D"),
signal_observed_at="open",
entry="current_close",
price_adjustment="total_return_adjusted",
)
gappy_labels = gappy_study.labels()
print(gappy_labels.evidence.metrics["source_missing_rows"])
print(pl.DataFrame(gappy_labels.evidence.table("coverage_by_horizon"))) 1
shape: (2, 3)
┌─────────┬───────────────┬───────────────┐
│ horizon ┆ eligible_rows ┆ censored_rows │
│ --- ┆ --- ┆ --- │
│ str ┆ i64 ┆ i64 │
╞═════════╪═══════════════╪═══════════════╡
│ 1D ┆ 788 ┆ 12 │
│ 5D ┆ 748 ┆ 52 │
└─────────┴───────────────┴───────────────┘ One price was missing. For the 1D horizon, 12 labels were censored: ten are the last observation of each of the ten assets, which has no later price, and two are the labels that start or end at the missing price. The 5D horizon censors 52, which is 50 end-of-sample labels and the same two. If you pass a long frame with null rows removed instead, the labels bridge the gap, because horizons count the observations that remain. Keep the null rows if you want the gap to cost a label. Lacuna also evaluates each horizon on its own eligible rows, so a row can count for 1D and be censored for 5D, as the table shows. A tool that drops a row missing any period would give slightly different samples.
A delisted instrument stops having prices, and its last labels have no exit. Name the column that holds its delisting return in delisting_return, and give the instrument a final row with a null price carrying that return. If the instrument’s rows simply stop, the labels are still dropped. Alphalens has no counterpart.
Quantile returns are raw means
mean_return_by_quantile in Alphalens has a demeaned option, on by default. Lacuna’s quantile_returns are the plain mean of the forward return in each bucket. Each mean_return is also the mean, over dates, of that date’s bucket mean, which equals the pooled mean only when bucket sizes are constant across dates; Alphalens may pool observations instead. If you compare numbers, either demean the forward returns yourself, subtracting the cross-sectional mean for each date and horizon before analysis, or compare against Alphalens with demeaning switched off.
The bucket numbers also follow a convention: bucket 1 holds the lowest signal and the top bucket the highest. Ties are split deterministically, by signal and then by instrument, so buckets have equal counts. When the count is not divisible by the number of buckets, bucket sizes differ by at most one. A factor with many tied values can fall into different buckets than the same Alphalens run assigns; check how your version bins ties before comparing bucket numbers. If you want tied values kept together, bucket explicitly with SignalStudy.bucketize(spec=lc.BucketSpec.quantiles(5, tie_policy="preserve")) and summarize with bucket_returns; lc.signal.quantiles itself supports only the balanced policy.
Turnover and autocorrelation are different statistics
lc.signal.turnover reports, for each pair of observations a lag apart:
| Column | Definition |
|---|---|
rank_turnover | Mean absolute change in each instrument’s rank fraction between the two observations. |
signal_autocorrelation | Pearson correlation of the raw signal values at the two observations. |
top_membership_turnover, bottom_membership_turnover | For the top and bottom buckets, the number of instruments that entered or left the bucket between the two observations, divided by the bucket’s combined size at both. The buckets are the same balanced midpoint buckets that quantiles reports. |
Alphalens has its own definitions of rank autocorrelation and quantile turnover; check them before comparing. Neither is the same computation as a Lacuna column above, so treat them as different measures of the same idea, not as a number to reproduce.
A lag is an exact offset in the index of distinct signal observation times, counted after null signals are dropped. Only instruments present at both ends are compared, and a gap does not count as a lag of one.
Groups need an availability time
Alphalens’s groupby takes a mapping of asset to group, or a Series of groups that can vary by date. A mapping is static: a sector label used today may not be the sector the asset had at the time. Time-varying groups fix that only if the dates reflect when each classification became known, and Alphalens has nowhere to record that. Lacuna lets you group by any column and accepts the analysis without an availability time, but marks it. Grouped analysis with no availability evidence returns an UNKNOWN finding:
sector = {asset: "A" if n < 5 else "B" for n, asset in enumerate(assets)}
grouped = signal.with_columns(
pl.col("instrument").replace_strict(sector).alias("group"),
pl.col("time").alias("group_known_at"),
)
by_group = ("observation_time", "group")
study_labels = study.labels()
unverified = lc.signal.ic(grouped, study_labels, by=by_group)
print([(f.code, f.state.value, f.severity.value) for f in unverified.findings])
verified = lc.signal.ic(
grouped, study_labels, by=by_group, group_available_time="group_known_at"
)
print([(f.code, f.state.value) for f in verified.findings]) [('GROUP_AVAILABILITY_UNKNOWN', 'UNKNOWN', 'high')]
[('GROUP_AVAILABILITY_VERIFIED', 'PASS')] The second call is only as good as the column you name: here the group is stamped as known on the date itself. Lacuna checks the timestamps against each observation. A group label that becomes available after the observation it is used at raises a DataContractError instead of passing, but it cannot tell whether the timestamps you supply are true.
No lookahead filter, no loss threshold
Alphalens’s filter_zscore drops forward returns that are extreme by a z-score threshold. If the statistics behind the threshold are estimated over the whole sample, the filter for an early row depends on later data; check how your version computes it. Lacuna has no such option. If you want to remove outliers, do it with a rule that uses only information available at each date, and apply it to the label table before analysis. max_loss has no counterpart either: Lacuna does not stop when too much is dropped. It reports what was dropped in data_attrition and coverage_by_horizon and leaves the threshold to you. No built-in audit rule checks attrition; to enforce a limit, write a rule and pass it to SignalStudy.audit through rules=.
Evidence instead of plots
SignalStudy.audit runs the analyses with bootstrap inference and returns an AuditReport. Missing evidence is reported as UNKNOWN, not left out, and a missing check is never a pass:
report = study.audit(bootstrap_resamples=200, seed=1)
print(sorted(finding.code for finding in report.findings if finding.state.value == "UNKNOWN")) ['DELISTING_HANDLING_DECLARED', 'PURGED_VALIDATION_SUPPLIED', 'SURVIVORSHIP_HANDLING_DECLARED', 'TRIAL_HISTORY_AVAILABLE'] The study declared a price basis, so PRICE_ADJUSTMENT_DECLARED is not on the list. Timing is not on it either way: leaving signal_observed_at and entry at their defaults raises no finding, so that declaration stays your responsibility. The study did not supply a purged validation split, a trial history, a delisting policy or a survivorship policy, so each of those is UNKNOWN until you provide the evidence. Leave price_adjustment at its default and PRICE_ADJUSTMENT_DECLARED joins the list. The report renders what the analyses stored and does not recompute it. See Audits and reports for how to answer each one.
The ic function warns that its t-statistic is the ordinary time-series statistic and does not adjust for serial dependence. Overlapping horizons make neighbouring IC values dependent, so for inference use the audit’s bootstrap, which samples non-overlapping label intervals, or bootstrap directly. The audit’s bootstrap covers one horizon, the first one you declared unless the inference_horizon policy names another, and is skipped when fewer than two non-overlapping IC values exist.
If you already have factor_data
When you have an Alphalens factor_data frame on disk and only want it in Lacuna, adapt_factor_panel maps its (date, asset) index, the factor column, one forward-return column and an optional group into Lacuna’s names, and records the conventions behind it. Other period columns pass through under their own names. The imported factor_quantile is kept as bucket, and Lacuna does not treat it as one of its own bucket assignments. bucket must be an integer column, so cast a float factor_quantile first. See Factor panels. For any serious comparison, rebuild from factor and prices with a SignalStudy, so the labels carry their timing and intervals.
A migration checklist
Before you trust a migrated study, answer these, because each one is a parameter:
- When is the factor known within its date, and where do you enter? That is
signal_observed_atandentry. Neither is required, so nothing will prompt you. - Do the prices include dividends and splits? That is
price_adjustment. - Is a horizon of five days five observations? That is
horizons. - What happens to a delisted instrument? That is
delisting_return. - Were the groups known at the time? That is
group_available_time. - Did you remove null rows from the long price frame, and did you mean to move the horizon’s end by doing so?
- Do the
timecolumns of the two tables have exactly the same dtype, including theDatetimeunit and time zone?
For every signature, see the lacuna.signal API reference and the lacuna.adapters API reference. The statistics behind each table are in Signal diagnostics.