Skip to content

← Tutorials overview

7. TimeManager

Reference

The reference for this topic is TimeManager & roll_out.

A feature computed today on today's data is fine, but training a model needs the feature as it was at past dates, not today's logic on a snapshot. A TimeManager holds the business dates (a calendar) and replays your processes at each of them, so the feature store accumulates a real time series. Here the calendar is the twelve month-ends of 2023, and the feature is the running count and amount of events up to each month-end.

import dataclasses
import getpass
import os

import tdfs4ds                      # importing it first also loads a .env file, if you have one
import teradataml as tdml

# 1. Open the Teradata session. Host and user come from the environment (TDFS4DS_TD_HOST,
#    TDFS4DS_TD_USERNAME), the password from TDFS4DS_TD_PASSWORD or a prompt: nothing secret
#    is written on this page.
host = os.environ["TDFS4DS_TD_HOST"]
user = os.environ["TDFS4DS_TD_USERNAME"]
password = os.environ.get("TDFS4DS_TD_PASSWORD") or getpass.getpass("Teradata password: ")
tdml.create_context(host=host, username=user, password=password)

# 2. Pick your industry. This is the ONLY line to change: retail, banking, healthcare, pharma,
#    manufacturing, assembly, energy or transportation. Every name below comes from S.
S = tdfs4ds.tutorial_scenario("retail")

# 3. Connect to the feature store (created when missing) and choose a data domain. disposable=True
#    records that this domain is an experiment, so the last page removes it in one call.
DATABASE = os.environ.get("TDFS4DS_TD_DATABASE") or user
tdfs4ds.connect(database=DATABASE, create_if_missing=True)
tdfs4ds.create_data_domain(f"TUTORIAL_{S.name.upper()}", disposable=True)   # an experiment: removable in one call

# 4. The tutorial data: three tables written once; a second run keeps them.
try:
    S = tdfs4ds.create_tutorial_data(S.name, DATABASE)
except ValueError:
    S = dataclasses.replace(S, database=DATABASE)


def register_entity_features():
    """Page 1 in one call: (re)register the entity features and return the process id."""
    sql = f"""
        SELECT {S.entity}, COUNT(*) AS nb_events, SUM({S.amount}) AS total_amount,
               AVG({S.amount}) AS avg_amount, COUNT(DISTINCT {S.partner}) AS nb_partners
        FROM {S.table('events')}
        GROUP BY 1"""
    return tdfs4ds.upload_features(
        df=None, sql_query=sql, target_view_name=f"{S.database}.{S.name}_entity_features",
        entity_id=[S.entity], feature_names=["nb_events", "total_amount", "avg_amount", "nb_partners"],
        replace=True, document=False, optimize_query=False, return_process_id=True)

You should see the connection and the data domain, as on every page.

tdfs4ds separates two clocks: business time (the date being materialised) and system time (when the row was written). See Concepts › Temporal model.

1 · The calendar

A Calendar rule produces the dates; the manager stores them in a table and exposes the current one (the cursor) through a one-row view.

from tdfs4ds import Calendar
from tdfs4ds.utils.time_management import TimeManager

tdfs4ds.TIME_MANAGER_CHECK = "error"        # refuse a manager the process view does not read
tm = TimeManager(table_name=f"{S.name}_month_end", schema_name=DATABASE,
                 calendar=Calendar.monthly(day="last"), start="2023-01-31", until="2023-12-31")
print(tm.nb_time_steps, "dates")
print(tm.display())

Output: the number of dates and the cursor, the first month-end. Creating the manager runs nothing.

12 dates
  BUSINESS_DATE
0    2023-01-31

2 · A process that reads the cursor

The view reads the business date with a scalar subquery on the manager's view, and measures everything from that date, never from CURRENT_DATE:

sql = f"""
SELECT {S.entity}
,      COUNT(*)        AS nb_events_to_date
,      SUM({S.amount}) AS total_amount_to_date
FROM {S.table('events')}
WHERE {S.event_date} <= (SELECT BUSINESS_DATE FROM {tm.sql_view})
GROUP BY 1"""

process_id = tdfs4ds.upload_features(
    df=None, sql_query=sql,
    target_view_name=f"{S.database}.{S.name}_monthly_features",
    entity_id=[S.entity],
    feature_names=["nb_events_to_date", "total_amount_to_date"],
    time_manager=tm,                    # attaches the manager: run(process_id) uses its current date
    replace=True, document=False, optimize_query=False,
    run_now=False, return_process_id=True,
)
print(process_id)

Output: a process id and nothing computed yet (run_now=False).

<process id>

3 · Build the history with roll_out

roll_out is the loop: for each date, move the cursor, run the process.

tdfs4ds.roll_out([process_id], time_manager=tm, time_id_start=1, time_id_end=12)

You should see twelve ingestions in the log, one per month-end. Replay a history in date order from the first date: values are stored valid from their business date, and a re-run skips the dates already COMPLETED (force_compute=True forces them).

4 · Read the history

history = tdfs4ds.build_historical_dataset(
    entity_id=[S.entity],
    selected_features=["nb_events_to_date", "total_amount_to_date"],
    view_name=f"{S.database}.{S.name}_monthly_history",
    start="2023-01-01", end="2024-01-01",
)
rows = tdml.execute_sql(
    f"SELECT TOP 12 * FROM {S.database}.{S.name}_monthly_history "
    f"WHERE {S.entity} = (SELECT MIN({S.entity}) FROM {S.database}.{S.name}_monthly_history) "
    "ORDER BY ValidStart").fetchall()
for row in rows:
    print(row)

Output with scenario='retail': one row per period of constant values for one entity: the key, the period, ValidStart and ValidEnd, then the running amount and count, growing from month to month (here for customer 100001, shortened). A period lasts several months when the values do not change (no event in between); an entity that churned stops growing.

[100001, '2023-01-31 ...,2023-02-28 ...', datetime(2023, 1, 31, ...), datetime(2023, 2, 28, ...), 750.93, 3]
[100001, '2023-02-28 ...,2023-03-31 ...', datetime(2023, 2, 28, ...), datetime(2023, 3, 31, ...), 1752.89, 9]
[100001, '2023-03-31 ...,2023-04-30 ...', datetime(2023, 3, 31, ...), datetime(2023, 4, 30, ...), 2089.93, 13]
...

A snapshot dataset reads one instant instead: read_dataset(name, as_of='2023-06-30').

Cloning a TimeManager

When several processes share the same dates, clone the timer instead of loading it again:

tm_copy = TimeManager(table_name=f"{S.name}_month_end_copy", schema_name=DATABASE)
tm_copy.clone_timer(tm, if_exists="replace")
print(tm_copy.display())
tdml.execute_sql(f"DROP VIEW {DATABASE}.{S.name}_month_end_copy")   # only a demonstration: remove the copy

Output: the cursor of the copy, at the same date as tm (2023-01-31). A soft clone creates only a new view; clone_mode='hard' copies the table, and take_ownership() passes the cleanup of a shared table to a clone.

Composing with FilterManager

The two managers stack: TimeManager for the when, FilterManager for the what. Register with both (time_manager=tm, filtermanager=fm) and roll_out replays each date segment by segment (module 6).

Clean up

tdfs4ds.remove_process(process_id, drop_view=True, refresh_index=False); the manager tables <flavor>_month_end* are dropped with DROP TABLE (and their views with DROP VIEW). Module 13 lists everything.

Learn more