| Title: | Event Study Analysis |
|---|---|
| Description: | Financial event study analysis. Implements the classical event study methodology of MacKinlay (1997) <https://www.jstor.org/stable/2729691> with multiple return models: market model, market adjusted, comparison period mean adjusted, Fama and French three-factor (1993) <doi:10.1016/0304-405X(93)90023-5> and five-factor (2015) <doi:10.1016/j.jfineco.2014.10.010>, Carhart (1997) four-factor <doi:10.1111/j.1540-6261.1997.tb03808.x>, generalized autoregressive conditional heteroskedasticity (GARCH; Bollerslev, 1986) <doi:10.1016/0304-4076(86)90063-1>, rolling window, and dynamic conditional correlation GARCH (DCC-GARCH; Engle, 2002) <doi:10.1198/073500102288618487>. Provides parametric and non-parametric test statistics, including the standardized cross-sectional test of Boehmer, Musumeci and Poulsen (1991) <doi:10.1016/0304-405X(91)90032-F> and its cross-correlation adjustment by Kolari and Pynnonen (2010) <doi:10.1093/rfs/hhq072>; buy-and-hold abnormal returns (Barber and Lyon, 1997) <doi:10.1016/S0304-405X(96)00890-2>; volume and volatility event studies; cross-sectional regression; intraday event studies; panel difference-in-differences event studies with the estimators of Callaway and Sant'Anna (2021) <doi:10.1016/j.jeconom.2020.12.001>, de Chaisemartin and D'Haultfoeuille (2020) <doi:10.1257/aer.20181169>, and Borusyak, Jaravel and Spiess (2024) <doi:10.1093/restud/rdae007>; synthetic control methods (Abadie, Diamond and Hainmueller, 2010) <doi:10.1198/jasa.2009.ap08746>; wild bootstrap inference; multiple testing corrections; power analysis via simulation; data download helpers; automated reporting; and visualization tools. Results can be exported to comma-separated values (CSV), 'Excel', or 'LaTeX'. |
| Authors: | Simon Mueller [cre, aut] |
| Maintainer: | Simon Mueller <[email protected]> |
| License: | AGPL-3 |
| Version: | 0.66.0 |
| Built: | 2026-10-21 12:12:50 UTC |
| Source: | https://github.com/cran/EventStudy |
Computes adjusted p-values for AAR and CAAR test statistics across the
event window, correcting for the multiple comparisons problem. Supports
all methods available in p.adjust.
adjust_p_values(task, method = "BH", stat_name = "CSectT", group = NULL)adjust_p_values(task, method = "BH", stat_name = "CSectT", group = NULL)
task |
A fitted EventStudyTask with |
method |
Adjustment method passed to |
stat_name |
Name of the multi-event test statistic to adjust.
Must match a column name in |
group |
Optional group name to filter. If NULL, adjusts all groups. |
A tibble with columns from the original test statistic result plus
p_raw_aar, p_adj_aar, p_raw_caar, p_adj_caar.
Other eventstudy-statistics:
ARTTest,
BHARTTest,
BMPTest,
CARTTest,
CSectTTest,
CalendarTimePortfolioTest,
GeneralizedSignTest,
KolariPynnonenTest,
MultiEventStatisticsSet,
PatellZTest,
RankTest,
SignTest,
SingleEventStatisticsSet,
StatisticsSetBase,
TestStatisticBase,
bootstrap_test(),
car_by_group(),
car_quantiles(),
cross_sectional_regression(),
model_diagnostics(),
pretrend_test(),
simulate_event_study(),
validate_task()
A provider that issues POST {base_url}/v1/messages against
the native Anthropic Messages API. The request carries the mandatory
max_tokens field and the anthropic-version header; when a
schema is supplied it adds a tool-use input_schema block
(tools + tool_choice) to obtain structured output, and the
response extractor prefers that tool call's structured input while
falling back to the first text block – so the provider never crashes when the
model replies with plain text instead of a tool call.
The API key is resolved at CALL time from ANTHROPIC_API_KEY (never at
construction, never stored on the object) and attached with
req_headers_redacted("x-api-key" = key), which redacts the key in
every print/error path. Note req_auth_bearer_token does NOT redact an
x-api-key header – the redacted-headers helper is mandatory here. A
missing key, transport/timeout failure, non-2xx status, malformed body, or
missing completion text each degrades to exactly one warning() plus an
'es_provider_response' with text = NA_character_ – it never crashes the
session and never returns a fabricated completion.
httr2 is required only for this provider and is guarded by
requireNamespace() at the top of complete(), so the package
installs and R CMD checks cleanly with httr2 absent.
ProviderBase -> AnthropicProvider
max_tokensInteger max completion tokens (Anthropic REQUIRES this).
AnthropicProvider$new()Construct an AnthropicProvider. Stores non-secret config only;
the API key is resolved at call time inside complete().
AnthropicProvider$new( model, base_url = "https://api.anthropic.com", max_tokens = 1024L, ... )
modelCharacter model identifier, e.g. "claude-opus-4-8".
base_urlCharacter base URL. Defaults to the Anthropic cloud endpoint.
max_tokensInteger maximum number of tokens to generate. The Anthropic Messages API REQUIRES this field; defaults to 1024.
...Ignored; accepted for forward-compatibility.
AnthropicProvider$complete()Complete a prompt via POST {base_url}/v1/messages.
Resolves the key at call time; on a missing key or any HTTP/parse failure
returns one warning + NA. Structured output is OPTIONAL: when
schema is supplied a tool-use input_schema block is added and
the extractor prefers the tool call's input, falling back to the
first text block.
AnthropicProvider$complete(prompt, schema = NULL, ...)
promptCharacter prompt.
schemaOptional structured-output schema (list) or NULL.
...Ignored; accepted for forward-compatibility.
An 'es_provider_response' (see ProviderBase$complete).
AnthropicProvider$clone()The objects of this class are cloneable with this method.
AnthropicProvider$clone(deep = FALSE)
deepWhether to make a deep clone.
Other eventstudy-advisor:
CustomProvider,
OpenAICompatProvider,
ProviderBase,
es_advise(),
es_diagnostics(),
es_kb(),
flag_robustness(),
provider(),
recommend_stat()
## Not run: # Reads ANTHROPIC_API_KEY from the environment at call time: p <- AnthropicProvider$new(model = "claude-opus-4-8") p$complete("Summarise these event-study diagnostics") # Structured output via a tool-use input_schema: schema <- list(type = "object", properties = list(advice = list(type = "string"))) p$complete("Recommend a test statistic", schema = schema) ## End(Not run)## Not run: # Reads ANTHROPIC_API_KEY from the environment at call time: p <- AnthropicProvider$new(model = "claude-opus-4-8") p$complete("Summarise these event-study diagnostics") # Structured output via a tool-use input_schema: schema <- list(type = "object", properties = list(advice = list(type = "string"))) p$complete("Recommend a test statistic", schema = schema) ## End(Not run)
The AR t-test is a statistical method used to determine whether the abnormal return of a security on a specific day is significantly different from zero. This test helps researchers identify whether the event of interest has a significant impact on the security's return at a particular point in time.
See also https://eventstudy.de/statistics/ar_car_statistics.html
TestStatisticBase -> ARTTest
nameShort code of the test statistic.
ARTTest$compute()Computes the test AR test statistics for a single event.
ARTTest$compute(data_tbl, model)
data_tblThe data for a single event with calculated abnormal returns.
modelThe fitted model that includes the necessary information for calculating the test statistic.
ARTTest$clone()The objects of this class are cloneable with this method.
ARTTest$clone(deep = FALSE)
deepWhether to make a deep clone.
Other eventstudy-statistics:
BHARTTest,
BMPTest,
CARTTest,
CSectTTest,
CalendarTimePortfolioTest,
GeneralizedSignTest,
KolariPynnonenTest,
MultiEventStatisticsSet,
PatellZTest,
RankTest,
SignTest,
SingleEventStatisticsSet,
StatisticsSetBase,
TestStatisticBase,
adjust_p_values(),
bootstrap_test(),
car_by_group(),
car_quantiles(),
cross_sectional_regression(),
model_diagnostics(),
pretrend_test(),
simulate_event_study(),
validate_task()
Implements Buy-and-Hold Abnormal Returns for long-horizon event studies. BHAR compounds returns over the event window instead of summing:
The benchmark is the market/index return by default. This model is appropriate for long-horizon studies (months/years) where compounding effects matter.
ModelBase -> BHARModel
model_nameName of the model.
BHARModel$fit()Fit the BHAR model. Computes estimation window statistics.
BHARModel$fit(data_tbl)
data_tblData frame or tibble.
BHARModel$abnormal_returns()Calculate abnormal returns using buy-and-hold compounding.
BHARModel$abnormal_returns(data_tbl)
data_tblData frame or tibble.
BHARModel$clone()The objects of this class are cloneable with this method.
BHARModel$clone(deep = FALSE)
deepWhether to make a deep clone.
Other eventstudy-models:
Carhart4FactorModel,
ComparisonPeriodMeanAdjustedModel,
DCCGARCHModel,
FamaFrench3FactorModel,
FamaFrench5FactorModel,
GARCHModel,
LinearFactorModel,
LogReturn,
MarketAdjustedModel,
MarketModel,
ModelBase,
ReturnCalculation,
RollingWindowModel,
SimpleReturn,
VolatilityModel,
VolumeModel
Tests whether the BHAR for a single event is significantly different from zero. The BHAR is the difference between compounded firm returns and compounded benchmark returns over the event window.
TestStatisticBase -> BHARTTest
nameShort code of the test statistic.
BHARTTest$compute()Computes the BHAR t test for a single event.
BHARTTest$compute(data_tbl, model)
data_tblThe data for a single event with calculated abnormal returns.
modelThe fitted model.
BHARTTest$clone()The objects of this class are cloneable with this method.
BHARTTest$clone(deep = FALSE)
deepWhether to make a deep clone.
Other eventstudy-statistics:
ARTTest,
BMPTest,
CARTTest,
CSectTTest,
CalendarTimePortfolioTest,
GeneralizedSignTest,
KolariPynnonenTest,
MultiEventStatisticsSet,
PatellZTest,
RankTest,
SignTest,
SingleEventStatisticsSet,
StatisticsSetBase,
TestStatisticBase,
adjust_p_values(),
bootstrap_test(),
car_by_group(),
car_quantiles(),
cross_sectional_regression(),
model_diagnostics(),
pretrend_test(),
simulate_event_study(),
validate_task()
Standardized cross-sectional test that is robust to event-induced variance
increases. The BMP test standardizes abnormal returns by each event's
MODEL sigma (the estimation-window residual standard deviation, i.e.
model$statistics$sigma) – NOT by the forecast-error-corrected
sigma – then applies a cross-sectional t-test to these standardized
residuals.
TestStatisticBase -> BMPTest
nameShort code of the test statistic.
BMPTest$compute()Computes the BMP standardized cross-sectional test.
BMPTest$compute(data_tbl, model)
data_tblThe data for a multiple event with calculated abnormal returns.
modelThe fitted model containing sigma estimates.
BMPTest$clone()The objects of this class are cloneable with this method.
BMPTest$clone(deep = FALSE)
deepWhether to make a deep clone.
Other eventstudy-statistics:
ARTTest,
BHARTTest,
CARTTest,
CSectTTest,
CalendarTimePortfolioTest,
GeneralizedSignTest,
KolariPynnonenTest,
MultiEventStatisticsSet,
PatellZTest,
RankTest,
SignTest,
SingleEventStatisticsSet,
StatisticsSetBase,
TestStatisticBase,
adjust_p_values(),
bootstrap_test(),
car_by_group(),
car_quantiles(),
cross_sectional_regression(),
model_diagnostics(),
pretrend_test(),
simulate_event_study(),
validate_task()
Computes bootstrap p-values for AAR and CAAR test statistics using the wild bootstrap approach. Per-firm random weights preserve the cross-sectional dependence structure while randomizing the sign of abnormal returns under the null hypothesis.
bootstrap_test( task, n_boot = 999L, weight_type = "rademacher", statistic = "both", group = NULL, seed = NULL )bootstrap_test( task, n_boot = 999L, weight_type = "rademacher", statistic = "both", group = NULL, seed = NULL )
task |
A fitted EventStudyTask with abnormal returns computed. |
n_boot |
Number of bootstrap replications. Default 999. |
weight_type |
Type of bootstrap weights: |
statistic |
Which statistic to bootstrap: |
group |
Optional group name to filter. |
seed |
Optional seed for reproducibility. |
A tibble with columns: relative_index, observed_aar,
observed_caar, boot_p_aar, boot_p_caar.
Other eventstudy-statistics:
ARTTest,
BHARTTest,
BMPTest,
CARTTest,
CSectTTest,
CalendarTimePortfolioTest,
GeneralizedSignTest,
KolariPynnonenTest,
MultiEventStatisticsSet,
PatellZTest,
RankTest,
SignTest,
SingleEventStatisticsSet,
StatisticsSetBase,
TestStatisticBase,
adjust_p_values(),
car_by_group(),
car_quantiles(),
cross_sectional_regression(),
model_diagnostics(),
pretrend_test(),
simulate_event_study(),
validate_task()
Calculate test statistics
calculate_statistics(task, parameter_set)calculate_statistics(task, parameter_set)
task |
The event study task |
parameter_set |
The parameter set that defines the event study. |
task
run_event_study, prepare_event_study,
fit_model
Other eventstudy-pipeline:
EventStudyTask,
ParameterSet,
fit_model(),
prepare_event_study(),
run_event_study()
Aggregates event-firm returns into calendar-time portfolios and tests whether the portfolio intercept (alpha) is significantly different from zero, using the Brown and Warner (1980, 1985) crude-dependence-adjustment: the standard deviation of the ESTIMATION-window cross-event average abnormal return (AAR) series is used as the (calendar-)time-series standard deviation, so the denominator is independent of the event window and of any event-window shock magnitude.
For each relative event day, the test forms an equal-weighted portfolio
of all event firms' abnormal returns and computes
, with degrees of freedom
n_estimation_days - 1 (the number of finite estimation-window AAR
observations), exposed as attr(result, "caltime_df").
TestStatisticBase -> CalendarTimePortfolioTest
nameShort code of the test statistic.
CalendarTimePortfolioTest$compute()Computes the calendar-time portfolio test.
CalendarTimePortfolioTest$compute(data_tbl, model)
data_tblThe data for multiple events with calculated abnormal returns.
modelThe fitted models (unused directly).
CalendarTimePortfolioTest$clone()The objects of this class are cloneable with this method.
CalendarTimePortfolioTest$clone(deep = FALSE)
deepWhether to make a deep clone.
Brown, S. J. and Warner, J. B. (1980). Measuring security price performance. Journal of Financial Economics, 8(3), 205–258.
Brown, S. J. and Warner, J. B. (1985). Using daily stock returns: The case of event studies. Journal of Financial Economics, 14(1), 3–31.
Other eventstudy-statistics:
ARTTest,
BHARTTest,
BMPTest,
CARTTest,
CSectTTest,
GeneralizedSignTest,
KolariPynnonenTest,
MultiEventStatisticsSet,
PatellZTest,
RankTest,
SignTest,
SingleEventStatisticsSet,
StatisticsSetBase,
TestStatisticBase,
adjust_p_values(),
bootstrap_test(),
car_by_group(),
car_quantiles(),
cross_sectional_regression(),
model_diagnostics(),
pretrend_test(),
simulate_event_study(),
validate_task()
Performs a t-test (two groups) or ANOVA (3+ groups) to test whether CARs differ significantly across groups.
car_by_group(task, group_var = "group", car_window = NULL)car_by_group(task, group_var = "group", car_window = NULL)
task |
A fitted EventStudyTask. |
group_var |
Name of the grouping variable. Defaults to "group" (the standard group column in EventStudyTask). |
car_window |
Optional two-element vector for CAR window. |
A list with test results and group-level summary statistics.
Other eventstudy-statistics:
ARTTest,
BHARTTest,
BMPTest,
CARTTest,
CSectTTest,
CalendarTimePortfolioTest,
GeneralizedSignTest,
KolariPynnonenTest,
MultiEventStatisticsSet,
PatellZTest,
RankTest,
SignTest,
SingleEventStatisticsSet,
StatisticsSetBase,
TestStatisticBase,
adjust_p_values(),
bootstrap_test(),
car_quantiles(),
cross_sectional_regression(),
model_diagnostics(),
pretrend_test(),
simulate_event_study(),
validate_task()
Compute quantiles of the CAR distribution across events.
car_quantiles(task, probs = c(0.05, 0.25, 0.5, 0.75, 0.95), car_window = NULL)car_quantiles(task, probs = c(0.05, 0.25, 0.5, 0.75, 0.95), car_window = NULL)
task |
A fitted EventStudyTask. |
probs |
Probability vector for quantiles. Default
|
car_window |
Optional two-element vector for CAR window. |
A named numeric vector of quantiles.
Other eventstudy-statistics:
ARTTest,
BHARTTest,
BMPTest,
CARTTest,
CSectTTest,
CalendarTimePortfolioTest,
GeneralizedSignTest,
KolariPynnonenTest,
MultiEventStatisticsSet,
PatellZTest,
RankTest,
SignTest,
SingleEventStatisticsSet,
StatisticsSetBase,
TestStatisticBase,
adjust_p_values(),
bootstrap_test(),
car_by_group(),
cross_sectional_regression(),
model_diagnostics(),
pretrend_test(),
simulate_event_study(),
validate_task()
Implements the Carhart (1997) four-factor model, which extends the Fama-French three-factor model with a momentum factor:
Requires columns: excess_return, market_excess, smb,
hml, mom.
ModelBase -> LinearFactorModel -> Carhart4FactorModel
model_nameName of the model.
formulaThe four-factor regression formula.
required_columnsRequired data columns.
Carhart4FactorModel$new()Create a new Carhart4FactorModel.
Carhart4FactorModel$new(use_hac = FALSE, hac_lag = NULL)
use_hacLogical. Use HAC (Newey-West) standard errors.
hac_lagInteger or NULL. Lag truncation for Newey-West.
Carhart4FactorModel$abnormal_returns()Calculate abnormal returns using the four-factor model.
Carhart4FactorModel$abnormal_returns(data_tbl)
data_tblData frame or tibble.
Carhart4FactorModel$clone()The objects of this class are cloneable with this method.
Carhart4FactorModel$clone(deep = FALSE)
deepWhether to make a deep clone.
Other eventstudy-models:
BHARModel,
ComparisonPeriodMeanAdjustedModel,
DCCGARCHModel,
FamaFrench3FactorModel,
FamaFrench5FactorModel,
GARCHModel,
LinearFactorModel,
LogReturn,
MarketAdjustedModel,
MarketModel,
ModelBase,
ReturnCalculation,
RollingWindowModel,
SimpleReturn,
VolatilityModel,
VolumeModel
The CAR t-test is a statistical method used to determine whether the cumulative abnormal return of a security over an event window is significantly different from zero. This test helps researchers identify whether the event of interest has a significant impact on the security's return over the entire event window, considering the cumulative effects of the event.
See also https://eventstudy.de/statistics/ar_car_statistics.html
TestStatisticBase -> CARTTest
nameShort code of the test statistic.
CARTTest$compute()Computes the test CAR test statistics for a single event.
CARTTest$compute(data_tbl, model)
data_tblThe data for a single event with calculated abnormal returns.
modelThe fitted model that includes the necessary information for calculating the test statistic.
CARTTest$clone()The objects of this class are cloneable with this method.
CARTTest$clone(deep = FALSE)
deepWhether to make a deep clone.
Other eventstudy-statistics:
ARTTest,
BHARTTest,
BMPTest,
CSectTTest,
CalendarTimePortfolioTest,
GeneralizedSignTest,
KolariPynnonenTest,
MultiEventStatisticsSet,
PatellZTest,
RankTest,
SignTest,
SingleEventStatisticsSet,
StatisticsSetBase,
TestStatisticBase,
adjust_p_values(),
bootstrap_test(),
car_by_group(),
car_quantiles(),
cross_sectional_regression(),
model_diagnostics(),
pretrend_test(),
simulate_event_study(),
validate_task()
The Comparison Period Mean Adjusted Model is another relatively simple approach used in event studies to estimate the expected returns of a stock and calculate its abnormal returns during an event window. This model is based on the assumption that a stock's expected return during the event window is equal to its average return during a comparison period (typically a pre-event period). This model is particularly useful when researchers want to control for a stock's historical performance and do not wish to rely on market return data.
ModelBase -> ComparisonPeriodMeanAdjustedModel
model_nameName of the model.
ComparisonPeriodMeanAdjustedModel$fit()Fit the model with given data.
ComparisonPeriodMeanAdjustedModel$fit(data_tbl)
data_tblData frame or tibble containing the data to fit.
ComparisonPeriodMeanAdjustedModel$abnormal_returns()Calculate the abnormal returns with given data.
ComparisonPeriodMeanAdjustedModel$abnormal_returns(data_tbl)
data_tblData frame or tibble containing the data to calculate abnormal returns.
ComparisonPeriodMeanAdjustedModel$clone()The objects of this class are cloneable with this method.
ComparisonPeriodMeanAdjustedModel$clone(deep = FALSE)
deepWhether to make a deep clone.
Other eventstudy-models:
BHARModel,
Carhart4FactorModel,
DCCGARCHModel,
FamaFrench3FactorModel,
FamaFrench5FactorModel,
GARCHModel,
LinearFactorModel,
LogReturn,
MarketAdjustedModel,
MarketModel,
ModelBase,
ReturnCalculation,
RollingWindowModel,
SimpleReturn,
VolatilityModel,
VolumeModel
Regress cumulative abnormal returns (CARs) on firm characteristics to explain cross-sectional variation in event effects. Supports OLS with heteroskedasticity-consistent (HC) standard errors.
cross_sectional_regression( task, formula, data, car_window = NULL, robust = TRUE )cross_sectional_regression( task, formula, data, car_window = NULL, robust = TRUE )
task |
A fitted EventStudyTask with abnormal returns computed. |
formula |
A formula with the response on the left (ignored; CAR is
always the dependent variable) and explanatory variables on the right,
e.g., |
data |
A data frame of firm characteristics. Must contain an
|
car_window |
Two-element integer vector specifying the CAR window
as |
robust |
Logical. If TRUE and the sandwich package is available, compute HC1 robust standard errors. Default TRUE. |
A list with class "es_cross_sectional" containing:
The fitted lm object
Coefficient table with (robust) standard errors
R-squared of the regression
Number of observations
The merged CAR + characteristics data
Other eventstudy-statistics:
ARTTest,
BHARTTest,
BMPTest,
CARTTest,
CSectTTest,
CalendarTimePortfolioTest,
GeneralizedSignTest,
KolariPynnonenTest,
MultiEventStatisticsSet,
PatellZTest,
RankTest,
SignTest,
SingleEventStatisticsSet,
StatisticsSetBase,
TestStatisticBase,
adjust_p_values(),
bootstrap_test(),
car_by_group(),
car_quantiles(),
model_diagnostics(),
pretrend_test(),
simulate_event_study(),
validate_task()
The Cross-Sectional Test (CSect T) is a statistical tool employed in event
studies to evaluate the null hypothesis that the average abnormal return at
the event date is zero. The test statistic is distributed as , where
N is the number of events in that group.
See also https://eventstudy.de/statistics/aar_caar_statistics.html
TestStatisticBase -> CSectTTest
nameShort code of the test statistic.
CSectTTest$compute()Computes the AAR/CAAR cross-sectional t test statistics.
CSectTTest$compute(data_tbl, model)
data_tblThe data for a multiple event with calculated abnormal returns.
modelThe fitted model: not necessary for this test statistics.
CSectTTest$clone()The objects of this class are cloneable with this method.
CSectTTest$clone(deep = FALSE)
deepWhether to make a deep clone.
Other eventstudy-statistics:
ARTTest,
BHARTTest,
BMPTest,
CARTTest,
CalendarTimePortfolioTest,
GeneralizedSignTest,
KolariPynnonenTest,
MultiEventStatisticsSet,
PatellZTest,
RankTest,
SignTest,
SingleEventStatisticsSet,
StatisticsSetBase,
TestStatisticBase,
adjust_p_values(),
bootstrap_test(),
car_by_group(),
car_quantiles(),
cross_sectional_regression(),
model_diagnostics(),
pretrend_test(),
simulate_event_study(),
validate_task()
A provider that wraps a user-supplied
function(prompt, schema, ...) -> list | character. This is the
offline end-to-end seam and the escape hatch for backends the built-in HTTP
providers do not cover. It uses NO network and needs neither httr2
nor jsonlite.
The user function is run inside tryCatch: if it errors, the provider
degrades to exactly one warning() plus an 'es_provider_response' with
text = NA_character_ – it never crashes the session.
ProviderBase -> CustomProvider
CustomProvider$new()Construct a CustomProvider.
CustomProvider$new(fn, model = NULL, ...)
fnA function of (prompt, schema, ...) returning a list or a
character completion. Required.
modelOptional character model identifier (informational only).
...Ignored; forwarded for forward-compatibility.
CustomProvider$complete()Run the wrapped user function and wrap its result in an 'es_provider_response'. A throwing function degrades to one warning + NA.
CustomProvider$complete(prompt, schema = NULL, ...)
promptCharacter prompt passed to the user function.
schemaOptional structured-output schema passed through to the user function.
...Additional arguments forwarded to the user function.
An 'es_provider_response' (see ProviderBase$complete).
CustomProvider$clone()The objects of this class are cloneable with this method.
CustomProvider$clone(deep = FALSE)
deepWhether to make a deep clone.
Other eventstudy-advisor:
AnthropicProvider,
OpenAICompatProvider,
ProviderBase,
es_advise(),
es_diagnostics(),
es_kb(),
flag_robustness(),
provider(),
recommend_stat()
# In-process, no network: the user function supplies the completion text. p <- CustomProvider$new(function(prompt, schema) "canned advice") res <- p$complete("Summarise these diagnostics") res$text res$source# In-process, no network: the user function supplies the completion text. p <- CustomProvider$new(function(prompt, schema) "canned advice") res <- p$complete("Summarise these diagnostics") res$text res$source
Event study model using Dynamic Conditional Correlation GARCH for
time-varying beta estimation. Requires the rmgarch package.
The bivariate DCC-GARCH model captures both time-varying volatility
and time-varying correlation between firm and market returns, yielding
a time-varying beta: .
ModelBase -> DCCGARCHModel
model_nameName of the model.
garch_orderGARCH order for each univariate model. Default c(1,1).
dcc_orderDCC order. Default c(1,1).
DCCGARCHModel$new()Create a new DCCGARCHModel.
DCCGARCHModel$new(garch_order = c(1, 1), dcc_order = c(1, 1))
garch_orderGARCH(p,q) order for univariate models.
dcc_orderDCC(a,b) order.
DCCGARCHModel$fit()Fit the DCC-GARCH model on the estimation window.
DCCGARCHModel$fit(data_tbl)
data_tblData frame or tibble with firm_returns, index_returns, estimation_window, event_window columns.
DCCGARCHModel$abnormal_returns()Calculate abnormal returns using the last conditional beta.
DCCGARCHModel$abnormal_returns(data_tbl)
data_tblData frame or tibble.
DCCGARCHModel$clone()The objects of this class are cloneable with this method.
DCCGARCHModel$clone(deep = FALSE)
deepWhether to make a deep clone.
Other eventstudy-models:
BHARModel,
Carhart4FactorModel,
ComparisonPeriodMeanAdjustedModel,
FamaFrench3FactorModel,
FamaFrench5FactorModel,
GARCHModel,
LinearFactorModel,
LogReturn,
MarketAdjustedModel,
MarketModel,
ModelBase,
ReturnCalculation,
RollingWindowModel,
SimpleReturn,
VolatilityModel,
VolumeModel
The degenerate-input contract defines how all EventStudy return models behave when the estimation data is degenerate. Two modes are supported:
Lenient (default): The model sets is_fitted = FALSE,
emits exactly one warning() per (event_id, firm_symbol)
per fit call, and propagates NA through all abnormal returns
and downstream statistics. No event is silently dropped; zeros are
never substituted for NA.
Strict: The model raises a descriptive stop() error
naming the component, event_id, and firm_symbol, plus
the specific reason for the degeneracy.
Configuration:
Via ParameterSet: ParameterSet$new(degenerate_handling = "strict")
Via package option: options(EventStudy.degenerate_handling = "strict")
The ParameterSet field takes precedence over the package option; if
neither is set, the default "lenient" mode is used.
Degenerate conditions covered:
Fewer than 2 finite observations in the estimation window (insufficient observations for OLS).
Zero or near-zero variance in index returns
(sd < .Machine$double.eps), making OLS estimation undefined.
Single-event group (relevant for multi-event statistics; applied in Phase 2).
NA propagation from upstream pipeline steps.
NA propagation semantics:
When is_fitted = FALSE, model$abnormal_returns() returns
a tibble with abnormal_returns = NA_real_ for all rows. All
downstream test statistics that depend on fitted models then receive
NA inputs and propagate NA to their outputs. The event
is retained in the output tibble – it is never silently dropped.
Multi-event exclusion (2026-09-24 re-evaluation, item A2):
A single-event's NA propagation above is not enough for
cumulative (CAR-based) multi-event statistics (CSectT, PatellZ, Sign,
GeneralizedSign, BMP, KolariPynnonen): an event with ZERO finite
event-window abnormal returns must be EXCLUDED from every such
statistic's group, not merely NA-propagated, because a cumulative sum
that coalesce()s a fully-degenerate event's abnormal returns to
0 would silently understate the true cross-sectional dispersion. The
exclusion is applied once per group (see .exclude_all_na_events)
before any statistic is computed, and reported exactly once: silently
if the excluded event's model already emitted the one contract warning
guaranteed by CONTRACT-04 (an unfitted ModelBase instance), or
via a single additional warning naming the excluded event_id(s)
otherwise. Strict mode errors instead. This exclusion rule leaves the
pre-existing STATS-03 convention for a PARTIAL gap unchanged: an event
with at least one finite event-window abnormal return, but a missing
value on some individual day, still contributes 0 to that event's CAR
on the missing day(s) via coalesce(abnormal_returns, 0).
Degenerate-Input Contract for EventStudy Models
A small, frozen dataset bundling daily prices for four German automakers and
the DAX benchmark index around the 2015 "dieselgate" emissions scandal, ready
to drive a complete multi-group event study (prepare_event_study() ->
fit_model() -> calculate_statistics()).
data(dieselgate)data(dieselgate)
A named list with four elements:
A tibble of daily prices for all four automakers combined,
with columns symbol (one of "VOW.DE", "PAH3.DE",
"BMW.DE", "MBG.DE"), date (character,
"%d.%m.%Y" format), and adjusted (numeric adjusted
close). Rows for all firms are stacked (1 440 rows total).
A tibble of DAX ("^GDAXI") daily prices with the same
symbol / date / adjusted columns, used as the
benchmark / reference market for all four events.
A four-row tibble giving the event-study request
specifications, one row per firm, with the nine columns expected by
EventStudyTask: event_id (1L to 4L),
firm_symbol, index_symbol, event_date
("18.09.2015"), group ("VW Group" for
VOW.DE/PAH3.DE, "Other" for BMW.DE/MBG.DE),
event_window_start (-10), event_window_end (10),
shift_estimation_window (-11), and
estimation_window_length (250). event_id = 1 is
VOW.DE for backward compatibility.
A list of provenance metadata: firm_tickers (character
vector of all four tickers), groups (named list mapping group
labels to tickers), index_ticker, event_date, from,
to, source, access_date, and note.
The event is the U.S. Environmental Protection Agency's Notice of Violation
issued to Volkswagen on 2015-09-18 (a Friday); the share-price crash
lands on the following trading days. The dataset covers two groups: the
"VW Group" (VOW.DE, PAH3.DE – directly implicated firms) and "Other"
(BMW.DE, MBG.DE – peer automakers). The bundled window layout uses a
250-trading-day estimation window ending 11 days before the event and an
event window of [-10, +10] trading days.
Fitting a market model on the "VW Group" events produces a strongly negative cumulative average abnormal return (CAAR approximately -39 roughly -17% and -13% average abnormal returns on the first two trading days after the disclosure, while the "Other" peer automakers show near-zero CAAR (approximately +1%), illustrating the idiosyncratic nature of the shock.
Firms:
VOW.DE – Volkswagen AG ordinary shares (Xetra), event_id = 1
PAH3.DE – Porsche Automobil Holding SE (Xetra), event_id = 2
BMW.DE – BMW AG (Xetra), event_id = 3
MBG.DE – Mercedes-Benz Group AG (Xetra), event_id = 4
Groups: "VW Group" (VOW.DE, PAH3.DE) vs "Other" (BMW.DE, MBG.DE).
Benchmark: DAX performance index (ticker ^GDAXI).
Date range: 2014-06-01 to 2015-11-01.
Yahoo Finance daily adjusted prices, retrieved 2026-09-04 via the
package's own download_stock_data. This is a small
illustrative sample bundled for academic / demonstration use only; see
data-raw/dieselgate.R for the reproducible fetch script.
data(dieselgate) # Build a multi-group task and run the full pipeline task <- EventStudyTask$new(dieselgate$firm, dieselgate$index, dieselgate$request) task <- run_event_study(task, ParameterSet$new()) # Single-firm: VW crash (event_id = 1) task$get_car(1L) # Multi-group: CAAR comparison vw_caar <- task$aar_caar_tbl[task$aar_caar_tbl$group == "VW Group", ]$CSectT[[1]] other_caar <- task$aar_caar_tbl[task$aar_caar_tbl$group == "Other", ]$CSectT[[1]] tail(vw_caar[, c("relative_index", "caar", "caar_t")], 1) tail(other_caar[, c("relative_index", "caar", "caar_t")], 1)data(dieselgate) # Build a multi-group task and run the full pipeline task <- EventStudyTask$new(dieselgate$firm, dieselgate$index, dieselgate$request) task <- run_event_study(task, ParameterSet$new()) # Single-firm: VW crash (event_id = 1) task$get_car(1L) # Multi-group: CAAR comparison vw_caar <- task$aar_caar_tbl[task$aar_caar_tbl$group == "VW Group", ]$CSectT[[1]] other_caar <- task$aar_caar_tbl[task$aar_caar_tbl$group == "Other", ]$CSectT[[1]] tail(vw_caar[, c("relative_index", "caar", "caar_t")], 1) tail(other_caar[, c("relative_index", "caar", "caar_t")], 1)
Downloads Fama-French factor data from the Kenneth French Data Library. No external package dependencies required (uses base R download + CSV parsing).
download_factor_data( model = c("ff3", "ff5", "mom"), frequency = c("daily", "monthly"), format_for_task = TRUE )download_factor_data( model = c("ff3", "ff5", "mom"), frequency = c("daily", "monthly"), format_for_task = TRUE )
model |
Factor model: |
frequency |
Data frequency: |
format_for_task |
Logical. If TRUE, formats for EventStudyTask factor_tbl. |
A tibble with factor data.
Downloads risk-free rate data from the Kenneth French Data Library (extracted from the Fama-French factor files).
download_risk_free_rate( frequency = c("daily", "monthly"), source = "french", format_for_task = TRUE )download_risk_free_rate( frequency = c("daily", "monthly"), source = "french", format_for_task = TRUE )
frequency |
Data frequency: |
source |
Data source: |
format_for_task |
Logical. If TRUE, formats for EventStudyTask. |
A tibble with date and risk_free_rate columns.
Downloads historical stock price data for specified symbols. Uses tidyquant if available, otherwise falls back to quantmod.
download_stock_data( symbols, from, to = Sys.Date(), source = "yahoo", format_for_task = TRUE )download_stock_data( symbols, from, to = Sys.Date(), source = "yahoo", format_for_task = TRUE )
symbols |
Character vector of stock ticker symbols. |
from |
Start date (Date or character in YYYY-MM-DD format). |
to |
End date. Default |
source |
Data source: |
format_for_task |
Logical. If TRUE, formats output for
|
A tibble with stock data.
A small, frozen dataset bundling daily prices for three U.S. large-cap firms
and the S&P 500 benchmark around the first-calendar-quarter 2023 (Jan-Mar)
earnings announcements, reported late April / early May 2023,
ready to drive a complete event study pipeline (prepare_event_study()
-> fit_model() -> calculate_statistics()).
data(earnings_surprises)data(earnings_surprises)
A named list with four elements:
A tibble of daily prices for all three firms combined,
with columns symbol (one of "AAPL", "MSFT",
"GOOGL"), date (character,
"%d.%m.%Y" format), and adjusted (numeric adjusted
close). Rows for all firms are stacked (813 rows total).
A tibble of S&P 500 ("^GSPC") daily prices with the
same symbol / date / adjusted columns, used as the
benchmark for all three events.
A three-row tibble giving the event-study request
specifications, one row per firm, with the nine columns expected by
EventStudyTask: event_id (1L to 3L),
firm_symbol, index_symbol, event_date
("04.05.2023" for AAPL, "25.04.2023" for MSFT and GOOGL),
group ("Earnings Beat" for all firms),
event_window_start (-5), event_window_end (5),
shift_estimation_window (-6), and
estimation_window_length (200).
A list of provenance metadata: firm_tickers,
index_ticker, event_dates, from, to,
source, access_date, and note.
All three firms beat consensus EPS estimates for their respective
January-to-March 2023 quarters: Apple Inc. reported on 2023-05-04
(its fiscal Q2 FY2023, which runs Jan-Mar) and beat by approximately 8%,
driving a strong next-day return; Microsoft Corporation reported on
2023-04-25 (its fiscal Q3 FY2023, which runs Jan-Mar), beating
cloud (Azure) estimates with a roughly +7% next-day response; Alphabet Inc.
reported on 2023-04-25 (Q1 CY2023, Jan-Mar), with advertising
revenue exceeding expectations. The bundled window layout uses a 200-trading-day
estimation window ending 6 days before each event and an event window of
[-5, +5] trading days. Running a market model on this single-group
panel produces a positive cumulative average abnormal return (CAAR) over the
event window, reflecting the shared earnings-beat signal across all three firms.
Firms:
AAPL – Apple Inc. (NASDAQ), event_id = 1
MSFT – Microsoft Corporation (NASDAQ), event_id = 2
GOOGL – Alphabet Inc. Class A (NASDAQ), event_id = 3
Group: "Earnings Beat" (all firms).
Benchmark: S&P 500 index (ticker ^GSPC).
Date range: 2022-06-01 to 2023-06-30.
Yahoo Finance daily adjusted prices, retrieved 2026-09-05 via the
package's own download_stock_data. This is a small
illustrative sample bundled for academic / demonstration use only; see
data-raw/earnings_surprises.R for the reproducible fetch script.
data(earnings_surprises) # Build task and run the full pipeline task <- EventStudyTask$new(earnings_surprises$firm, earnings_surprises$index, earnings_surprises$request) task <- run_event_study(task, ParameterSet$new()) # Multi-event: AAR/CAAR across all firms caar_tbl <- task$aar_caar_tbl$CSectT[[1]] tail(caar_tbl[, c("relative_index", "caar", "caar_t")], 1)data(earnings_surprises) # Build task and run the full pipeline task <- EventStudyTask$new(earnings_surprises$firm, earnings_surprises$index, earnings_surprises$request) task <- run_event_study(task, ParameterSet$new()) # Multi-event: AAR/CAAR across all firms caar_tbl <- task$aar_caar_tbl$CSectT[[1]] tail(caar_tbl[, c("relative_index", "caar", "caar_t")], 1)
Produces a grounded Advice S3 object by routing through a task-type
dispatch, calling an optional LLM provider, parsing the JSON response, and
running the runtime grounding guard – which drops any recommendation whose
evidence[] cites a diagnostic key absent from the computed diagnostics
or a value mismatching beyond numeric tolerance.
es_advise( diagnostics, task_type, provider = NULL, model = NULL, section_hint = NULL, ... )es_advise( diagnostics, task_type, provider = NULL, model = NULL, section_hint = NULL, ... )
diagnostics |
An |
task_type |
Character. One of |
provider |
An optional provider R6 object (from |
model |
Optional character model identifier. Reserved for forward
compatibility: the effective model is the one the provider was constructed
with (see |
section_hint |
Optional character scalar naming the report section to
scope the narrative to (e.g. |
... |
Additional arguments (currently ignored; reserved for future use). |
Grounding guarantee: Every returned recommendation is provably tied
to a value the package actually computed (es_diagnostics()). The guard
is enforced in R, independent of the prompt (ADV-04).
Task type routing:
recommend_stat, flag_robustness
No provider: returns the Phase 5 es_advice object (offline KB
path – deterministic, is_deterministic = TRUE).
With provider: KB produces grounded evidence[], LLM adds prose;
returns an Advice object (is_deterministic = FALSE).
interpret, recommend_model, design_discussion,
report_writing
LLM-required: stop() when provider = NULL (ADV-06).
With provider: LLM produces full advice; guard runs.
Failure discipline: Any provider failure, malformed JSON, or empty
response degrades to one warning() + an empty Advice object –
never a crash, never a fabricated result (mirrors .handle_degenerate()).
For KB task types without a provider: an es_advice S3 object
(Phase 5 offline path, is_deterministic = TRUE).
For all other paths: an Advice S3 object with fields
source, is_deterministic, task_type,
interpretation, recommendations, caveats,
n_dropped.
es_diagnostics, recommend_stat,
flag_robustness, provider,
run_event_study
Other eventstudy-advisor:
AnthropicProvider,
CustomProvider,
OpenAICompatProvider,
ProviderBase,
es_diagnostics(),
es_kb(),
flag_robustness(),
provider(),
recommend_stat()
# Offline KB path (no LLM, no network, no credentials): data(dieselgate) task <- EventStudyTask$new(dieselgate$firm, dieselgate$index, dieselgate$request) task <- run_event_study(task, ParameterSet$new()) diag <- es_diagnostics(task) advice_kb <- es_advise(diag, task_type = "recommend_stat") print(advice_kb) # es_advice S3 # LLM-grounded path (requires a network connection and provider credentials): ## Not run: p <- provider("openai") advice <- es_advise(diag, task_type = "recommend_stat", provider = p) print(advice) # Advice S3 with grounding guarantee ## End(Not run)# Offline KB path (no LLM, no network, no credentials): data(dieselgate) task <- EventStudyTask$new(dieselgate$firm, dieselgate$index, dieselgate$request) task <- run_event_study(task, ParameterSet$new()) diag <- es_diagnostics(task) advice_kb <- es_advise(diag, task_type = "recommend_stat") print(advice_kb) # es_advice S3 # LLM-grounded path (requires a network connection and provider credentials): ## Not run: p <- provider("openai") advice <- es_advise(diag, task_type = "recommend_stat", provider = p) print(advice) # Advice S3 with grounding guarantee ## End(Not run)
A named character vector of hex colours for EventStudy plots, anchored on the Okabe-Ito colorblind-safe (Color Universal Design) qualitative set with the EventStudy brand primary blue as the leading colour.
es_colourses_colours
A named character vector of length 12. Every value is a six-digit
hex colour (^#[0-9A-Fa-f]{6}$).
Semantic roles: primary (main series line/point/fill), event
(event-date marker), reference (zero lines, ACF baseline),
ci_band (confidence ribbon fill; apply alpha at the geom level), and
group1–group8 (qualitative multi-series palette in
Okabe-Ito order).
theme_eventstudy, plot_event_study
Other eventstudy-plots:
plot_car_distribution(),
plot_diagnostics(),
plot_event_study(),
plot_stocks(),
theme_eventstudy()
Extracts already-computed statistical signals from a fitted
EventStudyTask into a flat, JSON-ready S3 list. This is the
always-available grounding foundation for the knowledge base and offline
advice layer – it recomputes nothing; all signals already exist in the
fitted task.
es_diagnostics(task, max_events = 20L)es_diagnostics(task, max_events = 20L)
task |
A fitted |
max_events |
Integer. Maximum number of events to include in the
per-event sections ( |
A named list of class "es_diagnostics" with six sections:
metaList: n_events_total (integer), n_events_shown
(integer), n_events_summarized (integer), event_ids_shown
(integer vector).
estimation_windowList of plain numeric vectors (length
n_events_shown): r2, sigma, degree_of_freedom,
shapiro_p, dw_stat, ljung_box_p, acf1.
Each entry is NA_real_ when the model was not fitted or residuals
are insufficient for the test.
event_windowList of plain numeric vectors (length
n_events_shown): ar_t (last event-window day AR t-stat),
ar_p (two-sided p-value), car_t (full-window CAR t-stat),
car_p (two-sided p-value), final_car. All NA_real_
when the ART/CART columns are absent.
cross_sectionalList of scalars aggregated across ALL events:
n_events (total), n_valid_events (fitted count),
car_iqr, car_sd, n_overlap_pairs, any_overlap.
Multi-event fields degrade to NA when task$aar_caar_tbl
is NULL.
contract_stateList of logical/numeric vectors (length
n_events_shown): is_fitted, na_ar_count,
na_est_count, insufficient_obs, zero_var_index.
aggregate_summaryNamed list summarising remainder events
(those beyond max_events): n_summarized,
mean_r2, median_r2, mean_final_car,
n_fitted, n_degenerate. NULL when no events
are summarised (all shown).
model_diagnostics, recommend_stat,
flag_robustness, run_event_study
Other eventstudy-advisor:
AnthropicProvider,
CustomProvider,
OpenAICompatProvider,
ProviderBase,
es_advise(),
es_kb(),
flag_robustness(),
provider(),
recommend_stat()
Returns EVENTSTUDY_KB, the package-level pure-R list of rule records
that maps diagnostic conditions to grounded methodological recommendations.
Each rule carries a structured academic citation and can be evaluated against
an es_diagnostics object.
es_kb()es_kb()
The KB is the correctness-critical layer consumed by
recommend_stat and flag_robustness, and
exported here so that Phase 7 can inject its contents into an LLM
system prompt without accessing an internal package object.
KB-04 note: This function delivers the structure only – exported and serializable, ready for Phase 7 system-prompt injection. The actual prompt-injection behavior is a Phase 7 deliverable and is deliberately out of scope here.
A named list of rule records, each with fields:
id, category, condition, recommendation,
citation (list of author/year/key/venue),
and severity.
Each rule's condition field is an R function closure and is
therefore not JSON-serializable. Any consumer that serializes
the KB (e.g. Phase 7 system-prompt injection) must drop the
condition field from each rule record before encoding to JSON.
recommend_stat, flag_robustness,
es_diagnostics
Other eventstudy-advisor:
AnthropicProvider,
CustomProvider,
OpenAICompatProvider,
ProviderBase,
es_advise(),
es_diagnostics(),
flag_robustness(),
provider(),
recommend_stat()
kb <- es_kb() length(kb) # number of rules kb[[1]]$id # id of first rule kb[[1]]$citation # citation listkb <- es_kb() length(kb) # number of rules kb[[1]]$id # id of first rule kb[[1]]$citation # citation list
Generates a complete event study report in a single call: deep-clones the
task (non-mutation guarantee, REPORT-04), harvests diagnostics via
es_diagnostics(), and delegates rendering to
generate_report(). Returns the output file path(s) VISIBLY
so the path prints at the REPL without an explicit print().
es_report( task, output_file = "event_study_report.html", format = "html", sections = c("exec_summary", "data_methods", "results", "diagnostics", "robustness", "references"), provider = NULL, title = "Event Study Report", author = NULL, confidence_level = 0.95, interactive = TRUE, verbose = getOption("eventstudy.verbose", TRUE), ... )es_report( task, output_file = "event_study_report.html", format = "html", sections = c("exec_summary", "data_methods", "results", "diagnostics", "robustness", "references"), provider = NULL, title = "Event Study Report", author = NULL, confidence_level = 0.95, interactive = TRUE, verbose = getOption("eventstudy.verbose", TRUE), ... )
task |
A fitted |
output_file |
Output file path (extension overridden per format).
Default |
format |
Character vector of output formats, any subset of
|
sections |
Character vector of sections to include. Default is all six
fixed sections:
|
provider |
Optional LLM provider forwarded to |
title |
Report title string. |
author |
Author name (optional, default |
confidence_level |
Confidence level for plots. Default 0.95. |
interactive |
Logical. Use interactive plotly plots in HTML output.
Default |
verbose |
Logical; if FALSE, suppress informational messages. Default
|
... |
Additional arguments forwarded to |
The narrative is assembled ONCE inside generate_report() (NARR-01):
es_report() does NOT call assemble_report_narrative() or
es_advise() directly. A provider argument is forwarded to
generate_report(), which assembles the narrative once before the
format loop. When provider = NULL (default), the report is fully
offline with no network or API key required.
A named character vector of output file path(s), one per rendered
format, returned visibly (the path prints at the REPL).
Keyed by format name, e.g.
c(html = "/tmp/report.html"). A single-format call returns a
length-1 named vector; result[["html"]] and result[[1L]]
both resolve.
generate_report, es_diagnostics,
run_event_study
Other eventstudy-export:
export_results(),
generate_report(),
tidy.EventStudyTask()
data(dieselgate) task <- EventStudyTask$new(dieselgate$firm, dieselgate$index, dieselgate$request) task <- run_event_study(task, ParameterSet$new()) # Offline single-format report written to a temporary directory out <- file.path(tempdir(), "event_study_report.html") path <- es_report(task, output_file = out, format = "html") path[["html"]]data(dieselgate) task <- EventStudyTask$new(dieselgate$firm, dieselgate$index, dieselgate$request) task <- run_event_study(task, ParameterSet$new()) # Offline single-format report written to a temporary directory out <- file.path(tempdir(), "event_study_report.html") path <- es_report(task, output_file = out, format = "html") path[["html"]]
Estimate a panel event study using two-way fixed effects (TWFE) or dynamic TWFE. Returns event-time coefficient estimates suitable for event study plots.
estimate_panel_event_study( task, method = c("static_twfe", "dynamic_twfe", "sun_abraham", "callaway_santanna", "dechaisemartin_dhaultfoeuille", "borusyak_jaravel_spiess"), leads = 5, lags = 5, base_period = -1, cluster = NULL, verbose = getOption("eventstudy.verbose", TRUE), ... )estimate_panel_event_study( task, method = c("static_twfe", "dynamic_twfe", "sun_abraham", "callaway_santanna", "dechaisemartin_dhaultfoeuille", "borusyak_jaravel_spiess"), leads = 5, lags = 5, base_period = -1, cluster = NULL, verbose = getOption("eventstudy.verbose", TRUE), ... )
task |
A |
method |
Estimation method. One of |
leads |
Number of pre-treatment periods to include. Default 5. |
lags |
Number of post-treatment periods to include. Default 5. |
base_period |
The reference period (relative to treatment) to omit. Default -1 (the period just before treatment). |
cluster |
Name of the clustering variable for standard errors. Defaults to the unit ID. |
verbose |
Logical; if FALSE, suppress informational messages. Default
|
... |
Additional arguments passed to the underlying estimator
(used by |
The task with results populated, containing:
Tibble of event-time coefficients with std errors
The fitted model object
The estimation method used
Other eventstudy-tasks:
IntradayEventStudyTask,
PanelEventStudyTask,
SyntheticControlTask,
estimate_synthetic_control(),
nonparametric_intraday_test(),
plot_panel_event_study(),
plot_synthetic_control(),
prepare_intraday_event_study(),
sc_placebo_test()
Estimate synthetic control weights by minimizing the pre-treatment mean squared prediction error. Weights are non-negative and sum to one.
estimate_synthetic_control( task, method = c("quadprog", "optim"), covariates = NULL, verbose = getOption("eventstudy.verbose", TRUE) )estimate_synthetic_control( task, method = c("quadprog", "optim"), covariates = NULL, verbose = getOption("eventstudy.verbose", TRUE) )
task |
A |
method |
Optimization method: |
covariates |
Optional character vector of covariate column names in both treated and donor data to include in the matching. |
verbose |
Logical; if FALSE, suppress informational messages. Default
|
The task with results populated.
Other eventstudy-tasks:
IntradayEventStudyTask,
PanelEventStudyTask,
SyntheticControlTask,
estimate_panel_event_study(),
nonparametric_intraday_test(),
plot_panel_event_study(),
plot_synthetic_control(),
prepare_intraday_event_study(),
sc_placebo_test()
Policy: warn, never silently break.
Deprecated argument names and function names in EventStudy continue to work and emit exactly one deprecation warning per call, pointing the user to the replacement. Deprecated surfaces are never removed in a patch or minor release; removal (the "defunct" stage) is reserved for a future major version and will be announced in NEWS.md.
Mechanism:
Every renamed public argument has an explicit old-name shim that calls
.deprecate_arg() and then forwards the supplied value under the new
name. The shim fires before any computation, so the old name is
fully-equivalent to the new name for all valid inputs.
Warning source:
Deprecation warnings always use base .Deprecated() so
they work without any additional package dependency. When the optional
lifecycle package is installed (Suggests), the warning is also routed
through lifecycle::deprecate_warn() for richer IDE integration;
lifecycle is never a hard Imports dependency.
NEWS discipline:
Every deprecation and rename is documented in NEWS.md under the
release heading in which it was introduced.
The shape-contract system locks the column names and types of the EventStudy pipeline's result tibbles against accidental structural drift. It is designed for development and CI use only.
Default: OFF. When the option is unset (the default) the entire shape-contract path is a strict no-op — every existing caller and the full test suite are completely unaffected.
Opt-in:
options(EventStudy.shape_contracts = TRUE)
Philosophy (mirrors the degenerate-input contract):
On a column-name or type mismatch the contract emits exactly one
warning(), naming the context and the specific drift, and then
returns invisibly. It never calls stop(). The
correctly-shaped is_fitted = FALSE degenerate output (same
column names, NA-propagated values) is treated as a valid
shape and produces no warning.
Coverage:
Single-event statistics tibbles: ART (ARTTest) and
CART (CARTTest), including their is_fitted = FALSE
degenerate variants.
Multi-event AAR/CAAR statistics tibble: CSectT
(CSectTTest) and all other multi-event result tibbles, including
their is_fitted = FALSE degenerate variants.
Configuration:
Via package option: options(EventStudy.shape_contracts = TRUE)
Default is FALSE (off).
Return-Shape Contracts for EventStudy Pipeline Results
degenerate-input-contract, ParameterSet
Event Study Task
The Event Study task contains all necessary data for performing an event study. Furthermore, all calculations are saved in the internal dataframe named data_tbl.
data_tblAll calculations are saved in this dataframe. The dataframe is a nested object with each row is one event, identified by the event id, the group, and the firm symbol.
aar_caar_tblPlaceholder for AAR and CAAR test statistics.
.keysevent identifier. Do not change.
.indexThe time column name
.targetThe price column name.
.request_file_columnsThe necessary
column names of the request dataframe.
estimation_window_length here is an
input count (number of trading days before
the event window); it is distinct from the
derived 0/1 estimation_window flag
column that prepare_event_study()
later adds to each event's nested data.
factor_tblOptional factor data for multi-factor models
(Fama-French, Carhart). Must contain a date column.
symbolsRead-only field to get the firm symbols.
symbol_dataRead-only field to get the firm symbol data.
group_level_dataRead-only field to get the group data.
EventStudyTask$new()Create a new EventStudyTask from stock data, reference market data, and an event request specification.
EventStudyTask$new( firm_stock_data_tbl, reference_tbl, request_tbl, factor_tbl = NULL )
firm_stock_data_tblDataframe with firm stock data. This dataframe must contain the stock (col: symbol) the date (col: date) and the price (col: adjusted) column.
reference_tblDataframe with firm reference data.
request_tblThe request dataframe for each event.
factor_tblOptional dataframe with factor data
(e.g., Fama-French factors). Must contain a date
column plus factor columns.
EventStudyTask$print()Print a summary of the EventStudyTask.
EventStudyTask$print(...)
EventStudyTask$summary()Summarize the event study results.
EventStudyTask$summary()
A list with summary information about the event study results.
EventStudyTask$get_ar()Extract abnormal returns for a single event.
EventStudyTask$get_ar(event_id = NULL)
event_idThe event identifier.
A tibble with abnormal returns for the event window.
EventStudyTask$get_car()Extract cumulative abnormal returns for a single event.
EventStudyTask$get_car(event_id = NULL)
event_idThe event identifier.
A tibble with cumulative abnormal returns for the event window.
EventStudyTask$get_aar()Extract average abnormal returns across events.
EventStudyTask$get_aar(group = NULL, stat_name = "CSectT")
groupOptional group name to filter by.
stat_nameName of the multi-event test statistic to extract. Defaults to "CSectT".
A tibble with AAR/CAAR results.
EventStudyTask$get_model_stats()Extract model statistics for a single event.
EventStudyTask$get_model_stats(event_id = NULL)
event_idThe event identifier.
A list with model statistics.
EventStudyTask$clone()The objects of this class are cloneable with this method.
EventStudyTask$clone(deep = FALSE)
deepWhether to make a deep clone.
Other eventstudy-pipeline:
ParameterSet,
calculate_statistics(),
fit_model(),
prepare_event_study(),
run_event_study()
Export event study results to CSV, Excel, or LaTeX formats.
export_results( task, file, format = NULL, which = c("ar", "car", "aar", "model"), stat_name = "CSectT", ... )export_results( task, file, format = NULL, which = c("ar", "car", "aar", "model"), stat_name = "CSectT", ... )
task |
A fitted EventStudyTask with statistics computed. |
file |
Path to the output file. The file extension determines the format
unless |
format |
Output format: "csv", "xlsx", or "latex". If NULL, inferred from the file extension. |
which |
Which results to export. One or more of "ar", "car", "aar", "model". Defaults to all available. |
stat_name |
Name of the multi-event test statistic to use for AAR/CAAR tables. Defaults to "CSectT". |
... |
Additional arguments passed to the format-specific writer. |
The file path (invisibly).
run_event_study, tidy.EventStudyTask
Other eventstudy-export:
es_report(),
generate_report(),
tidy.EventStudyTask()
Implements the Fama and French (1993) three-factor model:
The data must contain columns: excess_return (firm return minus risk-free),
market_excess (market return minus risk-free), smb, and hml.
These can be joined via a factor table in EventStudyTask.
ModelBase -> LinearFactorModel -> FamaFrench3FactorModel
model_nameName of the model.
formulaThe three-factor regression formula.
required_columnsRequired data columns.
FamaFrench3FactorModel$new()Create a new FamaFrench3FactorModel.
FamaFrench3FactorModel$new(use_hac = FALSE, hac_lag = NULL)
use_hacLogical. Use HAC (Newey-West) standard errors.
hac_lagInteger or NULL. Lag truncation for Newey-West.
FamaFrench3FactorModel$abnormal_returns()Calculate abnormal returns using the three-factor model.
FamaFrench3FactorModel$abnormal_returns(data_tbl)
data_tblData frame or tibble.
FamaFrench3FactorModel$clone()The objects of this class are cloneable with this method.
FamaFrench3FactorModel$clone(deep = FALSE)
deepWhether to make a deep clone.
Other eventstudy-models:
BHARModel,
Carhart4FactorModel,
ComparisonPeriodMeanAdjustedModel,
DCCGARCHModel,
FamaFrench5FactorModel,
GARCHModel,
LinearFactorModel,
LogReturn,
MarketAdjustedModel,
MarketModel,
ModelBase,
ReturnCalculation,
RollingWindowModel,
SimpleReturn,
VolatilityModel,
VolumeModel
Implements the Fama and French (2015) five-factor model:
Requires columns: excess_return, market_excess, smb,
hml, rmw, cma.
ModelBase -> LinearFactorModel -> FamaFrench5FactorModel
model_nameName of the model.
formulaThe five-factor regression formula.
required_columnsRequired data columns.
FamaFrench5FactorModel$new()Create a new FamaFrench5FactorModel.
FamaFrench5FactorModel$new(use_hac = FALSE, hac_lag = NULL)
use_hacLogical. Use HAC (Newey-West) standard errors.
hac_lagInteger or NULL. Lag truncation for Newey-West.
FamaFrench5FactorModel$abnormal_returns()Calculate abnormal returns using the five-factor model.
FamaFrench5FactorModel$abnormal_returns(data_tbl)
data_tblData frame or tibble.
FamaFrench5FactorModel$clone()The objects of this class are cloneable with this method.
FamaFrench5FactorModel$clone(deep = FALSE)
deepWhether to make a deep clone.
Other eventstudy-models:
BHARModel,
Carhart4FactorModel,
ComparisonPeriodMeanAdjustedModel,
DCCGARCHModel,
FamaFrench3FactorModel,
GARCHModel,
LinearFactorModel,
LogReturn,
MarketAdjustedModel,
MarketModel,
ModelBase,
ReturnCalculation,
RollingWindowModel,
SimpleReturn,
VolatilityModel,
VolumeModel
Train the defined model on each event and calculate the abnormal return.
fit_model(task, parameter_set)fit_model(task, parameter_set)
task |
The event study task |
parameter_set |
The parameter set that defines the event study. |
task
run_event_study, prepare_event_study,
calculate_statistics
Other eventstudy-pipeline:
EventStudyTask,
ParameterSet,
calculate_statistics(),
prepare_event_study(),
run_event_study()
Evaluates the KB decision table (category "robustness" rules) against
the diagnostic signals extracted from a fitted EventStudyTask or a
precomputed es_diagnostics object, and returns a severity-ranked
es_advice S3 object.
flag_robustness(x, provider = NULL, ...) ## Default S3 method: flag_robustness(x, provider = NULL, ...) ## S3 method for class 'EventStudyTask' flag_robustness(x, provider = NULL, ...) ## S3 method for class 'es_diagnostics' flag_robustness(x, provider = NULL, ...)flag_robustness(x, provider = NULL, ...) ## Default S3 method: flag_robustness(x, provider = NULL, ...) ## S3 method for class 'EventStudyTask' flag_robustness(x, provider = NULL, ...) ## S3 method for class 'es_diagnostics' flag_robustness(x, provider = NULL, ...)
x |
A fitted |
provider |
Accepted but ignored in the offline path – present only so
the Phase 7 call shape is forward-compatible. Default |
... |
Additional arguments (currently ignored). |
No LLM provider, network connection, or API key is required. The returned
es_advice object has the same shape as the Phase 7 Advice contract,
flagged is_deterministic = TRUE and source = "offline_kb".
An S3 object of class "es_advice" – see recommend_stat
for field descriptions. Rules are filtered to category == "robustness".
recommend_stat, es_diagnostics,
es_kb
Other eventstudy-advisor:
AnthropicProvider,
CustomProvider,
OpenAICompatProvider,
ProviderBase,
es_advise(),
es_diagnostics(),
es_kb(),
provider(),
recommend_stat()
data(dieselgate) task <- EventStudyTask$new(dieselgate$firm, dieselgate$index, dieselgate$request) task <- run_event_study(task, ParameterSet$new()) advice <- flag_robustness(task) print(advice)data(dieselgate) task <- EventStudyTask$new(dieselgate$firm, dieselgate$index, dieselgate$request) task <- run_event_study(task, ParameterSet$new()) advice <- flag_robustness(task) print(advice)
Builds the character vector rendered by print.Advice (one element
per output line). The opt-in Advisor Pro footer is captured here (a no-op
unless options(eventstudy.advisor_pro_footer = TRUE)), so
print.Advice must not re-emit it.
## S3 method for class 'Advice' format(x, ...)## S3 method for class 'Advice' format(x, ...)
x |
An object of class |
... |
Additional arguments (ignored). |
A character vector, one element per printed line.
Builds the character vector rendered by print.es_advice (one element
per output line). The opt-in Advisor Pro footer is captured here (a no-op
unless options(eventstudy.advisor_pro_footer = TRUE)), so
print.es_advice must not re-emit it.
## S3 method for class 'es_advice' format(x, ...)## S3 method for class 'es_advice' format(x, ...)
x |
An object of class |
... |
Additional arguments (ignored). |
A character vector, one element per printed line.
Builds the character vector rendered by print.es_cross_sectional
(one element per output line). The coefficient table is rendered via
base::print.data.frame and spliced in at the same position.
## S3 method for class 'es_cross_sectional' format(x, ...)## S3 method for class 'es_cross_sectional' format(x, ...)
x |
An |
... |
Additional arguments (unused). |
A character vector, one element per printed line.
Builds the character vector rendered by print.es_diagnostics
(one element per output line). See print.es_diagnostics.
## S3 method for class 'es_diagnostics' format(x, ...)## S3 method for class 'es_diagnostics' format(x, ...)
x |
An object of class |
... |
Additional arguments (ignored). |
A character vector, one element per printed line.
Builds the character vector rendered by print.es_simulation
(one element per output line).
## S3 method for class 'es_simulation' format(x, ...)## S3 method for class 'es_simulation' format(x, ...)
x |
An object of class |
... |
Additional arguments (unused). |
A character vector, one element per printed line.
Builds the character vector rendered by print.EventStudySummary
(one element per output line). See print.EventStudySummary.
## S3 method for class 'EventStudySummary' format(x, ...)## S3 method for class 'EventStudySummary' format(x, ...)
x |
An EventStudySummary object. |
... |
Additional arguments (unused). |
A character vector, one element per printed line.
Event study model using GARCH(1,1) for time-varying volatility estimation. Uses the rugarch package to fit a GARCH(1,1) model with a market return regressor in the mean equation during the estimation window. Abnormal returns are computed as the difference between observed returns and the GARCH conditional mean. The time-varying sigma from GARCH can be used for standardized test statistics.
ModelBase -> GARCHModel
model_nameName of the model.
garch_orderGARCH order as c(p, q). Default c(1,1).
GARCHModel$fit()Fit the GARCH model on the estimation window.
GARCHModel$fit(data_tbl)
data_tblData frame or tibble with firm_returns, index_returns, estimation_window, event_window columns.
GARCHModel$abnormal_returns()Calculate abnormal returns from the GARCH model.
GARCHModel$abnormal_returns(data_tbl)
data_tblData frame or tibble.
GARCHModel$clone()The objects of this class are cloneable with this method.
GARCHModel$clone(deep = FALSE)
deepWhether to make a deep clone.
Other eventstudy-models:
BHARModel,
Carhart4FactorModel,
ComparisonPeriodMeanAdjustedModel,
DCCGARCHModel,
FamaFrench3FactorModel,
FamaFrench5FactorModel,
LinearFactorModel,
LogReturn,
MarketAdjustedModel,
MarketModel,
ModelBase,
ReturnCalculation,
RollingWindowModel,
SimpleReturn,
VolatilityModel,
VolumeModel
Adjusts the sign test for the expected proportion of positive abnormal returns estimated from the estimation window, rather than assuming 0.5. This accounts for asymmetry in the return distribution.
TestStatisticBase -> GeneralizedSignTest
nameShort code of the test statistic.
GeneralizedSignTest$compute()Computes the generalized sign test for multiple events.
GeneralizedSignTest$compute(data_tbl, model)
data_tblThe data for a multiple event with calculated abnormal returns.
modelThe fitted model (unused).
GeneralizedSignTest$clone()The objects of this class are cloneable with this method.
GeneralizedSignTest$clone(deep = FALSE)
deepWhether to make a deep clone.
Other eventstudy-statistics:
ARTTest,
BHARTTest,
BMPTest,
CARTTest,
CSectTTest,
CalendarTimePortfolioTest,
KolariPynnonenTest,
MultiEventStatisticsSet,
PatellZTest,
RankTest,
SignTest,
SingleEventStatisticsSet,
StatisticsSetBase,
TestStatisticBase,
adjust_p_values(),
bootstrap_test(),
car_by_group(),
car_quantiles(),
cross_sectional_regression(),
model_diagnostics(),
pretrend_test(),
simulate_event_study(),
validate_task()
Renders an automated report from a completed event study task in one or more
output formats. Uses a bundled RMarkdown template with configurable sections.
The narrative is assembled ONCE before the format loop – es_advise is
never called per format (NARR-01).
generate_report( task, output_file = "event_study_report.html", format = "html", title = "Event Study Report", author = NULL, sections = c("exec_summary", "data_methods", "results", "diagnostics", "robustness", "references"), cross_sectional = NULL, confidence_level = 0.95, interactive = TRUE, advice = NULL, narrative = NULL, provider = NULL, verbose = getOption("eventstudy.verbose", TRUE), ... )generate_report( task, output_file = "event_study_report.html", format = "html", title = "Event Study Report", author = NULL, sections = c("exec_summary", "data_methods", "results", "diagnostics", "robustness", "references"), cross_sectional = NULL, confidence_level = 0.95, interactive = TRUE, advice = NULL, narrative = NULL, provider = NULL, verbose = getOption("eventstudy.verbose", TRUE), ... )
task |
A fitted |
output_file |
Output file path (extension overridden per format).
Default |
format |
Character vector of output formats, any subset of
|
title |
Report title string. |
author |
Author name (optional, default |
sections |
Character vector of sections to include. Default is all six
fixed sections:
|
cross_sectional |
Optional cross-sectional regression results to include. |
confidence_level |
Confidence level for plots. Default 0.95. |
interactive |
Logical. Use interactive plotly plots in HTML output. Default TRUE. |
advice |
An optional grounded |
narrative |
An optional named list keyed by section (e.g.
|
provider |
Optional LLM provider passed to
|
verbose |
Logical; if FALSE, suppress informational messages. Default
|
... |
Additional arguments passed to |
A named character vector of output file paths, invisibly, keyed by
format name (e.g. c(html = "/tmp/report.html", pdf = "/tmp/report.pdf")).
A single-format call returns a length-1 named vector: result[["html"]]
and result[[1L]] both resolve (backward-compatible with prior
single-path callers).
Other eventstudy-export:
es_report(),
export_results(),
tidy.EventStudyTask()
data(dieselgate) task <- EventStudyTask$new(dieselgate$firm, dieselgate$index, dieselgate$request) task <- run_event_study(task, ParameterSet$new()) # Single HTML format written to a temporary directory out <- file.path(tempdir(), "event_study_report.html") path <- generate_report(task, output_file = out, format = "html") path[["html"]]data(dieselgate) task <- EventStudyTask$new(dieselgate$firm, dieselgate$index, dieselgate$request) task <- run_event_study(task, ParameterSet$new()) # Single HTML format written to a temporary directory out <- file.path(tempdir(), "event_study_report.html") path <- generate_report(task, output_file = out, format = "html") path[["html"]]
Extension of EventStudyTask for intraday (high-frequency)
event studies. Supports POSIXct timestamps and time-based windows
specified in minutes or hours.
Date column contains POSIXct timestamps instead of date strings
Event windows specified as time offsets (e.g., "-30min", "+60min")
Handles trading session boundaries
EventStudyTask -> IntradayEventStudyTask
.indexThe time column name (POSIXct).
.targetThe price column name.
.request_file_columnsRequired columns for intraday requests.
IntradayEventStudyTask$new()Create a new IntradayEventStudyTask.
IntradayEventStudyTask$new( firm_stock_data_tbl, reference_tbl, request_tbl, factor_tbl = NULL )
firm_stock_data_tblDataframe with firm intraday data.
Must contain columns: symbol, timestamp (POSIXct),
and price.
reference_tblDataframe with reference market intraday data.
request_tblRequest dataframe with event_timestamp
(POSIXct), and window specifications in minutes.
factor_tblOptional factor data.
IntradayEventStudyTask$print()Print summary.
IntradayEventStudyTask$print(...)
IntradayEventStudyTask$clone()The objects of this class are cloneable with this method.
IntradayEventStudyTask$clone(deep = FALSE)
deepWhether to make a deep clone.
Other eventstudy-tasks:
PanelEventStudyTask,
SyntheticControlTask,
estimate_panel_event_study(),
estimate_synthetic_control(),
nonparametric_intraday_test(),
plot_panel_event_study(),
plot_synthetic_control(),
prepare_intraday_event_study(),
sc_placebo_test()
Adjusts the BMP (Boehmer, Musumeci, Poulsen 1991) test for cross-sectional
correlation of abnormal returns using the Kolari and Pynnoenen (2010)
correction. Abnormal returns are standardized by each event's MODEL sigma
(model$statistics$sigma, same as BMPTest) – not the
forecast-error-corrected sigma. The adjustment scales the BMP statistic by
a factor that accounts for the average pairwise correlation of
standardized abnormal residuals in the estimation window, computed only
over "usable" events (at least 2 finite estimation-window SARs, finite
model sigma, and non-constant/non-degenerate SAR variance). The adjustment
is never silently substituted with 1: an event that cannot contribute a
usable estimation-window series is excluded from the correlation estimate
and reported once; if fewer than 2 usable events remain, kp_t and
ckp_t are NA.
TestStatisticBase -> KolariPynnonenTest
nameShort code of the test statistic.
KolariPynnonenTest$compute()Computes the Kolari-Pynnoenen adjusted BMP test.
KolariPynnonenTest$compute(data_tbl, model)
data_tblThe data for a multiple event with calculated abnormal returns.
modelThe fitted model containing sigma estimates.
KolariPynnonenTest$clone()The objects of this class are cloneable with this method.
KolariPynnonenTest$clone(deep = FALSE)
deepWhether to make a deep clone.
Kolari, J. W. and Pynnoenen, S. (2010). Event Study Testing with Cross-sectional Correlation of Abnormal Returns. The Review of Financial Studies, 23(11), 3996–4025.
Other eventstudy-statistics:
ARTTest,
BHARTTest,
BMPTest,
CARTTest,
CSectTTest,
CalendarTimePortfolioTest,
GeneralizedSignTest,
MultiEventStatisticsSet,
PatellZTest,
RankTest,
SignTest,
SingleEventStatisticsSet,
StatisticsSetBase,
TestStatisticBase,
adjust_p_values(),
bootstrap_test(),
car_by_group(),
car_quantiles(),
cross_sectional_regression(),
model_diagnostics(),
pretrend_test(),
simulate_event_study(),
validate_task()
Base class for multi-factor OLS models used in event studies. All factor models (Market Model, Fama-French, Carhart) share the same estimation approach: OLS regression of excess returns on factor returns during the estimation window.
ModelBase -> LinearFactorModel
model_nameName of the model.
formulaThe regression formula.
required_columnsColumns required in the data.
use_hacLogical. Use HAC (Newey-West) standard errors.
hac_lagInteger or NULL. Lag truncation for Newey-West.
LinearFactorModel$new()Create a new LinearFactorModel.
LinearFactorModel$new(use_hac = FALSE, hac_lag = NULL)
use_hacLogical. Use HAC (Newey-West) standard errors.
hac_lagInteger or NULL. Lag truncation for Newey-West.
LinearFactorModel$fit()Fit the linear factor model via OLS on the estimation window.
LinearFactorModel$fit(data_tbl)
data_tblData frame or tibble containing the data to fit.
LinearFactorModel$abnormal_returns()Calculate abnormal returns as observed minus predicted.
LinearFactorModel$abnormal_returns(data_tbl)
data_tblData frame or tibble.
LinearFactorModel$clone()The objects of this class are cloneable with this method.
LinearFactorModel$clone(deep = FALSE)
deepWhether to make a deep clone.
Other eventstudy-models:
BHARModel,
Carhart4FactorModel,
ComparisonPeriodMeanAdjustedModel,
DCCGARCHModel,
FamaFrench3FactorModel,
FamaFrench5FactorModel,
GARCHModel,
LogReturn,
MarketAdjustedModel,
MarketModel,
ModelBase,
ReturnCalculation,
RollingWindowModel,
SimpleReturn,
VolatilityModel,
VolumeModel
R6 class for log return calculation
ReturnCalculation -> LogReturn
nameName of the log return calculation.
LogReturn$calculate_return()Calculates the return for a single stock.
LogReturn$calculate_return( tbl, in_column = "adjusted", out_column = "adjusted_return" )
tblThe dataframe with the stock price.
in_columnThe column name of the price infromation.
out_columnThe column name were the return will be saved.
LogReturn$clone()The objects of this class are cloneable with this method.
LogReturn$clone(deep = FALSE)
deepWhether to make a deep clone.
Other eventstudy-models:
BHARModel,
Carhart4FactorModel,
ComparisonPeriodMeanAdjustedModel,
DCCGARCHModel,
FamaFrench3FactorModel,
FamaFrench5FactorModel,
GARCHModel,
LinearFactorModel,
MarketAdjustedModel,
MarketModel,
ModelBase,
ReturnCalculation,
RollingWindowModel,
SimpleReturn,
VolatilityModel,
VolumeModel
The Market Adjusted Model is another simple approach used in event studies to estimate the expected returns of a stock and calculate its abnormal returns during an event window. This model is less complex than the Market Model, as it assumes that a stock's expected return is equal to the market return, without considering any stock-specific factors. The Market Adjusted Model is particularly useful in situations where the estimation of individual stock parameters (such as alpha and beta) is not feasible or desired, and a basic benchmark for comparison is needed.
ModelBase -> MarketAdjustedModel
model_nameName of the model.
MarketAdjustedModel$fit()fit Fit the model with given data.
MarketAdjustedModel$fit(data_tbl)
data_tblData frame or tibble containing the data to fit.
MarketAdjustedModel$abnormal_returns()abnormal_returns Calculate the abnormal returns with given data.
MarketAdjustedModel$abnormal_returns(data_tbl)
data_tblData frame or tibble containing the data to calculate abnormal returns.
MarketAdjustedModel$clone()The objects of this class are cloneable with this method.
MarketAdjustedModel$clone(deep = FALSE)
deepWhether to make a deep clone.
Other eventstudy-models:
BHARModel,
Carhart4FactorModel,
ComparisonPeriodMeanAdjustedModel,
DCCGARCHModel,
FamaFrench3FactorModel,
FamaFrench5FactorModel,
GARCHModel,
LinearFactorModel,
LogReturn,
MarketModel,
ModelBase,
ReturnCalculation,
RollingWindowModel,
SimpleReturn,
VolatilityModel,
VolumeModel
The Market Model is a widely used method in event studies to estimate the expected returns of a stock and calculate its abnormal returns during an event window. The model is based on a simple linear regression framework and captures the relationship between a stock's return and the return of a market index, such as the S&P 500 or the Dow Jones Industrial Average. The underlying assumption of the Market Model is that a stock's return is primarily influenced by market movements, along with a stock-specific idiosyncratic component.
ModelBase -> MarketModel
model_nameName of the model.
formulaThe formula applied for calculating the market model
use_hacLogical. Use HAC (Newey-West) standard errors.
hac_lagInteger or NULL. Lag truncation for Newey-West. NULL uses the automatic bandwidth selection.
MarketModel$new()Create a new MarketModel.
MarketModel$new(use_hac = FALSE, hac_lag = NULL)
use_hacLogical. Use HAC (Newey-West) standard errors. Requires the sandwich package.
hac_lagInteger or NULL. Lag truncation for Newey-West.
MarketModel$set_formula()Set the formula
MarketModel$set_formula(formula)
formulaA formula.
MarketModel$fit()Fit the model with given data.
MarketModel$fit(data_tbl)
data_tblData frame or tibble containing the data to fit.
MarketModel$abnormal_returns()Calculate the abnormal returns with given data.
MarketModel$abnormal_returns(data_tbl)
data_tblData frame or tibble containing the data to calculate abnormal returns.
MarketModel$clone()The objects of this class are cloneable with this method.
MarketModel$clone(deep = FALSE)
deepWhether to make a deep clone.
Other eventstudy-models:
BHARModel,
Carhart4FactorModel,
ComparisonPeriodMeanAdjustedModel,
DCCGARCHModel,
FamaFrench3FactorModel,
FamaFrench5FactorModel,
GARCHModel,
LinearFactorModel,
LogReturn,
MarketAdjustedModel,
ModelBase,
ReturnCalculation,
RollingWindowModel,
SimpleReturn,
VolatilityModel,
VolumeModel
Run diagnostic tests on fitted event study models. Tests include normality of residuals, autocorrelation, and basic model fit quality.
model_diagnostics(task, event_id = NULL)model_diagnostics(task, event_id = NULL)
task |
A fitted EventStudyTask (after fit_model has been called). |
event_id |
Optional event identifier. If NULL, runs diagnostics for all events. |
A tibble with diagnostic test results for each event.
Other eventstudy-statistics:
ARTTest,
BHARTTest,
BMPTest,
CARTTest,
CSectTTest,
CalendarTimePortfolioTest,
GeneralizedSignTest,
KolariPynnonenTest,
MultiEventStatisticsSet,
PatellZTest,
RankTest,
SignTest,
SingleEventStatisticsSet,
StatisticsSetBase,
TestStatisticBase,
adjust_p_values(),
bootstrap_test(),
car_by_group(),
car_quantiles(),
cross_sectional_regression(),
pretrend_test(),
simulate_event_study(),
validate_task()
Base (abstract) class for return models used inside an
EventStudyTask. Each single event gets its own model instance, fitted on
that event's estimation-window data alone. Subclass this to plug a custom
return model into run_event_study() / fit_model().
A subclass must implement two methods:
fit(data_tbl) – fit the model on data_tbl (a single
event's rows, estimation and event window together) and populate
private$.statistics plus set private$.is_fitted.
abnormal_returns(data_tbl) – return data_tbl with an
abnormal_returns column added for the event window.
The statistics active binding exposes a named list consumed by the
test statistics layer. At minimum a subclass should populate:
sigma, degree_of_freedom, residuals,
forecast_error_corrected_sigma and
forecast_error_corrected_sigma_car. Since 2026-09-24, a model may
also set statistics$n_params (the number of parameters estimated
from the estimation window); PatellZTest reads this field for its
Q_i adjustment and falls back to 2 when a subclass does not report it.
Degenerate-input handling: subclasses that implement the shared contract
(see R/contract.R) read self$degenerate_mode,
self$event_id and self$firm_symbol, which are threaded onto
the cloned model instance by fit_model() before fit() is
called.
model_nameName of the model.
degenerate_modeResolved degenerate-input mode injected by fit_model() before fit() is called. Subclasses that implement the degenerate-input contract (MarketModel and Phase-2 models) read this field inside fit() via .resolve_degenerate_mode(self$degenerate_mode).
event_idEvent identifier threaded from the outer data_tbl row. Used in degenerate-input error/warning messages.
firm_symbolFirm identifier threaded from the outer data_tbl row. Used in degenerate-input error/warning messages.
statisticsRead-only field to get statistics.
modelRead-only field to get the fitted model.
is_fittedRead-only field to check if the model is fitted. Statistics object contains different model specific KPIs that describes the fitted model.
ModelBase$fit()Fits the model with given data.
ModelBase$fit(data_tbl)
data_tblA data frame or tibble containing the data to fit.
ModelBase$abnormal_returns()Calculate the abnormal returns with given data and fitted model.
ModelBase$abnormal_returns(data_tbl)
data_tblData frame or tibble containing the data to calculate abnormal returns.
ModelBase$clone()The objects of this class are cloneable with this method.
ModelBase$clone(deep = FALSE)
deepWhether to make a deep clone.
Other eventstudy-models:
BHARModel,
Carhart4FactorModel,
ComparisonPeriodMeanAdjustedModel,
DCCGARCHModel,
FamaFrench3FactorModel,
FamaFrench5FactorModel,
GARCHModel,
LinearFactorModel,
LogReturn,
MarketAdjustedModel,
MarketModel,
ReturnCalculation,
RollingWindowModel,
SimpleReturn,
VolatilityModel,
VolumeModel
Contains a set of multi event test statistics as, e.g., AAR and CAAR cross-sectional t test. These are the default test statistics.
StatisticsSetBase -> MultiEventStatisticsSet
testsContainer with the statistical tests.
MultiEventStatisticsSet$clone()The objects of this class are cloneable with this method.
MultiEventStatisticsSet$clone(deep = FALSE)
deepWhether to make a deep clone.
Other eventstudy-statistics:
ARTTest,
BHARTTest,
BMPTest,
CARTTest,
CSectTTest,
CalendarTimePortfolioTest,
GeneralizedSignTest,
KolariPynnonenTest,
PatellZTest,
RankTest,
SignTest,
SingleEventStatisticsSet,
StatisticsSetBase,
TestStatisticBase,
adjust_p_values(),
bootstrap_test(),
car_by_group(),
car_quantiles(),
cross_sectional_regression(),
model_diagnostics(),
pretrend_test(),
simulate_event_study(),
validate_task()
Implements the non-parametric intraday event study methodology of Rinaudo & Saha (2014). For each event time, cumulative abnormal returns (CARs) on the event day are compared to the empirical distribution of CARs from estimation-period days. Significance is assessed without distributional assumptions.
nonparametric_intraday_test( estimation_window, event_window, event_times, p = 0.05, init_window = 5L, upper = FALSE )nonparametric_intraday_test( estimation_window, event_window, event_times, p = 0.05, init_window = 5L, upper = FALSE )
estimation_window |
Data frame with columns |
event_window |
Data frame with columns |
event_times |
Character vector of intraday times at which events
occurred (e.g., |
p |
Numeric; significance level in (0, 1). Default 0.05. |
init_window |
Integer; number of initial observations to accumulate before testing significance. Default 5. |
upper |
Logical; if |
A named list of tibbles, one per event time. Each tibble contains:
Observation index within the significant window.
Cumulative abnormal return on the event day.
Empirical confidence interval boundary from estimation days.
Polynomial-smoothed CI (degree-4 polynomial fit).
When an event time is not significant, returns a single-row tibble with all values equal to zero.
Rinaudo, J.B. & Saha, A. (2014). Non-parametric intraday event studies.
Other eventstudy-tasks:
IntradayEventStudyTask,
PanelEventStudyTask,
SyntheticControlTask,
estimate_panel_event_study(),
estimate_synthetic_control(),
plot_panel_event_study(),
plot_synthetic_control(),
prepare_intraday_event_study(),
sc_placebo_test()
# Build a small intraday grid: estimation window (multiple days) and a # single event-day window sharing the same intraday time stamps. set.seed(1) times <- sprintf("%02d:%02d", 10L + seq_len(30L) %/% 60L, seq_len(30L) %% 60L) est_data <- data.frame( day = rep(seq_len(10L), each = 30L), time = rep(times, 10L), abnormalReturn = rnorm(300L, 0, 0.001) ) event_data <- data.frame( time = times, abnormalReturn = rnorm(30L, 0, 0.001) ) results <- nonparametric_intraday_test( estimation_window = est_data, event_window = event_data, event_times = times[c(5L, 20L)], p = 0.05, init_window = 5 )# Build a small intraday grid: estimation window (multiple days) and a # single event-day window sharing the same intraday time stamps. set.seed(1) times <- sprintf("%02d:%02d", 10L + seq_len(30L) %/% 60L, seq_len(30L) %% 60L) est_data <- data.frame( day = rep(seq_len(10L), each = 30L), time = rep(times, 10L), abnormalReturn = rnorm(300L, 0, 0.001) ) event_data <- data.frame( time = times, abnormalReturn = rnorm(30L, 0, 0.001) ) results <- nonparametric_intraday_test( estimation_window = est_data, event_window = event_data, event_times = times[c(5L, 20L)], p = 0.05, init_window = 5 )
A provider that issues POST {base_url}/chat/completions
with an OpenAI-shaped request body. Because the endpoint is selected purely
by base_url + model, this single class covers OpenAI itself
AND every OpenAI-compatible backend – Ollama, LM Studio, or any gateway –
via a base_url override, with no code change.
The API key is resolved at CALL time from OPENAI_API_KEY (never at
construction, never stored on the object) and attached with
req_auth_bearer_token(), which redacts the Authorization
header in every print/error path. A missing key, transport/timeout failure,
non-2xx status, malformed body, or missing completion text each degrades to
exactly one warning() plus an 'es_provider_response' with
text = NA_character_ – it never crashes the session and never returns
a fabricated completion.
httr2 is required only for this provider and is guarded by
requireNamespace() at the top of complete(), so the package
installs and R CMD checks cleanly with httr2 absent.
ProviderBase -> OpenAICompatProvider
OpenAICompatProvider$new()Construct an OpenAICompatProvider. Stores non-secret config
only; the API key is resolved at call time inside complete().
OpenAICompatProvider$new(model, base_url = "https://api.openai.com/v1", ...)
modelCharacter model identifier, e.g. "gpt-4o" or a local model name like "llama3".
base_urlCharacter base URL. Defaults to the OpenAI cloud endpoint; override for OpenAI-compatible servers (Ollama, LM Studio, gateways).
...Ignored; accepted for forward-compatibility.
OpenAICompatProvider$complete()Complete a prompt via POST {base_url}/chat/completions.
Resolves the key at call time; on a missing key or any HTTP/parse failure
returns one warning + NA. Structured output is OPTIONAL: when
schema is supplied a response_format json_schema is added to
the body, but omitting it uses the plain-text path (which local models
that lack response_format support still handle).
OpenAICompatProvider$complete(prompt, schema = NULL, ...)
promptCharacter prompt.
schemaOptional structured-output schema (list) or NULL.
...Ignored; accepted for forward-compatibility.
An 'es_provider_response' (see ProviderBase$complete).
OpenAICompatProvider$clone()The objects of this class are cloneable with this method.
OpenAICompatProvider$clone(deep = FALSE)
deepWhether to make a deep clone.
Other eventstudy-advisor:
AnthropicProvider,
CustomProvider,
ProviderBase,
es_advise(),
es_diagnostics(),
es_kb(),
flag_robustness(),
provider(),
recommend_stat()
## Not run: # OpenAI (reads OPENAI_API_KEY from the environment at call time): p <- OpenAICompatProvider$new(model = "gpt-4o") p$complete("Summarise these event-study diagnostics") # Any OpenAI-compatible endpoint works via a base_url override -- e.g. a local # Ollama server (no cloud key needed by the server, but OPENAI_API_KEY is still # read as the bearer token; set it to any non-empty value for local servers): p_local <- OpenAICompatProvider$new( model = "llama3", base_url = "http://localhost:11434/v1" # Ollama; LM Studio: :1234/v1 ) p_local$complete("Summarise these diagnostics") ## End(Not run)## Not run: # OpenAI (reads OPENAI_API_KEY from the environment at call time): p <- OpenAICompatProvider$new(model = "gpt-4o") p$complete("Summarise these event-study diagnostics") # Any OpenAI-compatible endpoint works via a base_url override -- e.g. a local # Ollama server (no cloud key needed by the server, but OPENAI_API_KEY is still # read as the bearer token; set it to any non-empty value for local servers): p_local <- OpenAICompatProvider$new( model = "llama3", base_url = "http://localhost:11434/v1" # Ollama; LM Studio: :1234/v1 ) p_local$complete("Summarise these diagnostics") ## End(Not run)
Task container for panel (difference-in-differences style) event studies. This is designed for settings where units receive treatment at potentially different times, and we observe outcomes over multiple periods.
new(panel_data, unit_id, time_id, outcome, treatment, treatment_time)Create a new panel event study task.
print()Print summary.
panel_dataThe panel dataset in long format.
unit_idName of the unit identifier column.
time_idName of the time identifier column.
outcomeName of the outcome column.
treatmentName of the treatment indicator column (0/1).
treatment_timeName of the treatment timing column (period when unit first treated; NA for never-treated).
resultsEstimation results (populated after estimation).
PanelEventStudyTask$new()Create a new PanelEventStudyTask.
PanelEventStudyTask$new( panel_data, unit_id = "unit_id", time_id = "time_id", outcome = "outcome", treatment = "treated", treatment_time = "treatment_time" )
panel_dataLong-format panel data frame.
unit_idName of the unit ID column.
time_idName of the time period column.
outcomeName of the outcome variable column.
treatmentName of the treatment indicator column (0/1).
treatment_timeName of column indicating when each unit is first treated (NA for never-treated controls).
PanelEventStudyTask$print()Print summary.
PanelEventStudyTask$print(...)
PanelEventStudyTask$clone()The objects of this class are cloneable with this method.
PanelEventStudyTask$clone(deep = FALSE)
deepWhether to make a deep clone.
Other eventstudy-tasks:
IntradayEventStudyTask,
SyntheticControlTask,
estimate_panel_event_study(),
estimate_synthetic_control(),
nonparametric_intraday_test(),
plot_panel_event_study(),
plot_synthetic_control(),
prepare_intraday_event_study(),
sc_placebo_test()
The parameter set defines the Event Study, e.g, the return calculation, the event study model, the AR, CAR, AAR, and CAAR test statistics that should be applied.
return_calculationA R6 object for calculating returns.
return_modelA R6 object for fitting the desired model.
single_event_statisticssingle event test statistic R6 object.
multi_event_statisticsmulti event test statistic R6 object.
study_typeType of event study: "return" (default), "volume", or "volatility". Affects axis labels in plots.
degenerate_handlingControls how degenerate estimation data
is handled. One of "lenient" (default), "strict",
or NULL (defer to package option or built-in default).
See ?degenerate-input-contract for details.
ParameterSet$new()Initialize the parameters that defines the Event Study that should be applied.
ParameterSet$new( return_calculation = SimpleReturn$new(), return_model = MarketModel$new(), single_event_statistics = SingleEventStatisticsSet$new(), multi_event_statistics = MultiEventStatisticsSet$new(), degenerate_handling = NULL )
return_calculationAn initialized return calculation class. Defaults to SimpleReturn.
return_modelAn initialized event study model. Defaults to MarketModel.
single_event_statisticsDefinition of single event test statistics. Defaults to SingleEventStatisticsSet (AR T and CAR T tests).
multi_event_statisticsDefinition of multiple event test statistics. Defaults to MultiEventStatisticsSet (CSect T test).
degenerate_handlingOne of "lenient", "strict",
or NULL. See ?degenerate-input-contract.
ParameterSet$print()Print a summary of the parameter set.
ParameterSet$print(...)
ParameterSet$clone()The objects of this class are cloneable with this method.
ParameterSet$clone(deep = FALSE)
deepWhether to make a deep clone.
Other eventstudy-pipeline:
EventStudyTask,
calculate_statistics(),
fit_model(),
prepare_event_study(),
run_event_study()
The Patell or Standardized Residual Test is a statistical tool employed in event studies to evaluate the null hypothesis that the average abnormal return at the event date is zero. The test statistics is approximately distributed as N(0, 1).
See also https://eventstudy.de/statistics/aar_caar_statistics.html
TestStatisticBase -> PatellZTest
nameShort code of the test statistic.
PatellZTest$compute()Computes the Patell Z test statistics for multiple events.
PatellZTest$compute(data_tbl, model)
data_tblThe data for a multiple event with calculated abnormal returns.
modelThe fitted model.
PatellZTest$clone()The objects of this class are cloneable with this method.
PatellZTest$clone(deep = FALSE)
deepWhether to make a deep clone.
Other eventstudy-statistics:
ARTTest,
BHARTTest,
BMPTest,
CARTTest,
CSectTTest,
CalendarTimePortfolioTest,
GeneralizedSignTest,
KolariPynnonenTest,
MultiEventStatisticsSet,
RankTest,
SignTest,
SingleEventStatisticsSet,
StatisticsSetBase,
TestStatisticBase,
adjust_p_values(),
bootstrap_test(),
car_by_group(),
car_quantiles(),
cross_sectional_regression(),
model_diagnostics(),
pretrend_test(),
simulate_event_study(),
validate_task()
Create a histogram of CARs across events, optionally colored by group.
plot_car_distribution( task, car_window = NULL, bins = 30, by_group = FALSE, title = NULL )plot_car_distribution( task, car_window = NULL, bins = 30, by_group = FALSE, title = NULL )
task |
A fitted EventStudyTask. |
car_window |
Optional two-element vector for CAR window. |
bins |
Number of histogram bins. Default 30. |
by_group |
Logical. If TRUE, color histogram by group. |
title |
Optional plot title. |
A ggplot2 object.
Other eventstudy-plots:
es_colours,
plot_diagnostics(),
plot_event_study(),
plot_stocks(),
theme_eventstudy()
Create diagnostic plots for fitted event study models, including residual plots and Q-Q plots.
plot_diagnostics(task, event_id = NULL)plot_diagnostics(task, event_id = NULL)
task |
A fitted EventStudyTask. |
event_id |
The event identifier to plot diagnostics for. |
A ggplot2 plot arranged in a gridExtra 2x2 grid layout.
Other eventstudy-plots:
es_colours,
plot_car_distribution(),
plot_event_study(),
plot_stocks(),
theme_eventstudy()
Create an event study plot showing abnormal returns (AR), cumulative abnormal returns (CAR), average abnormal returns (AAR), or cumulative average abnormal returns (CAAR) with confidence bands.
plot_event_study( task, type = "car", event_id = NULL, group = NULL, stat_name = "CSectT", confidence_level = 0.95, title = NULL )plot_event_study( task, type = "car", event_id = NULL, group = NULL, stat_name = "CSectT", confidence_level = 0.95, title = NULL )
task |
A fitted EventStudyTask with statistics computed. |
type |
Type of plot: "ar", "car", "aar", or "caar". |
event_id |
Event identifier for single-event plots ("ar", "car"). |
group |
Group name for multi-event plots ("aar", "caar"). |
stat_name |
Name of the multi-event test statistic to use for AAR/CAAR plots. Defaults to "CSectT". |
confidence_level |
Confidence level for the bands. Default is 0.95. |
title |
Optional plot title. |
A ggplot2 plot object.
Other eventstudy-plots:
es_colours,
plot_car_distribution(),
plot_diagnostics(),
plot_stocks(),
theme_eventstudy()
Create an event study plot from panel estimation results. Can also be
called via plot_event_study() when given a PanelEventStudyTask.
plot_panel_event_study(task, confidence_level = 0.95, title = NULL)plot_panel_event_study(task, confidence_level = 0.95, title = NULL)
task |
A PanelEventStudyTask with results. |
confidence_level |
Confidence level for error bars. Default 0.95. |
title |
Optional plot title. |
A ggplot2 object.
Other eventstudy-tasks:
IntradayEventStudyTask,
PanelEventStudyTask,
SyntheticControlTask,
estimate_panel_event_study(),
estimate_synthetic_control(),
nonparametric_intraday_test(),
plot_synthetic_control(),
prepare_intraday_event_study(),
sc_placebo_test()
Visualize the adjusted close prices or abnormal returns of selected stocks around a specified event date.
plot_stocks( task, target_variable = "firm_adjusted", add_event_date = FALSE, max_symbols = 6, sample_symbols = TRUE, do_sample = NULL )plot_stocks( task, target_variable = "firm_adjusted", add_event_date = FALSE, max_symbols = 6, sample_symbols = TRUE, do_sample = NULL )
task |
An EventStudyTask object. |
target_variable |
A character string specifying the target variable to plot. Default is "firm_adjusted". |
add_event_date |
Add vertical line for event date (TRUE/FALSE). |
max_symbols |
An integer specifying the maximum number of symbols to display. Default is 6. |
sample_symbols |
Logical; if |
do_sample |
Deprecated. Renamed to |
A plotly plot object.
Other eventstudy-plots:
es_colours,
plot_car_distribution(),
plot_diagnostics(),
plot_event_study(),
theme_eventstudy()
Create plots for synthetic control analysis: trajectory comparison, treatment effect gap, or placebo test results.
plot_synthetic_control(task, type = c("trajectory", "gap", "placebo"))plot_synthetic_control(task, type = c("trajectory", "gap", "placebo"))
task |
A |
type |
Plot type: |
A ggplot2 object.
Other eventstudy-tasks:
IntradayEventStudyTask,
PanelEventStudyTask,
SyntheticControlTask,
estimate_panel_event_study(),
estimate_synthetic_control(),
nonparametric_intraday_test(),
plot_panel_event_study(),
prepare_intraday_event_study(),
sc_placebo_test()
Perform return calculation for each stock and the corresponding reference market defined in the task and the parameter set.
prepare_event_study(task, parameter_set)prepare_event_study(task, parameter_set)
task |
An Event Study task. |
parameter_set |
A parameter set that defines the Event Study. |
The task object with returns and windows appended.
run_event_study, fit_model,
calculate_statistics
Other eventstudy-pipeline:
EventStudyTask,
ParameterSet,
calculate_statistics(),
fit_model(),
run_event_study()
Compute returns and assign estimation/event windows for intraday data. Windows are specified in number of observations (bars) rather than days.
prepare_intraday_event_study(task, parameter_set)prepare_intraday_event_study(task, parameter_set)
task |
An IntradayEventStudyTask. |
parameter_set |
A ParameterSet. |
The task with returns and windows appended.
Other eventstudy-tasks:
IntradayEventStudyTask,
PanelEventStudyTask,
SyntheticControlTask,
estimate_panel_event_study(),
estimate_synthetic_control(),
nonparametric_intraday_test(),
plot_panel_event_study(),
plot_synthetic_control(),
sc_placebo_test()
Performs a joint F-test of pre-event abnormal returns to assess whether there are statistically significant pre-event effects, which would indicate potential model misspecification or confounding.
pretrend_test(task, group = NULL)pretrend_test(task, group = NULL)
task |
A fitted EventStudyTask with abnormal returns computed. |
group |
Optional group to filter by. |
A tibble with pre-trend test results for each group.
Other eventstudy-statistics:
ARTTest,
BHARTTest,
BMPTest,
CARTTest,
CSectTTest,
CalendarTimePortfolioTest,
GeneralizedSignTest,
KolariPynnonenTest,
MultiEventStatisticsSet,
PatellZTest,
RankTest,
SignTest,
SingleEventStatisticsSet,
StatisticsSetBase,
TestStatisticBase,
adjust_p_values(),
bootstrap_test(),
car_by_group(),
car_quantiles(),
cross_sectional_regression(),
model_diagnostics(),
simulate_event_study(),
validate_task()
Prints a structured summary of the grounded AI advice, including source,
task type, grounding guard status, interpretation, recommendations with
evidence, and caveats. Follows the package convention of
print.es_advice (delegates to format.Advice, invisible
return).
## S3 method for class 'Advice' print(x, ...)## S3 method for class 'Advice' print(x, ...)
x |
An object of class |
... |
Additional arguments (ignored). |
Invisibly returns x.
Prints a structured summary of the offline advice, listing each matched rule
with its severity, citation key, and recommendation. Follows the package
convention of print.es_diagnostics and print.es_simulation
(delegates to format.es_advice, invisible return).
## S3 method for class 'es_advice' print(x, ...)## S3 method for class 'es_advice' print(x, ...)
x |
An object of class |
... |
Additional arguments (ignored). |
Invisibly returns x.
Print Cross-Sectional Regression Results
## S3 method for class 'es_cross_sectional' print(x, ...)## S3 method for class 'es_cross_sectional' print(x, ...)
x |
An |
... |
Additional arguments (unused). |
Prints a concise summary of the diagnostics, following the package
convention of print.es_simulation and print.es_cross_sectional.
## S3 method for class 'es_diagnostics' print(x, ...)## S3 method for class 'es_diagnostics' print(x, ...)
x |
An object of class |
... |
Additional arguments (ignored). |
Invisibly returns x.
Print method for EventStudySummary
## S3 method for class 'EventStudySummary' print(x, ...)## S3 method for class 'EventStudySummary' print(x, ...)
x |
An EventStudySummary object. |
... |
Additional arguments (unused). |
Convenience factory that resolves the backend by 3-tier precedence
(explicit type argument -> EVENTSTUDY_ADVISOR_PROVIDER env
selector -> default "custom") and constructs the matching provider
object. All three backends are wired: the in-process "custom" hook and
the HTTP "openai" (OpenAI-compatible) and "anthropic" (native
Anthropic Messages) providers.
provider(type = NULL, fn = NULL, model = NULL, base_url = NULL, ...)provider(type = NULL, fn = NULL, model = NULL, base_url = NULL, ...)
type |
Provider type, one of |
fn |
For |
model |
Optional character model identifier (resolved from
|
base_url |
Optional character base URL for HTTP providers (resolved from
|
... |
Additional arguments forwarded to the provider constructor. |
The "custom" branch needs no network and neither httr2 nor
jsonlite. Keys are never read here; the HTTP providers resolve them at
call time inside their own complete().
A ProviderBase subclass instance.
Other eventstudy-advisor:
AnthropicProvider,
CustomProvider,
OpenAICompatProvider,
ProviderBase,
es_advise(),
es_diagnostics(),
es_kb(),
flag_robustness(),
recommend_stat()
# Custom provider runs in-process, no network: p <- provider("custom", fn = function(prompt, schema) "advice text") p$complete("Summarise")$text ## Not run: # HTTP providers make live calls; never run in examples or on CRAN: p <- provider("openai", model = "gpt-4o") p$complete("Summarise these diagnostics") a <- provider("anthropic", model = "claude-opus-4-8") a$complete("Summarise these diagnostics") ## End(Not run)# Custom provider runs in-process, no network: p <- provider("custom", fn = function(prompt, schema) "advice text") p$complete("Summarise")$text ## Not run: # HTTP providers make live calls; never run in examples or on CRAN: p <- provider("openai", model = "gpt-4o") p$complete("Summarise these diagnostics") a <- provider("anthropic", model = "claude-opus-4-8") a$complete("Summarise these diagnostics") ## End(Not run)
Abstract base class for Grounded AI Advisor providers. Defines the uniform ‘complete(prompt, schema, ...)' contract, mirroring the package’s 'ModelBase' / 'TestStatisticBase' strategy-pattern idiom. Concrete providers ('CustomProvider', and the HTTP 'OpenAICompatProvider' / 'AnthropicProvider' delivered in later plans) inherit from this base and implement 'complete()'.
'ProviderBase' itself is abstract: calling 'complete()' on it errors. It stores only non-secret configuration ('model', 'base_url'); API keys are NEVER read at construction – they are resolved at call time inside each concrete provider's 'complete()'.
modelCharacter model identifier (or NULL for provider default).
base_urlCharacter base URL for HTTP providers (or NULL).
ProviderBase$new()Construct a provider. Stores non-secret config only; never reads or stores API keys (keys are resolved at call time).
ProviderBase$new(model = NULL, base_url = NULL, ...)
modelOptional character model identifier.
base_urlOptional character base URL (HTTP providers only).
...Ignored; accepted for subclass forward-compatibility.
ProviderBase$complete()Complete a prompt. Abstract on the base class – concrete providers override this.
ProviderBase$complete(prompt, schema = NULL, ...)
promptCharacter prompt to send to the provider.
schemaOptional structured-output schema (list) or NULL.
...Provider-specific arguments.
An 'es_provider_response' S3 list with fields:
source (character provider label),
is_deterministic (always FALSE for provider output),
text (character completion, or NA_character_ on failure),
error (NULL on success, character reason on failure).
These field names match the Phase 5 es_advice shape so the Phase 7
wrapper slots in trivially.
ProviderBase$clone()The objects of this class are cloneable with this method.
ProviderBase$clone(deep = FALSE)
deepWhether to make a deep clone.
Other eventstudy-advisor:
AnthropicProvider,
CustomProvider,
OpenAICompatProvider,
es_advise(),
es_diagnostics(),
es_kb(),
flag_robustness(),
provider(),
recommend_stat()
Non-parametric rank test for event studies. Ranks abnormal returns across the combined estimation and event windows, which is robust to non-normality of abnormal returns.
TestStatisticBase -> RankTest
nameShort code of the test statistic.
RankTest$compute()Computes the Corrado rank test for multiple events.
RankTest$compute(data_tbl, model)
data_tblThe data for a multiple event with calculated abnormal returns.
modelThe fitted model (unused).
RankTest$clone()The objects of this class are cloneable with this method.
RankTest$clone(deep = FALSE)
deepWhether to make a deep clone.
Other eventstudy-statistics:
ARTTest,
BHARTTest,
BMPTest,
CARTTest,
CSectTTest,
CalendarTimePortfolioTest,
GeneralizedSignTest,
KolariPynnonenTest,
MultiEventStatisticsSet,
PatellZTest,
SignTest,
SingleEventStatisticsSet,
StatisticsSetBase,
TestStatisticBase,
adjust_p_values(),
bootstrap_test(),
car_by_group(),
car_quantiles(),
cross_sectional_regression(),
model_diagnostics(),
pretrend_test(),
simulate_event_study(),
validate_task()
Evaluates the KB decision table (category "stat_choice" rules) against
the diagnostic signals extracted from a fitted EventStudyTask or a
precomputed es_diagnostics object, and returns a severity-ranked
es_advice S3 object.
recommend_stat(x, provider = NULL, ...) ## Default S3 method: recommend_stat(x, provider = NULL, ...) ## S3 method for class 'EventStudyTask' recommend_stat(x, provider = NULL, ...) ## S3 method for class 'es_diagnostics' recommend_stat(x, provider = NULL, ...)recommend_stat(x, provider = NULL, ...) ## Default S3 method: recommend_stat(x, provider = NULL, ...) ## S3 method for class 'EventStudyTask' recommend_stat(x, provider = NULL, ...) ## S3 method for class 'es_diagnostics' recommend_stat(x, provider = NULL, ...)
x |
A fitted |
provider |
Accepted but ignored in the offline path – present only so
the Phase 7 call shape is forward-compatible. Default |
... |
Additional arguments (currently ignored). |
No LLM provider, network connection, or API key is required. Both functions
are the always-available offline grounding layer (ADV-08). The returned
es_advice object has the same shape as the Phase 7 Advice contract,
flagged is_deterministic = TRUE and source = "offline_kb".
An S3 object of class "es_advice" – a named list with:
source"offline_kb" (character).
is_deterministicTRUE – advice is rule-based, not LLM-generated.
rules_matchedNamed list of matched rule records (severity-ranked:
"error" first, then "warning", then "info"), each with
fields id, recommendation, citation (list of
author/year/key/venue), severity,
category.
diagnostics_refThe es_diagnostics list that was evaluated
(possibly computed on-the-fly from the task).
flag_robustness, es_diagnostics,
es_kb
Other eventstudy-advisor:
AnthropicProvider,
CustomProvider,
OpenAICompatProvider,
ProviderBase,
es_advise(),
es_diagnostics(),
es_kb(),
flag_robustness(),
provider()
data(dieselgate) task <- EventStudyTask$new(dieselgate$firm, dieselgate$index, dieselgate$request) task <- run_event_study(task, ParameterSet$new()) advice <- recommend_stat(task) print(advice)data(dieselgate) task <- EventStudyTask$new(dieselgate$firm, dieselgate$index, dieselgate$request) task <- run_event_study(task, ParameterSet$new()) advice <- recommend_stat(task) print(advice)
Internal rendering helper used by the event study report skeleton and
es_report(). Exported so inst/rmarkdown/ templates can call
it without :::.
report_table(x, caption = NULL, col.names = NULL, digits = NULL)report_table(x, caption = NULL, col.names = NULL, digits = NULL)
x |
A data frame to render. |
caption |
Optional character scalar caption, or |
col.names |
Optional character vector of display column names, or
|
digits |
Optional integer digit count, or |
When tinytable is available (see .tinytable_available()),
renders via tinytable::tt() with a bold header, auto-aligned columns,
and optional digit rounding. Falls back to knitr::kable() when
tinytable is absent – byte-identical to the prior scattered
knitr::kable() call sites.
invisible(NULL). Side-effect: prints the table via
knit_print.
Base (abstract) class for return calculation strategies.
Subclass this to plug a custom return calculation into
prepare_event_study() / EventStudyTask$new() via
ParameterSet$return_calculation.
A subclass must implement calculate_return(tbl, in_column, out_column):
given a tibble of prices in in_column, add a column named
out_column with the calculated return (e.g. simple or log return).
See SimpleReturn and LogReturn for reference implementations.
nameName of the return calculation.
ReturnCalculation$calculate_return()Calculates the return for a single stock.
ReturnCalculation$calculate_return( tbl, in_column = "adjusted", out_column = "adjusted_return" )
tblThe dataframe with the stock price.
in_columnThe column name of the price infromation.
out_columnThe column name were the return will be saved.
ReturnCalculation$clone()The objects of this class are cloneable with this method.
ReturnCalculation$clone(deep = FALSE)
deepWhether to make a deep clone.
Other eventstudy-models:
BHARModel,
Carhart4FactorModel,
ComparisonPeriodMeanAdjustedModel,
DCCGARCHModel,
FamaFrench3FactorModel,
FamaFrench5FactorModel,
GARCHModel,
LinearFactorModel,
LogReturn,
MarketAdjustedModel,
MarketModel,
ModelBase,
RollingWindowModel,
SimpleReturn,
VolatilityModel,
VolumeModel
Event study model with time-varying parameters estimated via a rolling OLS window over the estimation period. The last rolling window's parameters are used for event-window prediction. This captures parameter instability that is common in financial return data.
ModelBase -> RollingWindowModel
model_nameName of the model.
window_sizeRolling window size. Default 60.
min_obsMinimum observations required. Default 30.
RollingWindowModel$new()Create a new RollingWindowModel.
RollingWindowModel$new(window_size = 60L, min_obs = 30L)
window_sizeSize of the rolling window.
min_obsMinimum valid (complete-pair) observations
required inside each individual rolling sub-window for that
sub-window to be fit. Distinct from validate_task()'s
min_estimation_obs, which is a whole-estimation-window
advisory threshold checked once per event, not per sub-window.
RollingWindowModel$fit()Fit the rolling window model on the estimation window.
RollingWindowModel$fit(data_tbl)
data_tblData frame or tibble with firm_returns, index_returns, estimation_window, event_window columns.
RollingWindowModel$abnormal_returns()Calculate abnormal returns using the last rolling window parameters.
RollingWindowModel$abnormal_returns(data_tbl)
data_tblData frame or tibble.
RollingWindowModel$clone()The objects of this class are cloneable with this method.
RollingWindowModel$clone(deep = FALSE)
deepWhether to make a deep clone.
Other eventstudy-models:
BHARModel,
Carhart4FactorModel,
ComparisonPeriodMeanAdjustedModel,
DCCGARCHModel,
FamaFrench3FactorModel,
FamaFrench5FactorModel,
GARCHModel,
LinearFactorModel,
LogReturn,
MarketAdjustedModel,
MarketModel,
ModelBase,
ReturnCalculation,
SimpleReturn,
VolatilityModel,
VolumeModel
Convenience wrapper that runs the full event study pipeline: prepare data, fit models, and calculate test statistics in a single call.
run_event_study( task, parameter_set = ParameterSet$new(), report = FALSE, report_args = list(), verbose = getOption("eventstudy.verbose", TRUE) )run_event_study( task, parameter_set = ParameterSet$new(), report = FALSE, report_args = list(), verbose = getOption("eventstudy.verbose", TRUE) )
task |
An EventStudyTask object. |
parameter_set |
A ParameterSet object defining the event study. Defaults to a new ParameterSet with default settings. |
report |
Logical. When |
report_args |
Named list forwarded to |
verbose |
Logical; if FALSE, suppress informational messages. Default
|
The task object with all results computed. When report = TRUE,
the returned task additionally carries attr(task, "report_path")
with the path(s) of the rendered report file(s). The return type is always
a fitted EventStudyTask in both paths.
prepare_event_study, fit_model,
calculate_statistics, MarketModel,
ARTTest
Other eventstudy-pipeline:
EventStudyTask,
ParameterSet,
calculate_statistics(),
fit_model(),
prepare_event_study()
data(dieselgate) task <- EventStudyTask$new(dieselgate$firm, dieselgate$index, dieselgate$request) # Run the pipeline and render a report to a temporary directory out <- file.path(tempdir(), "event_study_report.html") task <- run_event_study(task, ParameterSet$new(), report = TRUE, report_args = list(output_file = out)) attr(task, "report_path") # path to the rendered HTMLdata(dieselgate) task <- EventStudyTask$new(dieselgate$firm, dieselgate$index, dieselgate$request) # Run the pipeline and render a report to a temporary directory out <- file.path(tempdir(), "event_study_report.html") task <- run_event_study(task, ParameterSet$new(), report = TRUE, report_args = list(output_file = out)) attr(task, "report_path") # path to the rendered HTML
Performs a placebo (permutation) test by re-estimating the synthetic control for each donor unit as a pseudo-treated unit. The p-value is the rank of the treated unit's RMSPE ratio among all units.
sc_placebo_test(task, n_placebo = NULL)sc_placebo_test(task, n_placebo = NULL)
task |
A |
n_placebo |
Number of placebo units to use. Default NULL (all donors). |
The task with results$placebo populated, a list containing
rmspe_ratios, p_value, and placebo_gaps.
Other eventstudy-tasks:
IntradayEventStudyTask,
PanelEventStudyTask,
SyntheticControlTask,
estimate_panel_event_study(),
estimate_synthetic_control(),
nonparametric_intraday_test(),
plot_panel_event_study(),
plot_synthetic_control(),
prepare_intraday_event_study()
Tests whether the proportion of positive abnormal returns differs significantly from 0.5 under the null hypothesis. The test statistic is approximately distributed as N(0, 1).
TestStatisticBase -> SignTest
nameShort code of the test statistic.
SignTest$compute()Computes the sign test for multiple events.
SignTest$compute(data_tbl, model)
data_tblThe data for a multiple event with calculated abnormal returns.
modelThe fitted model (unused).
SignTest$clone()The objects of this class are cloneable with this method.
SignTest$clone(deep = FALSE)
deepWhether to make a deep clone.
Other eventstudy-statistics:
ARTTest,
BHARTTest,
BMPTest,
CARTTest,
CSectTTest,
CalendarTimePortfolioTest,
GeneralizedSignTest,
KolariPynnonenTest,
MultiEventStatisticsSet,
PatellZTest,
RankTest,
SingleEventStatisticsSet,
StatisticsSetBase,
TestStatisticBase,
adjust_p_values(),
bootstrap_test(),
car_by_group(),
car_quantiles(),
cross_sectional_regression(),
model_diagnostics(),
pretrend_test(),
simulate_event_study(),
validate_task()
R6 class for simple return calculation
ReturnCalculation -> SimpleReturn
nameName of the return calculation.
SimpleReturn$calculate_return()Calculates the simple return for a single stock.
SimpleReturn$calculate_return( tbl, in_column = "adjusted", out_column = "adjusted_return" )
tblThe dataframe with the stock price.
in_columnThe column name of the price infromation.
out_columnThe column name were the return will be saved.
SimpleReturn$clone()The objects of this class are cloneable with this method.
SimpleReturn$clone(deep = FALSE)
deepWhether to make a deep clone.
Other eventstudy-models:
BHARModel,
Carhart4FactorModel,
ComparisonPeriodMeanAdjustedModel,
DCCGARCHModel,
FamaFrench3FactorModel,
FamaFrench5FactorModel,
GARCHModel,
LinearFactorModel,
LogReturn,
MarketAdjustedModel,
MarketModel,
ModelBase,
ReturnCalculation,
RollingWindowModel,
VolatilityModel,
VolumeModel
Runs Monte Carlo simulations to estimate the statistical power (rejection rate) of an event study design. Each simulation generates synthetic data from a user-specified DGP, runs the full event study pipeline, and records whether the null hypothesis is rejected.
simulate_event_study( n_events = 20, event_window = c(-5, 5), estimation_window_length = 120, abnormal_return = 0, return_model = MarketModel$new(), test_statistic = "CSectT", alpha = 0.05, n_simulations = 1000, dgp_params = list(), seed = NULL )simulate_event_study( n_events = 20, event_window = c(-5, 5), estimation_window_length = 120, abnormal_return = 0, return_model = MarketModel$new(), test_statistic = "CSectT", alpha = 0.05, n_simulations = 1000, dgp_params = list(), seed = NULL )
n_events |
Number of events (firms) per simulation. Default 20. |
event_window |
Event window as |
estimation_window_length |
Length of the estimation window. Default 120. |
abnormal_return |
Injected abnormal return on the event day (day 0). Set to 0 for size analysis, positive for power analysis. Default 0. |
return_model |
An initialized return model object. Default |
test_statistic |
Name of the multi-event test statistic to evaluate.
Default |
alpha |
Significance level. Default 0.05. |
n_simulations |
Number of Monte Carlo replications. Default 1000. |
dgp_params |
List of DGP parameters: |
seed |
Optional seed for reproducibility. |
An S3 object of class es_simulation with components:
Rejection rate at the event day
Tibble of rejection rates for each event-window day
Vector of test statistics at the event day from each sim
List of simulation parameters
Other eventstudy-statistics:
ARTTest,
BHARTTest,
BMPTest,
CARTTest,
CSectTTest,
CalendarTimePortfolioTest,
GeneralizedSignTest,
KolariPynnonenTest,
MultiEventStatisticsSet,
PatellZTest,
RankTest,
SignTest,
SingleEventStatisticsSet,
StatisticsSetBase,
TestStatisticBase,
adjust_p_values(),
bootstrap_test(),
car_by_group(),
car_quantiles(),
cross_sectional_regression(),
model_diagnostics(),
pretrend_test(),
validate_task()
Contains a set of single event test statistics as, e.g., AR and CAR t test. These are the default test statistics.
StatisticsSetBase -> SingleEventStatisticsSet
testsContainer with the statistical tests.
SingleEventStatisticsSet$clone()The objects of this class are cloneable with this method.
SingleEventStatisticsSet$clone(deep = FALSE)
deepWhether to make a deep clone.
Other eventstudy-statistics:
ARTTest,
BHARTTest,
BMPTest,
CARTTest,
CSectTTest,
CalendarTimePortfolioTest,
GeneralizedSignTest,
KolariPynnonenTest,
MultiEventStatisticsSet,
PatellZTest,
RankTest,
SignTest,
StatisticsSetBase,
TestStatisticBase,
adjust_p_values(),
bootstrap_test(),
car_by_group(),
car_quantiles(),
cross_sectional_regression(),
model_diagnostics(),
pretrend_test(),
simulate_event_study(),
validate_task()
Base class for test statistic container
testsContainer with the statistical tests. Test container initialization
StatisticsSetBase$new()Initializes a test statistic container. Single event and multiple event test statistics are collected in separated containers.
StatisticsSetBase$new(tests = NULL)
testsList of test statistics.
StatisticsSetBase$add_test()StatisticsSetBase$add_test(test)
testA single event study tests.
StatisticsSetBase$clone()The objects of this class are cloneable with this method.
StatisticsSetBase$clone(deep = FALSE)
deepWhether to make a deep clone.
Other eventstudy-statistics:
ARTTest,
BHARTTest,
BMPTest,
CARTTest,
CSectTTest,
CalendarTimePortfolioTest,
GeneralizedSignTest,
KolariPynnonenTest,
MultiEventStatisticsSet,
PatellZTest,
RankTest,
SignTest,
SingleEventStatisticsSet,
TestStatisticBase,
adjust_p_values(),
bootstrap_test(),
car_by_group(),
car_quantiles(),
cross_sectional_regression(),
model_diagnostics(),
pretrend_test(),
simulate_event_study(),
validate_task()
Task container for synthetic control analysis. Holds treated unit data, donor pool data, treatment time, and results after estimation.
treated_dataTibble with time and outcome columns
for the treated unit.
donor_dataTibble in long format with unit, time,
and outcome columns for donor units.
treatment_timeThe time period when treatment begins.
resultsEstimation results (populated after estimation).
SyntheticControlTask$new()Create a new SyntheticControlTask.
SyntheticControlTask$new(treated_data, donor_data, treatment_time)
treated_dataTibble with time and outcome.
donor_dataLong-format tibble with unit, time,
outcome.
treatment_timePeriod when treatment begins.
SyntheticControlTask$print()Print summary.
SyntheticControlTask$print(...)
SyntheticControlTask$clone()The objects of this class are cloneable with this method.
SyntheticControlTask$clone(deep = FALSE)
deepWhether to make a deep clone.
Other eventstudy-tasks:
IntradayEventStudyTask,
PanelEventStudyTask,
estimate_panel_event_study(),
estimate_synthetic_control(),
nonparametric_intraday_test(),
plot_panel_event_study(),
plot_synthetic_control(),
prepare_intraday_event_study(),
sc_placebo_test()
Base (abstract) class for single-event and multi-event test
statistics. Subclass this to plug a custom test statistic into
calculate_statistics() / run_event_study().
A subclass must implement compute(data_tbl, model):
data_tbl – a single event's rows with an
abnormal_returns column already populated by the fitted model.
model – the fitted ModelBase (or list-mock)
instance for that event; its statistics field carries
sigma, degree_of_freedom, residuals and (since
2026-09-24) n_params.
compute() returns a tibble with the statistic's result columns for
that event; multi-event subclasses (see R/multi_event_test_statistics.R)
aggregate across all events in a group.
confidence_level and confidence_type are validated and
stored at construction (confidence_type must be one of
"two-sided" (default), "less" or "greater"); every
p-value computed anywhere in EventStudy is currently two-sided, so a
non-default confidence_type is accepted but ignored, with one
warning at construction (A10, 2026-09-24).
nameShort code of the test statistic.
confidence_levelThe chosen confidence level.
confidence_typeSide of the test. One of
"two-sided" (default), "less" or
"greater". A10 (2026-09-24): every p-value
computed anywhere in EventStudy is currently
two-sided; a non-default value is validated but
has NO effect on any computed statistic – it is
stored and a one-time warning is emitted at
construction. One-sided p-values are not
implemented.
TestStatisticBase$new()Initializes the test statistic. This includes the confidence level and the type of the test ('less', greater' or 'two-sided')
TestStatisticBase$new(confidence_level = 0.95, confidence_type = "two-sided")
confidence_levelThe confidence level for the confidence band. Must be anumber between 0 and 1.
confidence_typeSide of the test statistic:
"two-sided" (default), "less" or
"greater". Every p-value in EventStudy is
currently two-sided; supplying "less" or
"greater" emits one warning that the value
is stored but ignored by every compute() method.
TestStatisticBase$compute()Computes the test test statistics for a single event.
TestStatisticBase$compute(data_tbl, model)
data_tblThe data for a single event with calculated abnormal returns.
modelThe fitted model that includes the necessary information for calculating the test statistic.
TestStatisticBase$clone()The objects of this class are cloneable with this method.
TestStatisticBase$clone(deep = FALSE)
deepWhether to make a deep clone.
Other eventstudy-statistics:
ARTTest,
BHARTTest,
BMPTest,
CARTTest,
CSectTTest,
CalendarTimePortfolioTest,
GeneralizedSignTest,
KolariPynnonenTest,
MultiEventStatisticsSet,
PatellZTest,
RankTest,
SignTest,
SingleEventStatisticsSet,
StatisticsSetBase,
adjust_p_values(),
bootstrap_test(),
car_by_group(),
car_quantiles(),
cross_sectional_regression(),
model_diagnostics(),
pretrend_test(),
simulate_event_study(),
validate_task()
A clean, publication-ready ggplot2 theme for EventStudy plots. Built on
theme_minimal with a centred plot title, a bottom
legend, and subtle gridlines styled to the EventStudy palette.
theme_eventstudy(base_size = 11, base_family = "")theme_eventstudy(base_size = 11, base_family = "")
base_size |
Base font size in points. Default is 11. |
base_family |
Base font family. Default |
A theme object that composes with +.
Other eventstudy-plots:
es_colours,
plot_car_distribution(),
plot_diagnostics(),
plot_event_study(),
plot_stocks()
Extract event study results in a tidy (long-format) tibble compatible with broom conventions. This enables integration with standard tidyverse workflows.
tidy.EventStudyTask( x, type = c("ar", "car", "aar", "model"), stat_name = "CSectT", ... )tidy.EventStudyTask( x, type = c("ar", "car", "aar", "model"), stat_name = "CSectT", ... )
x |
An EventStudyTask object. |
type |
Type of results to extract: "ar" (abnormal returns), "car" (cumulative abnormal returns), "aar" (average abnormal returns with test statistics), or "model" (model fit statistics). |
stat_name |
For type "aar", the name of the multi-event test statistic. Defaults to "CSectT". |
... |
Additional arguments (unused). |
A tibble with columns following broom conventions:
Identifier for the observation (e.g., relative_index)
The estimated value (AR, CAR, AAR, or coefficient)
Standard error where available
Test statistic value
p-value where available
Other eventstudy-export:
es_report(),
export_results(),
generate_report()
Performs validation checks on the event study task: 1. Does the event date exist in the stock data for each event? 2. Are there sufficient observations in the estimation window? 3. Are there any gaps in the time series? 4. Do estimation and event windows overlap?
validate_task( task, parameter_set = NULL, min_estimation_obs = 30, verbose = getOption("eventstudy.verbose", TRUE) )validate_task( task, parameter_set = NULL, min_estimation_obs = 30, verbose = getOption("eventstudy.verbose", TRUE) )
task |
The event study task. |
parameter_set |
The parameter set that defines the event study. |
min_estimation_obs |
Minimum number of observations required in the
whole per-event estimation window (a task-level validation
threshold checked once per event). Default is 30. Distinct from
|
verbose |
Logical; if FALSE, suppress informational messages. Default
|
The task object (invisibly). Warnings are issued for each problem found.
Other eventstudy-statistics:
ARTTest,
BHARTTest,
BMPTest,
CARTTest,
CSectTTest,
CalendarTimePortfolioTest,
GeneralizedSignTest,
KolariPynnonenTest,
MultiEventStatisticsSet,
PatellZTest,
RankTest,
SignTest,
SingleEventStatisticsSet,
StatisticsSetBase,
TestStatisticBase,
adjust_p_values(),
bootstrap_test(),
car_by_group(),
car_quantiles(),
cross_sectional_regression(),
model_diagnostics(),
pretrend_test(),
simulate_event_study()
Model for volatility-based event studies. Computes abnormal volatility
as the ratio of event-window squared returns to estimation-window variance.
The abnormal measure is written to the abnormal_returns column
for compatibility with existing test statistics.
ModelBase -> VolatilityModel
model_nameName of the model.
VolatilityModel$fit()Fit the volatility model. Estimates expected variance from estimation window.
VolatilityModel$fit(data_tbl)
data_tblData frame or tibble.
VolatilityModel$abnormal_returns()Calculate abnormal volatility (squared returns / expected variance - 1).
VolatilityModel$abnormal_returns(data_tbl)
data_tblData frame or tibble.
VolatilityModel$clone()The objects of this class are cloneable with this method.
VolatilityModel$clone(deep = FALSE)
deepWhether to make a deep clone.
Other eventstudy-models:
BHARModel,
Carhart4FactorModel,
ComparisonPeriodMeanAdjustedModel,
DCCGARCHModel,
FamaFrench3FactorModel,
FamaFrench5FactorModel,
GARCHModel,
LinearFactorModel,
LogReturn,
MarketAdjustedModel,
MarketModel,
ModelBase,
ReturnCalculation,
RollingWindowModel,
SimpleReturn,
VolumeModel
Model for volume-based event studies. Computes abnormal volume as the
difference between observed volume and expected volume from the estimation
window mean. The data must contain a firm_volume column (and
optionally index_volume for market-adjusted volume).
The existing test statistics infrastructure works on the
abnormal_returns column, so this model writes abnormal volume
to that same column for compatibility.
ModelBase -> VolumeModel
model_nameName of the model.
log_transformWhether to log-transform volume. Default TRUE.
VolumeModel$new()Create a new VolumeModel.
VolumeModel$new(log_transform = TRUE)
log_transformWhether to log-transform volume before analysis.
VolumeModel$fit()Fit the volume model. Computes expected volume from estimation window.
VolumeModel$fit(data_tbl)
data_tblData frame or tibble with firm_volume column.
VolumeModel$abnormal_returns()Calculate abnormal volume.
VolumeModel$abnormal_returns(data_tbl)
data_tblData frame or tibble.
VolumeModel$clone()The objects of this class are cloneable with this method.
VolumeModel$clone(deep = FALSE)
deepWhether to make a deep clone.
Other eventstudy-models:
BHARModel,
Carhart4FactorModel,
ComparisonPeriodMeanAdjustedModel,
DCCGARCHModel,
FamaFrench3FactorModel,
FamaFrench5FactorModel,
GARCHModel,
LinearFactorModel,
LogReturn,
MarketAdjustedModel,
MarketModel,
ModelBase,
ReturnCalculation,
RollingWindowModel,
SimpleReturn,
VolatilityModel