Target Module¶
Signal labeling strategies for machine learning training. These classes generate look-ahead labels (direction, return magnitude, volume regime) at various horizons.
Module Name
The target functionality is implemented in the signalflow.target module.
Event Detection
Market-wide event detectors are in the detector.market module.
Use mask_targets_by_signals() to exclude labels around detected events.
Base Class¶
signalflow.target.base.Labeler
dataclass
¶
Labeler(raw_data_type: RawDataType | str = RawDataType.SPOT, signal_category: SignalCategory = SignalCategory.PRICE_DIRECTION, pair_col: str = 'pair', ts_col: str = 'timestamp', keep_input_columns: bool = False, output_columns: list[str] | None = None, filter_signal_type: SignalType | None = None, mask_to_signals: bool = True, out_col: str = 'label', include_meta: bool = False, meta_columns: tuple[str, ...] = ('t_hit', 'ret'), softness_k: float = 3.0)
Bases: ABC
Base class for Polars-only signal labeling.
Assigns forward-looking labels to historical data based on future price movement. Labels are computed per-pair with length-preserving operations.
Key concepts
- Forward-looking: Labels depend on future data (not available in live trading)
- Per-pair processing: Each pair labeled independently
- Length-preserving: Output has same row count as input
- Signal masking: Optionally label only at signal timestamps
Public API
- compute(): Main entry point (handles grouping, filtering, projection)
- compute_group(): Per-pair labeling logic (must implement)
Common labeling strategies
- Fixed horizon: Label based on return over N bars
- Triple barrier: Label based on first hit of profit/loss/time barrier
- Quantile-based: Label based on return quantiles
Attributes:
| Name | Type | Description |
|---|---|---|
component_type |
ClassVar[SfComponentType]
|
Always LABELER for registry. |
raw_data_type |
RawDataType
|
Type of raw data. Default: SPOT. |
pair_col |
str
|
Trading pair column. Default: "pair". |
ts_col |
str
|
Timestamp column. Default: "timestamp". |
keep_input_columns |
bool
|
Keep all input columns. Default: False. |
output_columns |
list[str] | None
|
Specific columns to output. Default: None. |
filter_signal_type |
SignalType | None
|
Filter to specific signal type. Default: None. |
mask_to_signals |
bool
|
Mask labels to signal timestamps only. Default: True. |
out_col |
str
|
Output label column name. Default: "label". |
include_meta |
bool
|
Include metadata columns. Default: False. |
meta_columns |
tuple[str, ...]
|
Metadata column names. Default: ("t_hit", "ret"). |
Example
from signalflow.target import Labeler
from signalflow.core import SignalType
import polars as pl
class FixedHorizonLabeler(Labeler):
'''Label based on fixed-horizon return'''
def __init__(self, horizon: int = 10, threshold: float = 0.01):
super().__init__()
self.horizon = horizon
self.threshold = threshold
def compute_group(self, group_df, data_context=None):
# Compute forward return
labels = group_df.with_columns([
pl.col("close").shift(-self.horizon).alias("future_close")
]).with_columns([
((pl.col("future_close") / pl.col("close")) - 1).alias("return")
]).with_columns([
pl.when(pl.col("return") > self.threshold)
.then(pl.lit(SignalType.RISE.value))
.when(pl.col("return") < -self.threshold)
.then(pl.lit(SignalType.FALL.value))
.otherwise(pl.lit(SignalType.NONE.value))
.alias("label")
])
return labels
# Usage
labeler = FixedHorizonLabeler(horizon=10, threshold=0.01)
labeled = labeler.compute(ohlcv_df, signals=signals)
Note
compute_group() must preserve row count (no filtering). All timestamps must be timezone-naive. Signal masking requires mask_to_signals=True and signal_keys in context.
See Also
FixedHorizonLabeler: Simple fixed-horizon implementation. TripleBarrierLabeler: Three-barrier labeling strategy.
filter_signal_type
class-attribute
instance-attribute
¶
signal_category
class-attribute
instance-attribute
¶
Signal category this labeler produces. Default: PRICE_DIRECTION.
soft_classes
class-attribute
¶
Ordered class names emitted by :meth:compute_soft as p_<class> columns.
Empty by default — subclasses that support soft labeling must declare this
tuple. The order is significant: it fixes the column order in the soft output.
Class names should mirror the hard labels written to out_col so the
default compute_group_soft one-hot fallback can map them.
soft_col_prefix
class-attribute
¶
Prefix prepended to each soft class name to form the output column.
With soft_classes=("rise", "fall") and the default prefix, soft output
has columns p_rise and p_fall.
softness_k
class-attribute
instance-attribute
¶
Sigmoid steepness for soft probability calibration.
Higher softness_k makes soft probabilities sharper (closer to 0/1) and
collapses toward the hard labeling at the limit. softness_k only
matters for subclasses that compute calibrated soft probabilities; the
default one-hot fallback ignores it.
_apply_signal_mask ¶
_apply_signal_mask(df: DataFrame, data_context: dict[str, Any], group_df: DataFrame) -> pl.DataFrame
Mask labels to signal timestamps only.
Labels are computed for all rows, but only signal timestamps get actual labels; others are set to SignalType.NONE.
Used for meta-labeling: only label at detected signal points, not every bar.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
df
|
DataFrame
|
DataFrame with computed labels. |
required |
data_context
|
dict[str, Any]
|
Must contain "signal_keys" DataFrame. |
required |
group_df
|
DataFrame
|
Original group data for extracting pair value. |
required |
Returns:
| Type | Description |
|---|---|
DataFrame
|
pl.DataFrame: DataFrame with masked labels. |
Example
# In compute_group with masking
def compute_group(self, group_df, data_context=None):
# Compute labels for all rows
labeled = group_df.with_columns([...])
# Mask to signal timestamps only
if self.mask_to_signals and data_context:
labeled = self._apply_signal_mask(
labeled, data_context, group_df
)
return labeled
Note
Requires signal_keys in data_context with (pair, timestamp) columns. Non-signal rows get label=SignalType.NONE. Metadata columns also masked if include_meta=True.
Source code in src/signalflow/target/base.py
470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 | |
_compute_pl ¶
_compute_pl(df: DataFrame, signals: Signals | None, data_context: dict[str, Any] | None) -> pl.DataFrame
Internal Polars-based computation.
Orchestrates validation, filtering, grouping, and projection.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
df
|
DataFrame
|
Input data. |
required |
signals
|
Signals | None
|
Optional signals. |
required |
data_context
|
dict[str, Any] | None
|
Optional context. |
required |
Returns:
| Type | Description |
|---|---|
DataFrame
|
pl.DataFrame: Labeled data. |
Source code in src/signalflow/target/base.py
_compute_soft_pl ¶
_compute_soft_pl(df: DataFrame, signals: Signals | None, data_context: dict[str, Any] | None) -> pl.DataFrame
Internal Polars-based soft computation.
Mirrors :meth:_compute_pl orchestration but dispatches to
:meth:compute_group_soft and projects only the soft probability
columns (plus pair/timestamp).
Source code in src/signalflow/target/base.py
_filter_by_signals_pl ¶
Filter input to rows matching signal timestamps.
Inner join with signal timestamps of specific type.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
df
|
DataFrame
|
Input data. |
required |
s
|
DataFrame
|
Signals DataFrame. |
required |
signal_type
|
SignalType
|
Signal type to filter. |
required |
Returns:
| Type | Description |
|---|---|
DataFrame
|
pl.DataFrame: Filtered data (only rows at signal timestamps). |
Raises:
| Type | Description |
|---|---|
ValueError
|
If signals missing required columns. |
Source code in src/signalflow/target/base.py
_signals_to_pl ¶
Convert Signals to Polars DataFrame.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
signals
|
Signals
|
Signals container. |
required |
Returns:
| Type | Description |
|---|---|
DataFrame
|
pl.DataFrame: Signals as DataFrame. |
Raises:
| Type | Description |
|---|---|
TypeError
|
If Signals.value is not pl.DataFrame. |
Source code in src/signalflow/target/base.py
_validate_input_pl ¶
Validate input DataFrame schema.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
df
|
DataFrame
|
Input to validate. |
required |
Raises:
| Type | Description |
|---|---|
ValueError
|
If required columns missing. |
Source code in src/signalflow/target/base.py
compute ¶
compute(df: DataFrame, signals: Signals | None = None, data_context: dict[str, Any] | None = None) -> pl.DataFrame
Compute labels for input DataFrame.
Main entry point - handles validation, filtering, grouping, and projection.
Processing steps
- Validate input schema
- Sort by (pair, timestamp)
- (optional) Filter to specific signal type
- Group by pair and apply compute_group()
- Validate output (length-preserving)
- Project to output columns
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
df
|
DataFrame
|
Input data with OHLCV and required columns. |
required |
signals
|
Signals | None
|
Signals for filtering/masking. |
None
|
data_context
|
dict[str, Any] | None
|
Additional context. |
None
|
Returns:
| Type | Description |
|---|---|
DataFrame
|
pl.DataFrame: Labeled data with columns: - pair, timestamp (always included) - label column(s) (as specified by out_col) - (optional) metadata columns |
Raises:
| Type | Description |
|---|---|
TypeError
|
If df not pl.DataFrame or compute_group returns wrong type. |
ValueError
|
If compute_group changes row count or columns missing. |
Example
Source code in src/signalflow/target/base.py
compute_group
abstractmethod
¶
Compute labels for single pair group.
Core labeling logic - must be implemented by subclasses.
CRITICAL: Must preserve row count (len(output) == len(input)). No filtering allowed inside compute_group.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
group_df
|
DataFrame
|
Single pair's data, sorted by timestamp. |
required |
data_context
|
dict[str, Any] | None
|
Additional context. |
required |
Returns:
| Type | Description |
|---|---|
DataFrame
|
pl.DataFrame: Same length as input with added label columns. |
Example
def compute_group(self, group_df, data_context=None):
# Compute 10-bar forward return
return group_df.with_columns([
pl.col("close").shift(-10).alias("future_close")
]).with_columns([
((pl.col("future_close") / pl.col("close")) - 1).alias("return"),
pl.when((pl.col("future_close") / pl.col("close") - 1) > 0.01)
.then(pl.lit(SignalType.RISE.value))
.otherwise(pl.lit(SignalType.NONE.value))
.alias("label")
])
Note
Output must have same height as input (length-preserving). Use shift(-n) for forward-looking operations. Last N bars will have null labels (no future data).
Source code in src/signalflow/target/base.py
compute_group_soft ¶
Compute soft labels for a single pair group.
Default implementation: one-hot encoding of the hard labels produced
by :meth:compute_group. For each class c in :attr:soft_classes,
emits column {soft_col_prefix}{c} = 1.0 where the hard label
equals c, 0.0 elsewhere, and null where the hard label is null.
This default is degenerate (probabilities are point masses) and only useful as a fallback for labelers where calibrated probabilities are not meaningful (e.g. event detectors). Labelers with smooth thresholds — percentile, sigmoid, or distance-based — should override this with a calibrated probability distribution.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
group_df
|
DataFrame
|
Single pair's data, sorted by timestamp. |
required |
data_context
|
dict[str, Any] | None
|
Additional context. |
None
|
Returns:
| Type | Description |
|---|---|
DataFrame
|
DataFrame with same height as input, plus probability columns |
DataFrame
|
|
Source code in src/signalflow/target/base.py
compute_soft ¶
compute_soft(df: DataFrame, signals: Signals | None = None, data_context: dict[str, Any] | None = None) -> pl.DataFrame
Compute soft labels — probability distribution over soft_classes.
Same orchestration as :meth:compute but produces probability columns
{soft_col_prefix}{class} instead of a single categorical label.
Contract
- For every valid row, probability columns sum to 1.0.
- For invalid rows (no forward data, warm-up, etc.), all probability columns are null.
- Column order follows :attr:
soft_classes.
Subclasses override :meth:compute_group_soft with calibrated logic
(sigmoid / percentile / Gaussian membership). If they don't, the
default falls back to a one-hot encoding of :meth:compute_group's
hard labels.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
df
|
DataFrame
|
Input data with OHLCV and required columns. |
required |
signals
|
Signals | None
|
Signals for filtering/masking (same semantics as compute). |
None
|
data_context
|
dict[str, Any] | None
|
Additional context (e.g. |
None
|
Returns:
| Type | Description |
|---|---|
DataFrame
|
|
Raises:
| Type | Description |
|---|---|
TypeError
|
If |
NotImplementedError
|
If |
ValueError
|
If |
Source code in src/signalflow/target/base.py
Labeling Strategies¶
Fixed Horizon¶
signalflow.target.fixed_horizon_labeler.FixedHorizonLabeler
dataclass
¶
FixedHorizonLabeler(raw_data_type: RawDataType | str = RawDataType.SPOT, signal_category: SignalCategory = SignalCategory.PRICE_DIRECTION, pair_col: str = 'pair', ts_col: str = 'timestamp', keep_input_columns: bool = False, output_columns: list[str] | None = None, filter_signal_type: SignalType | None = None, mask_to_signals: bool = True, out_col: str = 'label', include_meta: bool = False, meta_columns: tuple[str, ...] = ('t1', 'ret'), softness_k: float = 3.0, price_col: str = 'close', horizon: int = 60, soft_noise_floor: float = 0.0)
Bases: Labeler
Fixed-Horizon Labeling
label[t0] = sign(close[t0 + horizon] - close[t0])
If signals provided, labels are written only on signal rows, while horizon is computed on full series (per pair).
soft_noise_floor
class-attribute
instance-attribute
¶
Indifference band for soft labels (log-return units).
With the default 0.0 the soft cut sits exactly at zero and probabilities
collapse to the hard sign(fwd_ret) decision as softness_k grows.
Set to e.g. 0.001 (≈10 bps) to put a no-change bucket around zero so
bars with tiny forward moves get appreciable p_none mass.
__post_init__ ¶
compute_group ¶
Source code in src/signalflow/target/fixed_horizon_labeler.py
compute_group_soft ¶
Soft labels: sigmoid over the signed forward log-return.
Produces a calibrated probability triple (p_fall, p_none, p_rise)
from the same forward return that drives the hard sign(fwd_ret)
decision. The middle bucket gets meaningful mass only when
:attr:soft_noise_floor is set above zero; otherwise it collapses to
a near-binary rise/fall split.
Source code in src/signalflow/target/fixed_horizon_labeler.py
Triple Barrier (Dynamic)¶
signalflow.target.triple_barrier_labeler.TripleBarrierLabeler
dataclass
¶
TripleBarrierLabeler(raw_data_type: RawDataType | str = RawDataType.SPOT, signal_category: SignalCategory = SignalCategory.PRICE_DIRECTION, pair_col: str = 'pair', ts_col: str = 'timestamp', keep_input_columns: bool = False, output_columns: list[str] | None = None, filter_signal_type: SignalType | None = None, mask_to_signals: bool = True, out_col: str = 'label', include_meta: bool = False, meta_columns: tuple[str, ...] = ('t_hit', 'ret'), softness_k: float = 3.0, price_col: str = 'close', vol_window: int = 60, horizon: int = 1440, profit_multiplier: float = 1.0, stop_loss_multiplier: float = 1.0)
Bases: Labeler
Triple-Barrier Labeling (De Prado), Numba-accelerated.
__post_init__ ¶
Source code in src/signalflow/target/triple_barrier_labeler.py
_apply_labels ¶
Apply RISE/FALL/NONE labels based on barrier hits.
Source code in src/signalflow/target/triple_barrier_labeler.py
_compute_meta ¶
_compute_meta(df: DataFrame, prices: ndarray, up_off_series: Series, dn_off_series: Series, lf: int) -> pl.DataFrame
Compute t_hit and ret meta columns.
Source code in src/signalflow/target/triple_barrier_labeler.py
compute_group ¶
Source code in src/signalflow/target/triple_barrier_labeler.py
compute_group_soft ¶
Soft triple (p_fall, p_none, p_rise) based on barrier-hit timing.
Uses the same numba _find_first_hit to determine which barrier was
crossed first, then converts the timing gap into smooth probabilities:
* Let ``e_up = up_off if hit else horizon`` and likewise ``e_dn``.
* ``gap = (e_dn - e_up) / horizon`` ∈ ``[-1, 1]``;
* ``p_rise = sigmoid(k * gap)``, ``p_fall = sigmoid(-k * gap)``;
* ``p_none = max(1 - p_rise - p_fall, 0)`` (then renormalised) so
cases where neither barrier triggered carry probability mass on
``none``.
Source code in src/signalflow/target/triple_barrier_labeler.py
131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 | |
Take Profit (Symmetric Barrier)¶
signalflow.target.take_profit_labeler.TakeProfitLabeler
dataclass
¶
TakeProfitLabeler(raw_data_type: RawDataType | str = RawDataType.SPOT, signal_category: SignalCategory = SignalCategory.PRICE_DIRECTION, pair_col: str = 'pair', ts_col: str = 'timestamp', keep_input_columns: bool = False, output_columns: list[str] | None = None, filter_signal_type: SignalType | None = None, mask_to_signals: bool = True, out_col: str = 'label', include_meta: bool = False, meta_columns: tuple[str, ...] = ('t_hit', 'ret'), softness_k: float = 3.0, price_col: str = 'close', horizon: int = 1440, barrier_pct: float = 0.01)
Bases: Labeler
First-touch labeling with symmetric fixed-percentage barriers.
Label by first touch
- RISE if TP touched first (ties -> TP)
- FALL if SL touched first
- NONE if neither touched within horizon
__post_init__ ¶
Source code in src/signalflow/target/take_profit_labeler.py
compute_group ¶
Source code in src/signalflow/target/take_profit_labeler.py
compute_group_soft ¶
Soft triple (p_fall, p_none, p_rise) from barrier-hit timing.
Same calibration scheme as :class:TripleBarrierLabeler but with the
fixed ±barrier_pct barriers from this labeler.
Source code in src/signalflow/target/take_profit_labeler.py
Non-Price-Direction Labelers¶
Anomaly Labeler¶
signalflow.target.anomaly_labeler.AnomalyLabeler
dataclass
¶
AnomalyLabeler(raw_data_type: RawDataType | str = RawDataType.SPOT, signal_category: SignalCategory = SignalCategory.ANOMALY, pair_col: str = 'pair', ts_col: str = 'timestamp', keep_input_columns: bool = False, output_columns: list[str] | None = None, filter_signal_type: SignalType | None = None, mask_to_signals: bool = True, out_col: str = 'label', include_meta: bool = False, meta_columns: tuple[str, ...] = ('forward_ret', 'vol'), softness_k: float = 3.0, price_col: str = 'close', horizon: int = 60, vol_window: int = 1440, threshold_return_std: float = 4.0, flash_horizon: int = 10)
Bases: Labeler
Labels black swan and flash crash events in historical data.
Forward-looking labeler that identifies anomalous price movements by comparing forward return magnitude against rolling volatility.
Algorithm
- Compute log returns: log(close[t] / close[t-1])
- Compute rolling std of returns over
vol_windowbars - Compute forward return magnitude: |log(close[t+horizon] / close[t])|
- If forward return > threshold_return_std * rolling_std -> "extreme_positive_anomaly"
- If additionally the return is negative AND happened in < flash_horizon bars -> "extreme_negative_anomaly"
- Otherwise -> null (no label)
Attributes:
| Name | Type | Description |
|---|---|---|
price_col |
str
|
Price column name. Default: "close". |
horizon |
int
|
Forward-looking horizon in bars. Default: 60. |
vol_window |
int
|
Rolling window for volatility estimation. Default: 1440. |
threshold_return_std |
float
|
Number of standard deviations for anomaly threshold. Default: 4.0. |
flash_horizon |
int
|
Maximum bars for flash crash classification. Default: 10. |
Example
Note
This is a forward-looking labeler -- it uses future data and is NOT
suitable for live trading. Use AnomalyDetector for real-time
anomaly detection.
meta_columns
class-attribute
instance-attribute
¶
soft_classes
class-attribute
¶
__post_init__ ¶
Source code in src/signalflow/target/anomaly_labeler.py
compute_group ¶
Compute anomaly labels for a single pair group.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
group_df
|
DataFrame
|
Single pair's data sorted by timestamp. |
required |
data_context
|
dict[str, Any] | None
|
Additional context. |
None
|
Returns:
| Type | Description |
|---|---|
DataFrame
|
pl.DataFrame: Same length as input with anomaly label column added. Labels are "extreme_positive_anomaly", "extreme_negative_anomaly", or null. |
Source code in src/signalflow/target/anomaly_labeler.py
89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 | |
compute_group_soft ¶
Soft triple (p_extreme_negative_anomaly, p_normal, p_extreme_positive_anomaly).
Treats the signed horizon return scaled by per-bar volatility as the
decision metric: z = fwd_ret / (rolling_vol * sqrt(horizon)). The
symmetric threshold from :attr:threshold_return_std defines the
anomaly cut for both tails, and :func:signed_tercile_soft produces
calibrated probabilities.
Source code in src/signalflow/target/anomaly_labeler.py
Volatility Regime Labeler¶
signalflow.target.volatility_labeler.VolatilityRegimeLabeler
dataclass
¶
VolatilityRegimeLabeler(raw_data_type: RawDataType | str = RawDataType.SPOT, signal_category: SignalCategory = SignalCategory.VOLATILITY, pair_col: str = 'pair', ts_col: str = 'timestamp', keep_input_columns: bool = False, output_columns: list[str] | None = None, filter_signal_type: SignalType | None = None, mask_to_signals: bool = True, out_col: str = 'label', include_meta: bool = False, meta_columns: tuple[str, ...] = ('realized_vol', 'vol_percentile'), softness_k: float = 20.0, price_col: str = 'close', horizon: int = 60, upper_quantile: float = 0.67, lower_quantile: float = 0.33, lookback_window: int = 1440)
Bases: Labeler
Label bars by forward realized volatility regime.
Algorithm
- Compute log returns:
ln(close[t] / close[t-1]) - Forward realized volatility:
std(log_returns[t+1 : t+horizon+1])computed using reverse-shifted rolling std. - Rolling percentile of realized vol over
lookback_window. - If vol >
upper_quantilepercentile ->"high_volatility" - If vol <
lower_quantilepercentile ->"low_volatility" - Otherwise ->
null(Polars null)
Implementation
Uses pure Polars expressions instead of numpy loops for better performance and memory efficiency.
Attributes:
| Name | Type | Description |
|---|---|---|
price_col |
str
|
Price column name. Default: |
horizon |
int
|
Number of forward bars for realized vol. Default: |
upper_quantile |
float
|
Upper percentile threshold (0-1). Default: |
lower_quantile |
float
|
Lower percentile threshold (0-1). Default: |
lookback_window |
int
|
Rolling window for percentile calc. Default: |
Example
meta_columns
class-attribute
instance-attribute
¶
soft_classes
class-attribute
¶
__post_init__ ¶
Source code in src/signalflow/target/volatility_labeler.py
_compute_percentile_series
staticmethod
¶
Compute rolling percentile for a series of structs.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
s
|
Series
|
Series of structs with 'val' and 'idx' fields. |
required |
window
|
int
|
Lookback window size. |
required |
Returns:
| Type | Description |
|---|---|
Series
|
Series of percentile values. |
Source code in src/signalflow/target/volatility_labeler.py
_rolling_percentile_expr ¶
Compute rolling percentile using Polars expressions.
For each row, computes the fraction of values in the lookback window that are less than or equal to the current value.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
col_name
|
str
|
Column to compute percentile for. |
required |
window
|
int
|
Lookback window size. |
required |
Returns:
| Type | Description |
|---|---|
Expr
|
Polars expression computing rolling percentile. |
Source code in src/signalflow/target/volatility_labeler.py
compute_group ¶
Compute volatility regime labels for a single pair.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
group_df
|
DataFrame
|
Single pair data sorted by timestamp. |
required |
data_context
|
dict[str, Any] | None
|
Optional additional context. |
None
|
Returns:
| Type | Description |
|---|---|
DataFrame
|
DataFrame with same row count, plus label and optional meta columns. |
Source code in src/signalflow/target/volatility_labeler.py
compute_group_soft ¶
Soft tercile probabilities from the rolling vol percentile.
Uses the same forward-realised-vol percentile that drives the hard
low_volatility / high_volatility cut, then maps it through
:func:percentile_tercile_soft so the middle bucket (rows that the
hard pipeline emits as null) is represented explicitly as
p_mid_volatility.
Source code in src/signalflow/target/volatility_labeler.py
Trend Scanning Labeler¶
signalflow.target.trend_scanning.TrendScanningLabeler
dataclass
¶
TrendScanningLabeler(raw_data_type: RawDataType | str = RawDataType.SPOT, signal_category: SignalCategory = SignalCategory.TREND_MOMENTUM, pair_col: str = 'pair', ts_col: str = 'timestamp', keep_input_columns: bool = False, output_columns: list[str] | None = None, filter_signal_type: SignalType | None = None, mask_to_signals: bool = True, out_col: str = 'label', include_meta: bool = False, meta_columns: tuple[str, ...] = ('t_stat', 'best_window'), softness_k: float = 3.0, price_col: str = 'close', min_lookforward: int = 5, max_lookforward: int = 60, step: int = 5, critical_value: float = 1.96)
Bases: Labeler
Label bars using De Prado's trend scanning method.
For each bar, fits OLS regressions over multiple forward windows and selects the window with the strongest t-statistic. The sign and magnitude of the t-statistic determine the label.
Reference
De Prado, M. L. (2020). Machine Learning for Asset Managers, Ch. 5.
Algorithm
-
For each bar t, for each window L in range(min_lookforward, max_lookforward+1, step):
-
Fit OLS: Price[t+i] = alpha + beta * i, for i=0..L-1
-
Compute t-statistic: t = beta / SE(beta)
-
Select L* = argmax_L |t_stat(t, L)|
-
Label:
-
"rise"if t_stat > critical_value "fall"if t_stat < -critical_valuenullotherwise
Attributes:
| Name | Type | Description |
|---|---|---|
price_col |
str
|
Price column. Default: |
min_lookforward |
int
|
Minimum forward window. Default: |
max_lookforward |
int
|
Maximum forward window. Default: |
step |
int
|
Step between window sizes. Default: |
critical_value |
float
|
T-stat threshold for significance. Default: |
Example
meta_columns
class-attribute
instance-attribute
¶
signal_category
class-attribute
instance-attribute
¶
__post_init__ ¶
Source code in src/signalflow/target/trend_scanning.py
compute_group ¶
Compute trend scanning labels for a single pair.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
group_df
|
DataFrame
|
Single pair data sorted by timestamp. |
required |
data_context
|
dict[str, Any] | None
|
Optional additional context. |
None
|
Returns:
| Type | Description |
|---|---|
DataFrame
|
DataFrame with same row count, plus label and optional meta columns. |
Source code in src/signalflow/target/trend_scanning.py
compute_group_soft ¶
Soft triple (p_fall, p_neutral, p_rise) from the best-window t-statistic.
Maps the signed t-stat through :func:signed_tercile_soft with the
symmetric ±critical_value threshold so probabilities reflect
statistical confidence in the trend rather than a hard 1.96 cut.
Source code in src/signalflow/target/trend_scanning.py
Structure Labeler (Local Extrema)¶
signalflow.target.structure_labeler.StructureLabeler
dataclass
¶
StructureLabeler(raw_data_type: RawDataType | str = RawDataType.SPOT, signal_category: SignalCategory = SignalCategory.PRICE_STRUCTURE, pair_col: str = 'pair', ts_col: str = 'timestamp', keep_input_columns: bool = False, output_columns: list[str] | None = None, filter_signal_type: SignalType | None = None, mask_to_signals: bool = True, out_col: str = 'label', include_meta: bool = False, meta_columns: tuple[str, ...] = ('swing_pct',), softness_k: float = 3.0, price_col: str = 'close', lookforward: int = 60, lookback: int = 60, min_swing_pct: float = 0.02, min_swing_zscore: float | None = None, vol_window: int = 500)
Bases: Labeler
Label local tops and bottoms using a symmetric window.
Uses future knowledge (look-forward) to identify bars that are local extrema within a combined lookback + lookforward window, filtered by either a fixed percentage or a rolling z-score threshold.
Swing Filter Modes
Fixed percentage (default): swing must exceed min_swing_pct.
Rolling z-score: set min_swing_zscore to enable. Computes
rolling mean and std of window swings over vol_window bars,
then filters by z-score >= threshold. Adapts to market volatility
automatically — tighter in calm markets, wider in volatile ones.
Algorithm
- For each bar t, examine
close[t-lookback : t+lookforward+1]. - Compute swing =
(window_max - window_min) / window_min. - If
close[t]is the maximum in that window -> candidate top. - If
close[t]is the minimum in that window -> candidate bottom. - Apply swing filter to confirm:
- Fixed:
swing >= min_swing_pct - Z-score:
(swing - rolling_mean) / rolling_std >= min_swing_zscore - Otherwise ->
null.
Implementation
Uses Polars rolling expressions for computing window max/min and detecting extrema, reducing numpy loop overhead.
Attributes:
| Name | Type | Description |
|---|---|---|
price_col |
str
|
Price column. Default: |
lookforward |
int
|
Forward window size. Default: |
lookback |
int
|
Backward window size. Default: |
min_swing_pct |
float
|
Fixed minimum swing percentage. Default: |
min_swing_zscore |
float | None
|
Z-score threshold for adaptive filtering.
Default: |
vol_window |
int
|
Rolling window for z-score baseline. Default: |
Example
signal_category
class-attribute
instance-attribute
¶
__post_init__ ¶
Source code in src/signalflow/target/structure_labeler.py
compute_group ¶
Compute structure labels for a single pair.
Source code in src/signalflow/target/structure_labeler.py
115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 | |
Zigzag Structure Labeler (Global)¶
signalflow.target.structure_labeler.ZigzagStructureLabeler
dataclass
¶
ZigzagStructureLabeler(raw_data_type: RawDataType | str = RawDataType.SPOT, signal_category: SignalCategory = SignalCategory.PRICE_STRUCTURE, pair_col: str = 'pair', ts_col: str = 'timestamp', keep_input_columns: bool = False, output_columns: list[str] | None = None, filter_signal_type: SignalType | None = None, mask_to_signals: bool = True, out_col: str = 'label', include_meta: bool = False, meta_columns: tuple[str, ...] = ('swing_pct',), softness_k: float = 3.0, price_col: str = 'close', min_swing_pct: float = 0.02, min_swing_zscore: float | None = None, vol_window: int = 500)
Bases: Labeler
Label local tops and bottoms using a full-series zigzag algorithm.
Unlike StructureLabeler (which uses fixed-size windows around each bar),
this labeler scans the entire price series to find alternating swing
highs and lows. A new pivot is confirmed only when the price reverses
by more than the threshold from the current extreme.
The zigzag algorithm ensures
- Tops and bottoms strictly alternate (no consecutive tops or bottoms).
- Each swing exceeds the threshold (either fixed % or adaptive).
- Pivots are globally consistent across the full series.
Swing Filter Modes
Fixed percentage (default): reversal must exceed min_swing_pct.
Adaptive (z-score): set min_swing_zscore to enable. Uses
rolling volatility (std of log-returns) to compute a per-bar
threshold: threshold = zscore x vol x sqrt(vol_window).
Algorithm
- Find first significant swing to determine initial direction.
- Track the running extreme (highest high or lowest low).
- When price reverses from the extreme by > threshold:
- Mark the extreme as
"local_max"or"local_min". - Switch direction and start tracking the new extreme.
- Result: alternating pivots across the full price series.
Implementation
Uses a sequential state-machine algorithm. This is inherently not parallelizable, so numpy/python loops are used. Polars is used for rolling volatility computation in z-score mode.
Attributes:
| Name | Type | Description |
|---|---|---|
price_col |
str
|
Price column. Default: |
min_swing_pct |
float
|
Fixed minimum reversal percentage. Default: |
min_swing_zscore |
float | None
|
Z-score multiplier for adaptive threshold.
Default: |
vol_window |
int
|
Rolling window for volatility computation. Default: |
Example
signal_category
class-attribute
instance-attribute
¶
__post_init__ ¶
Source code in src/signalflow/target/structure_labeler.py
_adaptive_thresholds ¶
Compute per-bar thresholds: zscore x rolling_vol x sqrt(vol_window).
Uses Polars for rolling std computation.
Source code in src/signalflow/target/structure_labeler.py
_zigzag ¶
Run zigzag algorithm with per-bar adaptive thresholds.
This is a state-machine algorithm that must process bars sequentially to maintain alternating top/bottom structure.
Returns:
| Type | Description |
|---|---|
tuple[list[str | None], ndarray]
|
(labels, swing_pcts) — parallel arrays of length n. |
Source code in src/signalflow/target/structure_labeler.py
408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 | |
compute_group ¶
Compute zigzag structure labels for a single pair.
Source code in src/signalflow/target/structure_labeler.py
Volume Regime Labeler¶
signalflow.target.volume_labeler.VolumeRegimeLabeler
dataclass
¶
VolumeRegimeLabeler(raw_data_type: RawDataType | str = RawDataType.SPOT, signal_category: SignalCategory = SignalCategory.VOLUME_LIQUIDITY, pair_col: str = 'pair', ts_col: str = 'timestamp', keep_input_columns: bool = False, output_columns: list[str] | None = None, filter_signal_type: SignalType | None = None, mask_to_signals: bool = True, out_col: str = 'label', include_meta: bool = False, meta_columns: tuple[str, ...] = ('volume_ratio',), softness_k: float = 3.0, volume_col: str = 'volume', horizon: int = 60, vol_sma_window: int = 1440, spike_threshold: float = 2.0, drought_threshold: float = 0.3)
Bases: Labeler
Label bars by forward volume regime.
Detects volume spikes and droughts by comparing forward average volume to a trailing volume SMA.
Algorithm
- Compute trailing volume SMA:
rolling_mean(volume, vol_sma_window). - Compute forward volume ratio:
mean(volume[t+1 : t+horizon+1]) / trailing_sma[t] - If ratio >
spike_threshold->"abnormal_volume" - If ratio <
drought_threshold->"illiquidity" - Otherwise ->
null
Implementation
Uses pure Polars expressions instead of numpy loops for better performance and memory efficiency.
Attributes:
| Name | Type | Description |
|---|---|---|
volume_col |
str
|
Volume column. Default: |
horizon |
int
|
Number of forward bars. Default: |
vol_sma_window |
int
|
Trailing SMA window. Default: |
spike_threshold |
float
|
Threshold for volume spike. Default: |
drought_threshold |
float
|
Threshold for volume drought. Default: |
Example
signal_category
class-attribute
instance-attribute
¶
soft_classes
class-attribute
¶
__post_init__ ¶
Source code in src/signalflow/target/volume_labeler.py
compute_group ¶
Compute volume regime labels for a single pair.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
group_df
|
DataFrame
|
Single pair data sorted by timestamp. |
required |
data_context
|
dict[str, Any] | None
|
Optional additional context. |
None
|
Returns:
| Type | Description |
|---|---|
DataFrame
|
DataFrame with same row count, plus label and optional meta columns. |
Source code in src/signalflow/target/volume_labeler.py
compute_group_soft ¶
Soft triple (p_illiquidity, p_normal_volume, p_abnormal_volume).
Centres the volume ratio at 1.0 (no excess) and uses
:func:signed_tercile_soft with thresholds derived from
:attr:spike_threshold (ratio - 1 > spike - 1) and
:attr:drought_threshold (1 - ratio > 1 - drought).
Source code in src/signalflow/target/volume_labeler.py
Multi-Target Generation¶
signalflow.target.multi_target_generator.MultiTargetGenerator
dataclass
¶
MultiTargetGenerator(horizons: list[HorizonConfig] = (lambda: list(DEFAULT_HORIZONS))(), target_types: list[TargetType] = (lambda: list(DEFAULT_TARGET_TYPES))(), volume_window: int = 60, volume_quantiles: tuple[float, float] = (0.33, 0.67), crash_quantiles: tuple[float, float] = (0.1, 0.9), pair_col: str = 'pair', ts_col: str = 'timestamp', price_col: str = 'close')
Generates multiple targets at multiple horizons from OHLCV data.
For each (horizon, target_type) combination, adds a column to the
DataFrame. Column naming convention: target_{target_name}_{horizon_name}.
Direction targets use the existing Labeler infrastructure.
Return magnitude is |log(close[t+h] / close[t])|.
Volume regime discretizes volume / sma(volume) into HIGH/MED/LOW.
Crash regime classifies forward return into crash/rally/normal.
Attributes:
| Name | Type | Description |
|---|---|---|
horizons |
list[HorizonConfig]
|
List of HorizonConfig. |
target_types |
list[TargetType]
|
List of TargetType to generate. |
volume_window |
int
|
Rolling window for volume SMA baseline. |
volume_quantiles |
tuple[float, float]
|
(low, high) thresholds for volume regime. |
crash_quantiles |
tuple[float, float]
|
(crash, rally) quantile thresholds for crash regime. |
pair_col |
str
|
Trading pair column name. |
ts_col |
str
|
Timestamp column name. |
price_col |
str
|
Price column name. |
crash_quantiles
class-attribute
instance-attribute
¶
horizons
class-attribute
instance-attribute
¶
target_types
class-attribute
instance-attribute
¶
volume_quantiles
class-attribute
instance-attribute
¶
_crash_regime_expr ¶
Polars expression for crash/rally regime classification.
Computes forward log-return over horizon bars, then discretizes
into crash/rally/normal based on quantile thresholds.
Source code in src/signalflow/target/multi_target_generator.py
_create_labeler ¶
Instantiate a labeler for the given horizon.
Source code in src/signalflow/target/multi_target_generator.py
_generate_crash_regime ¶
Source code in src/signalflow/target/multi_target_generator.py
_generate_direction ¶
Source code in src/signalflow/target/multi_target_generator.py
_generate_return_magnitude ¶
Source code in src/signalflow/target/multi_target_generator.py
_generate_volume_regime ¶
Source code in src/signalflow/target/multi_target_generator.py
_validate ¶
Source code in src/signalflow/target/multi_target_generator.py
_volume_regime_expr ¶
Polars expression for volume regime classification.
Computes forward-looking average volume ratio vs current rolling SMA, then discretizes into HIGH/MED/LOW based on quantile thresholds.
Source code in src/signalflow/target/multi_target_generator.py
generate ¶
Generate all target columns.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
df
|
DataFrame
|
OHLCV DataFrame with pair, timestamp, open, high, low, close, volume. |
required |
Returns:
| Type | Description |
|---|---|
DataFrame
|
Original DataFrame with added |
Source code in src/signalflow/target/multi_target_generator.py
target_columns ¶
Return metadata for all generated target columns.
Returns:
| Type | Description |
|---|---|
list[dict[str, str]]
|
List of dicts with keys: column, horizon, target_type, kind. |
Source code in src/signalflow/target/multi_target_generator.py
signalflow.target.multi_target_generator.HorizonConfig
dataclass
¶
HorizonConfig(name: str, horizon: int, labeler_cls: type[Labeler] = TripleBarrierLabeler, labeler_kwargs: dict[str, Any] = dict())
Configuration for a single prediction horizon.
Attributes:
| Name | Type | Description |
|---|---|---|
name |
str
|
Human-readable name (e.g., "short", "mid", "long"). |
horizon |
int
|
Number of bars for the horizon. |
labeler_cls |
type[Labeler]
|
Labeler class to use for direction targets. |
labeler_kwargs |
dict[str, Any]
|
Extra kwargs passed to the labeler constructor. |
signalflow.target.multi_target_generator.TargetType
dataclass
¶
Defines a target type derived from OHLCV data.
Attributes:
| Name | Type | Description |
|---|---|---|
name |
str
|
Target name (e.g., "direction", "return_magnitude", "volume_regime"). |
kind |
str
|
"discrete" or "continuous" — determines MI computation method. |
Utility Functions¶
mask_targets_by_signals¶
signalflow.target.utils.mask_targets_by_signals ¶
mask_targets_by_signals(df: DataFrame, signals: Signals, mask_signal_types: set[str], horizon_bars: int, cooldown_bars: int = 60, target_columns: list[str] | None = None, pair_col: str = 'pair', ts_col: str = 'timestamp') -> pl.DataFrame
Mask target columns for timestamps overlapping with specified signals.
For each signal at time T with type in mask_signal_types: - Masks range [T - horizon_bars, T + cooldown_bars]
This is useful for excluding labels that overlap with exogenous events (e.g., flash crashes, global market events) from training data, since no feature could predict such events.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
df
|
DataFrame
|
DataFrame with target columns. |
required |
signals
|
Signals
|
Signals object containing detected events. |
required |
mask_signal_types
|
set[str]
|
Signal types to mask (e.g. {"flash_crash", "global_event"}). |
required |
horizon_bars
|
int
|
Forward horizon (bars before signal that "see" it). |
required |
cooldown_bars
|
int
|
Bars after signal to mask (default: 60). |
60
|
target_columns
|
list[str] | None
|
Columns to mask (default: all columns ending with "_label"). |
None
|
pair_col
|
str
|
Pair column name (default: "pair"). |
'pair'
|
ts_col
|
str
|
Timestamp column name (default: "timestamp"). |
'timestamp'
|
Returns:
| Type | Description |
|---|---|
DataFrame
|
DataFrame with affected target columns set to null. |
Example
from signalflow.detector import ZScoreAnomalyDetector
from signalflow.target.utils import mask_targets_by_signals
# Detect anomalies
detector = ZScoreAnomalyDetector(threshold=4.0)
signals = detector.run(raw_data_view)
# Mask labels overlapping with flash crashes
labeled_df = mask_targets_by_signals(
df=labeled_df,
signals=signals,
mask_signal_types={"anomaly_low"}, # flash crashes
horizon_bars=60,
cooldown_bars=60,
)
Note
- Masking is done per-pair: signal at time T for pair A only masks labels for pair A at affected timestamps.
- If signals DataFrame is empty or has no matching signal_types, the input DataFrame is returned unchanged.
Source code in src/signalflow/target/utils.py
16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 | |
mask_targets_by_timestamps¶
signalflow.target.utils.mask_targets_by_timestamps ¶
mask_targets_by_timestamps(df: DataFrame, event_timestamps: list, horizon_bars: int, cooldown_bars: int = 60, target_columns: list[str] | None = None, ts_col: str = 'timestamp') -> pl.DataFrame
Mask target columns for timestamps overlapping with event timestamps.
Simpler version of mask_targets_by_signals that works with raw timestamps instead of Signals objects. Applies masking globally (not per-pair).
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
df
|
DataFrame
|
DataFrame with target columns. |
required |
event_timestamps
|
list
|
List of event timestamps to mask around. |
required |
horizon_bars
|
int
|
Forward horizon (bars before event that "see" it). |
required |
cooldown_bars
|
int
|
Bars after event to mask (default: 60). |
60
|
target_columns
|
list[str] | None
|
Columns to mask (default: all columns ending with "_label"). |
None
|
ts_col
|
str
|
Timestamp column name (default: "timestamp"). |
'timestamp'
|
Returns:
| Type | Description |
|---|---|
DataFrame
|
DataFrame with affected target columns set to null. |
Example
from signalflow.target.utils import mask_targets_by_timestamps
from datetime import datetime
# Mask around known events
labeled_df = mask_targets_by_timestamps(
df=labeled_df,
event_timestamps=[
datetime(2024, 3, 1, 10, 30), # Known flash crash
datetime(2024, 5, 15, 14, 0), # Fed announcement
],
horizon_bars=60,
cooldown_bars=120,
)
Source code in src/signalflow/target/utils.py
164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 | |