Time-window features#
Aggregate event data, such as transactions, and monthly repayment statuses over windows that end at an observation time, using only what is known then. window_features() computes the number of events, sums, means, extremes and other aggregations of each window, panel_features() the bad months, the longest runs of bad and good months and the worst status of a monthly panel, and FeatureSpec keeps the definitions of both, computes them again on any sample and saves them as versioned JSON.
See Time-window features for examples and the rules of the windows.
|
Aggregate the events of each entity over windows before an observation time. |
|
Summarize the monthly repayment status of each entity before an observation time. |
|
Definitions of time-window features, to compute them the same way again. |
- kivi.features.window_features(events, observations, *, id, time, observation_time, windows=('3M', '6M', '12M'), aggregations=None, ratios=None, closed='left', prefix='')#
Aggregate the events of each entity over windows before an observation time.
For each row of observations, an entity and a time \(t\), every window collects the events of that entity in an interval that ends at or before \(t\), such as the last three months \([t - 3M, t)\), and aggregates the values of the chosen columns: their number, sum, mean, extremes and so on. Events at or after \(t\) are never used, so the features are known at the observation time.
- Parameters:
- eventspandas.DataFrame
One row per event, such as a transaction, in any order, with the columns id and time and the columns to aggregate. Several events of an entity may share one time.
- observationspandas.DataFrame
One row per entity and observation time, with the columns id and observation_time, such as the applicants and their application dates. An entity may appear in several rows, for example once a month to compute its features over time, and two rows may be equal.
- idstr
Column of both tables that names the entity, such as a customer number. Values are matched by equality, so
1and"1"are different entities.- timestr
Column of events with the time of each event, of a datetime dtype.
- observation_timestr
Column of observations with the time of each observation, of a datetime dtype, tz-naive or in the time zone of time.
- windowssequence, default (“3M”, “6M”, “12M”)
Windows before the observation time.
"3M"is the last three calendar months and"90D"the last 90 days. A pair such as("6M", "3M")is the earlier period from six to three months before the observation time; its two bounds must have the same unit and the first must be further back. A pair is one window only as an item of the list, as inwindows=[("6M", "3M")]:windows=("6M", "3M")is the two windows"6M"and"3M".- aggregationsdict, optional
The aggregations of each column of events, such as
{"amount": ["count", "sum", "max"]}, among"count","sum","mean","min","max","std","nunique","first","last"and"days_since_last"; see the Notes. By default, only the number of events of each window is computed.- ratiossequence of pairs of str, optional
Ratios of two features, each a pair of column names of the result such as
("amount_sum_3m", "amount_sum_12m"). A ratio of a recent window to an earlier one, such as("amount_sum_3m", "amount_sum_6m_3m"), measures the change from one period to the next.- closed{“left”, “right”}, default “left”
"left"takes the windows as \([t - k, t)\), without the events at the observation time."right"takes them as \((t - k, t]\), for events that are known at their own time, such as balances at the end of a day; whether they are known at the observation time is the caller’s judgment. A pair of windows is closed on the same side.- prefixstr, default “”
Text put in front of every column name, as given, such as
"cash_"for the features of cash withdrawals. Ratios name columns with the prefix.
- Returns:
- pandas.DataFrame
One row per row of observations, on its index and in its order. For each window in turn, the column
{prefix}events_{window}and then, column by column and aggregation by aggregation, the columns{prefix}{column}_{aggregation}_{window}, such asamount_sum_3moramount_sum_6m_3m. The prefix and the column names are kept as given, and only kivi’s own parts, the aggregations and the windows, are in lower case, soAmountandamountgive different columns. The ratios follow, named{numerator}_over_{window}when the numerator and the denominator differ only in their windows, such asamount_sum_3m_over_12m, and{numerator}_over_{denominator}otherwise.events,countandnuniqueare integers and all other columns floats.
- Raises:
- ValueError
If events or observations is not a DataFrame, if id, time or observation_time is not the name of a single column of its table, if an id or a time is missing, if a time column does not hold datetimes, or if the two time columns are not both tz-naive or in one time zone. Also if a window, an aggregation, a ratio, closed or prefix is invalid or repeated, if aggregations names a column that events lacks, if a column with an aggregation other than
count,nuniqueanddays_since_lastholds values that are not numbers or are infinite, or if two columns of the result would have one name.
See also
FeatureSpecKeep the definitions and compute them again.
kivi.univariate.profile_tableScreen the features against a target.
kivi.datasets.make_applicationsApplications with dates to observe.
Notes
A window of \(k\) months starts \(k\) calendar months before the observation time, as
pandas.DateOffset(months=k)counts them: one month before 31 March is 29 February in a leap year, and the time of day is kept. A window of \(k\) days starts \(k\) days before. With time zones, the bounds are computed on the local calendar and the events compared as instants. A bound that falls into the hour skipped when clocks go forward moves to the end of that hour, and one in the hour repeated when they go back takes its first occurrence.The aggregations leave out the missing values of their column; the
eventscolumns count every event of the window. In a window without values,count,sumandnuniqueare 0 and the other aggregations NaN:count: the number of values;sumandmean: their sum and mean;minandmax: the smallest and the largest value;std: the sample standard deviation, aspandas.Series.stdgives it;nunique: the number of distinct values;firstandlast: the value of the earliest and of the latest event;days_since_last: the days from the latest event to the observation time.
stdis NaN for fewer than two values.firstandlasttake events of one time in the order of the rows of events.days_since_lastcounts fractions of a day, so an event twelve hours before the observation is 0.5 days old; for a pair of windows it is still measured from the observation time. It is the time that has passed, so with a time zone it can differ by the hour that clocks change from the local calendar days that windows such as"90D"count.count,nuniqueanddays_since_lasttake columns of any dtype, such as the type of a merchant; the other aggregations need numbers, and booleans count as 0 and 1. A ratio is NaN where its denominator is 0 or NaN.Entities of observations without events get the values of empty windows, and events of entities that observations lacks are ignored. The events are sorted once, and the bounds of every window are found by binary search. Counts, sums, means, first and last values and
days_since_lastthen take a time that grows with the number of rows of the two tables, and a sum adds only values inside its window, so a large earlier value does not round away the small ones in it.min,max,stdandnuniquevisit each event once for every window that contains it, so their time grows with the events of all windows together; they are expanded a bounded number at a time, so memory does not.Examples
>>> import pandas as pd >>> from kivi.features import window_features >>> events = pd.DataFrame({ ... "customer": [1, 1, 1, 2], ... "time": pd.to_datetime(["2024-01-15", "2024-03-02", "2024-03-31", "2024-02-10"]), ... "amount": [100.0, 40.0, 60.0, 80.0], ... }) >>> observations = pd.DataFrame({ ... "customer": [1, 2, 3], ... "date": pd.to_datetime(["2024-03-31", "2024-03-31", "2024-03-31"]), ... }) >>> window_features( ... events, observations, id="customer", time="time", observation_time="date", ... windows=["1M", "3M"], aggregations={"amount": ["sum"]}, ... ) events_1m amount_sum_1m events_3m amount_sum_3m 0 1 40.0 2 140.0 1 0 0.0 1 80.0 2 0 0.0 0 0.0
The event of 31 March is on the observation date, so no window uses it, and the month before 31 March starts on 29 February.
A pair of bounds is one window only as an item of the list of windows; on its own, it is two windows:
>>> pair = window_features( ... events, observations, id="customer", time="time", observation_time="date", ... windows=[("3M", "1M")], ... ) >>> pair events_3m_1m 0 1 1 1 2 0 >>> two = window_features( ... events, observations, id="customer", time="time", observation_time="date", ... windows=("3M", "1M"), ... ) >>> list(two.columns) ['events_3m', 'events_1m']
- kivi.features.panel_features(panel, observations, *, id, month, status, observation_time, windows=('6M', '12M'), bad='30-59', prefix='')#
Summarize the monthly repayment status of each entity before an observation time.
For each row of observations, an entity and a time \(t\), every window collects the month-end statuses of that entity in the months before the month of \(t\), such as the last six months, and counts how many were bad, the longest runs of bad and of good months and the worst status. A status is bad from bad on, in the order of the categories. The status at the end of the month of \(t\) is not known at \(t\), so that month and the later ones are never used.
- Parameters:
- panelpandas.DataFrame
One row per loan and month, with the columns id, month and status, such as the result of kivi.vintage.delinquency_panel or kivi.datasets.make_loan_panel, in any order. An entity with several loans has several rows in a month, and its status in that month is the worst of them.
- observationspandas.DataFrame
One row per entity and observation time, with the columns id and observation_time, as in window_features.
- idstr
Column of both tables that names the entity, such as a customer or a loan. Values are matched by equality.
- monthstr
Column of panel with the month of each status: monthly periods, or datetimes, which stand for their month on their own calendar. Tz-aware datetimes must be in the time zone of observation_time if that has one too.
- statusstr
Column of panel with the status at the end of each month, an ordered categorical from the best status to the worst, such as the
statusof kivi.vintage.delinquency_panel.- observation_timestr
Column of observations with the time of each observation, of a datetime dtype. Its month is taken on its own calendar, also with a time zone.
- windowssequence, default (“6M”, “12M”)
Windows of months before the month of the observation time:
"6M"is the six months before it. A pair such as("12M", "6M")is the earlier period from twelve to six months before it, and is one window only as an item of the list, as inwindows=[("12M", "6M")]. Windows of days are not allowed, because the statuses are monthly.- badstr or int, default “30-59”
The first bad status, one of the categories of status. It and every later category are bad, the earlier ones good. The default is 30 days past due in the buckets of kivi.vintage.delinquency_panel.
- prefixstr, default “”
Text put in front of every column name, as given, such as
"card_"for the panel of credit cards.
- Returns:
- pandas.DataFrame
One row per row of observations, on its index and in its order. For each window in turn, the columns
{prefix}months_{window}, the number of months of the window with a status,{prefix}bad_months_{window}, the number of bad months,{prefix}longest_bad_run_{window}and{prefix}longest_good_run_{window}, the longest runs of consecutive bad and good months, and{prefix}worst_status_{window}, the worst status. Then{prefix}months_since_bad, the months from the latest bad month before the month of the observation time to that month, whatever the windows. The counts are integers, the worst status has the dtype of status and is missing for a window without months, andmonths_since_badis a float, NaN for an entity that was never bad before. The prefix is kept as given, and the windows are in lower case, as in window_features.
- Raises:
- ValueError
If panel or observations is not a DataFrame, if id, month, status or observation_time is not the name of a single column of its table, if an id, a month or a status is missing, if month does not hold monthly periods or datetimes, if status is not an ordered categorical or bad not one of its categories, if observation_time does not hold datetimes, or if the months and the observation times are tz-aware in two different time zones. Also if a window is not a number of months or is repeated, or if prefix is not a string.
See also
window_featuresThe features of event data.
FeatureSpecKeep the definitions and compute them again.
kivi.vintage.delinquency_panelThe monthly panel of instalment loans.
Notes
The month of an observation time is its calendar month, so an observation on 31 March uses the statuses up to the end of February. Months and observation times are each taken on their own calendar, which is why two time zones raise an error: 1 April in Tokyo is still 31 March in New York, before the status at the end of March in New York exists. A window of \(k\) months holds the \(k\) months before it, so
"6M"for an observation in March holds September to February.Only months with a status count: a window that holds months before the first month of an entity, after its last loan ended or in a gap between its loans has fewer than \(k\) months, which
months_{window}shows. A month without a status ends a run, so a bad month, a missing month and a bad month are two runs of one. A run that started before a window counts only with its months inside the window.Examples
>>> import pandas as pd >>> from kivi.features import panel_features >>> buckets = ["current", "1-29", "30-59", "60-89", "90+"] >>> panel = pd.DataFrame({ ... "customer": ["a"] * 6 + ["b"] * 2, ... "month": pd.PeriodIndex( ... ["2023-10", "2023-11", "2023-12", "2024-01", "2024-02", "2024-03", ... "2024-02", "2024-03"], freq="M", ... ), ... "status": pd.Categorical( ... ["current", "1-29", "30-59", "60-89", "current", "current", ... "current", "30-59"], categories=buckets, ordered=True, ... ), ... }) >>> observations = pd.DataFrame({ ... "customer": ["a", "b", "c"], ... "date": pd.to_datetime(["2024-03-15", "2024-03-15", "2024-03-15"]), ... }) >>> panel_features( ... panel, observations, id="customer", month="month", status="status", ... observation_time="date", windows=["3M"], ... ).T 0 1 2 months_3m 3 1 0 bad_months_3m 2 0 0 longest_bad_run_3m 2 0 0 longest_good_run_3m 1 1 0 worst_status_3m 60-89 current NaN months_since_bad 2.0 NaN NaN
The three months before March are December to February. Customer
bfalls 30 days behind in March, the month of the observation, which is not used.
- class kivi.features.FeatureSpec(id, observation_time, events=(), ratios=(), panel=(), kivi_version=None)#
Definitions of time-window features, to compute them the same way again.
A specification records the columns that identify the entities and the observation times, and groups of window features and of panel features. A group of window features holds the arguments of one call of window_features: the event table it reads, its time column, its windows, its aggregations, the side on which its windows are closed and the prefix of its column names. Groups that read filtered events, such as only the cash withdrawals, use their own table and prefix. A group of panel features holds the arguments of one call of panel_features in the same way. compute gives the features of any sample, and to_json and from_json save and load the definitions. Nothing is fitted to data, so a specification can be written by hand.
A specification is immutable: its groups are read-only mappings with tuples for lists. To change a field, use dataclasses.replace, which validates the result again.
- Parameters:
- idstr
Column of the observations and of every event table that names the entity; all groups share it.
- observation_timestr
Column of the observations with the observation times.
- eventssequence of dict, default ()
One dict per group of window features, with the keys
time(required),windows,aggregations,closedandprefix, which mean and default to what the arguments of window_features do, andtable, the name of the event table that the group reads,"events"by default.- ratiossequence of pairs of str, default ()
Ratios of two features of any groups, named by their columns, as in window_features.
- panelsequence of dict, default ()
One dict per group of panel features, with the keys
monthandstatus(both required),windows,badandprefix, which mean and default to what the arguments of panel_features do, andtable, the name of the panel that the group reads,"panel"by default. The specification needs at least one group of either kind.- kivi_versionstr, optional
Version of kivi that wrote the specification. By default, or if None, the installed version.
- Attributes:
- FORMAT_VERSIONint
Version of the JSON format that to_json writes and the newest that from_json reads.
- Raises:
- ValueError
If id or observation_time is not a string, if events or panel is not a list of dicts with valid entries or both are empty, if two features of the groups have one name, if a ratio is invalid or divides a status, or if kivi_version is not a string. The checks of each entry are those of the arguments of window_features and panel_features.
See also
window_featuresCompute the features of one group of events directly.
panel_featuresCompute the features of one group of a panel directly.
kivi.spec.BinningSpecThe binning of the features, saved the same way.
Notes
Two specifications are equal when to_json gives the same text for both, which includes kivi_version.
Examples
>>> import pandas as pd >>> from kivi.features import FeatureSpec >>> spec = FeatureSpec( ... id="customer", ... observation_time="date", ... events=[{"time": "time", "windows": ["1M", "3M"], "aggregations": {"amount": ["sum"]}}], ... ratios=[("amount_sum_1m", "amount_sum_3m")], ... ) >>> spec FeatureSpec(columns=['events_1m', 'amount_sum_1m', 'events_3m', 'amount_sum_3m', 'amount_sum_1m_over_3m']) >>> events = pd.DataFrame({ ... "customer": [1, 1, 2], ... "time": pd.to_datetime(["2024-01-15", "2024-03-02", "2024-02-10"]), ... "amount": [100.0, 40.0, 80.0], ... }) >>> observations = pd.DataFrame({ ... "customer": [1, 2], ... "date": pd.to_datetime(["2024-03-31", "2024-03-31"]), ... }) >>> spec.compute(observations, events=events) events_1m amount_sum_1m events_3m amount_sum_3m amount_sum_1m_over_3m 0 1 40.0 2 140.0 0.285714 1 0 0.0 1 80.0 0.000000
- property columns#
Names of the columns that compute returns, in their order.
The window features of each group come in the order of the groups, then the panel features, and the ratios last, so the names can select or check the columns of a result before any data is read.
See also
computeCompute the columns.
Examples
>>> from kivi.features import FeatureSpec >>> spec = FeatureSpec( ... id="customer", ... observation_time="date", ... events=[ ... {"time": "time", "windows": ["3M"], "aggregations": {"amount": ["sum"]}}, ... {"table": "cash", "time": "time", "windows": ["3M"], "prefix": "cash_"}, ... ], ... ) >>> spec.columns Index(['events_3m', 'amount_sum_3m', 'cash_events_3m'], dtype='object')
- compute(observations, *, events=None, panel=None)#
Compute the features of every observation.
Each group of window features gives the columns that window_features gives for its definitions and its event table, without ratios, and each group of panel features the columns that panel_features gives for its definitions and its panel. The ratios of the specification follow.
- Parameters:
- observationspandas.DataFrame
One row per entity and observation time, with the columns id and observation_time of the specification.
- eventspandas.DataFrame or dict of pandas.DataFrame, optional
The event table, or a dict from the
tablename of every group of window features to its event table. A single table is allowed when all these groups read the same table. Required when the specification has groups of window features, and otherwise None.- panelpandas.DataFrame or dict of pandas.DataFrame, optional
The monthly panel, or a dict from the
tablename of every group of panel features to its panel, in the same way.
- Returns:
- pandas.DataFrame
The columns of columns, one row per row of observations, on its index and in its order.
- Raises:
- ValueError
If events or panel is neither a DataFrame nor a dict of DataFrames with one entry per table of the groups, or is given without groups to read it, or for the reasons that window_features and panel_features give.
See also
window_featuresThe features of one group of events.
panel_featuresThe features of one group of a panel.
columnsThe names of the columns.
Examples
>>> import pandas as pd >>> from kivi.features import FeatureSpec >>> spec = FeatureSpec( ... id="customer", ... observation_time="date", ... events=[ ... {"time": "time", "windows": ["3M"], "aggregations": {"amount": ["sum"]}}, ... {"table": "cash", "time": "time", "windows": ["3M"], ... "aggregations": {"amount": ["sum"]}, "prefix": "cash_"}, ... ], ... ratios=[("cash_amount_sum_3m", "amount_sum_3m")], ... ) >>> events = pd.DataFrame({ ... "customer": [1, 1, 1], ... "time": pd.to_datetime(["2024-01-15", "2024-02-03", "2024-03-02"]), ... "kind": ["purchase", "cash", "purchase"], ... "amount": [100.0, 60.0, 40.0], ... }) >>> observations = pd.DataFrame({"customer": [1], "date": pd.to_datetime(["2024-03-31"])}) >>> tables = {"events": events, "cash": events[events["kind"] == "cash"]} >>> spec.compute(observations, events=tables).T 0 events_3m 3.0 amount_sum_3m 200.0 cash_events_3m 1.0 cash_amount_sum_3m 60.0 cash_amount_sum_3m_over_amount_sum_3m 0.3
- to_dict()#
Return the feature specification as a dict of JSON types.
The dict holds the arguments of the constructor as the constructor takes them, with lists for tuples, so they rebuild the specification. It holds only dicts, lists, strings and integers, so
json.dumpscan write it without further conversion, and its keys are always in the same order. to_json writes this dict.- Returns:
- dict
The keys
format,format_versionandkivi_version, then the argumentsid,observation_time,events,ratiosandpanel. Each group ofeventshas all its keys:table,time,windows,aggregations, a dict from each column to the list of its aggregations in the order of the columns of the result,closedandprefix. Each group ofpanelhas the keystable,month,status,windows,badandprefix.
Examples
>>> from kivi.features import FeatureSpec >>> spec = FeatureSpec( ... id="customer", ... observation_time="date", ... events=[{"time": "time", "windows": ["3M", ("6M", "3M")]}], ... ) >>> data = spec.to_dict() >>> list(data) ['format', 'format_version', 'kivi_version', 'id', 'observation_time', 'events', 'ratios', 'panel'] >>> data["events"][0] {'table': 'events', 'time': 'time', 'windows': ['3M', ['6M', '3M']], 'aggregations': {}, 'closed': 'left', 'prefix': ''} >>> arguments = ["id", "observation_time", "events", "ratios", "panel", "kivi_version"] >>> FeatureSpec(**{name: data[name] for name in arguments}) == spec True
- classmethod from_dict(data)#
Rebuild a feature specification from the result of to_dict.
The dict is checked before the specification is built, so that a damaged or hand-edited file fails with a message that names the problem.
- Parameters:
- datamapping
A dict in the format of to_dict, for example from
json.load. Every key that to_dict writes must be present, also in each group.
- Returns:
- FeatureSpec
The feature specification, equal to the one that wrote data.
- Raises:
- ValueError
If data is not a kivi feature specification, has a
format_versionnewer than this version of kivi reads, lacks a key or has an unknown one, or holds an invalid value.
Examples
>>> from kivi.features import FeatureSpec >>> spec = FeatureSpec(id="customer", observation_time="date", events=[{"time": "time"}]) >>> FeatureSpec.from_dict(spec.to_dict()) == spec True
- to_json(*, indent=None)#
Return the feature specification as JSON text.
The text is the dict of to_dict written by
json.dumps. The same specification always gives the same text, so saved specifications can be compared and kept under version control. Non-ASCII names are written as they are, so save the text as UTF-8.- Parameters:
- indentint, optional
Indentation of nested values, as in
json.dumps. By default the text is a single line.
- Returns:
- str
JSON text that from_json reads back into an equal feature specification.
Examples
>>> from kivi.features import FeatureSpec >>> spec = FeatureSpec( ... id="customer", ... observation_time="date", ... events=[{"time": "time", "windows": ["3M"], "aggregations": {"amount": ["sum"]}}], ... ) >>> print(spec.to_json(indent=2)) { "format": "kivi.FeatureSpec", "format_version": 1, "kivi_version": "...", "id": "customer", "observation_time": "date", "events": [ { "table": "events", "time": "time", "windows": [ "3M" ], "aggregations": { "amount": [ "sum" ] }, "closed": "left", "prefix": "" } ], "ratios": [], "panel": [] }
Write the text to a file with
Path("features.json").write_text(text, encoding="utf-8").
- classmethod from_json(text)#
Read a feature specification from the JSON text of to_json.
A file written by a newer version of the format is rejected rather than read in part, and so is a JSON object that repeats a key, which
json.loadswould otherwise read as its last value.- Parameters:
- textstr or bytes
JSON text, for example from
Path(...).read_text(encoding="utf-8").
- Returns:
- FeatureSpec
The feature specification, equal to the one that wrote text.
- Raises:
- ValueError
If text is neither a str nor bytes, is not valid JSON, repeats a key of an object, or does not describe a valid specification; see from_dict.
See also
Examples
>>> from kivi.features import FeatureSpec >>> spec = FeatureSpec(id="customer", observation_time="date", events=[{"time": "time"}]) >>> FeatureSpec.from_json(spec.to_json()) == spec True