ts-features-sculptor 1.25.1
Package for transforming time series features
License: MIT
Requires Python: >=3.10

# ts_features_sculptor

> [!CAUTION]
> Research / prototyping package (feature engineering).
> Public API is stable and backward-compatible, but the implementation is NOT production-hardened:
> test coverage is limited; some features may be approximate or insufficiently validated.
> No warranty, no liability, best-effort maintenance. Production use is at your own risk.

A package for feature engineering on time series data.

The library is designed for experiments with feature engineering in ML.
It includes transformers, generators, and examples of feature 
construction for time series. Intended for educational and research 
purposes, not for production use. Users must verify results 
independently.

This is a sandbox for feature engineering experiments, 
not ready-made solutions.

## Installation

```bash
pip install ts_features_sculptor
```

## Example

A simple example of feature engineering creation:

```python
import numpy as np
import pandas as pd
from sklearn.pipeline import Pipeline
from ts_features_sculptor import (
    ToDateTime,
    SortByTime,
    Tte,
    TimedRollingAggregator
)

data = {
    'time': [
        '2025-10-01 06:00:00',
        '2025-02-01 12:00:00',
        '2025-02-11 18:00:00',
        '2025-01-10 06:00:00'
    ],
    'value': [
        10., 11., 12., 11.
    ]
}
df = pd.DataFrame(data)

pippeline = Pipeline([
    ('to_datetime', ToDateTime(time_col="time")),
    ('sort_by_time', SortByTime(time_col="time")),
    ('tte', Tte(time_col="time")),
    ('time_rolling_aggregator', TimedRollingAggregator(
        time_col = "time",
        feature_col = "tte",
        window_days = 30,
        agg_funcs = ['mean', 'count'],
        fillna = np.nan
    ))
])

result_df = pippeline.transform(df)

print(result_df.to_string(index=False))
               time  value    tte  tte_time_rolling_mean_30  tte_time_rolling_count_30
2025-01-10 06:00:00   11.0  22.25                       NaN                        NaN
2025-02-01 12:00:00   11.0  10.25                     22.25                        1.0
2025-02-11 18:00:00   12.0 231.50                     10.25                        1.0
2025-10-01 06:00:00   10.0    NaN                       NaN                        NaN
```


## Transformers

- **ToDateTime** - Converts string time values to datetime format
- **SortByTime** - Sorts data by timestamp.
- **TimeValidator** - Validates the correctness of timestamps.
- **Tte** -  Computes time to event in days.
- **Lag** - Creates lag features (time-shifted values).
- **RowRollingAggregator** - Aggregates data using a fixed-row rolling window.
- **TimedRollingAggregator** -Aggregates data using a time-based rolling window (in days).
- **DaysOfLife** - Calculates the number of days since the start of observations (from the earliest date).
- **DateTimeDecomposer** - Decomposes timestamps into components (year, month, day, day of week, hour, etc.).
- **Expanding** - Computes expanding aggregates (cumulative statistics).
- **Expression** - Applies custom expressions to data using numpy functions.
- **IsHolidays** - Checks if a date is a holiday.
- **LongHoliday** - Detects long holiday blocks.
- **SegmentLongHoliday** - Segments data into holiday and non-holiday segments.
- **WindowActivity** -  Assigns the object's activity.
- **ActiveToInactive** -  Marks transitions from active to inactive states.
- **IntervalEventsMerge** - Merges interval event data.
- **ActivityRangeClassifier** - Extracts segments for the specified object activity.
- **GroupAggregate** - Generates individual and group features.
- **TimeLag** - Creates time-based lag features with nearest-value matching within epsilon window.
- **GroupDailyLag** - Computes lags for daily aggregated features with days/months/years offsets.
- **EventCounters** - Counts interval events, visits, ignore ratio and related metrics.
- **EventCountersPostproc** - Post-processes EventCounters output with normalization and Laplace smoothing.
- **EventDaysFeatures** - Computes temporal features relative to interval events (days to next, days since last, etc.).
- **DaysSinceLastEvent** - Calculates calendar days since the last event.
- **EventDrivenTSCompressor** - Compresses time series by extracting features before each interval event.
- **TteEventEffect** - Calculates rolling average TTE inside/outside events with uplift metric.
- **FlaggedEventsExpandingStats** - Computes expanding statistics separately for inside/outside flagged events.
- **TimeGridResampler** - Resamples time series to a uniform grid with specified frequency.
- **TimeBucketAggregator** - Aggregates event series by time buckets (daily, weekly, monthly, etc.).
- **EpisodeSplitter** - Splits event sequence into episodes based on time gaps with censoring labels.
- **ObservationEndMarker** - Marks last observation with observation end time and censoring flags.
- **OutflowTarget** - Builds outflow (churn) target from TTE and censoring.
- **TimeGapSessionizer** - Collapses event sequences into sessions based on time gap threshold.
- **CooldownEligibility** - Computes treatment eligibility based on cooldown period after last event.
- **FutureWindowTarget** - Builds forward-looking target as sum of metric in a future window.
- **WorkdayWindowIndexer** - Indexes windows in workdays (excluding holidays) with anchor support.
- **IndexedWindowAggregator** - Aggregates values over pre-computed window boundaries.
- **EwmSmoother** - Exponential weighted moving average smoothing with multiple passes.
- **Ratio** - Safe division of two columns with NaN/infinity handling.
- **CalendarAssignmentPolicyStats** - Calendar-based assignment policy using global profile with Poisson-Gamma smoothing.
- **HierarchicalAssignmentPolicyWeights** - Hierarchical mixing of coarse and fine calendar assignment policy weights.

## Composed

- **DailyGridAggregator** - Converts to datetime, sorts, aggregates to daily buckets, and fills grid gaps.
- **ActivityProfileFeatures** - Builds activity profile with inactivity days, tenure, rolling averages, smoothing, and trend.
- **EligibilityClassifier** - Threshold-based classifier for treatment eligibility (declining, lapsing, low_activity).
- **TreatmentCooldown** - Merges interval events, computes days since last end, and determines cooldown eligibility.
- **HierarchicalAssignmentPolicyProfile** - Two-level calendar assignment policy profile with coarse and fine granularity mixing.
- **UpliftDecisionFramework** - Builds decision rows for uplift modeling with gate, treatment, forward target, and clean horizon.

## Scallers

- **RobustLogScaler** - Ribust log scalling using median / MAD.  


## License

This project is licensed under the [MIT License](LICENSE).