Skip to Content

Event studies

Align events to price paths from the moment they could be acted on, keep track of censored and overlapping windows, and estimate the average response with intervals that respect clustering.

An event study asks what prices did around a dated event: an earnings release, an index addition, a rating change. Three things go wrong most often. The window starts at the date the event happened instead of the moment anyone could have known about it, so the path includes a move nobody could trade. Windows run off the edge of the data and are silently averaged as if they were complete. And events on the same instrument, or on the same day, are treated as independent observations, which makes the average look far more certain than it is.

lacuna.events has two functions. lc.events.event_windows aligns each event to a price path and records what could not be aligned. lc.events.event_response averages the paths and puts intervals around the average that treat events sharing an aligned anchor time as one unit.

What you need

Two long-form tables, as elsewhere in Lacuna. The events table has one row per event with four columns, and the price table has one row per instrument and observation.

TableColumns
Eventsevent_id (unique), instrument, event_time (when the event happened), available_time (when it became known)
Pricestime, instrument, close

event_time, available_time and the price time must all have exactly the same dtype, including the time unit and time zone of a datetime, and instrument must match between the two tables. A mismatch raises a DataContractError before anything is joined. Time keys may be dates, datetimes, durations, integers or whole-number floats. Null event keys or null price times raise, event_id must be unique, and duplicate (time, instrument) rows in the price table are rejected. If no event can be aligned at all, event_windows raises a DataContractError instead of returning an empty result. Input formats and column naming are covered in Data, and the timing vocabulary in Time and data.

A first example

The panel has 40 instruments over 160 sessions. Thirty events are planted, each announced after the close on its event day, with a 3% price reaction on the next session and a smaller drift after that.

from datetime import date, timedelta

import lacuna as lc
import numpy as np
import polars as pl

rng = np.random.default_rng(21)
n_instruments, n_sessions = 40, 160
days = (date(2024, 1, 1) + timedelta(days=n) for n in range(260))
sessions = [day for day in days if day.weekday() < 5][:n_sessions]
ids = [f"E{i:02d}" for i in range(n_instruments)]

returns = 0.01 * rng.normal(size=(n_sessions, n_instruments))
event_instruments = rng.permutation(n_instruments)[:30]
event_days = np.sort(rng.integers(10, n_sessions - 15, size=30))
for instrument_index, day in zip(event_instruments, event_days):
    returns[day + 1, instrument_index] += 0.03
    returns[day + 2 : day + 6, instrument_index] += 0.004
close = 50 * np.exp(np.cumsum(returns, axis=0))

prices = pl.DataFrame(
    {
        "time": pl.Series(sessions).repeat_by(n_instruments).explode(),
        "instrument": ids * n_sessions,
        "close": close.ravel(),
    }
)
events = pl.DataFrame(
    {
        "event_id": [f"ev{k:02d}" for k in range(30)],
        "instrument": [ids[i] for i in event_instruments],
        "event_time": [sessions[d] for d in event_days],
        "available_time": [sessions[d] for d in event_days],
    }
)
print(events.head(3))
shape: (3, 4)
┌──────────┬────────────┬────────────┬────────────────┐
│ event_id ┆ instrument ┆ event_time ┆ available_time │
│ ---      ┆ ---        ┆ ---        ┆ ---            │
│ str      ┆ str        ┆ date       ┆ date           │
╞══════════╪════════════╪════════════╪════════════════╡
│ ev00     ┆ E06        ┆ 2024-01-15 ┆ 2024-01-15     │
│ ev01     ┆ E31        ┆ 2024-01-22 ┆ 2024-01-22     │
│ ev02     ┆ E05        ┆ 2024-01-22 ┆ 2024-01-22     │
└──────────┴────────────┴────────────┴────────────────┘

Align the events to the prices with a window of three observations before the anchor and five after:

windows = lc.events.event_windows(
    events, prices, before=3, after=5, price_adjustment="split_adjusted"
)
path = windows.frame.filter(pl.col("event_id") == "ev00")
print(path.select("offset", "price_time", "price", "response").with_columns(pl.col("price", "response").round(4)))
print(windows.evidence.metrics)
shape: (9, 4)
┌────────┬────────────┬─────────┬──────────┐
│ offset ┆ price_time ┆ price   ┆ response │
│ ---    ┆ ---        ┆ ---     ┆ ---      │
│ i64    ┆ date       ┆ f64     ┆ f64      │
╞════════╪════════════╪═════════╪══════════╡
│ -3     ┆ 2024-01-10 ┆ 48.0887 ┆ -0.0378  │
│ -2     ┆ 2024-01-11 ┆ 48.509  ┆ -0.0294  │
│ -1     ┆ 2024-01-12 ┆ 49.1319 ┆ -0.0169  │
│ 0      ┆ 2024-01-15 ┆ 49.9759 ┆ 0.0      │
│ 1      ┆ 2024-01-16 ┆ 50.9893 ┆ 0.0203   │
│ 2      ┆ 2024-01-17 ┆ 51.0952 ┆ 0.0224   │
│ 3      ┆ 2024-01-18 ┆ 51.6362 ┆ 0.0332   │
│ 4      ┆ 2024-01-19 ┆ 52.4389 ┆ 0.0493   │
│ 5      ┆ 2024-01-22 ┆ 51.992  ┆ 0.0403   │
└────────┴────────────┴─────────┴──────────┘
{'n_events': 30, 'aligned_events': 30, 'n_window_rows': 270, 'censored_events': 0, 'overlapping_events': 0, 'retrospective_lookahead_events': 0, 'skipped_null_anchor_prices': 0}

Each event becomes nine rows, one per offset from -3 to +5. Offset 0 is the anchor: the first price observation at or after the moment the event was available. The response column is the price at each offset relative to the price at the anchor, so it is exactly 0.0 at offset 0, and the jump after the announcement shows up at offset 1. The reaction for this one event is about 2% on top of ordinary noise; the average over all 30 events, below, is close to the planted 3%.

windows is an EventWindowResult. windows.frame is a Polars DataFrame with one row per event and offset, and windows.evidence is an AnalysisResult with the counts, findings, a coverage table and every parameter you chose.

How a window is defined

Offsets count rows of that instrument in the price table, not calendar days, and rows whose price is null count too. Offset +5 is the fifth row after the anchor in that instrument’s own price history, whatever dates those fall on, so holidays and weekends do not stretch or shrink the window. For daily data that is five sessions. The window covers the half-open offset interval [-before, after + 1), which is the offsets -before through after inclusive.

The anchor is chosen by the only alignment Lacuna implements, alignment="next_observation": the first observation of the same instrument whose time is at or after the anchor time and whose price is not null. A null price is skipped when looking for the anchor, and skipped_null_anchor_prices counts those skipped observations, summed over events. A null price elsewhere in the window is not skipped over: that offset is simply absent from frame and counted in missing_price_rows in the coverage table. An event whose anchor time exactly equals an observation time anchors at that observation.

For each offset jj from -before to after, with Pa+jP_{a+j} the price jj observations from the anchor observation aa:

responsej=Pa+jPa−1\text{response}_j = \frac{P_{a+j}}{P_a} - 1

That is the whole definition. Pre-event offsets are measured against the same anchor price, so a move that happened before the anchor appears at negative offsets as a negative number: if the price jumped from 100 to 103 between offsets -1 and 0, offset -1 has a response of about -2.9%. The frame also carries the anchor_price, so you can recompute any response yourself.

The frame has these columns:

ColumnMeaning
event_id, instrument, event_time, available_timeThe event as you supplied it.
anchor_timeThe time the window was anchored to: available_time or event_time, according to anchor.
aligned_anchor_timeThe time of the observation that became offset 0.
offsetObservations from the anchor.
price_time, priceThe observation at that offset.
anchor_priceThe price at offset 0.
responseprice / anchor_price - 1.
overlap_clusterAn identifier shared by same-instrument events whose windows overlap. Always written, so a cluster with one event means no overlap. See Overlapping windows.

This is not an abnormal-return model

Lacuna does not compute abnormal returns. There is no estimation window, no market model and no expected return: response is the raw price path relative to the anchor. If you need a market-adjusted path, build a positive relative-price series first and pass that as price. Dividing a price by an index gives relative wealth, so the response becomes (1 + r_i) / (1 + r_index) - 1, which is not the difference r_i - r_index. The index in this example is an unrebalanced equal-weight buy-and-hold of all 40 instruments, so it includes the event stock itself.

index_level = (
    prices.with_columns((pl.col("close") / pl.col("close").first().over("instrument")).alias("level"))
    .group_by("time")
    .agg(pl.col("level").mean())
)
relative = (
    prices.join(index_level, on="time")
    .with_columns((pl.col("close") / pl.col("level")).alias("close"))
    .select("time", "instrument", "close")
)
relative_windows = lc.events.event_windows(
    events, relative, before=3, after=5, price_adjustment="split_adjusted"
)
for name, result in (("raw", windows), ("relative to an equal-weight index", relative_windows)):
    mean_at_five = result.frame.filter(pl.col("offset") == 5)["response"].mean()
    print(f"{name}: {mean_at_five:.4f}")
raw: 0.0480
relative to an equal-weight index: 0.0447

The relative path is lower by roughly the index’s own movement over the same five sessions. Lacuna cannot check that the series you pass means what you say. The only declaration it records about prices is price_adjustment, which accepts any non-empty text and is not validated. Leaving it at "unknown" adds an EVENT_PRICE_ADJUSTMENT_UNKNOWN finding in the UNKNOWN state, because corporate actions inside a window distort a raw price path.

Anchoring to availability

anchor="available_time", the default, starts every window at the moment the event was known. anchor="event_time" starts it at the economic date. The two differ whenever the information was published late, and the difference is the leak.

late = events.with_columns(available_time=pl.col("event_time") + pl.duration(days=2))
by_availability = lc.events.event_windows(late, prices, before=3, after=5, price_adjustment="split_adjusted")
by_event_time = lc.events.event_windows(
    late, prices, before=3, after=5, anchor="event_time", price_adjustment="split_adjusted"
)
print(by_availability.frame.filter(pl.col("event_id") == "ev00").select("event_time", "available_time", "anchor_time", "aligned_anchor_time").head(1))
print([(f.code, f.state.value) for f in by_event_time.evidence.findings])
print(by_event_time.evidence.metrics["retrospective_lookahead_events"])
shape: (1, 4)
┌────────────┬────────────────┬─────────────┬─────────────────────┐
│ event_time ┆ available_time ┆ anchor_time ┆ aligned_anchor_time │
│ ---        ┆ ---            ┆ ---         ┆ ---                 │
│ date       ┆ date           ┆ date        ┆ date                │
╞════════════╪════════════════╪═════════════╪═════════════════════╡
│ 2024-01-15 ┆ 2024-01-17     ┆ 2024-01-17  ┆ 2024-01-17          │
└────────────┴────────────────┴─────────────┴─────────────────────┘
[('EVENT_RETROSPECTIVE_ANCHOR_LOOKAHEAD', 'WARN')]
30

Anchoring to event_time when available_time is later is allowed, because retrospective studies of the event itself are legitimate. But a path that begins before the event was known contains returns no decision could have used. The result flags it with EVENT_RETROSPECTIVE_ANCHOR_LOOKAHEAD and counts the events in retrospective_lookahead_events. Do not use such a window to evaluate a trading rule.

available_time is your assertion. Lacuna uses it as given and cannot verify when an event was really published.

With date columns, Lacuna cannot tell an announcement made before the open from one made after the close: both anchor at the observation dated that day. For an after-close announcement that anchors at the last price before the news, so the reaction falls after offset 0 and is in the path. For a pre-open announcement the anchor is a close taken after the opening reaction, which the path therefore misses. Timestamps can tell the two apart, but with close-only prices they have a cost of their own, shown next.

With timestamps, the anchor is the first observation at or after the availability time, and anchor_delay in the coverage table shows how long the wait was:

intraday_prices = prices.with_columns(pl.col("time").cast(pl.Datetime("us")) + pl.duration(hours=16))
intraday_events = events.with_columns(
    event_time=pl.col("event_time").cast(pl.Datetime("us")) + pl.duration(hours=17),
    available_time=pl.col("event_time").cast(pl.Datetime("us")) + pl.duration(hours=17, minutes=30),
)
intraday = lc.events.event_windows(
    intraday_events, intraday_prices, before=1, after=2, price_adjustment="split_adjusted"
)
first = intraday.frame.filter(pl.col("event_id") == "ev00").select("available_time", "aligned_anchor_time").head(1)
print(first)
coverage = pl.DataFrame(intraday.evidence.table("event_coverage")).filter(pl.col("event_id") == "ev00")
print(coverage.select("anchor_delay").item() / 3600, "hours")
shape: (1, 2)
┌─────────────────────┬─────────────────────┐
│ available_time      ┆ aligned_anchor_time │
│ ---                 ┆ ---                 │
│ datetime[μs]        ┆ datetime[μs]        │
╞═════════════════════╪═════════════════════╡
│ 2024-01-15 17:30:00 ┆ 2024-01-16 16:00:00 │
└─────────────────────┴─────────────────────┘
22.5 hours

The closes are stamped 16:00 and the announcement is available at 17:30, so the window anchors at the next day’s close, 22.5 hours later. With close-only prices this cuts the other way from the date case. The return from the announcement day’s close to the next close is where the after-close reaction lives, and it ends at offset 0, so it falls before the anchor. It shows up only as the step between offsets -1 and 0, and response at offset 1 and later excludes it. Keeping it needs observations between the announcement and the next close, such as open or intraday prices, or a deliberate anchor choice, such as date columns for an after-close announcement, which anchor at that day’s close.

Coverage and censoring

A window can run past the start or end of an instrument’s price history, hit a missing price, or belong to an event with no usable anchor at all. Lacuna keeps what exists and records what does not. It never fills.

edge_times = [sessions[1], sessions[-2], sessions[5], sessions[-1] + timedelta(days=30)]
edge = pl.DataFrame(
    {
        "event_id": ["early", "late", "ghost", "beyond"],
        "instrument": ["E00", "E01", "NOPE", "E02"],
        "event_time": edge_times,
        "available_time": edge_times,
    }
)
edge_windows = lc.events.event_windows(edge, prices, before=3, after=5, price_adjustment="split_adjusted")
coverage = pl.DataFrame(edge_windows.evidence.table("event_coverage"))
print(coverage.select("event_id", "observed_rows", "left_censored_rows", "right_censored_rows", "status").sort("event_id"))
print([f.code for f in edge_windows.evidence.findings])
shape: (4, 5)
┌──────────┬───────────────┬────────────────────┬─────────────────────┬──────────────────────┐
│ event_id ┆ observed_rows ┆ left_censored_rows ┆ right_censored_rows ┆ status               │
│ ---      ┆ ---           ┆ ---                ┆ ---                 ┆ ---                  │
│ str      ┆ i64           ┆ i64                ┆ i64                 ┆ str                  │
╞══════════╪═══════════════╪════════════════════╪═════════════════════╪══════════════════════╡
│ beyond   ┆ 0             ┆ 3                  ┆ 6                   ┆ no_eligible_anchor   │
│ early    ┆ 7             ┆ 2                  ┆ 0                   ┆ aligned              │
│ ghost    ┆ 0             ┆ 3                  ┆ 6                   ┆ no_instrument_prices │
│ late     ┆ 5             ┆ 0                  ┆ 4                   ┆ aligned              │
└──────────┴───────────────┴────────────────────┴─────────────────────┴──────────────────────┘
['EVENT_WINDOWS_CENSORED']

The coverage table has one row for every event. anchor_delay is the gap between the anchor time and the aligned observation, in seconds for date and datetime keys (dates count 86,400 seconds per day) and in index units for numeric time.

statusMeaning
alignedThe event has an anchor. Its path may still be partial: left_censored_rows and right_censored_rows count offsets beyond the start and end of the price history, and missing_price_rows counts offsets inside it whose price is null.
no_instrument_pricesThe instrument has no prices at all. The event has no rows in frame.
no_eligible_anchorThe instrument has prices, but none at or after the anchor time with a non-null price.

Partial paths stay in frame and are marked by EVENT_WINDOWS_CENSORED. The censored_events metric counts every event with fewer rows than the window expects, including those that could not be aligned. The data_attrition table shows the same loss in rows, first by events and then by window rows.

Overlapping windows

Two events on the same instrument, close in time, have windows that share price observations. Their responses are not independent draws, and averaging them as if they were counts the shared observations twice. By default, event_windows refuses:

two_events = pl.DataFrame(
    {
        "event_id": ["a", "b"],
        "instrument": ["E00", "E00"],
        "event_time": [sessions[40], sessions[44]],
        "available_time": [sessions[40], sessions[44]],
    }
)
lc.events.event_windows(two_events, prices, before=3, after=5, price_adjustment="split_adjusted")
DataContractError: 2 events have overlapping same-instrument windows

overlap_policy="keep" retains them and adds EVENT_WINDOWS_OVERLAP. The overlap_cluster identifier is written on every row of the frame whatever the policy: events on the same instrument whose windows overlap, directly or through a chain of overlaps, share a cluster, and a cluster of one event means no overlap. Overlap is judged on the nominal inclusive index ranges [anchor - before, anchor + after], so windows that only touch at one observation count, and so do parts of a window that are censored or have null prices.

kept = lc.events.event_windows(
    two_events, prices, before=3, after=5, overlap_policy="keep", price_adjustment="split_adjusted"
)
print(kept.frame.select("event_id", "overlap_cluster").unique().sort("event_id"))
print(kept.evidence.metrics["overlapping_events"])
shape: (2, 2)
┌──────────┬─────────────────┐
│ event_id ┆ overlap_cluster │
│ ---      ┆ ---             │
│ str      ┆ str             │
╞══════════╪═════════════════╡
│ a        ┆ overlap-0001    │
│ b        ┆ overlap-0001    │
└──────────┴─────────────────┘
2

Use overlap_cluster for your own clustering or de-duplication. lc.events.event_response does not resample by it: it clusters by aligned anchor time, which handles events that are aligned to the same observation, but it does not remove the repeated use of the same price observations by overlapping same-instrument windows. It does report the overlap it left in: its inference finding counts overlap_clusters_with_multiple_events and events_in_overlap_clusters, and records overlap_cluster_used_for_resampling as False. If your events overlap heavily, thin them yourself before estimating a response, or treat the intervals as too narrow.

The average response

lc.events.event_response averages the paths and puts intervals around the average.

response = lc.events.event_response(windows, seed=3, resamples=1000)
print(response.metrics)
rows = pl.DataFrame(response.table("event_response"))
print(rows.select("offset", "mean_response", "pointwise_lower", "pointwise_upper", "simultaneous_lower", "simultaneous_upper").with_columns(pl.exclude("offset").round(4)))
{'n_events': 30, 'n_complete_events': 30, 'n_clusters': 24, 'successful_resamples': 1000, 'simultaneous_critical_value': 2.496986999650286, 'pre_event_mean_response': -0.001880640431848198, 'pre_event_max_absolute_mean': 0.0029313522473610187}
shape: (9, 6)
┌────────┬───────────────┬─────────────────┬─────────────────┬──────────────────┬──────────────────┐
│ offset ┆ mean_response ┆ pointwise_lower ┆ pointwise_upper ┆ simultaneous_low ┆ simultaneous_upp │
│ ---    ┆ ---           ┆ ---             ┆ ---             ┆ er               ┆ er               │
│ i64    ┆ f64           ┆ f64             ┆ f64             ┆ ---              ┆ ---              │
│        ┆               ┆                 ┆                 ┆ f64              ┆ f64              │
╞════════╪═══════════════╪═════════════════╪═════════════════╪══════════════════╪══════════════════╡
│ -3     ┆ -0.0029       ┆ -0.0091         ┆ 0.0021          ┆ -0.0103          ┆ 0.0044           │
│ -2     ┆ -0.0025       ┆ -0.0082         ┆ 0.0026          ┆ -0.0095          ┆ 0.0044           │
│ -1     ┆ -0.0002       ┆ -0.005          ┆ 0.0042          ┆ -0.0061          ┆ 0.0057           │
│ 0      ┆ 0.0           ┆ 0.0             ┆ 0.0             ┆ null             ┆ null             │
│ 1      ┆ 0.0292        ┆ 0.0263          ┆ 0.0317          ┆ 0.0257           ┆ 0.0327           │
│ 2      ┆ 0.035         ┆ 0.0303          ┆ 0.0399          ┆ 0.0287           ┆ 0.0412           │
│ 3      ┆ 0.0375        ┆ 0.0302          ┆ 0.0443          ┆ 0.0285           ┆ 0.0465           │
│ 4      ┆ 0.0434        ┆ 0.0351          ┆ 0.0515          ┆ 0.0328           ┆ 0.054            │
│ 5      ┆ 0.048         ┆ 0.0402          ┆ 0.0563          ┆ 0.0376           ┆ 0.0585           │
└────────┴───────────────┴─────────────────┴─────────────────┴──────────────────┴──────────────────┘

Thirty events fall on 24 distinct aligned anchor times, because several events share a day. The bootstrap resamples these 24 clusters, not the 30 events. Events whose windows share an aligned anchor time face the same market over the same dates, so they are treated as one unit. The resampling is a heuristic, not an exact treatment of dependence: it draws blocks of consecutive occupied anchor times, in order and ignoring the calendar gaps between them, to mimic dependence between nearby anchors. A move shared by windows anchored on adjacent days is handled only indirectly, through those blocks.

Each row has two intervals for the mean response at an offset:

ColumnsMeaning
pointwise_lower, pointwise_upperA percentile interval for the mean at that one offset. Use it to ask about a single offset that you chose before looking.
simultaneous_lower, simultaneous_upperA band meant to cover the whole path at once at the stated confidence. Use it to ask whether the path as a whole leaves zero.

The simultaneous band is wider, as it should be: looking across offsets and reporting the one that stands out is a multiple comparison. The band is computed over the offsets whose bootstrap spread is not degenerate, which is eight of the nine here. At offset 0 the response is exactly zero for every event, so the bootstrap spread is zero and the band is null.

pre_event_mean_response and pre_event_max_absolute_mean summarise the negative offsets: the unweighted mean of the per-offset average responses before the anchor, and the largest absolute per-offset average. Both are taken from the descriptive mean_response, so partial paths are included. n_events in the metrics counts events with at least one aligned row. A pre-event drift that is large relative to the post-event response suggests anticipation, leakage, or a window that starts too late.

When inference is available, event_response returns EVENT_CLUSTERED_INFERENCE_AVAILABLE in the PASS state. It covers only the cluster-count requirement, and its evidence names the clustering unit (clustering_unit is "aligned_anchor_time"), the cluster and complete-event counts, and overlap_cluster_used_for_resampling (always False, because same-instrument overlap clusters are reported but not resampled). The result then carries every WARN, FAIL and UNKNOWN finding of the windows it was given, unchanged and after its own: EVENT_WINDOWS_OVERLAP, EVENT_WINDOWS_CENSORED, EVENT_RETROSPECTIVE_ANCHOR_LOOKAHEAD and EVENT_PRICE_ADJUSTMENT_UNKNOWN show up on the response without a separate lookup. PASS findings of the windows are not copied, and the response’s own PASS is not a clean bill of health for the windows, so read the whole list: the response’s finding comes first and the inherited ones follow.

Some details on what is averaged. mean_response and n_events in each row describe every path that has an observation at that offset, partial paths included. The intervals and inference_mean use complete paths only, the events with every offset from -before to after observed, because a mean taken over different events at different offsets is not one estimand. The data_attrition table records how many events were complete. When some are not, the two means differ slightly:

mixed = pl.concat([events, edge.filter(pl.col("event_id").is_in(["early", "late"]))])
mixed_windows = lc.events.event_windows(mixed, prices, before=3, after=5, price_adjustment="split_adjusted")
mixed_response = lc.events.event_response(mixed_windows, seed=3, resamples=500)
print({key: mixed_response.metrics[key] for key in ("n_events", "n_complete_events", "n_clusters")})
print(pl.DataFrame(mixed_response.table("event_response")).select("offset", "n_events", "mean_response", "inference_mean").head(3).with_columns(pl.exclude("offset", "n_events").round(5)))
print([(f.code, f.state.value) for f in mixed_response.findings])
{'n_events': 32, 'n_complete_events': 30, 'n_clusters': 24}
shape: (3, 4)
┌────────┬──────────┬───────────────┬────────────────┐
│ offset ┆ n_events ┆ mean_response ┆ inference_mean │
│ ---    ┆ ---      ┆ ---           ┆ ---            │
│ i64    ┆ i64      ┆ f64           ┆ f64            │
╞════════╪══════════╪═══════════════╪════════════════╡
│ -3     ┆ 31       ┆ -0.0029       ┆ -0.00293       │
│ -2     ┆ 31       ┆ -0.00211      ┆ -0.00251       │
│ -1     ┆ 32       ┆ -0.00029      ┆ -0.0002        │
└────────┴──────────┴───────────────┴────────────────┘
[('EVENT_CLUSTERED_INFERENCE_AVAILABLE', 'PASS'), ('EVENT_WINDOWS_CENSORED', 'WARN')]

The two partial-path events in mixed add the windows’ EVENT_WINDOWS_CENSORED warning after the response’s own PASS. The same inheritance applies when inference is unavailable, as in the next example.

When there is too little to infer from

Inference needs min_clusters complete clusters, meaning distinct aligned anchor times, twenty by default. With fewer, event_response returns only the descriptive means, leaves every interval null, and records EVENT_INFERENCE_SUPPORT_INSUFFICIENT in the UNKNOWN state. That is what Lacuna reports for “is this average distinguishable from zero” when you have six anchor times.

few = lc.events.event_response(
    lc.events.event_windows(events.head(8), prices, before=3, after=5, price_adjustment="split_adjusted")
)
print(few.metrics)
print([(f.code, f.state.value) for f in few.findings])
print(few.table("event_response")[0]["pointwise_lower"])
{'n_events': 8, 'n_complete_events': 8, 'n_clusters': 6, 'successful_resamples': 0}
[('EVENT_INFERENCE_SUPPORT_INSUFFICIENT', 'UNKNOWN')]
None

Lowering min_clusters below the default is permitted, down to 2, but it does not create information. The result is as thin as the cluster count says.

Reproducibility

The bootstrap is seeded. Pass seed to get the same intervals on every run; it is recorded in metadata.seed and in the parameters. Without one, metadata.seed is None and Lacuna draws fresh entropy, recorded as root_entropy in the result’s parameters, so the run can be replayed. (When there are too few clusters to run the bootstrap, nothing is drawn and no root_entropy is recorded.) See Results for how seeds and provenance are stored.

How it is computed

Alignment. For each event, take the instrument’s observations sorted by time and numbered 0,1,…0, 1, \dots. The anchor is the first observation aa with a non-null price and time at or after the anchor time. The path is the observations numbered a−beforea - \text{before} through a+aftera + \text{after} that exist and have a price.

Clusters for inference. Events are grouped by the time of the observation that became offset 0, the aligned anchor time. Within event_response, only complete paths are used. Let the GG clusters be ordered by aligned anchor time, cluster gg contain mgm_g complete events, and Sg,jS_{g,j} be the sum of their responses at offset jj. The estimate is

rˉj=∑gSg,j∑gmg\bar r_j = \frac{\sum_g S_{g,j}}{\sum_g m_g}

Resampling. A stationary bootstrap draws GG clusters, in blocks of geometrically distributed length with mean expected_block_length, continuing circularly through the ordered clusters. A replicate’s mean at offset jj is the sum of the drawn clusters’ Sg,jS_{g,j} divided by the sum of their mgm_g. The default block length is max⁡(2,round⁡(G1/3))\max(2, \operatorname{round}(G^{1/3})).

Intervals. With BB replicates rˉb,j∗\bar r^{*}_{b,j}, the pointwise interval at offset jj is the α/2\alpha/2 and 1−α/21 - \alpha/2 percentiles of the replicates, with α=1−confidence\alpha = 1 - \text{confidence}. For the simultaneous band, let σ^j\hat\sigma_j be the standard deviation of the replicates at offset jj with B−1B - 1 in the denominator, and

c=quantileconfidence(max⁡j∣rˉb,j∗−rˉj∣σ^j),rˉj±c σ^jc = \text{quantile}_{\text{confidence}}\left( \max_j \frac{\lvert \bar r^{*}_{b,j} - \bar r_j \rvert}{\hat\sigma_j} \right), \qquad \bar r_j \pm c\,\hat\sigma_j

where the maximum is taken over the offsets with non-zero σ^j\hat\sigma_j, and the quantile over the replicates bb. The critical value cc is in the metrics as simultaneous_critical_value.

Parameters

ParameterMeaning
eventsThe events table.
pricesThe long-form price table.
event_idThe unique event identifier column.
instrumentThe instrument column, in both tables. Use a stable ID, not a reusable ticker.
event_timeWhen the event happened.
available_timeWhen it became known. Your assertion; Lacuna uses it as given.
price_timeThe time column of the price table.
priceThe price column. Must be positive and finite where present.
anchor"available_time" (default) or "event_time". The second adds a finding when any event was available later than it happened.
beforeObservations before the anchor to include. A non-negative integer.
afterObservations after the anchor to include. A non-negative integer.
alignmentOnly "next_observation" is implemented.
overlap_policy"raise" (default) or "keep" for same-instrument windows that overlap.
price_adjustmentYour declaration of what the prices include, recorded but not validated.
ParameterMeaning
windowsThe EventWindowResult from event_windows.
confidenceThe coverage of both interval types.
resamplesBootstrap replicates, at least 100.
expected_block_lengthThe mean block length, at least 1. Defaults from the number of clusters.
seedA non-negative integer. Without it the root entropy is drawn fresh and recorded.
min_clustersThe fewest complete clusters, meaning distinct aligned anchor times, that inference needs. At least 2.

The full signatures are in the API reference. The signal-side counterpart of this page is Signal diagnostics.