Signal diagnostics
Measure how well a signal ranks forward returns with IC, quantiles, turnover, decay, neutralization and portfolio projection, and what each number assumes.
A signal is a score for each instrument at each point in time. The question a diagnostic answers is whether that score sorted what happened next. Each diagnostic answers a slightly different version of the question, and each one carries an assumption that can quietly inflate the answer: labels that overlap, ties that are broken by row order, a signal that is mostly a size or sector tilt, a spread that nobody could trade.
lacuna.signal holds the functions. SignalStudy calls the same functions with your table and label settings filled in, so the two always agree. This page uses the functions, then shows the study equivalents at the end.
The example panel
Everything below reuses one synthetic panel: 50 instruments over 250 sessions, built once with a fixed seed. The structure is planted so the outputs mean something.
- The signal is a persistent “news” component, plus a size tilt and a sector tilt that have nothing to do with returns.
- Returns respond to the news component on the session after it arrives, and to nothing else. The signal therefore has a weak real effect that does not last, hidden under exposures that carry no information.
- Prices carry
openandclose. Each open equals the previous close, which keeps the panel small.
Because the signal is computed from a close, the labels enter at the next open. The labels are built with lc.labels.forward_returns; see Forward-return labels for every timing choice. A horizon such as "5D" means five observations per instrument, here five sessions, not five calendar days. Turnover lags count observations the same way.
from datetime import date, timedelta
import lacuna as lc
import numpy as np
import polars as pl
rng = np.random.default_rng(7)
n_instruments, n_sessions = 50, 250
days = (date(2024, 1, 1) + timedelta(days=n) for n in range(400))
sessions = [day for day in days if day.weekday() < 5][:n_sessions]
sector_codes = rng.integers(0, 5, n_instruments)
size = rng.normal(size=n_instruments)
sector_tilt = np.array([0.8, 0.4, 0.0, -0.4, -0.8])
sector_names = np.array(["energy", "tech", "health", "banks", "retail"])
news = rng.normal(size=(n_sessions, n_instruments))
persistent = np.zeros((n_sessions, n_instruments))
persistent[0] = news[0]
for t in range(1, n_sessions):
persistent[t] = 0.8 * persistent[t - 1] + np.sqrt(1 - 0.8**2) * news[t]
score = persistent + 0.7 * size + sector_tilt[sector_codes]
returns = np.zeros((n_sessions, n_instruments))
returns[1:] = 0.006 * news[:-1] + 0.02 * rng.normal(size=(n_sessions - 1, n_instruments))
close = 100 * np.exp(np.cumsum(returns, axis=0))
open_ = np.vstack([close[:1], close[:-1]])
ids = [f"S{i:02d}" for i in range(n_instruments)]
times = pl.Series("time", sessions).repeat_by(n_instruments).explode()
prices = pl.DataFrame(
{"time": times, "instrument": ids * n_sessions, "open": open_.ravel(), "close": close.ravel()}
)
signal = pl.DataFrame(
{
"time": times,
"instrument": ids * n_sessions,
"signal": score.ravel(),
"sector": np.tile(sector_names[sector_codes], n_sessions),
"log_size": np.tile(size, n_sessions),
"sector_available_time": times,
}
)
label_options = {"signal_time": "close", "entry": "next_open", "price_adjustment": "split_adjusted"}
labels = lc.labels.forward_returns(
prices, horizons=("1D", "2D", "3D", "5D", "7D", "10D"), **label_options
)
labels_5d = lc.labels.forward_returns(prices, horizon="5D", **label_options)
def pick(result, *names, digits=4):
metrics = getattr(result, "evidence", result).metrics
return {name: round(metrics[name], digits) if isinstance(metrics[name], float) else metrics[name] for name in names}
def show(result, name, *columns, digits=4):
frame = pl.DataFrame(result.table(name)).select(columns)
return frame.with_columns(
pl.col(column).round(digits) for column in columns if frame.schema[column] == pl.Float64
)
print(signal.select("time", "instrument", "signal", "sector").head(3)) shape: (3, 4)
┌────────────┬────────────┬───────────┬────────┐
│ time ┆ instrument ┆ signal ┆ sector │
│ --- ┆ --- ┆ --- ┆ --- │
│ date ┆ str ┆ f64 ┆ str │
╞════════════╪════════════╪═══════════╪════════╡
│ 2024-01-01 ┆ S00 ┆ -0.241448 ┆ retail │
│ 2024-01-01 ┆ S01 ┆ -2.488945 ┆ banks │
│ 2024-01-01 ┆ S02 ┆ -1.145661 ┆ banks │
└────────────┴────────────┴───────────┴────────┘ pick and show are small helpers for this page: they round numbers for display. Lacuna stores full precision and rounds only in what you print.
The functions take a signal table with time, instrument and signal columns, and labels from lc.labels.forward_returns. Extra columns, such as sector, are ignored unless you name them. Column names are parameters, so you do not need to rename your time, signal, price or identifier columns. Labels and bucket frames that Lacuna produces always name the identifier instrument, whatever the source column was called, and the functions read that name on the label side. The instrument parameter names the identifier column in your own signal table, and in a label table you built yourself. Input formats are covered in Data.
Information coefficient
The information coefficient (IC) is the cross-sectional correlation between the signal and the forward return, computed separately for each time. One number per time answers “did the signal rank this date’s returns”, and the sequence of those numbers shows whether the answer is stable.
ic = lc.signal.ic(signal, labels_5d)
print(pick(ic, "mean_ic", "std_ic", "ic_information_ratio", "t_statistic", "positive_fraction", "n_periods"))
print(pick(ic, "signal_rows", "matched_rows_before_policy", "excluded_rows"))
print(ic.warnings[0]) {'mean_ic': 0.0567, 'std_ic': 0.1365, 'ic_information_ratio': 0.4153, 't_statistic': 6.5001, 'positive_fraction': 0.6408, 'n_periods': 245}
{'signal_rows': 12500, 'matched_rows_before_policy': 12250, 'excluded_rows': 0}
The reported t-statistic is the ordinary time-series statistic and does not adjust for serial dependence. The mean IC is about 0.057 and the IC information ratio, the mean over the standard deviation of the per-period ICs, is about 0.42. Real signals usually sit in the low hundredths, and a large IC is a reason to recheck label timing before celebrating. This panel plants a larger effect than most real signals have, so the later diagnostics have something to show.
signal_rows counts signal rows and matched_rows_before_policy counts the rows that found a label. The last five sessions have no 5D label, so 250 of the 12,500 signal rows drop out of the join. Nothing is filled in.
Read the t-statistic with care
t_statistic is the ordinary statistic for a mean, mean_ic / (std_ic / sqrt(n_periods)). It assumes the per-period ICs are independent, and with a 5D horizon they are not: the labels at consecutive sessions share four of their five return observations. The statistic is too large, and ic.warnings says so every time. Use it to compare runs on the same labels, not as a p-value. SignalStudy.audit resamples only the IC periods whose label intervals do not overlap for exactly this reason. It bootstraps one declared horizon: the first in the study’s horizons, unless you pass policies={"inference_horizon": ...}. It skips the bootstrap when fewer than two non-overlapping periods remain.
Spearman and Pearson
method="spearman", the default, is the Pearson correlation of ranks. Ties receive the average of the ranks they span, which does not depend on row order. method="pearson" correlates the raw values, so a few extreme values can dominate it. Both are accepted for NumPy arrays too, which is the quickest way to see the difference on tied data.
tied_signal = np.array([1.0, 1.0, 2.0, 3.0, 3.0, 3.0, 5.0, 4.0])
next_return = np.array([0.01, 0.03, 0.02, 0.00, 0.05, 0.01, 0.06, 0.02])
for method in ("spearman", "pearson"):
print(method, pick(lc.signal.ic(tied_signal, next_return, method=method), "mean_ic", "n_observations")) spearman {'mean_ic': 0.3044, 'n_observations': 8}
pearson {'mean_ic': 0.4472, 'n_observations': 8} Two one-dimensional arrays are treated as a single cross-section, so there is one IC. The result still carries an IC_PERIOD_SUPPORT_LOW finding because one period supports no statement about stability.
A period where the signal or the labels are constant has no defined correlation. That IC is null, not zero, and the result records an IC_UNDEFINED_GROUPS finding.
Grouping
by chooses the groups an IC is computed in. The default, "observation_time", gives one IC per time. Passing a different by replaces the default, it does not add to it. This matters:
by_sector = lc.signal.ic(signal, labels_5d, by="sector")
by_date_and_sector = lc.signal.ic(signal, labels_5d, by=["time", "sector"])
print(len(by_sector.table("ic_by_period")), len(by_date_and_sector.table("ic_by_period")))
print(sorted(by_date_and_sector.tables)) 5 1225
['data_attrition', 'ic_by_horizon', 'ic_by_period', 'ic_overall_by_horizon', 'ic_overall_by_period'] by="sector" pools every date into one correlation per sector, five rows. by=["time", "sector"] gives one IC per date and sector. The grouped results sit in ic_by_period and ic_by_horizon. The headline metrics are computed with the grouping column removed, and the ic_overall_* tables hold the periods behind them: by=["time", "sector"] still gives one IC per time over the whole cross-section, and by="sector" gives one pooled IC. You can write the time column by its name in your table ("time") or as "observation_time".
A grouping column is a classification, and a classification has a history. Sector codes assigned after the fact leak the future. Declare when the classification was known with group_available_time:
undeclared = lc.signal.ic(signal, labels_5d, by=["time", "sector"])
declared = lc.signal.ic(
signal, labels_5d, by=["time", "sector"], group_available_time="sector_available_time"
)
print([(f.code, f.state.value) for f in undeclared.findings])
print([(f.code, f.state.value) for f in declared.findings]) [('GROUP_AVAILABILITY_UNKNOWN', 'UNKNOWN')]
[('GROUP_AVAILABILITY_VERIFIED', 'PASS')] Lacuna checks that the named column is never later than the observation time and raises a DataContractError if it is. It cannot check that the column says when the classification was truly known. That is your assertion, and Lacuna records it. Without the declaration the result carries GROUP_AVAILABILITY_UNKNOWN. In ic the named column must exist, but it is only checked when by includes a grouping column. quantiles and bucketize(available_time=...) verify it whenever you pass it, and raise if it is later than the observation time.
Several horizons at once
When the labels contain several horizons, every pair of time and horizon is its own group, and ic_by_horizon has one row per horizon, ordered by horizon length. A 1D and a 10D IC answer different questions, so the headline metrics (mean_ic, std_ic, ic_information_ratio, t_statistic, n_periods) never pool them. They describe one horizon, recorded as headline_horizon in the result’s parameters: the first horizon in the order a LabelResult declares. That is the horizons you passed to forward_returns, and it is the same default SignalStudy.audit infers on.
ic_all = lc.signal.ic(signal, labels)
print(ic_all.metadata.parameters["headline_horizon"], pick(ic_all, "mean_ic", "n_periods"))
print(show(ic_all, "ic_by_horizon", "horizon", "mean_ic", "ic_information_ratio", "n_periods")) 1D {'mean_ic': 0.1291, 'n_periods': 249}
shape: (6, 4)
┌─────────┬─────────┬──────────────────────┬───────────┐
│ horizon ┆ mean_ic ┆ ic_information_ratio ┆ n_periods │
│ --- ┆ --- ┆ --- ┆ --- │
│ str ┆ f64 ┆ f64 ┆ i64 │
╞═════════╪═════════╪══════════════════════╪═══════════╡
│ 1D ┆ 0.1291 ┆ 0.8833 ┆ 249 │
│ 2D ┆ 0.1023 ┆ 0.7387 ┆ 248 │
│ 3D ┆ 0.0837 ┆ 0.6126 ┆ 247 │
│ 5D ┆ 0.0567 ┆ 0.4153 ┆ 245 │
│ 7D ┆ 0.0432 ┆ 0.3308 ┆ 243 │
│ 10D ┆ 0.0236 ┆ 0.1821 ┆ 240 │
└─────────┴─────────┴──────────────────────┴───────────┘ The headline is the 1D row, because 1D is first in horizons. Put the horizon you care about first when you build the labels. The headline never moves to a later horizon: if the declared one has no aligned rows, the headline metrics are empty.
A bare label table has no declared order. With a single horizon in the table, that horizon is the headline. With several, the headline metrics are null and the result carries an IC_HEADLINE_HORIZON_UNDECLARED finding in the UNKNOWN state, rather than a pooled number or a horizon picked by text order. The per-horizon table is still complete.
bare = lc.signal.ic(signal, labels.frame)
print(bare.metadata.parameters["headline_horizon"], bare.metrics["mean_ic"])
print([(f.code, f.state.value) for f in bare.findings])
print(bare.table("ic_by_horizon")[0]["horizon"], len(bare.table("ic_by_horizon"))) None None
[('IC_HEADLINE_HORIZON_UNDECLARED', 'UNKNOWN')]
1D 6 Missing values, sizes and backends
null_policy="drop" removes rows whose signal or label is null or NaN and counts them in excluded_rows. "raise" raises instead. Infinite values are never dropped, because that would hide a data error. ic raises a DataContractError for an infinite signal or label value anywhere in the inputs, including rows that find no join partner, such as the final observations that have no label. quantiles, bucketize and turnover check every signal row and raise.
min_observations sets the smallest cross-section that gets an IC. Smaller groups are excluded and reported as IC_UNDERSIZED_GROUPS. It must be at least 2, and the call raises if no group reaches it. Fewer than 20 defined periods adds an IC_PERIOD_SUPPORT_LOW finding.
use_native=True computes Spearman with the Rust kernel when it is available, and falls back to the NumPy reference implementation if the extension cannot be imported. use_native=False forces the reference. Both agree to floating-point tolerance, and the one used is recorded in the result’s provenance. Pearson always uses the reference path.
reference = lc.signal.ic(signal, labels_5d, use_native=False)
print(reference.metadata.parameters["backend"], abs(reference.metrics["mean_ic"] - ic.metrics["mean_ic"]) < 1e-12) numpy_reference True Quantiles
An IC averages over the whole cross-section. Quantile analysis asks the question an investor asks: if you sorted instruments into buckets by signal, did the top bucket earn more than the bottom one, and are the buckets in order in between?
quantile_result = lc.signal.quantiles(signal, labels_5d, quantiles=5)
print(pick(quantile_result, "mean_top_bottom_spread", "spearman_monotonicity", "adjacent_order_fraction", "n_quantiles"))
print(show(quantile_result, "quantile_returns", "quantile", "mean_return", "median_return", "n_observations")) {'mean_top_bottom_spread': 0.0081, 'spearman_monotonicity': 1.0, 'adjacent_order_fraction': 1.0, 'n_quantiles': 5}
shape: (5, 4)
┌──────────┬─────────────┬───────────────┬────────────────┐
│ quantile ┆ mean_return ┆ median_return ┆ n_observations │
│ --- ┆ --- ┆ --- ┆ --- │
│ i64 ┆ f64 ┆ f64 ┆ i64 │
╞══════════╪═════════════╪═══════════════╪════════════════╡
│ 1 ┆ -0.0024 ┆ -0.0047 ┆ 2450 │
│ 2 ┆ -0.0021 ┆ -0.003 ┆ 2450 │
│ 3 ┆ -0.0012 ┆ -0.0017 ┆ 2450 │
│ 4 ┆ 0.0022 ┆ 0.0011 ┆ 2450 │
│ 5 ┆ 0.0057 ┆ 0.0046 ┆ 2450 │
└──────────┴─────────────┴───────────────┴────────────────┘ At every time, the instruments are sorted by (signal, instrument) and split into quantiles buckets of sizes that differ by at most one. Bucket 1 holds the lowest signal. The tie rule is "balanced": tied values are split across buckets in instrument order, so the result never depends on row order. That is deterministic, but it means a tie between two instruments is broken by their IDs. If your signal has many ties, read Balanced or preserved ties.
The spread is the mean return of the top bucket minus the mean return of bucket 1, computed at each time and then averaged over times. The two monotonicity metrics ask whether the bucket means are ordered. spearman_monotonicity is the rank correlation between bucket number and mean return, and adjacent_order_fraction is the share of neighbouring bucket pairs where the higher bucket earned more. A strongly ordered signal has both near 1, and a signal whose top and bottom buckets are the only informative ones scores lower. The result adds a QUANTILE_MONOTONICITY_WEAK finding when the Spearman value is below 0.5.
ascending=False numbers the highest signal as bucket 1. The “top bucket” is then the lowest-signal group, so the spread changes sign. Use it for a signal where low means good, and keep the sign in mind when you read the spread.
Groups with fewer instruments than quantiles (by default, times) are dropped and reported as QUANTILE_UNDERSIZED_GROUPS. With several horizons, the headline spread and both monotonicity metrics describe one horizon, chosen the way the IC’s is: the first horizon of a LabelResult, recorded as headline_horizon. A bare label table with several horizons gives null headline metrics and a QUANTILE_HEADLINE_HORIZON_UNDECLARED finding in the UNKNOWN state. n_observations counts the aligned rows of the headline horizon, like the spread beside it: it is null when the headline is undeclared and 0 when the headline horizon has no aligned rows. signal_rows, matched_rows_before_policy and excluded_rows describe the join over every horizon. quantile_returns and monotonicity hold every horizon, ordered by horizon length.
Buckets
lc.signal.quantiles is a convenience. It calls lc.signal.bucketize with BucketSpec.quantiles(quantiles) and small_group_policy="drop", then lc.signal.bucket_returns. When you want a different bucketing, call them yourself. bucketize assigns every eligible signal row to a bucket and returns a SignalTransformResult: the rows in .frame, and the counts, findings and parameters in .evidence.
spec = lc.signal.BucketSpec.quantiles(5)
bucketed = lc.signal.bucketize(signal, spec=spec)
print(bucketed.frame.head(3))
print(pick(bucketed, "input_rows", "retained_rows", "requested_buckets", "effective_buckets"))
returns_by_bucket = lc.signal.bucket_returns(bucketed, labels_5d)
print(returns_by_bucket.metrics["mean_top_bottom_spread"] - quantile_result.metrics["mean_top_bottom_spread"]) shape: (3, 4)
┌──────────────────┬────────────┬───────────┬────────┐
│ observation_time ┆ instrument ┆ signal ┆ bucket │
│ --- ┆ --- ┆ --- ┆ --- │
│ date ┆ str ┆ f64 ┆ i32 │
╞══════════════════╪════════════╪═══════════╪════════╡
│ 2024-01-01 ┆ S01 ┆ -2.488945 ┆ 1 │
│ 2024-01-01 ┆ S05 ┆ -1.89912 ┆ 1 │
│ 2024-01-01 ┆ S06 ┆ -1.438108 ┆ 1 │
└──────────────────┴────────────┴───────────┴────────┘
{'input_rows': 12500, 'retained_rows': 12500, 'requested_buckets': 5, 'effective_buckets': 5}
0.0 bucket_returns accepts only the result of bucketize. Its spread is the highest requested bucket minus bucket 1, as in quantiles. It follows the same headline-horizon rule as ic. If the declared headline horizon has no aligned rows, the headline metrics are null and the result carries BUCKET_HEADLINE_HORIZON_EMPTY (UNKNOWN); quantiles reports the same case as QUANTILE_HEADLINE_HORIZON_EMPTY. The headline does not fall back to a later horizon.
A BucketSpec records the policy, and its constructors cover four kinds of bucket:
| Constructor | Buckets | Use it for |
|---|---|---|
BucketSpec.quantiles(count) | Equal-count buckets within each group. Pass edges=[0, 0.3, 0.7, 1] to cut at probabilities instead. | The standard case. |
BucketSpec.quantiles(count, split_at=0.0) | count // 2 buckets below the split and the rest above, each side divided into equal-count buckets, so an odd count puts the extra bucket above. | A signal with a natural zero, such as a z-score. |
BucketSpec.equal_width(count) | Equal-width buckets between the group’s minimum and maximum. | A signal whose magnitude matters. A constant group has no width and is rejected. |
BucketSpec.edges([...]) | Fixed numeric buckets between the edges you give. A value equal to an inner edge goes to the upper bucket. | Absolute thresholds that must not move with the data. |
BucketSpec.threshold(value) | Two buckets, below and at or above the value. | A rule such as “signal above zero”. |
fixed = lc.signal.bucketize(signal, spec=lc.signal.BucketSpec.edges([-1.0, 0.0, 1.0], out_of_range="drop"))
print(pick(fixed, "input_rows", "retained_rows", "excluded_bucket_rows", "effective_buckets"))
split = lc.signal.bucketize(signal, spec=lc.signal.BucketSpec.quantiles(4, split_at=0.0))
print(split.frame.group_by("bucket").len().sort("bucket").to_dicts()) {'input_rows': 12500, 'retained_rows': 6724, 'excluded_bucket_rows': 5776, 'effective_buckets': 2}
[{'bucket': 1, 'len': 3405}, {'bucket': 2, 'len': 3536}, {'bucket': 3, 'len': 2714}, {'bucket': 4, 'len': 2845}] Values outside the outermost edges raise by default. out_of_range="drop" removes them and counts them in excluded_bucket_rows. With the default out_of_range="raise" and small_group_policy="drop", a group that contains an out-of-range value is excluded whole and counted in excluded_groups. For threshold and quantiles(..., split_at=...), equal_to chooses whether a value exactly at the threshold goes to the lower or the upper side. The default is the upper side.
Balanced or preserved ties
With tie_policy="balanced", equal signal values can land in different buckets. With tie_policy="preserve", equal values always share a bucket, which can leave other buckets empty. Neither is wrong; they answer different questions, and the result tells you what happened.
six = pl.DataFrame(
{"time": [sessions[0]] * 6, "instrument": list("ABCDEF"), "signal": [1.0, 1.0, 1.0, 1.0, 2.0, 3.0]}
)
for tie_policy in ("balanced", "preserve"):
result = lc.signal.bucketize(six, spec=lc.signal.BucketSpec.quantiles(3, tie_policy=tie_policy))
print(tie_policy, result.frame["bucket"].to_list(), [f.code for f in result.evidence.findings]) balanced [1, 1, 2, 2, 3, 3] []
preserve [2, 2, 2, 2, 3, 3] ['BUCKETS_EFFECTIVE_COUNT_REDUCED'] Four tied values at the bottom of three buckets are split two and two under balanced. Under preserve they all go to bucket 2, bucket 1 is empty, and the result carries BUCKETS_EFFECTIVE_COUNT_REDUCED.
Small groups
When you bucket within groups, some groups may be too small. small_group_policy="raise", the default for bucketize, stops at the first one. "drop" excludes the whole group, counts its rows, and adds a BUCKET_UNDERSIZED_GROUPS finding. A group is too small for a quantile spec when it has fewer rows than buckets, for a split spec when one side lacks rows, and for an equal-width spec when it is constant.
lc.signal.bucketize(signal, spec=lc.signal.BucketSpec.quantiles(10), by=["time", "sector"]) DataContractError: bucket group has 8 rows but requires at least 10 by_sector = lc.signal.bucketize(
signal, spec=lc.signal.BucketSpec.quantiles(10), by=["time", "sector"], small_group_policy="drop"
)
print(pick(by_sector, "input_rows", "retained_rows", "excluded_groups")) {'input_rows': 12500, 'retained_rows': 6000, 'excluded_groups': 750} Dropping is only safe if the dropped groups are not systematically the small sectors or the thin dates. The counts are in the result so you can check.
bucketize takes by="time" by default, one set of buckets per time. A bucketed result keeps only the grouping columns you name in by, plus available_time (renamed) if you pass one, which is why a group_neutral portfolio below has to bucket by that column first.
Turnover
A signal that reorders the whole universe every day may be right and still impossible to trade. lc.signal.turnover measures how much the cross-section changes between observations, with no labels involved.
turn = lc.signal.turnover(signal, quantiles=5, lags=(1, 5))
print(show(turn, "turnover_by_lag", "lag", "mean_rank_turnover", "mean_signal_autocorrelation", "mean_top_membership_turnover", "n_transitions")) shape: (2, 5)
┌─────┬────────────────────┬───────────────────────────┬───────────────────────────┬───────────────┐
│ lag ┆ mean_rank_turnover ┆ mean_signal_autocorrelati ┆ mean_top_membership_turno ┆ n_transitions │
│ --- ┆ --- ┆ on ┆ ver ┆ --- │
│ i64 ┆ f64 ┆ --- ┆ --- ┆ i64 │
│ ┆ ┆ f64 ┆ f64 ┆ │
╞═════╪════════════════════╪═══════════════════════════╪═══════════════════════════╪═══════════════╡
│ 1 ┆ 0.1108 ┆ 0.8896 ┆ 0.2835 ┆ 249 │
│ 5 ┆ 0.2055 ┆ 0.6114 ┆ 0.5049 ┆ 245 │
└─────┴────────────────────┴───────────────────────────┴───────────────────────────┴───────────────┘ Three measures are reported for each lag:
| Column | Meaning |
|---|---|
mean_rank_turnover | Mean absolute change in an instrument’s percentile rank, over the instruments present at both observations. 0 means the ordering did not change. |
mean_signal_autocorrelation | Pearson correlation between the raw signal and its value lag observations earlier, over the same instruments. |
mean_top_membership_turnover and mean_bottom_membership_turnover | Share of the top (or bottom) quantile bucket that changed, from the symmetric-difference definition under How it is computed. |
The lag counts observations on a global clock: the sorted distinct observation times in your table. A lag of 5 compares each time with the one five distinct times earlier. An instrument absent from the earlier time is not paired. lags must include 1, and the headline metrics (mean_rank_turnover and mean_signal_autocorrelation) describe lag 1 only. Other lags are in turnover_by_lag and the per-period tables.
Turnover assigns its quantile buckets with the balanced midpoint rule that quantiles and bucketize use, from each instrument’s ordinal rank by (signal, instrument) at that time. The result records it as membership_bucket_rule, with the value balanced_midpoint_position. A boundary instrument therefore sits in the same bucket for returns and for turnover, and the top and bottom legs have the same size when the period size is not a multiple of quantiles. Turnover does not take a BucketSpec, and it always breaks ties by instrument ID. If you have turnover numbers from 0.14.1 (method version 1), membership turnover can differ whenever the period size is not a multiple of quantiles; rank turnover and signal autocorrelation are unchanged. High turnover is the first thing to check before you spend effort on costs.
Decay
IC at one horizon is one point on a curve. Decay computes the curve: the Spearman IC and the top-minus-bottom spread at each horizon in the labels.
decay_result = lc.signal.decay(signal, labels)
print(show(decay_result, "ic_decay", "horizon", "mean_ic", "ic_information_ratio", "mean_top_bottom_spread"))
print(decay_result.warnings[0]) shape: (6, 4)
┌─────────┬─────────┬──────────────────────┬────────────────────────┐
│ horizon ┆ mean_ic ┆ ic_information_ratio ┆ mean_top_bottom_spread │
│ --- ┆ --- ┆ --- ┆ --- │
│ str ┆ f64 ┆ f64 ┆ f64 │
╞═════════╪═════════╪══════════════════════╪════════════════════════╡
│ 1D ┆ 0.1291 ┆ 0.8833 ┆ 0.0078 │
│ 2D ┆ 0.1023 ┆ 0.7387 ┆ 0.0086 │
│ 3D ┆ 0.0837 ┆ 0.6126 ┆ 0.0084 │
│ 5D ┆ 0.0567 ┆ 0.4153 ┆ 0.0081 │
│ 7D ┆ 0.0432 ┆ 0.3308 ┆ 0.0066 │
│ 10D ┆ 0.0236 ┆ 0.1821 ┆ 0.0054 │
└─────────┴─────────┴──────────────────────┴────────────────────────┘
A half-life is not estimated unless a validated identifiable decay model is supplied. The table is ordered by horizon length, and also holds std_top_bottom_spread and n_spread_periods, the number of periods behind each horizon’s spread. The IC falls with horizon. The planted effect lasts one session, so a longer label adds return that the signal knows nothing about, and the correlation dilutes. The spread is a cumulative return, so it does not fall the same way: it stays between 0.005 and 0.009 while the IC drops by a factor of five. For measuring how fast the signal fades, read the IC.
decay also accepts prices. With horizons, it builds the labels with lc.labels.forward_returns and the entry, price, price_time and price_adjustment you pass.
from_prices = lc.signal.decay(
signal, prices, horizons=(1, 2, 3, 5), entry="next_open", price_adjustment="split_adjusted"
)
print(pick(from_prices, "n_horizons")) {'n_horizons': 4} This path builds labels without a signal_time declaration, so the same-close check on labels does not run, and the default entry=None enters at the signal’s own observation price (the current close). For a close-observed signal pass entry="next_open" or "next_close", as above. Build the labels yourself when you want the same-close check. horizons is rejected when you pass labels, because the labels already define them.
Fitting a half-life
lc.signal.fit_decay turns the decay curve into a half-life, with an interval, when the data support one. It needs SciPy, which is in the statistics extra (pip install "lacuna-quant[statistics]").
fit = lc.signal.fit_decay(decay_result, seed=7, resamples=500)
print(pick(fit, "half_life", "half_life_lower", "half_life_upper", "r_squared", "successful_resamples"))
print([(f.code, f.state.value) for f in fit.findings])
print(fit.metadata.seed, fit.metadata.parameters["root_entropy"])
print(show(fit, "decay_fit", "horizon", "direction_adjusted_mean", "fitted_value", "residual")) {'half_life': 3.499, 'half_life_lower': 2.1299, 'half_life_upper': 7.2918, 'r_squared': 0.9922, 'successful_resamples': 462}
[('DECAY_HALF_LIFE_IDENTIFIED', 'PASS')]
7 7
shape: (6, 4)
┌─────────┬─────────────────────────┬──────────────┬──────────┐
│ horizon ┆ direction_adjusted_mean ┆ fitted_value ┆ residual │
│ --- ┆ --- ┆ --- ┆ --- │
│ str ┆ f64 ┆ f64 ┆ f64 │
╞═════════╪═════════════════════════╪══════════════╪══════════╡
│ 1D ┆ 0.1256 ┆ 0.1221 ┆ 0.0035 │
│ 2D ┆ 0.0981 ┆ 0.1001 ┆ -0.002 │
│ 3D ┆ 0.0788 ┆ 0.0821 ┆ -0.0033 │
│ 5D ┆ 0.0525 ┆ 0.0553 ┆ -0.0027 │
│ 7D ┆ 0.0407 ┆ 0.0372 ┆ 0.0035 │
│ 10D ┆ 0.0236 ┆ 0.0205 ┆ 0.003 │
└─────────┴─────────────────────────┴──────────────┴──────────┘ The model is an exponential in the horizon , measured in observations:
It is fitted by least squares with scipy.optimize.curve_fit to the mean metric at each horizon, with and . The point estimate is the half-life of that fit. The interval comes from a stationary bootstrap that resamples whole periods at once, keeping every horizon of a period together so the horizons stay as correlated as they were. Each resample is refitted. The interval is the percentile range of the refitted half-lives at confidence.
Read the fit as a summary of the curve, not as a measurement of a mechanism. The planted effect here lasts exactly one session, and an exponential is only an approximation of how a one-session effect dilutes across longer labels. The half-life is conditional on the exponential model, and the result’s warning says so.
fit_decay refuses to report a half-life unless every condition holds. It checks them in this order, and each failure is a finding with its own code:
| Code | State | Condition that failed |
|---|---|---|
DECAY_JOINT_PERIOD_EVIDENCE_MISSING | UNKNOWN | The source result has no per-period table for the metric. |
DECAY_SUPPORT_INSUFFICIENT | UNKNOWN | Fewer than four horizons, or fewer than twenty periods in which every horizon has a value. |
DECAY_DIRECTION_INVALID | WARN | A direction-adjusted horizon mean is not positive. |
DECAY_OPTIMIZATION_FAILED | WARN | The optimizer raised an error. |
DECAY_FIT_NOT_IDENTIFIABLE | WARN | The fitted ran to its upper bound (1,000 times the longest horizon), or is below minimum_r_squared. |
DECAY_BOOTSTRAP_UNSTABLE | WARN | Fewer than 80% of the resamples refitted to an identifiable half-life. A resample fails if a horizon mean is not positive, the optimizer fails, or the fitted reaches its bound. |
DECAY_HALF_LIFE_IDENTIFIED | PASS | All of the above passed. |
When any gate fails, half_life and its bounds are null. SciPy is imported only after the support and direction gates pass, so a short or wrong-signed curve never needs it.
expected_direction is your statement of which way the metric should point. It multiplies the metric by +1 or -1 before fitting, so a signal that predicts reversals, with a negative IC at every horizon, is fitted with expected_direction="negative". It is an assertion, not a search: if the means do not have the stated sign, the fit stops at DECAY_DIRECTION_INVALID.
wrong_way = lc.signal.fit_decay(decay_result, expected_direction="negative", seed=7, resamples=500)
print(wrong_way.findings[0].code, wrong_way.metrics["half_life"]) DECAY_DIRECTION_INVALID None minimum_r_squared is the fit-quality gate. Lower it only if you accept a curve the data barely follow. expected_block_length is the mean block length of the bootstrap. The default is max(2, round(n ** (1/3))) for n periods. Overlapping labels make the IC at consecutive times correlated over about h - 1 periods, so with long horizons a larger block length is the safer choice.
The bootstrap uses the periods in which every horizon has a value. That set is smaller than the set behind each horizon’s mean_ic in the decay table, so the direction_adjusted_mean values differ slightly from the table’s mean_ic. Pass seed to reproduce the interval. A supplied seed is recorded in metadata.seed. Without one, Lacuna draws fresh entropy, leaves metadata.seed empty, and records the entropy as root_entropy in the result’s parameters so the run can be replayed. A fit that stops at any gate above except DECAY_BOOTSTRAP_UNSTABLE ends before the bootstrap, so it draws no random numbers and leaves root_entropy null, even when you pass a seed. See Results.
Neutralize
A signal can look good because it loads on something you did not mean to bet on. If high signal values are large companies, or all in one sector, the IC may be measuring size or sector. lc.signal.neutralize removes the part of the signal explained by exposures you name, one regression per time, and returns the residual as a new signal.
neutralized = lc.signal.neutralize(signal, exposures=["log_size", "sector"], categorical=["sector"])
print(neutralized.frame.head(3))
print(pick(neutralized, "n_groups", "rank_deficient_groups", "retained_rows"))
raw_ic = lc.signal.ic(signal, labels_5d)
neutral_ic = lc.signal.ic(neutralized.frame, labels_5d, signal_time="observation_time")
print(pick(raw_ic, "mean_ic", "ic_information_ratio"), pick(neutral_ic, "mean_ic", "ic_information_ratio")) shape: (3, 4)
┌──────────────────┬────────────┬───────────────┬───────────┐
│ observation_time ┆ instrument ┆ source_signal ┆ signal │
│ --- ┆ --- ┆ --- ┆ --- │
│ date ┆ str ┆ f64 ┆ f64 │
╞══════════════════╪════════════╪═══════════════╪═══════════╡
│ 2024-01-01 ┆ S00 ┆ -0.241448 ┆ 0.814453 │
│ 2024-01-01 ┆ S01 ┆ -2.488945 ┆ -0.185221 │
│ 2024-01-01 ┆ S02 ┆ -1.145661 ┆ -0.027998 │
└──────────────────┴────────────┴───────────────┴───────────┘
{'n_groups': 250, 'rank_deficient_groups': 0, 'retained_rows': 12500}
{'mean_ic': 0.0567, 'ic_information_ratio': 0.4153} {'mean_ic': 0.0723, 'ic_information_ratio': 0.5064} The IC rises once the size and sector tilts are removed, because those tilts were noise with respect to returns. The output frame names its time column observation_time, so pass signal_time="observation_time" when you give it to ic or bucketize. source_signal is the original value and signal is the residual.
At each time, the signal is regressed on an intercept, the continuous exposures, and a dummy for each level of each categorical exposure except the first level in sorted order, which is the baseline. With intercept=False there is no constant to absorb a baseline, so the first categorical keeps a dummy for every level, and the residuals are demeaned within each of its levels. A second categorical still drops its first level to keep the design full rank. The residual is the signal minus the fitted values.
With weight, the regression is weighted least squares. The weights must be positive and come from the exposure table. The residual is still the plain difference between the signal and the fit, and with an intercept the weighted residuals sum to zero.
Each group’s design must leave enough degrees of freedom. The residual degrees of freedom are the number of rows minus the rank of the design, and a group below min_residual_df raises, or with insufficient_policy="drop" is excluded and counted.
lc.signal.neutralize(signal, exposures=["log_size"], min_residual_df=60) DataContractError: neutralization group has insufficient residual degrees of freedom A rank-deficient design, such as two collinear exposures, still returns the minimum-norm solution, and the result carries a NEUTRALIZATION_RANK_DEFICIENT finding.
Exposures usually come from another table. Pass it as exposure_data with its own time column (exposure_time), and the weights and availability column are read from it.
exposures = signal.select(
"time", "instrument", "sector", "log_size", pl.col("time").alias("available_time")
).with_columns(market_cap=(pl.col("log_size") * 0.5 + 3).exp())
weighted = lc.signal.neutralize(
signal.select("time", "instrument", "signal"),
exposures=["log_size", "sector"],
categorical=["sector"],
exposure_data=exposures,
weight="market_cap",
available_time="available_time",
)
print([(f.code, f.state.value) for f in weighted.evidence.findings])
print(weighted.frame.columns) [('GROUP_AVAILABILITY_VERIFIED', 'PASS')]
['observation_time', 'instrument', 'source_signal', 'signal', 'available_time'] The join between the signal and the exposures is on exact (time, instrument) keys. There is no as-of matching, so an exposure that is updated monthly has to be repeated on every date you want to use it. Rows without a match are dropped and counted in the data_attrition table. As with group_available_time, available_time is an assertion: Lacuna verifies it is not later than the exposure’s time, and records that it was declared, but it cannot tell whether the exposure was really known then. Without it the result carries GROUP_AVAILABILITY_UNKNOWN, whose message and evidence name the exposure and group columns it concerns:
print(neutralized.evidence.findings[0].code, neutralized.evidence.findings[0].evidence) GROUP_AVAILABILITY_UNKNOWN {'available_time_column': None, 'group_columns': (), 'exposure_columns': ('log_size', 'sector')} To see the intercept=False rule, regress on sector alone. The residuals are demeaned within every sector, including the baseline one:
no_intercept = lc.signal.neutralize(signal, exposures=["sector"], categorical=["sector"], intercept=False)
sectors = signal.select(pl.col("time").alias("observation_time"), "instrument", "sector")
residual_means = (
no_intercept.frame.join(sectors, on=["observation_time", "instrument"])
.group_by("observation_time", "sector")
.agg(pl.col("signal").mean().abs().alias("mean_residual"))
)
print(residual_means["mean_residual"].max() < 1e-12) True Portfolio projection
Quantile spreads are averages of returns. lc.signal.portfolio_projection turns chosen buckets into explicit target weights and shows what those weights would have earned over one label horizon, so you can look at exposure, concentration and weight turnover.
five = lc.signal.bucketize(signal, spec=lc.signal.BucketSpec.quantiles(5))
projection = lc.signal.portfolio_projection(
five, labels, horizon="5D", long_buckets=[5], short_buckets=[1]
)
print(projection.frame.select("observation_time", "instrument", "bucket", "leg", "target_weight", "contribution").head(3))
print(pick(projection, "n_cohorts", "matched_rows", "excluded_alignment_rows", "mean_cohort_return", "mean_one_way_target_turnover", digits=5))
print({key: projection.metadata.parameters[key] for key in ("compounding", "overlapping_holdings_resolution", "execution_simulation")}) shape: (3, 6)
┌──────────────────┬────────────┬────────┬──────┬───────────────┬──────────────┐
│ observation_time ┆ instrument ┆ bucket ┆ leg ┆ target_weight ┆ contribution │
│ --- ┆ --- ┆ --- ┆ --- ┆ --- ┆ --- │
│ date ┆ str ┆ i32 ┆ str ┆ f64 ┆ f64 │
╞══════════════════╪════════════╪════════╪══════╪═══════════════╪══════════════╡
│ 2024-01-01 ┆ S04 ┆ 5 ┆ long ┆ 0.05 ┆ 0.000615 │
│ 2024-01-01 ┆ S09 ┆ 5 ┆ long ┆ 0.05 ┆ 0.001711 │
│ 2024-01-01 ┆ S13 ┆ 5 ┆ long ┆ 0.05 ┆ -0.000923 │
└──────────────────┴────────────┴────────┴──────┴───────────────┴──────────────┘
{'n_cohorts': 245, 'matched_rows': 4900, 'excluded_alignment_rows': 100, 'mean_cohort_return': 0.00404, 'mean_one_way_target_turnover': 0.26742}
{'compounding': False, 'overlapping_holdings_resolution': False, 'execution_simulation': False} This is a diagnostic projection, not a backtest. Each observation time is an independent cohort: its weights are applied to the forward return over the label horizon, and nothing carries over. Returns are not compounded, overlapping holdings are not resolved (with a 5D horizon and daily cohorts, five cohorts are held at once and the cohort return is a 5D return, not a daily one), no execution is simulated, and there are no costs. Use it to inspect the weights, and use costs and capacity before you believe any return.
The projection frame has one row per held position: target_weight, the label’s forward_return, and contribution, which is their product. The cohort_returns table sums contributions per cohort, split into long_contribution and short_contribution. Other tables hold the exposure reconciliation, per-cohort concentration (weight_hhi and max_absolute_weight) and the turnover of target weights between consecutive cohorts, 0.5 * sum(|w_t - w_(t-1)|) over the union of instruments.
The long and short legs share gross_exposure, split by net_exposure: the long leg gets (gross + net) / 2 and the short leg (gross - net) / 2. With the defaults, gross 1 and net 0, each leg holds 0.5. That is why the mean cohort return here is half the quantile spread: 0.5 of the top bucket minus 0.5 of the bottom. Lacuna checks that every cohort’s weights reconcile to the requested gross and net exposure, to a tolerance of 1e-10, and raises if they do not.
weighting | Weight within a leg |
|---|---|
"equal" | Equal. |
"rank" | Proportional to the rank of +signal in the long leg and of -signal in the short leg, whatever the bucket numbering. With ascending=True the most extreme signal gets the largest weight. |
"absolute_signal" | Proportional to the absolute signal value. A leg where every signal is zero falls back to equal weights and adds PORTFOLIO_ZERO_SIGNAL_FALLBACK. |
Pass group_neutral to build both legs inside each group, such as a sector, so the portfolio does not take a sector bet. The group column has to be in the bucketed result, so bucket by it first. Each group that has both legs receives an equal share of the exposure, not a share by size.
by_sector = lc.signal.bucketize(
signal, spec=lc.signal.BucketSpec.quantiles(5), by=["time", "sector"], small_group_policy="drop"
)
neutral_projection = lc.signal.portfolio_projection(
by_sector, labels, horizon="5D", long_buckets=[5], short_buckets=[1],
weighting="rank", group_neutral="sector",
)
week = neutral_projection.frame.filter(pl.col("observation_time") == sessions[40])
by_group = week.group_by("sector").agg(
pl.col("target_weight").abs().sum().round(6).alias("gross_weight"),
pl.col("target_weight").sum().abs().round(6).alias("net_weight"),
)
print(by_group.sort("sector"))
print(pick(neutral_projection, "n_rows", "mean_cohort_return", digits=5)) shape: (5, 3)
┌────────┬──────────────┬────────────┐
│ sector ┆ gross_weight ┆ net_weight │
│ --- ┆ --- ┆ --- │
│ str ┆ f64 ┆ f64 │
╞════════╪══════════════╪════════════╡
│ banks ┆ 0.2 ┆ 0.0 │
│ energy ┆ 0.2 ┆ 0.0 │
│ health ┆ 0.2 ┆ 0.0 │
│ retail ┆ 0.2 ┆ 0.0 │
│ tech ┆ 0.2 ┆ 0.0 │
└────────┴──────────────┴────────────┘
{'n_rows': 5390, 'mean_cohort_return': 0.00439} Each of the five sectors holds a gross weight of 0.2 and a net weight of zero in that cohort.
With ascending=False, bucket 1 is the highest signal. A long leg built from the low-signal buckets under weighting="rank" then gives the largest weight to its highest-signal, least extreme names, and the short leg does the same in reverse. In a run on this panel, the lowest-signal long name received the smallest weight. Use equal or absolute_signal weights there, or keep the long leg on the high-signal side.
A group that has only one leg in a cohort cannot be neutral. incomplete_group_policy="raise", the default, stops. "drop" excludes it, renormalises the rest and adds PORTFOLIO_INCOMPLETE_GROUPS_EXCLUDED. A cohort left with no group that holds both legs raises under either policy. horizon must be a string that appears in the labels, such as "5D", and the labels must carry entry_time and label_end, which lc.labels.forward_returns provides.
With SignalStudy
SignalStudy holds the signal, the prices and the label settings once, builds the labels when first needed and caches them, and passes them and your column names to each function. The study below is the setup from this page.
study = lc.SignalStudy(
signal=signal,
prices=prices,
horizons=("1D", "2D", "3D", "5D", "7D", "10D"),
signal_observed_at="close",
entry="next_open",
price_adjustment="split_adjusted",
quantiles=5,
)
study_decay = study.decay()
study_fit = study.fit_decay(seed=7, resamples=500)
print(pick(study_fit, "half_life", "r_squared"))
print(show(study.turnover(lags=(1, 5)), "turnover_by_lag", "lag", "mean_rank_turnover")) {'half_life': 3.499, 'r_squared': 0.9922}
shape: (2, 2)
┌─────┬────────────────────┐
│ lag ┆ mean_rank_turnover │
│ --- ┆ --- │
│ i64 ┆ f64 │
╞═════╪════════════════════╡
│ 1 ┆ 0.1108 │
│ 5 ┆ 0.2055 │
└─────┴────────────────────┘ | Study method | Calls | What the study supplies |
|---|---|---|
study.ic(...) | lc.signal.ic | The labels and column names. |
study.quantiles(...) | lc.signal.quantiles | The labels, column names, and the study’s quantiles (5 by default, not 10) unless you pass a count. The same study value also sets decay’s quantile_count and turnover’s quantiles. |
study.bucketize(...) | lc.signal.bucketize | The signal and column names. by defaults to the study’s signal time. |
study.bucket_returns(bucketed) | lc.signal.bucket_returns | The labels. |
study.neutralize(...) | lc.signal.neutralize | The signal and column names. The exposure table’s time column must have the study’s signal-time name. |
study.turnover(...) | lc.signal.turnover | The signal and column names, and the study’s quantiles unless you pass a count. |
study.decay(...) | lc.signal.decay | The labels, and the study’s quantiles as quantile_count unless you pass a count. |
study.fit_decay(...) | lc.signal.decay then lc.signal.fit_decay | Both calls in one, so it takes the parameters of both. |
study.portfolio_projection(bucketed, ...) | lc.signal.portfolio_projection | The labels. |
The study’s default horizons are ("1D", "5D", "20D"). Three horizons cannot support a decay fit, so study.fit_decay() on a study with the defaults returns DECAY_SUPPORT_INSUFFICIENT. Pass at least four horizons to fit a half-life. The study methods do not expose every function parameter, for example null_policy. Call the function directly when you need one that is missing. study.audit() runs several of these methods and turns the results into findings; see Audits and reports.
How it is computed
Information coefficient. For time with signal values and forward returns over the instruments with both, the Spearman IC is the Pearson correlation of the average ranks and :
A block of tied values spanning sorted positions to shares the rank . If the denominator is zero, the IC is null. Pearson uses the raw values in place of ranks. Over the defined periods:
where is the sample standard deviation with in the denominator. The information ratio is not annualised. The statistic ignores dependence between periods.
Quantile spread and monotonicity. Sort the instruments of a group by . The -th has position and goes to bucket , where the are the inner bucket boundaries, for equal buckets. The period spread is
the mean return of the top bucket minus the mean return of bucket 1. The reported spread averages over times where both exist. spearman_monotonicity is the Spearman correlation between bucket number and the period-averaged bucket mean return. adjacent_order_fraction is the share of neighbouring bucket pairs with a higher mean for the higher bucket.
Turnover. With the percentile rank from average ranks over the full cross-section at time , and the instruments present at both and :
where and are the members of bucket at and at , with buckets assigned by the midpoint rule from the quantile formula above. It is null when both are empty.
Decay fit. Let be the mean of the chosen metric over the common periods, multiplied by or for expected_direction. Minimise over and , starting from and equal to the median horizon. Then
Each bootstrap resample draws periods in blocks with geometric lengths whose mean is the expected block length, continuing circularly, recomputes every from the resampled periods and refits .
Neutralization. For each group, with design matrix (intercept, continuous exposures, categorical dummies) and weights , the coefficients solve
by least squares, taking the minimum-norm solution when is rank deficient. The residual degrees of freedom are .
Projection weights. For each cohort (and group), with long allocation and short allocation , where is gross_exposure, is net_exposure and is the number of groups holding both legs, a position with score in a leg with total score gets the weight . The contribution is the weight times the forward return, and the cohort return is the sum of contributions.
Parameters
The generated signature reference lists types and defaults. The tables below say what each parameter means. Time, instrument and value column names (signal_time, label_time, instrument, signal_value, label_value) default to the names used on this page.
| Parameter | Meaning |
|---|---|
signal | The signal table, or a one-dimensional NumPy array to treat as a single cross-section. |
labels | A LabelResult or a label table with observation_time, instrument and forward_return. A horizon column makes each horizon its own group. |
method | "spearman" (average ranks) or "pearson". |
by | The groups an IC is computed in. Replaces the default of one group per time, so include the time column if you want per-date groups. |
signal_time | The name of the time column in the signal table. |
label_time | The name of the time column in the label table. |
instrument | The identifier column of the signal table. Labels from forward_returns always name theirs instrument, and that name is read when you pass the LabelResult. A bare label table is read with this name when it has the column and with instrument otherwise, so labels.frame works too. |
signal_value | The signal value column. |
label_value | The forward-return column. |
min_observations | The smallest cross-section that gets an IC. At least 2. |
group_available_time | A column giving when each group classification was known. It must exist, and is checked against the observation time only when by includes a grouping column; what it claims is your assertion. |
null_policy | "drop" or "raise" for null and NaN. Infinity in the signal or label values always raises, on any row. |
use_native | Use the Rust kernel for Spearman when available. |
| Parameter | Meaning |
|---|---|
signal, labels | As for ic. |
quantiles | The number of buckets, at least 2. Ten by default here. |
by | The groups buckets are formed in, as for ic. |
signal_time, label_time, instrument, signal_value, label_value | Column names, as for ic. |
ascending | True numbers the lowest signal as bucket 1. False reverses it and flips the sign of the spread. |
tie_policy | Only "balanced" is supported here. Use bucketize for "preserve". |
group_available_time | As for ic, except that it is always verified and raises if later than the observation time. |
null_policy | As for ic. |
| Parameter | Meaning |
|---|---|
signal | The signal table. |
spec | A BucketSpec. Defaults to ten quantile buckets. |
by | The groups buckets are formed in. Defaults to "time". Only the grouping columns named here, and available_time if given, survive in the output. |
time, instrument, signal_value | Column names. |
available_time | A column giving when each grouping attribute was known, verified as for ic. |
ascending | True numbers the lowest signal as bucket 1. |
small_group_policy | "raise" or "drop" for groups that cannot be bucketed. |
null_policy | "drop" or "raise" for null and NaN. |
| Parameter | Meaning |
|---|---|
bucketed | The SignalTransformResult from bucketize. |
labels | A LabelResult or label table. |
by | The groups the spread is computed in. |
label_time, instrument, label_value | Column names in the label table. Labels from forward_returns always name the identifier instrument, so instrument matters only for a label table you built yourself. |
null_policy | "drop" or "raise" for null and NaN. |
| Parameter | Meaning |
|---|---|
count | The number of equal-count buckets. |
edges | Probability cut points from 0 to 1, such as [0, 0.3, 0.7, 1]. They set the number of buckets. |
tie_policy | "balanced" splits ties across buckets by instrument order. "preserve" keeps equal values together. |
split_at | A signal value that divides the buckets: count // 2 below it and the rest above. |
equal_to | Whether a value exactly at split_at goes to the "lower" or "upper" side. |
| Parameter | Meaning |
|---|---|
signal | The signal table. |
time, instrument, signal_value | Column names. |
quantiles | The number of buckets used for membership turnover, assigned by the same balanced midpoint rule as quantiles. |
lags | Unique positive lags, in observations. Must include 1. |
null_policy | "drop" or "raise" for null and NaN. |
| Parameter | Meaning |
|---|---|
signal | The signal table. |
labels_or_prices | A LabelResult, a label table, or a price table. |
horizons | Required for prices and rejected for labels. |
signal_time, instrument, signal_value | Column names in the signal table. |
price_time, price | Column names in the price table. |
entry | The entry rule used to build labels from prices. The default enters at the current close; use "next_open" or "next_close" for a close-observed signal. |
price_adjustment | The price adjustment you declare, recorded in the labels. |
min_observations | The smallest cross-section that gets an IC. |
quantile_count | The number of buckets behind the spread. |
use_native | As for ic. |
| Parameter | Meaning |
|---|---|
decay_result | The result of lc.signal.decay or study.decay(). |
metric | "mean_ic", or "mean_spread" (also written "mean_top_bottom_spread"). |
expected_direction | "positive" or "negative", the sign you expect the metric to have at every horizon. |
model | Only "exponential". |
confidence | Coverage of the half-life interval. |
resamples | Bootstrap resamples, at least 100. |
expected_block_length | The mean bootstrap block length. Defaults from the number of periods. |
seed | A non-negative integer. Without it the root entropy is drawn fresh and recorded. |
minimum_r_squared | The fit-quality gate, from 0 to 1. |
| Parameter | Meaning |
|---|---|
signal | The signal table. |
exposures | The columns to neutralize against. |
exposure_data | A separate table holding the exposures. By default they are read from signal. |
categorical | The exposures to treat as categories. Must be a subset of exposures. |
by | The groups a regression is run in. Defaults to "time". |
signal_time, exposure_time, instrument, signal_value | Column names. |
weight | A positive weight column for weighted least squares, read from the exposure table. |
available_time | A column giving when each exposure was known, verified not to exceed its time. |
intercept | Include an intercept. Without one, the first categorical exposure keeps a dummy for every level. |
min_residual_df | The smallest residual degrees of freedom a group may have. |
insufficient_policy | "raise" or "drop" for groups below min_residual_df. |
null_policy | "drop" or "raise" for null and NaN. |
| Parameter | Meaning |
|---|---|
bucketed | The result of bucketize. |
labels | A LabelResult, or a label table with horizon, entry and exit columns. |
horizon | One label horizon, as it appears in the labels, such as "5D". |
long_buckets, short_buckets | Bucket numbers for each leg. Must not overlap. |
weighting | "equal", "rank" or "absolute_signal". |
gross_exposure | Total absolute weight per cohort. |
net_exposure | Net weight per cohort. Its absolute value cannot exceed the gross. |
group_neutral | Column(s) to build both legs within. They must be in the bucketed result. |
incomplete_group_policy | "raise" or "drop" for groups with only one leg. |
The full signatures are in the API reference.