---
url: /dev/tutorials/time-and-cutoffs.md
description: >-
  Predict at a point in time: declare time columns, pass a cutoff per sample,
  use windows such as the last 30 days, and validate with TemporalCutoffSplit.
---

# Time, cutoffs and temporal cross-validation

**To predict as of a particular moment, put that moment in a `cutoff` column
of `X` and pass `time="cutoff"` to the estimator. Declare timestamp columns
on event tables so the estimator can use only events from before each
sample's cutoff.** For static data, leave `time` unset.

## Temporal data with several cutoffs

With `with_time=True`, the synthetic generator adds `orders.created_at` and a
`cutoff` column to `X`. With `n_cutoffs=4`, every customer appears four times,
90 days apart, and the label at each cutoff depends only on the orders created
before it. After each cutoff, the generator adds orders that follow the
pattern of the opposite class, so a model that reads the future is misled.

```python
from sklink.datasets import make_relational_classification

db, X, y, rule = make_relational_classification(
    n_entities=600,
    signal="child_categorical",
    with_time=True,
    n_cutoffs=4,
    return_rule=True,
    random_state=0,
)
print(rule)
print(X.shape)
print(X.head(3))
print(db.describe()["tables"]["orders"]["time_column"])
```

```text
proportion(orders[type == 'express']) >= 0.21
(2400, 2)
   customer_id     cutoff
0            0 2024-03-31
1            1 2024-03-31
2            2 2024-03-31
created_at
```

Each sample represents a customer at one cutoff. On your own
data, declare a column such as `orders.created_at` with
`Database(..., time_columns={"orders": "created_at"})`. An order at exactly
the cutoff is excluded, as are later orders.

## Temporal cross-validation

The estimator's `time` parameter controls which related rows each sample can
see. `TemporalCutoffSplit` controls which samples are in each fold. It keeps
all samples with the same cutoff together and tests on later cutoffs than it
trains on.

```python
from sklink.model_selection import TemporalCutoffSplit

cv = TemporalCutoffSplit(time="cutoff", n_splits=3)
for train, test in cv.split(X):
    print(
        len(train),
        len(test),
        X["cutoff"].iloc[train].max().date(),
        "<",
        X["cutoff"].iloc[test].min().date(),
    )
```

```text
600 600 2024-03-31 < 2024-06-29
1200 600 2024-06-29 < 2024-09-27
1800 600 2024-09-27 < 2024-12-26
```

Each fold adds the previous test cutoff to its training data, so the
training set grows by one cutoff's samples while the test set stays the same
size.

| Fold | Mar 31 | Jun 29 | Sep 27 | Dec 26 |
| --- | --- | --- | --- | --- |
| 1 | Train | Test | | |
| 2 | Train | Train | Test | |
| 3 | Train | Train | Train | Test |

`CutoffSplitDisplay.from_splitter(cv, X)` draws this table for any splitter,
with its gaps and label horizons: see [plot a model](./plotting#temporal-splits).

This split measures future predictions for customers already seen in
training. The same customer can appear on both sides of a fold at different
cutoffs.

## Respect the cutoff, or learn from the future

Compare two trees on the same folds. The temporal tree reads each customer's
orders as of the cutoff in `X`. The static tree reads the customer's full order
history in the database, including future orders.

```python
from sklearn.model_selection import cross_val_score
from sklink.tree import RelationalDecisionTreeClassifier

splits = list(cv.split(X))
temporal = RelationalDecisionTreeClassifier(
    db, entity="customers", key="customer_id", time="cutoff", max_depth=3
)
static = RelationalDecisionTreeClassifier(
    db, entity="customers", key="customer_id", max_depth=3
)
print(f"temporal {cross_val_score(temporal, X, y, cv=splits).mean():.3f}")
print(
    f"static   {cross_val_score(static, X[['customer_id']], y, cv=splits).mean():.3f}"
)
```

```text
temporal 0.998
static   0.699
```

In this dataset, future orders deliberately follow a different pattern, and
including them lowers the static model's accuracy. A temporal split alone
leaves those orders visible to the static model. Use the estimator's cutoff
as well as the time-aware splitter when evaluating this kind of prediction.
The static tree gets only the key column of `X`; otherwise it would keep
`cutoff` as a feature of its own.

The cutoff applies as the estimator follows each path. Here `order_items`
has no time column, but an item can only be reached through an order that
already passed the cutoff. If a child table is reachable without any time
filter, the estimator warns that its rows are visible at every cutoff. Add a
time column to event tables whose rows can arrive independently.

The cutoff hides rows, not values. A row is visible once its time column has
passed the cutoff, and then every column of it is read as stored. A column
filled in later, such as `orders.returned_at` or `orders.status` updated after
delivery, shows the model what happened after the cutoff, and no warning can
tell it from a date scheduled in advance. Leave such columns out with
`Database(..., exclude={"orders": ["returned_at"]})`, or store the later fact
as its own event table with its own time column (a `returns` table), so the
cutoff hides it until it happens. A validation score close to perfect on a
temporal task is the usual sign of one of these columns.

## Windows

In temporal mode, `windows` adds features for recent history. A 30-day
window includes rows from 30 days before the cutoff up to the cutoff itself,
with the cutoff excluded. The featurizer also keeps the corresponding
all-history feature.

```python
from sklink.feature_extraction import RelationalFeaturizer

featurizer = RelationalFeaturizer(
    db,
    entity="customers",
    key="customer_id",
    time="cutoff",
    max_relationship_depth=1,
    primitives=["count", "sum"],
    windows=["30D", "90D"],
)
featurizer.fit(X)
names = featurizer.get_feature_names_out()
print(
    [
        name
        for name in names
        if name.startswith("count(orders") and "type == 'express'" in name
    ]
)
```

```text
["count(orders[type == 'express'])", "count(orders[type == 'express']|30d)", "count(orders[type == 'express']|90d)"]
```

The names after `|` are the window lengths. Both `windows` and
`TemporalCutoffSplit` accept strings such as `"30D"`, `"12h"` and `"1D12h"`,
or a `datetime.timedelta`.

## Recency primitives

`time_since_first` and `time_since_last` give the number of days between the
earliest or latest visible row and the cutoff. In temporal mode, the default
primitives include them for the datetime columns of tables with a time
column. When you pass a list of
primitives, name the ones you want to keep.

```python
recency = RelationalFeaturizer(
    db,
    entity="customers",
    key="customer_id",
    time="cutoff",
    max_relationship_depth=1,
    primitives=["count", "time_since_last"],
)
recency.fit(X)
print([name for name in recency.get_feature_names_out() if "time_since" in name])
```

```text
['time_since_last(orders.created_at)']
```

`last` and `trend` follow a value over time. `last` is the latest non-missing
value among the rows visible at the cutoff, such as the amount of the most
recent order, and `trend` the least-squares slope of the value over time,
per day. In temporal mode, the default primitives include both for the
numeric columns of tables with a time column; `first` is available when you
name it. `last` and `first` also work on categorical and boolean columns,
such as the type of the latest order.

```python
latest = RelationalFeaturizer(
    db,
    entity="customers",
    key="customer_id",
    time="cutoff",
    max_relationship_depth=1,
    primitives=["last", "trend"],
)
latest.fit(X)
print([name for name in latest.get_feature_names_out() if "amount" in name])
```

```text
['last(orders.amount)', 'trend(orders.amount)']
```

## Gaps and label horizons

Suppose the target is whether a customer buys in the next 60 days. A
training label may use events from that full 60-day period. Set
`label_horizon="60D"` so a fold trains only on samples whose label period
ends by the first test cutoff. `gap="30D"` adds 30 more days between that
period and the test cutoff.

```python
cv = TemporalCutoffSplit(time="cutoff", n_splits=2, label_horizon="60D", gap="30D")
for train, test in cv.split(X):
    print(
        X["cutoff"].iloc[train].max().date(), "->", X["cutoff"].iloc[test].min().date()
    )
```

```text
2024-06-29 -> 2024-09-27
2024-09-27 -> 2024-12-26
```

Every training cutoff `c` satisfies `c + label_horizon + gap <= first test
cutoff`.

## `TemporalCutoffSplit` parameters

| Parameter | Default | What it does |
| --- | --- | --- |
| `time` | required | Column of `X` with the cutoffs, by name or position |
| `n_splits` | `5` | Number of splits, at least 2 |
| `gap` | `None` | Extra separation between training and test cutoffs |
| `label_horizon` | `None` | How far after its cutoff a label looks |
| `test_size` | `None` | Distinct cutoffs per test block, or a fraction of samples |
| `max_train_size` | `None` | Keep only the most recent cutoffs: a sliding window |

For static data, keep the scikit-learn splitters: `KFold`, `StratifiedKFold`,
or `GroupKFold` with `groups=X["customer_id"]` when an entity has several
rows.

Use these folds in a hyperparameter search as shown in
[Model selection](./model-selection).
