label
label
Leakage-explicit target construction for financial machine learning.
Labeling functions intentionally inspect observations after each event. They produce model targets and must not be used as point-in-time input features. Event-indexed outputs use the event start time as their pandas index, named event_time. This index is the row key for aligning labels, weights, metadata, and event-time features in pandas operations and :class:Dataset.
Functions
| Name | Description |
|---|---|
| average_uniqueness | Compute each label’s mean inverse concurrency. |
| class_balance_weights | Give every observed class equal total sample weight. |
| combine_weights | Multiply aligned sample-weight components. |
| concurrency | Count active label intervals at every observation. |
| cusum_filter | Detect structural events with a symmetric CUSUM filter. |
| fixed_horizon | Label future returns at a fixed horizon. |
| indicator_matrix | Build a sparse observation-by-event membership matrix. |
| meta_label | Label whether a proposed trading side produces a positive outcome. |
| prune_labels | Iteratively remove classes below a minimum sample fraction. |
| purging_metadata | Export event-lifetime metadata for leakage-aware splitters. |
| sample_weights | Weight labels by absolute return attributed through concurrency. |
| sequential_bootstrap | Draw events sequentially in proportion to marginal uniqueness. |
| time_decay | Create linear recency factors from cumulative sample importance. |
| trend_scanning | Label events using the strongest forward linear trend. |
| triple_barrier | Apply profit-taking, stop-loss, and vertical barriers to events. |
| vertical_barriers | Map events to the first observation at or beyond a future horizon. |
average_uniqueness
label.average_uniqueness(observations, end_times, *, concurrency_counts=None)Compute each label’s mean inverse concurrency.
Parameters
| Name | Type | Description | Default |
|---|---|---|---|
| observations | pd.Index | Ordered, unique observation index. | required |
| end_times | pd.Series | Series indexed by event start and containing inclusive end times. | required |
| concurrency_counts | pd.Series | None | Optional precomputed output from :func:concurrency. |
None |
Returns
| Name | Type | Description |
|---|---|---|
| pd.Series | Event-indexed Series in the interval (0, 1]. |
Notes
Precomputed concurrency may be zero outside all event lifetimes, but it must be positive at every observation belonging to an event.
class_balance_weights
label.class_balance_weights(labels)Give every observed class equal total sample weight.
Parameters
| Name | Type | Description | Default |
|---|---|---|---|
| labels | pd.Series | Ordered target labels without missing values. | required |
Returns
| Name | Type | Description |
|---|---|---|
| pd.Series | Event-indexed inverse-frequency factors normalized to unit mean. | |
| pd.Series | Empty input produces an empty Series. |
combine_weights
label.combine_weights(*weights, normalize=True)Multiply aligned sample-weight components.
Parameters
| Name | Type | Description | Default |
|---|---|---|---|
| *weights | pd.Series | One or more non-negative Series with identical indexes. | () |
| normalize | bool | Scale a nonzero result to unit mean. | True |
Returns
| Name | Type | Description |
|---|---|---|
| pd.Series | Combined event-indexed sample weights. |
Notes
A zero in any component eliminates that event multiplicatively. When normalization is requested, an all-zero result is rejected because it cannot define usable training weights.
concurrency
label.concurrency(observations, end_times)Count active label intervals at every observation.
Event intervals include both their start and end observations.
Parameters
| Name | Type | Description | Default |
|---|---|---|---|
| observations | pd.Index | Ordered, unique observation index. | required |
| end_times | pd.Series | Series indexed by event start and containing inclusive event end times. | required |
Returns
| Name | Type | Description |
|---|---|---|
| pd.Series | Integer Series aligned to observations. |
cusum_filter
label.cusum_filter(prices, threshold, *, drift=0.0, log_returns=True)Detect structural events with a symmetric CUSUM filter.
Positive and negative cumulative changes are tracked independently. An event is emitted when either accumulator crosses threshold; the triggered accumulator is then reset. With log_returns=True, thresholds and drift are expressed as decimal log returns.
Parameters
| Name | Type | Description | Default |
|---|---|---|---|
| prices | pd.Series | Ordered prices for one instrument. | required |
| threshold | float | pd.Series | Positive scalar or an aligned Series of time-varying thresholds. Missing Series values suppress events and reset the accumulators at those observations. | required |
| drift | float | Non-negative drift subtracted from each directional increment. | 0.0 |
| log_returns | bool | Use log-price changes instead of arithmetic differences. | True |
Returns
| Name | Type | Description |
|---|---|---|
| pd.Index | Index containing the timestamps where a threshold was crossed. |
fixed_horizon
label.fixed_horizon(
prices,
horizon,
*,
events=None,
threshold=0.0,
drop_censored=True,
)Label future returns at a fixed horizon.
Returns above threshold receive label 1, returns below its negative receive -1, and values inside the neutral band receive 0. Missing dynamic thresholds are excluded. By default, events without a complete future horizon are also excluded.
Parameters
| Name | Type | Description | Default |
|---|---|---|---|
| prices | pd.Series | Ordered positive prices for one instrument. | required |
| horizon | Horizon | Positive number of bars or positive timedelta-like value. | required |
| events | pd.Index | Iterable[Any] | None | Event labels drawn from prices.index. Defaults to all. |
None |
| threshold | float | pd.Series | Non-negative scalar or event-aligned neutral-band width. | 0.0 |
| drop_censored | bool | Drop events whose horizon extends past available data. | True |
Returns
| Name | Type | Description |
|---|---|---|
| pd.DataFrame | DataFrame indexed by event start time, named event_time, with end |
|
| pd.DataFrame | time, realized return, threshold, and label. The index aligns rows with | |
| pd.DataFrame | event-time features and metadata in pandas operations. |
indicator_matrix
label.indicator_matrix(observations, end_times)Build a sparse observation-by-event membership matrix.
A value of 1 means the observation belongs to the event’s inclusive lifetime. Summing rows therefore reproduces :func:concurrency, while summing inverse row counts over columns supports uniqueness calculations.
Parameters
| Name | Type | Description | Default |
|---|---|---|---|
| observations | pd.Index | Ordered, unique observation index. | required |
| end_times | pd.Series | Series indexed by event start and containing inclusive event end times. | required |
Returns
| Name | Type | Description |
|---|---|---|
| pd.DataFrame | Sparse integer DataFrame with observations as rows and event starts as | |
| pd.DataFrame | columns. |
meta_label
label.meta_label(returns, side, *, threshold=0.0)Label whether a proposed trading side produces a positive outcome.
Parameters
| Name | Type | Description | Default |
|---|---|---|---|
| returns | pd.Series | Realized underlying returns. | required |
| side | pd.Series | Aligned directional predictions in {-1, 0, 1}. Zero represents no proposed trade and always receives label 0. | required |
| threshold | float | pd.Series | Non-negative scalar or aligned minimum side-adjusted return. | 0.0 |
Returns
| Name | Type | Description |
|---|---|---|
| pd.Series | Nullable integer Series containing 1 for accepted sides and 0 for | |
| pd.Series | rejected sides. Missing inputs remain missing. |
prune_labels
label.prune_labels(labels, *, min_fraction=0.05, min_classes=2)Iteratively remove classes below a minimum sample fraction.
Fractions are recomputed after each removal. Pruning stops when every remaining class meets min_fraction or only min_classes remain, so a classification target is not silently collapsed to one class by default. Tied rare classes are removed in first-observed order.
Parameters
| Name | Type | Description | Default |
|---|---|---|---|
| labels | pd.Series | Ordered target labels without missing values. | required |
| min_fraction | float | Minimum class fraction in the interval (0, 1]. | 0.05 |
| min_classes | int | Minimum number of classes to preserve. | 2 |
Returns
| Name | Type | Description |
|---|---|---|
| pd.Series | A pair containing the filtered labels and a class-level audit DataFrame | |
| pd.DataFrame | with initial/final counts and fractions, removal status, and drop step. |
purging_metadata
label.purging_metadata(observations, end_times, *, embargo=0)Export event-lifetime metadata for leakage-aware splitters.
max_end_time is the latest endpoint among the current and all earlier events. A chronological training block ending at that row can only be followed safely at next_safe_time after also skipping embargo observations. Missing safe times mean the required point lies beyond the available timeline.
Parameters
| Name | Type | Description | Default |
|---|---|---|---|
| observations | pd.Index | Ordered, unique observation index. | required |
| end_times | pd.Series | Series indexed by event start and containing inclusive event end times. | required |
| embargo | int | Non-negative number of observations to skip after the running maximum label end. | 0 |
Returns
| Name | Type | Description |
|---|---|---|
| pd.DataFrame | Event-indexed DataFrame containing endpoint positions and labels, | |
| pd.DataFrame | running maximum endpoints, prior-overlap flags, and next safe points. |
sample_weights
label.sample_weights(prices, end_times, *, normalize=True)Weight labels by absolute return attributed through concurrency.
Each log return is divided by the number of labels active at that observation before it is accumulated over an event’s lifetime. Optional normalization scales nonzero weights to sum to the number of events.
Parameters
| Name | Type | Description | Default |
|---|---|---|---|
| prices | pd.Series | Ordered positive prices aligned to the labeling timeline. | required |
| end_times | pd.Series | Series indexed by event start and containing inclusive end times, such as triple_barrier(...)["touch_time"]. |
required |
| normalize | bool | Scale weights to have unit mean when their sum is nonzero. | True |
Returns
| Name | Type | Description |
|---|---|---|
| pd.Series | Non-negative event-indexed sample weights. |
sequential_bootstrap
label.sequential_bootstrap(
observations,
end_times,
*,
size=None,
random_state=None,
)Draw events sequentially in proportion to marginal uniqueness.
After every draw, candidate probabilities are recomputed from the average inverse concurrency that each event would have if selected next. Events may be drawn repeatedly, as in an ordinary bootstrap, while isolated or underrepresented lifetimes receive higher probability.
Parameters
| Name | Type | Description | Default |
|---|---|---|---|
| observations | pd.Index | Ordered, unique observation index. | required |
| end_times | pd.Series | Series indexed by event start and containing inclusive event end times. | required |
| size | int | None | Number of events to draw. Defaults to the original event count. | None |
| random_state | int | np.random.Generator | None | Seed or NumPy random generator for reproducible draws. | None |
Returns
| Name | Type | Description |
|---|---|---|
| pd.Index | Index of sampled event starts, potentially containing duplicates. |
time_decay
label.time_decay(weights, *, minimum_weight=0.0)Create linear recency factors from cumulative sample importance.
The ordered input commonly contains average uniqueness. Its cumulative mass defines progress through the sample: the factor starts at minimum_weight before the oldest mass and reaches 1 at the newest event. Multiplying these factors into other sample weights gradually reduces older observations without deleting them.
Parameters
| Name | Type | Description | Default |
|---|---|---|---|
| weights | pd.Series | Ordered, non-negative event importance values. | required |
| minimum_weight | float | Decay intercept in the closed interval [0, 1]. | 0.0 |
Returns
| Name | Type | Description |
|---|---|---|
| pd.Series | Event-indexed factors between minimum_weight and 1. |
trend_scanning
label.trend_scanning(
prices,
*,
events=None,
horizons=range(5, 21),
min_t_value=0.0,
log_prices=True,
drop_censored=True,
)Label events using the strongest forward linear trend.
For each event, ordinary least squares is fitted over every eligible forward horizon. The horizon whose slope has the largest absolute t-value is retained. A horizon of n means n bars after the event and fits n + 1 observations including the event itself.
Parameters
| Name | Type | Description | Default |
|---|---|---|---|
| prices | pd.Series | Ordered prices for one instrument. | required |
| events | pd.Index | Iterable[Any] | None | Event labels drawn from prices.index. Defaults to all. |
None |
| horizons | Iterable[int] | Unique, increasing forward bar counts of at least 2. | range(5, 21) |
| min_t_value | float | Absolute t-value required for a directional label. | 0.0 |
| log_prices | bool | Regress log prices, making slope units approximately continuously compounded return per bar. | True |
| drop_censored | bool | Drop events for which no requested horizon is complete. | True |
Returns
| Name | Type | Description |
|---|---|---|
| pd.DataFrame | DataFrame indexed by event start time, named event_time, containing |
|
| pd.DataFrame | the selected end time, horizon, slope, t-value, realized return, and | |
| pd.DataFrame | directional label. The index aligns rows with other event-indexed | |
| pd.DataFrame | objects. |
triple_barrier
label.triple_barrier(
prices,
target,
*,
events=None,
horizon=None,
vertical=None,
upper=1.0,
lower=1.0,
side=None,
min_target=0.0,
drop_censored=True,
)Apply profit-taking, stop-loss, and vertical barriers to events.
Horizontal barriers are multiples of an event-specific return target. The first barrier touched by the close-price path determines touch_time. Without side, labels are directional (-1, 0, 1). With an explicit side, returns are side-adjusted for barrier detection and labels become binary meta-labels: 1 for a profitable side and 0 otherwise.
Parameters
| Name | Type | Description | Default |
|---|---|---|---|
| prices | pd.Series | Ordered positive close prices for one instrument. | required |
| target | float | pd.Series | Positive scalar or Series of event-specific return widths. Missing Series values and values at or below min_target are excluded. |
required |
| events | pd.Index | Iterable[Any] | None | Event labels drawn from prices.index. Defaults to all. |
None |
| horizon | Horizon | None | Positive bar count or timedelta-like vertical horizon. | None |
| vertical | pd.Series | None | Explicit event-indexed vertical-barrier times. Supply exactly one of horizon or vertical. |
None |
| upper | float | None | Profit-taking multiplier. None disables this barrier. |
1.0 |
| lower | float | None | Stop-loss multiplier. None disables this barrier. |
1.0 |
| side | float | pd.Series | None | Optional scalar or event-aligned Series containing -1 or 1. | None |
| min_target | float | Minimum eligible target width. | 0.0 |
| drop_censored | bool | Drop events without a complete vertical horizon. | True |
Returns
| Name | Type | Description |
|---|---|---|
| pd.DataFrame | DataFrame indexed by event start time, named event_time, describing |
|
| pd.DataFrame | barriers, realized returns, and labels. The index aligns rows with | |
| pd.DataFrame | event-time features and metadata in pandas operations. Side-aware | |
| pd.DataFrame | results also include side and adjusted_return. |
vertical_barriers
label.vertical_barriers(observations, horizon, *, events=None)Map events to the first observation at or beyond a future horizon.
Integer horizons count observations after each event. Timedelta-like horizons use the first observed timestamp greater than or equal to the requested wall-clock duration. Events without enough future data receive a missing barrier.
Parameters
| Name | Type | Description | Default |
|---|---|---|---|
| observations | pd.Index | Ordered, unique observation index. | required |
| horizon | Horizon | Positive number of bars or a positive timedelta-like value. | required |
| events | pd.Index | Iterable[Any] | None | Event labels drawn from observations. Defaults to every observation. |
None |
Returns
| Name | Type | Description |
|---|---|---|
| pd.Series | Series indexed by event start time, named event_time, and |
|
| pd.Series | containing vertical-barrier times. The index is the pandas alignment | |
| pd.Series | key for other event-indexed objects. |