Event studies constitute one of the most enduring and widely deployed empirical methodologies in financial economics. At their core, event studies measure the impact of a specific event on the value of a firm by examining abnormal security returns around the time the event occurs. The methodology rests on a simple premise: if capital markets are informationally efficient, the effect of an event will be reflected immediately in security prices, and any deviation from “normal” expected returns can be attributed to the event itself.
Since the pioneering work of Eugene F. Fama et al. (1969), who studied how stock prices adjust to new information around stock splits, event studies have become a cornerstone of empirical research across finance, accounting, economics, and law. Ball and Brown (2013) demonstrated that accounting earnings announcements convey information to the market, a finding that launched decades of research in accounting and disclosure. The methodology has since been refined through contributions by Brown and Warner (1980) and Brown and Warner (1985), who established the statistical properties of event study methods, and MacKinlay (1997) codified best practices that remain standard today.
The enduring popularity of event studies stems from several compelling properties:
Direct measurement of economic significance. Unlike regression-based approaches that estimate associations, event studies directly quantify the dollar impact of events on firm value. A cumulative abnormal return (CAR) of 3% for a firm with $10 billion market capitalization translates to $300 million in wealth creation, which is a tangible, economically meaningful magnitude.
Minimal maintained assumptions. The methodology requires only semi-strong market efficiency (i.e., prices reflect publicly available information), a weaker assumption than many alternatives.
Statistical power. Daily event studies have remarkable power to detect abnormal performance, even with modest sample sizes. Brown and Warner (1985) demonstrated that the market model detects abnormal returns of 1% or more with high reliability using samples as small as 20 securities.
Versatility. The basic framework accommodates events that are firm-specific or market-wide, anticipated or surprising, and can be adapted to various asset classes and market structures.
41.1 Literature Review and Methodological Evolution
41.1.1 The Classical Framework (1969-1985)
The modern event study traces its origins to Eugene F. Fama et al. (1969), hereafter FFJR, who examined monthly stock returns around 940 stock splits between 1927 and 1959. Their key innovation was the use of the market model to decompose returns into expected (normal) and unexpected (abnormal) components.
Ball and Brown (2013) independently developed a similar approach to study earnings announcements, establishing the information content of accounting data. It was a finding with profound implications for both the efficient markets hypothesis and the relevance of financial reporting.
Brown and Warner (1980) provided the first systematic analysis of event study methodology using simulation. Their study of monthly data established several important results: (i) the simple market model performs at least as well as more complex models, (ii) value-weighted market indices can lead to misspecification when the sample is tilted toward smaller firms, and (iii) the standard cross-sectional test has well-specified size under the null hypothesis. Their follow-up study (Brown and Warner 1985) extended the analysis to daily data, documenting the importance of non-normality in daily returns and the increased power of daily versus monthly studies.
41.1.2 Risk Model Refinements (1992-2015)
The advent of the Fama-French three-factor model(Eugene F. Fama and French 1993) represented a major advance in modeling expected returns. Adding size (SMB) and value (HML) factors to the market model improved the cross-sectional fit of expected returns considerably. Carhart (1997) augmented this with a momentum factor (UMD), yielding the four-factor model that became standard in event studies through the 2000s. Eugene F. Fama and French (2015) subsequently introduced profitability (RMW) and investment (CMA) factors in their five-factor model.
The choice of risk model matters for event studies primarily in long-horizon settings. Kothari and Warner (2007) showed that for short-window studies (3-5 days), the market model and multi-factor models produce virtually identical results because the incremental factors explain very little daily return variation for individual firms. However, for event windows exceeding 20 trading days, model choice can materially affect inferences.
41.1.3 Testing for Abnormal Returns (1976-2010)
The statistical testing of abnormal returns has evolved considerably:
Table 41.1: Summary of major event study test statistics
Test
Year
Key Property
Reference
Patell Z
1976
Standardizes by estimation-period \(\sigma\); weights firms inversely by volatility
Cumulative abnormal returns (CARs) sum daily abnormal returns, while buy-and-hold abnormal returns (BHARs) compound returns and subtract the compounded benchmark. Barber and Lyon (1997) demonstrated that BHARs better capture the actual investor experience, since investors earn compound, not cumulative, returns. However, Eugene F. Fama (1998) and Mitchell and Stafford (2000) showed that BHARs exhibit severe cross-sectional dependence and positive skewness. For short event windows (under 10 days), the difference between CARs and BHARs is negligible. For longer windows, both should be reported.
41.1.5 Emerging Market Considerations
Event studies in emerging markets face distinct challenges:
Thin trading. Many emerging market securities trade infrequently, inducing bias in market model beta estimates. Scholes and Williams (1977) and Dimson (1979) proposed corrections using leading and lagging market returns.
Factor availability. While Fama-French factors are readily available for developed markets, emerging market factors must often be constructed locally.
Market microstructure. Price limits (\(\pm\) 7% on HOSE, \(\pm\) 10% on HNX, \(\pm\) 15% on UPCOM in Vietnam), T+2 settlement, and the absence of short-selling affect the speed of price adjustment. Researchers should consider wider event windows to accommodate slower information incorporation (Bhattacharya et al. 2000; Griffin, Kelly, and Nardari 2010).
41.2 Mathematical Framework
This section presents the complete mathematical specification of the event study methodology. We follow the notation conventions of Campbell et al. (1998) and Kothari and Warner (2007).
41.2.1 Timeline and Windows
The event study timeline is defined relative to the event date, denoted \(\tau = 0\). All dates are measured in trading days:
Estimation window: \(L_1\) trading days over which the risk model parameters are estimated
Gap: \(G\) trading days separating estimation and event windows, preventing contamination by pre-event information leakage
Event window: \(L_2 = \tau_2 - \tau_1 + 1\) trading days centered around the event date
For example, with \(L_1 = 150\), \(G = 15\), \(\tau_1 = -10\), \(\tau_2 = +10\): the estimation window covers trading days \([-175, -25]\) relative to the event, and the event window covers \([-10, +10]\).
41.2.2 Normal Return Models
Let \(R_{it}\) denote the return on security \(i\) on trading day \(t\), \(R_{ft}\) the risk-free rate, and \(R_{mt}\) the market return. We implement six models:
Model 0: Market-Adjusted Returns. Assumes \(\beta_i = 1\) and \(\alpha_i = 0\) for all firms:
class RiskModel(Enum):"""Supported risk models for expected return computation.""" MARKET_ADJ ="market_adjusted" MARKET_MODEL ="market_model" FF3 ="ff3" CARHART ="carhart" FF5 ="ff5" CUSTOM ="custom"@dataclassclass EventStudyConfig:"""Complete configuration for an event study. Attributes ---------- estimation_window : int Length of estimation period in trading days. Brown and Warner (1985) suggest ≥100 days; MacKinlay (1997) recommends 120 as standard. event_window_start : int Start of event window relative to event date (e.g., -10). event_window_end : int End of event window relative to event date (e.g., +10). gap : int Trading days between estimation and event windows. Prevents contamination from pre-event information leakage. min_estimation_obs : int Minimum non-missing returns required in estimation period. risk_model : RiskModel Risk model for computing expected returns. custom_factors : list Column names for user-specified factors (CUSTOM model only). thin_trading_adj : str or None None, 'scholes_williams', or 'dimson'. dimson_lags : int Number of leads/lags for Dimson (1979) correction. """ estimation_window: int=150 event_window_start: int=-10 event_window_end: int=10 gap: int=15 min_estimation_obs: int=120 risk_model: RiskModel = RiskModel.MARKET_MODEL custom_factors: List[str] = field(default_factory=list) thin_trading_adj: Optional[str] =None dimson_lags: int=1@propertydef event_window_length(self) ->int:returnself.event_window_end -self.event_window_start +1def validate(self):assertself.estimation_window >0assertself.event_window_start <=self.event_window_endassertself.gap >=0assertself.min_estimation_obs <=self.estimation_windowifself.risk_model == RiskModel.CUSTOM:assertlen(self.custom_factors) >0returnTrue# Demonstrateconfig_demo = EventStudyConfig( estimation_window=150, event_window_start=-10, event_window_end=10, gap=15, min_estimation_obs=120, risk_model=RiskModel.FF3)config_demo.validate()print(f"Event window length: {config_demo.event_window_length} days")print(f"Model: {config_demo.risk_model.value}")
Event window length: 21 days
Model: ff3
41.3.4 Step 1: Trading Calendar Construction
A correct trading calendar is fundamental. It maps any event date to the exact calendar dates for the start/end of estimation and event windows, accounting for weekends, holidays, and non-trading days.
Build trading calendar
def build_trading_calendar(trading_dates, config):"""Build a trading calendar mapping event dates to window boundaries. For each potential event date, identifies the calendar dates for the start/end of the estimation period and event window using only actual trading days. Parameters ---------- trading_dates : array-like Sorted unique trading dates in the market. config : EventStudyConfig Returns ------- pd.DataFrame with columns: estper_beg, estper_end, evtwin_beg, evtdate, evtwin_end, cal_index """ dates = pd.Series(sorted(pd.to_datetime(trading_dates).unique())) n =len(dates) L1 = config.estimation_window G = config.gap s = config.event_window_start L2 = config.event_window_length# Offsets (FIRSTOBS logic) o0 =0# estper_beg o1 = L1 -1# estper_end o2 = L1 + G # evtwin_beg o3 = L1 + G - s # evtdate o4 = L1 + G + L2 -1# evtwin_end max_offset = o4 valid = n - max_offsetif valid <=0:raiseValueError(f"Need ≥{max_offset+1} trading dates, have {n}") cal = pd.DataFrame({'estper_beg': dates.iloc[o0:o0+valid].values,'estper_end': dates.iloc[o1:o1+valid].values,'evtwin_beg': dates.iloc[o2:o2+valid].values,'evtdate': dates.iloc[o3:o3+valid].values,'evtwin_end': dates.iloc[o4:o4+valid].values, }) cal['cal_index'] =range(1, len(cal)+1)# Validate window lengths using a sample row idx =min(10, len(cal)-1) row = cal.iloc[idx] est_n = dates[(dates >= row['estper_beg']) & (dates <= row['estper_end'])].shape[0] evt_n = dates[(dates >= row['evtwin_beg']) & (dates <= row['evtwin_end'])].shape[0]assert est_n == L1, f"Estimation window: {est_n} ≠ {L1}"assert evt_n == L2, f"Event window: {evt_n} ≠ {L2}"return cal# Demodemo_dates = pd.bdate_range('2018-01-01', '2023-12-31', freq='B')demo_cal = build_trading_calendar(demo_dates, config_demo)print(f"Calendar: {len(demo_cal)} potential event dates")print(demo_cal.head(3).to_string(index=False))
def run_event_study(events, prices, factors, config, id_col='symbol', date_col='date', ret_col='ret', event_date_col='event_date', mkt_col='mkt_excess', rf_col='risk_free', group_col=None, verbose=True):"""Run a complete event study from raw inputs to test statistics. This is the main entry point. Provide your events, price data, factor data, and configuration—get back everything you need. Parameters ---------- events : pd.DataFrame Columns: [id_col, event_date_col], optional 'group'. prices : pd.DataFrame Daily returns: [id_col, date_col, ret_col or 'ret_excess', rf_col]. factors : pd.DataFrame Factor returns: [date_col, mkt_col, 'smb', 'hml', ...]. config : EventStudyConfig Returns ------- dict with keys: 'config', 'daily_ar', 'event_ar', 'daily_stats', 'test_stats', 'params' """ config.validate()if verbose:print(f"═══ Event Study: {config.risk_model.value} model ═══")print(f" Windows: estimation={config.estimation_window}, "f"gap={config.gap}, event=({config.event_window_start},{config.event_window_end})")print(f" Min obs: {config.min_estimation_obs}\n")# 1. Trading calendarif verbose: print("Step 1: Building trading calendar...") trading_dates = pd.Series(sorted(prices[date_col].unique())) calendar = build_trading_calendar(trading_dates, config)if verbose: print(f" {len(calendar)} potential event dates\n")# 2. Align eventsif verbose: print("Step 2: Aligning events to trading calendar...") aligned = align_events(events, calendar, id_col, event_date_col)if verbose: print(f" {len(aligned)} aligned events\n")# 3. Extract returnsif verbose: print("Step 3: Extracting returns and merging factors...") evt_rets = extract_returns(aligned, prices, factors, config, id_col, date_col, ret_col, mkt_col, rf_col)if verbose: print()# 4. Estimate modelif verbose: print("Step 4: Estimating risk model parameters...") params = estimate_model(evt_rets, config, id_col, date_col, ret_col)if verbose: print()# 5. Compute abnormal returnsif verbose: print("Step 5: Computing abnormal returns...") daily_ar, event_ar = compute_abnormal_returns( evt_rets, params, config, id_col, date_col, ret_col)if verbose: print()# 6. Test statisticsif verbose: print("Step 6: Computing test statistics...") test_stats = compute_test_statistics(event_ar, params, group_col) daily_stats = compute_daily_stats(daily_ar, id_col)if verbose:print(f" Done.\n")print("═══ Results Summary ═══") cols = ['group', 'N', 'mean_CAR', 'mean_BHAR', 'pct_positive','t_CS', 'p_CS', 't_BMP', 'p_BMP', 't_KP', 'p_KP'] avail = [c for c in cols if c in test_stats.columns]print(test_stats[avail].to_string(index=False))return {'config': config,'params': params,'daily_ar': daily_ar,'event_ar': event_ar,'daily_stats': daily_stats,'test_stats': test_stats,'calendar': calendar, }print("Master pipeline ready.")
Master pipeline ready.
41.4 Demonstration with Simulated Data
Since we are building a general-purpose framework (the actual event data will be supplied later), we demonstrate the full pipeline with realistic simulated data.
Figure 41.1: Dynamics of cumulative abnormal returns (CARs) and buy-and-hold abnormal returns (BHARs) around the event date. The positive jump at t=0 reflects the injected 2% abnormal return.
Figure 41.2: Cross-sectional distribution of cumulative abnormal returns. The rightward shift from zero and positive skewness are consistent with the injected positive event effect.
41.4.3 Complete Test Statistics
Show code
# Format for displayts = results['test_stats'].copy()# Select key columnsdisplay_cols = ['group', 'N', 'mean_CAR', 'mean_BHAR', 'pct_positive','t_CS', 'p_CS', 'Z_Patell', 'p_Patell','t_BMP', 'p_BMP', 't_KP', 'p_KP','Z_GSign', 'p_GSign', 't_SkAdj', 'p_SkAdj']avail = [c for c in display_cols if c in ts.columns]display_df = ts[avail].copy()# Formatfor c in display_df.columns:if c in ['N']: display_df[c] = display_df[c].astype(int)elif c.startswith('p_'): display_df[c] = display_df[c].map(lambda x: f'{x:.4f}'if pd.notna(x) else'')elif c in ['mean_CAR', 'mean_BHAR']: display_df[c] = display_df[c].map(lambda x: f'{x:.4%}'if pd.notna(x) else'')elif c =='pct_positive': display_df[c] = display_df[c].map(lambda x: f'{x:.1%}'if pd.notna(x) else'')elifisinstance(display_df[c].iloc[0], (int, float, np.floating)): display_df[c] = display_df[c].map(lambda x: f'{x:.3f}'if pd.notna(x) else'')print(display_df.to_string(index=False))
Table 41.3: Event study test statistics for the full sample and by subgroup
Since our data provides ret_excess rather than raw returns, we recover raw returns as \(R_{it} = R^e_{it} + R_{f,t}\), and the market return as \(R_{m,t} = R^e_{m,t} + R_{f,t}\). The extract_event_returns() function handles this automatically.
41.6.1 Loading the Data
Load Vietnamese market data
# --- Recover raw returns ---# ret = ret_excess + risk_freeprices_daily['ret'] = prices_daily['ret_excess'] + prices_daily['risk_free']prices_monthly['ret'] = prices_monthly['ret_excess'] + prices_monthly['risk_free']# --- Inspect the data ---print("="*70)print("VIETNAMESE MARKET DATA SUMMARY")print("="*70)print(f"\nprices_daily: {prices_daily.shape[0]:,} rows, "f"{prices_daily['symbol'].nunique()} stocks, "f"{prices_daily['date'].min().date()} to {prices_daily['date'].max().date()}")print(f"prices_monthly: {prices_monthly.shape[0]:,} rows, "f"{prices_monthly['symbol'].nunique()} stocks")print(f"\nfactors_ff3_daily: {factors_ff3_daily.shape[0]:,} trading days")print(f" Columns: {list(factors_ff3_daily.columns)}")print(f"factors_ff5_daily: {factors_ff5_daily.shape[0]:,} trading days")print(f" Columns: {list(factors_ff5_daily.columns)}")print(f"\nSample daily returns:")print(prices_daily[['symbol', 'date', 'ret_excess', 'ret', 'risk_free', 'mktcap']] .head(5).to_string(index=False))print(f"\nSample daily factors:")print(factors_ff3_daily.head(5).to_string(index=False))
For this demonstration, we create a sample event file. In practice, events would come from corporate announcements (earnings, M&A, dividends), regulatory changes, or other information shocks. Here we select 50 large-cap Vietnamese stocks and assign random event dates from the most recent two years of data to illustrate the pipeline mechanics.
Create sample event file for demonstration
np.random.seed(2024)# Select the 50 largest stocks by median market caplargest = (prices_daily.groupby('symbol')['mktcap'] .median() .nlargest(50) .index.tolist())# Date range for events: last 2 years of data, with buffer for windowsdate_range = prices_daily['date'].sort_values().unique()n_dates =len(date_range)# Events from the middle portion (need room for estimation + event windows)event_eligible = date_range[int(n_dates *0.3):int(n_dates *0.85)]# Generate 50 random firm-event pairsevent_firms = np.random.choice(largest, 50, replace=True)event_dates = np.random.choice(event_eligible, 50, replace=False)events_demo = pd.DataFrame({'symbol': event_firms,'event_date': pd.to_datetime(event_dates),'group': np.random.choice(['Group_A', 'Group_B'], 50)})# Remove any duplicate firm-date pairsevents_demo = events_demo.drop_duplicates(subset=['symbol', 'event_date'])print(f"Sample event file: {len(events_demo)} firm-event observations")print(f"Unique firms: {events_demo['symbol'].nunique()}")print(f"Date range: {events_demo['event_date'].min().date()} to "f"{events_demo['event_date'].max().date()}")print(f"\nGroup distribution:")print(events_demo['group'].value_counts().to_string())print(f"\nFirst 10 events:")print(events_demo.sort_values('event_date').head(10).to_string(index=False))
Sample event file: 50 firm-event observations
Unique firms: 35
Date range: 2014-06-25 to 2021-10-29
Group distribution:
group
Group_B 26
Group_A 24
First 10 events:
symbol event_date group
MCH 2014-06-25 Group_B
SIP 2014-10-23 Group_B
VRE 2014-11-14 Group_B
QNS 2014-12-25 Group_A
FOX 2015-01-16 Group_B
THD 2015-01-26 Group_A
QNS 2015-02-12 Group_A
HNG 2015-05-07 Group_B
MML 2015-08-17 Group_B
ACV 2015-10-15 Group_A
41.6.3 Daily Event Study: Fama-French 3-Factor Model
Figure 41.3: Cumulative abnormal returns around event dates for Vietnamese stocks using the Fama-French 3-factor model. The event window spans [-10, +10] trading days.
Figure 41.4: Cross-sectional distribution of cumulative abnormal returns (CARs) across firm-events. The histogram and Q-Q plot assess normality assumptions underlying parametric tests.
41.6.5 Complete Test Statistics (Daily)
Show code
ts = results_ff3['test_stats'].copy()display_cols = ['group', 'N', 'mean_CAR', 'median_CAR', 'mean_BHAR', 'pct_positive','t_CS', 'p_CS', 'Z_Patell', 'p_Patell','t_BMP', 'p_BMP', 't_KP', 'p_KP','Z_GSign', 'p_GSign', 't_SkAdj', 'p_SkAdj','W_Wilcoxon', 'p_Wilcoxon']avail = [c for c in display_cols if c in ts.columns]display_df = ts[avail].copy()for c in display_df.columns:if c in ['N']: display_df[c] = display_df[c].astype(int)elif c =='group':continueelif c.startswith('p_'): display_df[c] = display_df[c].map(lambda x: f'{x:.4f}'if pd.notna(x) else'')elif c in ['mean_CAR', 'median_CAR', 'mean_BHAR']: display_df[c] = display_df[c].map(lambda x: f'{x:.4%}'if pd.notna(x) else'')elif c =='pct_positive': display_df[c] = display_df[c].map(lambda x: f'{x:.1%}'if pd.notna(x) else'')elifisinstance(display_df[c].iloc[0], (int, float, np.floating)): display_df[c] = display_df[c].map(lambda x: f'{x:.3f}'if pd.notna(x) else'')print(display_df.to_string(index=False))
Table 41.4: Event study test statistics for the full sample and by subgroup — Daily frequency, FF3 model
Figure 41.5: Monthly cumulative abnormal returns around event dates. Wider windows capture slower information incorporation typical of emerging markets.
41.6.9 Daily Event Study: Fama-French 5-Factor Model
Table 41.7: Comparison of estimation quality between FF3 and FF5 models
Model Estimation Diagnostics
============================================================
Metric FF3 FF5
------------------------------------------------------
Firm-events estimated 26 26
Mean R^2 0.2245 0.2675
Median R^2 0.1943 0.2692
Mean σ(ε) 0.021753 0.021351
Mean |α| 0.001022 0.001130
Mean β(MKT) 0.8867 0.9721
Mean β(SMB) -0.0434 0.0265
Mean β(HML) 0.2489 0.1493
Mean β(RMW) — -0.0934
Mean β(CMA) — 0.1070
41.6.11 Event-Level Detail
Show code
detail = results_ff3['event_ar'].copy()detail_cols = ['symbol', 'evtdate', 'CAR', 'BHAR', 'SCAR', 'sigma','nobs', 'alpha', 'beta_mkt_excess']detail_avail = [c for c in detail_cols if c in detail.columns]detail_show = detail[detail_avail].copy()detail_show['CAR'] = detail_show['CAR'].map(lambda x: f'{x:.4%}')detail_show['BHAR'] = detail_show['BHAR'].map(lambda x: f'{x:.4%}')detail_show['SCAR'] = detail_show['SCAR'].map(lambda x: f'{x:.3f}')print("Event-Level Results (first 20 firm-events)")print("="*100)print(detail_show.head(20).to_string(index=False))
Table 41.8: Event-level detail: CARs and BHARs for each firm-event (FF3 model)
ds = results_ff3['daily_stats'].copy()ds_cols = ['evttime', 'N', 'mean_AR', 'mean_CAR', 'mean_BHAR', 't_AR_CS', 't_AR_BMP']ds_avail = [c for c in ds_cols if c in ds.columns]ds_show = ds[ds_avail].copy()for c in ['mean_AR', 'mean_CAR', 'mean_BHAR']:if c in ds_show.columns: ds_show[c] = ds_show[c].map(lambda x: f'{x:.4%}')for c in ['t_AR_CS', 't_AR_BMP']:if c in ds_show.columns: ds_show[c] = ds_show[c].map(lambda x: f'{x:.3f}'if pd.notna(x) else'')print("Daily Event-Window Dynamics (FF3 Model)")print("="*80)print(ds_show.to_string(index=False))
Table 41.9: Daily dynamics of mean abnormal returns and test statistics within the event window
print("="*70)print("EVENT STUDY RESULTS SUMMARY")print("="*70)ff3_all = results_ff3['test_stats'][results_ff3['test_stats']['group'] =='All'].iloc[0]print(f"\nSample: {int(ff3_all['N'])} firm-event observations")print(f"Frequency: Daily")print(f"Primary Model: Fama-French 3-Factor")print(f"Estimation Window: {config_ff3.estimation_window} trading days")print(f"Event Window: ({config_ff3.event_window_start}, {config_ff3.event_window_end})")print(f"Gap: {config_ff3.gap} trading days")print(f"\n--- Abnormal Return Measures ---")print(f"Mean CAR({config_ff3.event_window_start},{config_ff3.event_window_end}): "f"{ff3_all['mean_CAR']:.4%}")print(f"Median CAR: {ff3_all['median_CAR']:.4%}")print(f"Mean BHAR: {ff3_all['mean_BHAR']:.4%}")print(f"Fraction positive CARs: {ff3_all['pct_positive']:.1%}")print(f"\n--- Statistical Significance ---")print(f"Cross-Sectional t: {ff3_all['t_CS']:.3f} (p = {ff3_all['p_CS']:.4f})")print(f"Patell Z: {ff3_all['Z_Patell']:.3f} (p = {ff3_all['p_Patell']:.4f})")print(f"BMP t: {ff3_all['t_BMP']:.3f} (p = {ff3_all['p_BMP']:.4f})")print(f"Kolari-Pynnönen t: {ff3_all['t_KP']:.3f} (p = {ff3_all['p_KP']:.4f})")print(f"Generalized Sign Z: {ff3_all['Z_GSign']:.3f} (p = {ff3_all['p_GSign']:.4f})")sig_005 =sum(1for k in ['p_CS','p_Patell','p_BMP','p_KP','p_GSign','p_SkAdj','p_Wilcoxon']if k in ff3_all and pd.notna(ff3_all[k]) and ff3_all[k] <0.05)total_tests =sum(1for k in ['p_CS','p_Patell','p_BMP','p_KP','p_GSign','p_SkAdj','p_Wilcoxon']if k in ff3_all and pd.notna(ff3_all[k]))print(f"\n{sig_005}/{total_tests} tests significant at 5% level")# Robustness noteprint(f"\nRobustness: Results checked across {len(models_daily)} risk models "f"and {len(windows)} event windows")
======================================================================
EVENT STUDY RESULTS SUMMARY
======================================================================
Sample: 26 firm-event observations
Frequency: Daily
Primary Model: Fama-French 3-Factor
Estimation Window: 150 trading days
Event Window: (-10, 10)
Gap: 15 trading days
--- Abnormal Return Measures ---
Mean CAR(-10,10): 2.1513%
Median CAR: 1.5701%
Mean BHAR: 2.4885%
Fraction positive CARs: 61.5%
--- Statistical Significance ---
Cross-Sectional t: 0.775 (p = 0.4456)
Patell Z: 0.961 (p = 0.3364)
BMP t: 0.727 (p = 0.4741)
Kolari-Pynnönen t: 0.700 (p = 0.4904)
Generalized Sign Z: 1.177 (p = 0.2393)
0/7 tests significant at 5% level
Robustness: Results checked across 4 risk models and 7 event windows
41.7 Practical Recommendations
Based on the literature and our implementation experience:
Estimation window: Use 150 trading days (~7 months) for daily studies. This balances parameter precision against structural breaks. For monthly studies, 60 months is standard (Kothari and Warner 2007).
Gap: 15 trading days is standard. Increase to 30 if information leakage is a concern.
Event window: Start with (-1, +1) for short-window tests, then expand to (-5, +5) and (-10, +10) for robustness. Report all windows.
Model choice: Always report market model as the baseline. Add FF3 or FF5 for robustness. For Vietnam, local factors are preferable to global factors.
Test statistics: Report at minimum: cross-sectional t (for ease of interpretation), BMP (robust to event-induced variance), and one non-parametric test (sign or Wilcoxon). Report Kolari-Pynnönen if events cluster in calendar time.
Thin trading: For Vietnamese small-caps, consider Dimson (1979) with 1 lead/lag or increase min_estimation_obs to filter out illiquid stocks.
Multiple testing: If testing multiple event windows or subgroups, apply Bonferroni or Holm corrections to control family-wise error rate.
Aharony, Joseph, and Itzhak Swary. 1980. “Quarterly Dividend and Earnings Announcements and Stockholders’ Returns: An Empirical Analysis.”The Journal of Finance 35 (1): 1–12.
Andrade, Gregor, Mark Mitchell, and Erik Stafford. 2001. “New Evidence and Perspectives on Mergers.”Journal of Economic Perspectives 15 (2): 103–20.
Ball, Ray, and Philip Brown. 2013. “An Empirical Evaluation of Accounting Income Numbers.” In Financial Accounting and Equity Markets, 27–46. Routledge.
Barber, Brad M, and John D Lyon. 1997. “Detecting Long-Run Abnormal Stock Returns: The Empirical Power and Specification of Test Statistics.”Journal of Financial Economics 43 (3): 341–72.
Bernard, Victor L, and Jacob K Thomas. 1989. “Post-Earnings-Announcement Drift: Delayed Price Response or Risk Premium?”Journal of Accounting Research 27: 1–36. https://doi.org/10.2307/2491062.
Bhattacharya, Utpal, Hazem Daouk, Brian Jorgenson, and Carl-Heinrich Kehr. 2000. “When an Event Is Not an Event: The Curious Case of an Emerging Market.”Journal of Financial Economics 55 (1): 69–101.
Binder, John. 1998. “The Event Study Methodology Since 1969.”Review of Quantitative Finance and Accounting 11 (2): 111–37.
Boehmer, Ekkehart, Jim Masumeci, and Annette B Poulsen. 1991. “Event-Study Methodology Under Conditions of Event-Induced Variance.”Journal of Financial Economics 30 (2): 253–72.
Brown, Stephen J, and Jerold B Warner. 1980. “Measuring Security Price Performance.”Journal of Financial Economics 8 (3): 205–58.
———. 1985. “Using Daily Stock Returns: The Case of Event Studies.”Journal of Financial Economics 14 (1): 3–31.
Campbell, John Y, Andrew W Lo, A Craig MacKinlay, and Robert F Whitelaw. 1998. “The Econometrics of Financial Markets.”Macroeconomic Dynamics 2 (4): 559–62.
Corrado, Charles J. 1989. “A Nonparametric Test for Abnormal Security-Price Performance in Event Studies.”Journal of Financial Economics 23 (2): 385–95.
Cowan, Arnold Richard. 1992. “Nonparametric Event Study Tests.”Review of Quantitative Finance and Accounting 2 (4): 343–58.
Dimson, Elroy. 1979. “Risk Measurement When Shares Are Subject to Infrequent Trading.”Journal of Financial Economics 7 (2): 197–226. https://doi.org/10.1016/0304-405X(79)90013-8.
Fama, Eugene F. 1998. “Market Efficiency, Long-Term Returns, and Behavioral Finance.”Journal of Financial Economics 49 (3): 283–306.
Fama, Eugene F, Lawrence Fisher, Michael C Jensen, and Richard Roll. 1969. “The Adjustment of Stock Prices to New Information.”International Economic Review 10 (1): 1–21.
Fama, Eugene F., and Kenneth R. French. 1993. “Common risk factors in the returns on stocks and bonds.”Journal of Financial Economics 33 (1): 3–56. https://doi.org/10.1016/0304-405X(93)90023-5.
Flannery, Mark J, and Aris A Protopapadakis. 2002. “Macroeconomic Factors Do Influence Aggregate Stock Returns.”The Review of Financial Studies 15 (3): 751–82.
Griffin, John M, Patrick J Kelly, and Federico Nardari. 2010. “Do Market Efficiency Measures Yield Correct Inferences? A Comparison of Developed and Emerging Markets.”The Review of Financial Studies 23 (8): 3225–77.
Hall, Peter. 1992. “On the Removal of Skewness by Transformation.”Journal of the Royal Statistical Society Series B: Statistical Methodology 54 (1): 221–28.
Jensen, Michael C, and Richard S Ruback. 1983. “The Market for Corporate Control: The Scientific Evidence.”Journal of Financial Economics 11 (1-4): 5–50.
Kolari, James W, and Seppo Pynnönen. 2010. “Event Study Testing with Cross-Sectional Correlation of Abnormal Returns.”The Review of Financial Studies 23 (11): 3996–4025.
Kothari, Sagar P, and Jerold B Warner. 2007. “Econometrics of Event Studies.” In Handbook of Empirical Corporate Finance, 3–36. Elsevier.
MacKinlay, A Craig. 1997. “Event Studies in Economics and Finance.”Journal of Economic Literature 35 (1): 13–39.
Mitchell, Mark L, and Jeffry M Netter. 1993. “The Role of Financial Economics in Securities Fraud Cases: Applications at the Securities and Exchange Commission.”Bus. Law. 49: 545.
Mitchell, Mark L, and Erik Stafford. 2000. “Managerial Decisions and Long-Term Stock Price Performance.”The Journal of Business 73 (3): 287–329.
Patell, James M. 1976. “Corporate Forecasts of Earnings Per Share and Stock Price Behavior: Empirical Test.”Journal of Accounting Research, 246–76.
Scholes, Myron, and Joseph Williams. 1977. “Estimating Betas from Nonsynchronous Data.”Journal of Financial Economics 5 (3): 309–27. https://doi.org/10.1016/0304-405X(77)90041-1.
Schwert, G William. 1981. “Using Financial Data to Measure Effects of Regulation.”The Journal of Law and Economics 24 (1): 121–58.
# Event Studies in FinanceEvent studies constitute one of the most enduring and widely deployed empirical methodologies in financial economics. At their core, event studies measure the impact of a specific event on the value of a firm by examining **abnormal security returns** around the time the event occurs. The methodology rests on a simple premise: if capital markets are informationally efficient, the effect of an event will be reflected immediately in security prices, and any deviation from "normal" expected returns can be attributed to the event itself.Since the pioneering work of @fama1969adjustment, who studied how stock prices adjust to new information around stock splits, event studies have become a cornerstone of empirical research across finance, accounting, economics, and law. @ball2013empirical demonstrated that accounting earnings announcements convey information to the market, a finding that launched decades of research in accounting and disclosure. The methodology has since been refined through contributions by @brown1980measuring and @brown1985using, who established the statistical properties of event study methods, and @mackinlay1997event codified best practices that remain standard today.The breadth of applications is remarkable. Event studies have been used to examine the wealth effects of mergers and acquisitions [@jensen1983market; @andrade2001new], earnings announcements [@bernard1989post], dividend changes [@aharony1980quarterly], regulatory changes [@schwert1981using], executive turnover [@warner1988stock], and macroeconomic announcements [@flannery2002macroeconomic]. In law and economics, event studies serve as the primary tool for measuring damages in securities fraud litigation [@mitchell1993role] and assessing the impact of regulatory interventions [@binder1998event]. @kothari2007econometrics documented over 500 published event studies in the top five finance journals alone between 1974 and 2000.### Why Event Studies MatterThe enduring popularity of event studies stems from several compelling properties:- **Direct measurement of economic significance.** Unlike regression-based approaches that estimate associations, event studies directly quantify the dollar impact of events on firm value. A cumulative abnormal return (CAR) of 3% for a firm with \$10 billion market capitalization translates to \$300 million in wealth creation, which is a tangible, economically meaningful magnitude.- **Minimal maintained assumptions.** The methodology requires only semi-strong market efficiency (i.e., prices reflect publicly available information), a weaker assumption than many alternatives.- **Statistical power.** Daily event studies have remarkable power to detect abnormal performance, even with modest sample sizes. @brown1985using demonstrated that the market model detects abnormal returns of 1% or more with high reliability using samples as small as 20 securities.- **Versatility.** The basic framework accommodates events that are firm-specific or market-wide, anticipated or surprising, and can be adapted to various asset classes and market structures.------------------------------------------------------------------------## Literature Review and Methodological Evolution### The Classical Framework (1969-1985)The modern event study traces its origins to @fama1969adjustment, hereafter FFJR, who examined monthly stock returns around 940 stock splits between 1927 and 1959. Their key innovation was the use of the **market model** to decompose returns into expected (normal) and unexpected (abnormal) components.@ball2013empirical independently developed a similar approach to study earnings announcements, establishing the information content of accounting data. It was a finding with profound implications for both the efficient markets hypothesis and the relevance of financial reporting.@brown1980measuring provided the first systematic analysis of event study methodology using simulation. Their study of monthly data established several important results: (i) the simple market model performs at least as well as more complex models, (ii) value-weighted market indices can lead to misspecification when the sample is tilted toward smaller firms, and (iii) the standard cross-sectional test has well-specified size under the null hypothesis. Their follow-up study [@brown1985using] extended the analysis to daily data, documenting the importance of non-normality in daily returns and the increased power of daily versus monthly studies.### Risk Model Refinements (1992-2015)The advent of the **Fama-French three-factor model** [@Fama1993] represented a major advance in modeling expected returns. Adding size (SMB) and value (HML) factors to the market model improved the cross-sectional fit of expected returns considerably. @Carhart1997 augmented this with a momentum factor (UMD), yielding the four-factor model that became standard in event studies through the 2000s. @FamaFrench2015 subsequently introduced profitability (RMW) and investment (CMA) factors in their five-factor model.The choice of risk model matters for event studies primarily in **long-horizon settings**. @kothari2007econometrics showed that for short-window studies (3-5 days), the market model and multi-factor models produce virtually identical results because the incremental factors explain very little daily return variation for individual firms. However, for event windows exceeding 20 trading days, model choice can materially affect inferences.### Testing for Abnormal Returns (1976-2010)The statistical testing of abnormal returns has evolved considerably:| Test | Year | Key Property | Reference ||------------------|------------------|-------------------|------------------|| **Patell Z** | 1976 | Standardizes by estimation-period $\sigma$; weights firms inversely by volatility | @patell1976corporate || **Cross-Sectional** $t$ | 1980 | Allows event-induced variance change | @brown1980measuring || **BMP** | 1991 | Robust to event-induced variance | @boehmer1991event || **Corrado Rank** | 1989 | Non-parametric; robust to non-normality | @corrado1989nonparametric || **Generalized Sign** | 1992 | Non-parametric; uses estimation-window baseline | @cowan1992nonparametric || **Kolari-Pynnönen** | 2010 | Accounts for cross-sectional dependence | @kolari2010event || **Skewness-Adjusted** | 1992 | Corrects for BHAR skewness | @hall1992removal |: Summary of major event study test statistics {#tbl-tests}### CARs versus BHARsCumulative abnormal returns (CARs) sum daily abnormal returns, while buy-and-hold abnormal returns (BHARs) compound returns and subtract the compounded benchmark. @barber1997detecting demonstrated that BHARs better capture the actual investor experience, since investors earn compound, not cumulative, returns. However, @fama1998market and @mitchell2000managerial showed that BHARs exhibit severe cross-sectional dependence and positive skewness. For **short event windows** (under 10 days), the difference between CARs and BHARs is negligible. For longer windows, both should be reported.### Emerging Market ConsiderationsEvent studies in emerging markets face distinct challenges:- **Thin trading.** Many emerging market securities trade infrequently, inducing bias in market model beta estimates. @scholes1977estimating and @dimson1979risk proposed corrections using leading and lagging market returns.- **Factor availability.** While Fama-French factors are readily available for developed markets, emerging market factors must often be constructed locally.- **Market microstructure.** Price limits ($\pm$ 7% on HOSE, $\pm$ 10% on HNX, $\pm$ 15% on UPCOM in Vietnam), T+2 settlement, and the absence of short-selling affect the speed of price adjustment. Researchers should consider wider event windows to accommodate slower information incorporation [@bhattacharya2000event; @griffin2010market].### Beyond Announcement Returns: Mergers, Acquisitions, and Employee Welfare {#sec-event-ma-employees}Mergers and acquisitions are the archetypal event-study application, and the announcement-window facts are well established: target shareholders earn large positive abnormal returns while average acquirer returns hover near zero [@jensen1983market; @andrade2001new]. Announcement CARs, however, measure only shareholder wealth. A growing literature applies the same event logic to non-price outcomes to ask what mergers do to the firm's other stakeholders, employees above all.The most direct evidence comes from @bach2026mergers, who link Swedish matched employer-employee records to individual health registries and document that the incidence of stress, anxiety, and depression and the use of psychiatric medication rise significantly among employees after mergers. The effects are not a phenomenon of distressed targets: they appear among employees of both targets and acquirers, in weak as well as growing and profitable firms, and they concentrate among blue-collar workers, lower-skilled employees, and those whose careers stall inside the merged firm. Strikingly, mergers that generate more mental illness among employees also perform worse after the transaction: the human costs of a badly integrated deal and its economic costs move together, so employee welfare is informative about deal quality rather than being a pure transfer from workers to shareholders.The pecuniary counterpart to these health costs is documented by @lagaras2026mas, who links Brazilian matched employer-employee administrative records to hand-collected M&A data and traces the earnings of incumbent target-firm employees for years after a deal. Target employees suffer large and persistent earnings declines, but the losses are concentrated almost entirely among workers who *leave* the target: those who stay are largely unaffected. Decomposing the losses is what makes the paper methodologically valuable. Part is displacement (a sharp, mostly short-lived shock to employment), but the larger and more durable part is a reallocation cost: displaced workers move to lower-paying employers, with roughly 47% landing at firms with lower wage premiums, and the fall in the *employer* wage premium accounts for the majority of the long-run wage loss. The losses are worst for low-skilled and older workers and for those with substantial firm-specific human capital, consistent with the destruction of job-specific match value and the depreciation of industry-specific skills rather than a uniform decline in worker productivity. Read alongside @bach2026mergers, the two papers describe the same event through different registries: a merger reallocates labor, and the workers who are reallocated bear the cost in both earnings and health.These results sit at the intersection of several literatures. On the health side, @sullivan2009job show with US administrative data that job displacement raises worker mortality for decades afterward, and @engelberg2016worrying document that stock market declines predict same-day hospital admissions, especially for anxiety and related psychological conditions, so economic shocks transmit to health quickly and persistently. On the labor side of M&A, @dessaint2017employment show that stringent employment protection legislation, by making post-merger labor restructuring costlier, reduces both takeover activity and merger gains; @john2015employee find that acquirers operating under strong employee rights earn lower announcement returns, cut fewer jobs after deals, and realize smaller combined gains; @lee2018human show that deals between firms with related human capital are more likely to occur, earn higher announcement returns, and perform better afterward; and @ma2025mergers document that M&A serves as a channel of technology adoption in which routine-intensive jobs at targets are displaced, linking merger activity to wage inequality.For Vietnam, the shareholder side of this research program is directly implementable with the pipeline developed in this chapter: landmark transactions such as ThaiBev's 2017 acquisition of Sabeco, the wave of foreign strategic stakes in banking and consumer sectors, and the compulsory transfers of weak banks to healthier institutions in 2024--2025 all provide clean announcement dates for CAR estimation (subject to the price-limit caveats above). The stakeholder side is harder, but less out of reach than it first appears. Vietnam has no linkable health registry, so a Swedish-style design in the spirit of @bach2026mergers is not currently feasible. The Brazilian design of @lagaras2026mas, however, is a much closer template: it requires only matched employer-employee administrative records, and Vietnam Social Security maintains exactly this kind of longitudinal contribution data, recording employer identity and insured earnings for participating workers. A researcher who obtained access to those records (or to anonymized extracts) could replicate the core decomposition---separating displacement effects from reallocation effects, and identifying employer wage premiums from workers who switch firms---for Vietnamese deals, with the caveats that informal employment lies outside the system and that contribution earnings are capped and therefore censored at the top. Failing that, enterprise surveys, labor-force surveys, and firm-level employment and payroll disclosures offer coarser but usable windows onto post-merger employment and wage outcomes. That an emerging-market study is the methodological model here is not incidental: Brazil's combination of administrative data coverage and an active but less-regulated M&A market resembles Vietnam's trajectory far more than the Nordic or US settings do. The broader lesson of @bach2026mergers and @lagaras2026mas for any M&A event study is worth internalizing: a price-based CAR captures the market's estimate of shareholder value creation at announcement, not the deal's welfare consequences. And because employee distress predicts weak post-merger performance, even a shareholder-focused analyst has reason to track what happens to the workforce.## Mathematical FrameworkThis section presents the complete mathematical specification of the event study methodology. We follow the notation conventions of @campbell1998econometrics and @kothari2007econometrics.### Timeline and WindowsThe event study timeline is defined relative to the event date, denoted $\tau = 0$. All dates are measured in **trading days**:$$\underbrace{T_0 + 1, \ldots, T_1}_{\text{Estimation Window (L₁ days)}} \quad \underbrace{\quad}_{\text{Gap (G days)}} \quad \underbrace{\tau_1, \ldots, 0, \ldots, \tau_2}_{\text{Event Window (L₂ days)}}$$where:- **Estimation window**: $L_1$ trading days over which the risk model parameters are estimated- **Gap**: $G$ trading days separating estimation and event windows, preventing contamination by pre-event information leakage- **Event window**: $L_2 = \tau_2 - \tau_1 + 1$ trading days centered around the event dateFor example, with $L_1 = 150$, $G = 15$, $\tau_1 = -10$, $\tau_2 = +10$: the estimation window covers trading days $[-175, -25]$ relative to the event, and the event window covers $[-10, +10]$.### Normal Return ModelsLet $R_{it}$ denote the return on security $i$ on trading day $t$, $R_{ft}$ the risk-free rate, and $R_{mt}$ the market return. We implement six models:**Model 0: Market-Adjusted Returns.** Assumes $\beta_i = 1$ and $\alpha_i = 0$ for all firms:$$AR_{it}^{MA} = R_{it} - R_{mt}$$**Model 1: Market Model** [@Sharpe1964]:$$R_{it} = \alpha_i + \beta_i R_{mt} + \varepsilon_{it}, \quad E[\varepsilon_{it}] = 0, \quad \text{Var}[\varepsilon_{it}] = \sigma^2_{\varepsilon_i}$$$$AR_{it}^{MM} = R_{it} - \hat{\alpha}_i - \hat{\beta}_i R_{mt}$$**Model 2: Fama-French Three-Factor** [@Fama1993]:$$R_{it} - R_{ft} = \alpha_i + \beta_{i,1}(R_{mt} - R_{ft}) + \beta_{i,2} \cdot SMB_t + \beta_{i,3} \cdot HML_t + \varepsilon_{it}$$**Model 3: Carhart Four-Factor** [@Carhart1997]:$$R_{it} - R_{ft} = \alpha_i + \beta_{i,1}(R_{mt} - R_{ft}) + \beta_{i,2} \cdot SMB_t + \beta_{i,3} \cdot HML_t + \beta_{i,4} \cdot UMD_t + \varepsilon_{it}$$**Model 4: Fama-French Five-Factor** [@FamaFrench2015]:$$R_{it} - R_{ft} = \alpha_i + \beta_{i,1}(R_{mt} - R_{ft}) + \beta_{i,2} \cdot SMB_t + \beta_{i,3} \cdot HML_t + \beta_{i,4} \cdot RMW_t + \beta_{i,5} \cdot CMA_t + \varepsilon_{it}$$**Model 5: User-Specified Factor Model:**$$R_{it} - R_{ft} = \alpha_i + \sum_{k=1}^{K} \beta_{i,k} F_{k,t} + \varepsilon_{it}$$### Aggregation: CARs and BHARs**Cumulative Abnormal Returns** sum daily abnormal returns:$$CAR_i(\tau_1, \tau_2) = \sum_{t=\tau_1}^{\tau_2} AR_{it}, \qquad \overline{CAR}(\tau_1, \tau_2) = \frac{1}{N} \sum_{i=1}^{N} CAR_i(\tau_1, \tau_2)$$**Buy-and-Hold Abnormal Returns** compound returns:$$BHAR_i(\tau_1, \tau_2) = \prod_{t=\tau_1}^{\tau_2}(1 + R_{it}) - \prod_{t=\tau_1}^{\tau_2}(1 + \hat{E}[R_{it}])$$### Standardized ReturnsThe **standardized abnormal return** for firm $i$ on day $t$ is:$$SAR_{it} = \frac{AR_{it}}{\hat{\sigma}_{\varepsilon_i}}$$The **standardized cumulative abnormal return** is:$$SCAR_i(\tau_1, \tau_2) = \frac{CAR_i(\tau_1, \tau_2)}{\hat{\sigma}_{\varepsilon_i} \sqrt{L_2}}$$### Test StatisticsLet $N$ denote the number of firm-event observations.**Test 1: Cross-Sectional** $t$-Test. Allows event-induced variance; assumes cross-sectional independence:$$t_{CS} = \frac{\overline{CAR}}{s_{CAR}/\sqrt{N}}, \quad s_{CAR} = \sqrt{\frac{1}{N-1}\sum_{i=1}^{N}(CAR_i - \overline{CAR})^2}$$**Test 2: Patell Z-Test** [@patell1976corporate]. Weights firms inversely by volatility:$$Z_{Patell} = \frac{\sum_{i=1}^{N} SCAR_i}{\sqrt{\sum_{i=1}^{N} \frac{K_i - 2}{K_i - 4}}}$$**Test 3: BMP Test** [@boehmer1991event]. Robust to event-induced variance:$$t_{BMP} = \frac{\overline{SCAR}}{s_{SCAR}/\sqrt{N}}$$**Test 4: Kolari-Pynnönen Adjusted BMP** [@kolari2010event]. Accounts for cross-sectional dependence:$$t_{KP} = t_{BMP} \times \sqrt{\frac{1}{1 + (N-1)\bar{r}}}$$where $\bar{r}$ is the mean pairwise cross-correlation of estimation-period residuals.**Test 5: Generalized Sign Test** [@cowan1992nonparametric]:$$Z_{GSign} = \frac{\hat{p} - \hat{p}_0}{\sqrt{\hat{p}_0(1-\hat{p}_0)/N}}$$**Test 6: Sign Test:**$$Z_{Sign} = \frac{N^{+} - 0.5N}{\sqrt{0.25N}}$$**Test 7: Skewness-Adjusted** $t$-Test [@hall1992removal]:$$t_{SA} = \sqrt{N}\left(\bar{z} + \frac{1}{3}\hat{\gamma}\bar{z}^2 + \frac{1}{27}\hat{\gamma}^2\bar{z}^3 + \frac{1}{6N}\hat{\gamma}\right)$$**Test 8: Wilcoxon Signed-Rank Test:** A non-parametric test of whether the median CAR differs from zero.The table below summarizes the assumptions of each test:| Test | Event-Induced Variance | Cross-Sectional Independence | Normality ||------------------|:----------------:|:----------------:|:----------------:|| Cross-Sectional $t$ | Robust | Assumes | Assumes || Patell Z | Assumes no change | Assumes | Assumes || BMP | Robust | Assumes | Assumes || Kolari-Pynnönen | Robust | Robust | Assumes || Generalized Sign | Robust | Assumes | Robust || Corrado Rank | Robust | Assumes | Robust || Skewness-Adjusted | Robust | Assumes | Partially || Wilcoxon | Robust | Assumes | Robust |: Assumption requirements for event study test statistics {#tbl-test-assumptions}## Python Implementation### Design PhilosophyOur implementation follows these principles:1. **Modularity**: Each component (calendar, estimation, AR computation, testing) is a separate function.2. **Vectorization**: All operations use pandas/numpy for performance on large datasets.3. **Configurability**: All parameters are user-configurable via a dataclass.4. **Transparency**: Intermediate outputs are preserved for inspection.5. **Production-ready**: Comprehensive input validation, missing data handling, and edge cases.### Setup and Imports```{python}#| label: setup#| code-summary: "Import required libraries"import numpy as npimport pandas as pdimport statsmodels.api as smfrom scipy import statsfrom dataclasses import dataclass, fieldfrom typing import Optional, List, Tuplefrom enum import Enumimport warningsimport matplotlib.pyplot as pltimport matplotlib.ticker as mtickerwarnings.filterwarnings('ignore')pd.set_option('display.float_format', '{:.6f}'.format)print("All libraries loaded.")``````{python}import pandas as pdimport sqlite3tidy_finance = sqlite3.connect(database="data/tidy_finance_python.sqlite")factors_ff3_daily = pd.read_sql_query( sql="SELECT * FROM factors_ff3_daily", con=tidy_finance, parse_dates=["date"])factors_ff5_daily = pd.read_sql_query( sql="SELECT * FROM factors_ff5_daily", con=tidy_finance, parse_dates=["date"])factors_ff3_monthly = pd.read_sql_query( sql="SELECT * FROM factors_ff3_monthly", con=tidy_finance, parse_dates=["date"])factors_ff5_monthly = pd.read_sql_query( sql="SELECT * FROM factors_ff5_monthly", con=tidy_finance, parse_dates=["date"])``````{python}prices_monthly = pd.read_sql_query( sql=""" SELECT symbol, date, ret_excess, mktcap, mktcap_lag, risk_free FROM prices_monthly """, con=tidy_finance, parse_dates={"date"}).dropna()prices_daily = pd.read_sql_query( sql=""" SELECT symbol, date, ret_excess, mktcap, mktcap_lag, risk_free FROM prices_daily """, con=tidy_finance, parse_dates={"date"}).dropna()```### Configuration```{python}#| label: config#| code-summary: "Event study configuration"class RiskModel(Enum):"""Supported risk models for expected return computation.""" MARKET_ADJ ="market_adjusted" MARKET_MODEL ="market_model" FF3 ="ff3" CARHART ="carhart" FF5 ="ff5" CUSTOM ="custom"@dataclassclass EventStudyConfig:"""Complete configuration for an event study. Attributes ---------- estimation_window : int Length of estimation period in trading days. Brown and Warner (1985) suggest ≥100 days; MacKinlay (1997) recommends 120 as standard. event_window_start : int Start of event window relative to event date (e.g., -10). event_window_end : int End of event window relative to event date (e.g., +10). gap : int Trading days between estimation and event windows. Prevents contamination from pre-event information leakage. min_estimation_obs : int Minimum non-missing returns required in estimation period. risk_model : RiskModel Risk model for computing expected returns. custom_factors : list Column names for user-specified factors (CUSTOM model only). thin_trading_adj : str or None None, 'scholes_williams', or 'dimson'. dimson_lags : int Number of leads/lags for Dimson (1979) correction. """ estimation_window: int=150 event_window_start: int=-10 event_window_end: int=10 gap: int=15 min_estimation_obs: int=120 risk_model: RiskModel = RiskModel.MARKET_MODEL custom_factors: List[str] = field(default_factory=list) thin_trading_adj: Optional[str] =None dimson_lags: int=1@propertydef event_window_length(self) ->int:returnself.event_window_end -self.event_window_start +1def validate(self):assertself.estimation_window >0assertself.event_window_start <=self.event_window_endassertself.gap >=0assertself.min_estimation_obs <=self.estimation_windowifself.risk_model == RiskModel.CUSTOM:assertlen(self.custom_factors) >0returnTrue# Demonstrateconfig_demo = EventStudyConfig( estimation_window=150, event_window_start=-10, event_window_end=10, gap=15, min_estimation_obs=120, risk_model=RiskModel.FF3)config_demo.validate()print(f"Event window length: {config_demo.event_window_length} days")print(f"Model: {config_demo.risk_model.value}")```### Step 1: Trading Calendar ConstructionA correct trading calendar is fundamental. It maps any event date to the exact calendar dates for the start/end of estimation and event windows, accounting for weekends, holidays, and non-trading days.```{python}#| label: calendar#| code-summary: "Build trading calendar"def build_trading_calendar(trading_dates, config):"""Build a trading calendar mapping event dates to window boundaries. For each potential event date, identifies the calendar dates for the start/end of the estimation period and event window using only actual trading days. Parameters ---------- trading_dates : array-like Sorted unique trading dates in the market. config : EventStudyConfig Returns ------- pd.DataFrame with columns: estper_beg, estper_end, evtwin_beg, evtdate, evtwin_end, cal_index """ dates = pd.Series(sorted(pd.to_datetime(trading_dates).unique())) n =len(dates) L1 = config.estimation_window G = config.gap s = config.event_window_start L2 = config.event_window_length# Offsets (FIRSTOBS logic) o0 =0# estper_beg o1 = L1 -1# estper_end o2 = L1 + G # evtwin_beg o3 = L1 + G - s # evtdate o4 = L1 + G + L2 -1# evtwin_end max_offset = o4 valid = n - max_offsetif valid <=0:raiseValueError(f"Need ≥{max_offset+1} trading dates, have {n}") cal = pd.DataFrame({'estper_beg': dates.iloc[o0:o0+valid].values,'estper_end': dates.iloc[o1:o1+valid].values,'evtwin_beg': dates.iloc[o2:o2+valid].values,'evtdate': dates.iloc[o3:o3+valid].values,'evtwin_end': dates.iloc[o4:o4+valid].values, }) cal['cal_index'] =range(1, len(cal)+1)# Validate window lengths using a sample row idx =min(10, len(cal)-1) row = cal.iloc[idx] est_n = dates[(dates >= row['estper_beg']) & (dates <= row['estper_end'])].shape[0] evt_n = dates[(dates >= row['evtwin_beg']) & (dates <= row['evtwin_end'])].shape[0]assert est_n == L1, f"Estimation window: {est_n} ≠ {L1}"assert evt_n == L2, f"Event window: {evt_n} ≠ {L2}"return cal# Demodemo_dates = pd.bdate_range('2018-01-01', '2023-12-31', freq='B')demo_cal = build_trading_calendar(demo_dates, config_demo)print(f"Calendar: {len(demo_cal)} potential event dates")print(demo_cal.head(3).to_string(index=False))```### Step 2: Event Date AlignmentWhen an event occurs on a non-trading day, align to the **next** available trading day.```{python}#| label: alignment#| code-summary: "Align events to trading calendar"def align_events(events, calendar, id_col='symbol', date_col='event_date'):"""Align event dates to trading calendar. Non-trading-day events are shifted forward to the next trading day. Parameters ---------- events : pd.DataFrame with [id_col, date_col] and optional 'group' calendar : pd.DataFrame from build_trading_calendar() Returns ------- pd.DataFrame with window boundaries for each firm-event """ events = events.copy() events[date_col] = pd.to_datetime(events[date_col]) cal_dates = calendar[['evtdate']].drop_duplicates().sort_values('evtdate') merged = pd.merge_asof( events.sort_values(date_col), cal_dates.rename(columns={'evtdate': 'aligned_date'}), left_on=date_col, right_on='aligned_date', direction='forward' ) result = merged.merge(calendar, left_on='aligned_date', right_on='evtdate', how='inner') shifted = (result[date_col] != result['evtdate']).sum()if shifted >0:print(f" {shifted} event(s) shifted to next trading day") result = result.rename(columns={date_col: 'original_date'}) result = result.drop_duplicates(subset=[id_col, 'evtdate'])return result```### Step 3: Data Extraction and Factor MergingExtract returns for each security-event across the full estimation + event window and merge risk factors.```{python}#| label: extraction#| code-summary: "Extract returns and merge factors"def extract_returns(aligned_events, prices, factors, config, id_col='symbol', date_col='date', ret_col='ret', mkt_col='mkt_excess', rf_col='risk_free'):"""Extract stock returns and merge risk factors for each event. For each security-event, retrieves daily returns from estper_beg through evtwin_end and merges appropriate risk factors. """ prices = prices.copy() factors = factors.copy() prices[date_col] = pd.to_datetime(prices[date_col]) factors[date_col] = pd.to_datetime(factors[date_col])# Recover raw return from excess return if neededif ret_col notin prices.columns and'ret_excess'in prices.columns:if rf_col in factors.columns: prices = prices.merge(factors[[date_col, rf_col]].drop_duplicates(), on=date_col, how='left') prices[ret_col] = prices['ret_excess'] + prices[rf_col]# Factor columns based on model model = config.risk_model fac_cols = [mkt_col] if mkt_col in factors.columns else []if rf_col in factors.columns: fac_cols.append(rf_col) model_factors = { RiskModel.FF3: ['smb', 'hml'], RiskModel.CARHART: ['smb', 'hml', 'umd'], RiskModel.FF5: ['smb', 'hml', 'rmw', 'cma'], RiskModel.CUSTOM: config.custom_factors, }for f in model_factors.get(model, []):if f in factors.columns: fac_cols.append(f) fac_cols =list(set([date_col] + fac_cols))# Vectorized merge approach: join events with prices on id + date range frames = []for _, evt in aligned_events.iterrows(): mask = ((prices[id_col] == evt[id_col]) & (prices[date_col] >= evt['estper_beg']) & (prices[date_col] <= evt['evtwin_end'])) fd = prices.loc[mask, [id_col, date_col, ret_col]].copy()iflen(fd) ==0:continue fd['evtdate'] = evt['evtdate'] fd['estper_beg'] = evt['estper_beg'] fd['estper_end'] = evt['estper_end'] fd['evtwin_beg'] = evt['evtwin_beg'] fd['evtwin_end'] = evt['evtwin_end']if'group'in evt.index: fd['group'] = evt['group'] frames.append(fd)ifnot frames:raiseValueError("No return data found for any events") result = pd.concat(frames, ignore_index=True) result = result.merge(factors[fac_cols].drop_duplicates(), on=date_col, how='left')# Excess and market-adjusted returnsif rf_col in result.columns: result['ret_excess'] = result[ret_col] - result[rf_col]else: result['ret_excess'] = result[ret_col]if mkt_col in result.columns: result['ret_mktadj'] = result['ret_excess'] - result[mkt_col] result = result.sort_values([id_col, 'evtdate', date_col]).reset_index(drop=True) n_evts = result.groupby([id_col, 'evtdate']).ngroupsprint(f" Extracted {len(result):,} obs for {n_evts} firm-events")return result```### Step 4: Risk Model EstimationEstimate risk model parameters over the estimation window.```{python}# | label: estimation# | code-summary: "Risk model estimation"def estimate_model( event_returns, config, id_col="symbol", date_col="date", ret_col="ret"):"""Estimate risk model parameters for each firm-event. Runs OLS over the estimation window. Returns alpha, betas, sigma, R^2, nobs, and residuals for cross-correlation computation. """ model = config.risk_model# Define regression specification dep_var_map = { RiskModel.MARKET_ADJ: "ret_mktadj", RiskModel.MARKET_MODEL: ret_col, RiskModel.FF3: "ret_excess", RiskModel.CARHART: "ret_excess", RiskModel.FF5: "ret_excess", RiskModel.CUSTOM: "ret_excess", } indep_var_map = { RiskModel.MARKET_ADJ: [], RiskModel.MARKET_MODEL: ["mkt_excess"], RiskModel.FF3: ["mkt_excess", "smb", "hml"], RiskModel.CARHART: ["mkt_excess", "smb", "hml", "umd"], RiskModel.FF5: ["mkt_excess", "smb", "hml", "rmw", "cma"], RiskModel.CUSTOM: config.custom_factors, } dep_var = dep_var_map[model] indep_vars = indep_var_map[model] est = event_returns[ (event_returns[date_col] >= event_returns["estper_beg"])& (event_returns[date_col] <= event_returns["estper_end"]) ].copy() params_list = []for (firm, evtdate), grp in est.groupby([id_col, "evtdate"]): valid = grp.dropna(subset=[dep_var] + indep_vars) nobs =len(valid)if nobs < config.min_estimation_obs:continue y = valid[dep_var].valuesiflen(indep_vars) ==0:# Market-adjusted: intercept-only for variance p = { id_col: firm,"evtdate": evtdate,"alpha": y.mean(),"sigma": y.std(ddof=1),"variance": y.var(ddof=1),"nobs": nobs,"r_squared": 0.0,"_residuals": y - y.mean(), }else: X = sm.add_constant(valid[indep_vars].values) res = sm.OLS(y, X).fit() p = { id_col: firm,"evtdate": evtdate,"alpha": res.params[0],"sigma": np.sqrt(res.mse_resid),"variance": res.mse_resid,"nobs": nobs,"r_squared": res.rsquared if np.isfinite(res.rsquared) else np.nan,"_residuals": res.resid, }for j, var inenumerate(indep_vars): p[f"beta_{var}"] = res.params[j +1]# Skip degenerate firms (zero or near-zero variance)if p["sigma"] <1e-6:continue params_list.append(p)ifnot params_list:raiseValueError("No firm-events passed minimum observation filter") params_df = pd.DataFrame(params_list) n_total = event_returns.groupby([id_col, "evtdate"]).ngroupsprint(f" Estimated {len(params_df)}/{n_total} firm-events "f"(mean R^2 = {params_df['r_squared'].dropna().mean():.4f})" )return params_df```### Step 5: Abnormal Return ComputationCompute AR, CAR, BHAR, SAR, SCAR for each firm-event-date.```{python}# | label: abnormal-returns# | code-summary: "Compute abnormal returns, CARs, BHARs"def compute_abnormal_returns( event_returns, params, config, id_col="symbol", date_col="date", ret_col="ret"):"""Compute abnormal returns and aggregate to CARs/BHARs. Returns ------- daily_ar : pd.DataFrame - daily AR/SAR/CAR/BHAR per firm-event-date event_ar : pd.DataFrame - event-level CAR/BHAR/SCAR per firm-event """ model = config.risk_model factor_map = { RiskModel.MARKET_ADJ: [], RiskModel.MARKET_MODEL: ["mkt_excess"], RiskModel.FF3: ["mkt_excess", "smb", "hml"], RiskModel.CARHART: ["mkt_excess", "smb", "hml", "umd"], RiskModel.FF5: ["mkt_excess", "smb", "hml", "rmw", "cma"], RiskModel.CUSTOM: config.custom_factors, } factor_cols = factor_map[model]# Filter to event window evt = event_returns[ (event_returns[date_col] >= event_returns["evtwin_beg"])& (event_returns[date_col] <= event_returns["evtwin_end"]) ].copy()# Merge params (drop residuals column for merge) merge_cols = [c for c in params.columns if c !="_residuals"] evt = evt.merge(params[merge_cols], on=[id_col, "evtdate"], how="inner")# Expected returnsif model == RiskModel.MARKET_ADJ: evt["expected_ret"] = evt.get("mkt_excess", 0) + evt.get("risk_free", 0) evt["AR"] = evt[ret_col] - evt["expected_ret"]else: evt["expected_ret"] = evt["alpha"]for fc in factor_cols: bcol =f"beta_{fc}"if bcol in evt.columns: evt["expected_ret"] += evt[bcol] * evt[fc]if model == RiskModel.MARKET_MODEL: evt["AR"] = evt[ret_col] - evt["expected_ret"]else: evt["AR"] = evt["ret_excess"] - evt["expected_ret"] evt["SAR"] = evt["AR"] / evt["sigma"] evt = evt.sort_values([id_col, "evtdate", date_col])# Compute event time all_dates =sorted(event_returns[date_col].unique()) d2i = {d: i for i, d inenumerate(all_dates)} evt["evttime"] = evt[date_col].map(d2i) - evt["evtdate"].map(d2i)# Cumulative measures per firm-event daily_recs = [] event_recs = []for (firm, evtdate), g in evt.groupby([id_col, "evtdate"]): g = g.sort_values(date_col).copy() nd =len(g) g["CAR"] = g["AR"].cumsum() g["cum_ret"] = (1+ g[ret_col]).cumprod() -1 g["cum_expected"] = (1+ g["expected_ret"]).cumprod() -1 g["BHAR"] = g["cum_ret"] - g["cum_expected"] g["SCAR"] = g["CAR"] / (g["sigma"].iloc[0] * np.sqrt(np.arange(1, nd +1))) daily_recs.append(g) last = g.iloc[-1] sigma = g["sigma"].iloc[0] nobs = g["nobs"].iloc[0] rec = { id_col: firm,"evtdate": evtdate,"CAR": last["CAR"],"BHAR": last["BHAR"],"cum_ret": last["cum_ret"],"SCAR": last["CAR"] / (sigma * np.sqrt(nd)),"sigma": sigma,"variance": g["variance"].iloc[0],"nobs": nobs,"n_event_days": nd,"alpha": g["alpha"].iloc[0],"pat_scale": (nobs -2) / (nobs -4) if nobs >4else np.nan,"pos_car": int(last["CAR"] >0), }for fc in factor_cols: bcol =f"beta_{fc}"if bcol in g.columns: rec[bcol] = g[bcol].iloc[0]if"group"in g.columns: rec["group"] = g["group"].iloc[0] event_recs.append(rec) daily_ar = pd.concat(daily_recs, ignore_index=True) event_ar = pd.DataFrame(event_recs)print(f" {len(event_ar)} firm-events | Mean CAR: {event_ar['CAR'].mean():.6f} | "f"Mean BHAR: {event_ar['BHAR'].mean():.6f} | "f"% positive: {event_ar['pos_car'].mean():.1%}" )return daily_ar, event_ar```### Step 6: Comprehensive Test StatisticsEight tests covering parametric, non-parametric, and cross-correlation-robust approaches.```{python}#| label: tests#| code-summary: "Eight test statistics"def compute_test_statistics(event_ar, params=None, group_col=None):"""Compute comprehensive test statistics for abnormal returns. Implements 8 tests with varying assumptions about variance, cross-dependence, and distributional form. """def _stats(data, label=None): N =len(data)if N <3:returnNone cars = data['CAR'].values bhars = data['BHAR'].values scars = data['SCAR'].values pos = data['pos_car'].values m_car, s_car = np.mean(cars), np.std(cars, ddof=1) m_scar, s_scar = np.mean(scars), np.std(scars, ddof=1) r = {'group': label or'All', 'N': N,'mean_CAR': m_car, 'median_CAR': np.median(cars),'std_CAR': s_car, 'mean_BHAR': np.mean(bhars),'pct_positive': np.mean(pos)}# 1. Cross-sectional t t1 = m_car / (s_car / np.sqrt(N)) if s_car >0else np.nan r['t_CS'] = t1 r['p_CS'] =2* (1- stats.t.cdf(abs(t1), N-1)) if np.isfinite(t1) else np.nan# 2. Patell Zif'pat_scale'in data.columns: ps = data['pat_scale'].dropna().values z2 = np.sum(scars[:len(ps)]) / np.sqrt(np.sum(ps)) iflen(ps) >0else np.nanelse: z2 = m_scar * np.sqrt(N) r['Z_Patell'] = z2 r['p_Patell'] =2*(1-stats.norm.cdf(abs(z2))) if np.isfinite(z2) else np.nan# 3. BMP t3 = m_scar / (s_scar / np.sqrt(N)) if s_scar >0else np.nan r['t_BMP'] = t3 r['p_BMP'] =2*(1-stats.t.cdf(abs(t3), N-1)) if np.isfinite(t3) else np.nan# 4. Kolari-Pynnönen rbar =0.0if params isnotNoneand'_residuals'in params.columns: resids = [row['_residuals'] for _, row in params.iterrows()ifisinstance(row.get('_residuals'), np.ndarray)]iflen(resids) >1: ml =min(len(x) for x in resids) aligned = np.column_stack([x[:ml] for x in resids]) cm = np.corrcoef(aligned.T) np.fill_diagonal(cm, 0) rbar = cm.sum() / (len(resids) * (len(resids)-1)) adj = np.sqrt(1/(1+(N-1)*rbar)) if (1+(N-1)*rbar) >0else1 t4 = t3 * adj if np.isfinite(t3) else np.nan r['t_KP'] = t4 r['p_KP'] =2*(1-stats.t.cdf(abs(t4), N-1)) if np.isfinite(t4) else np.nan r['r_bar'] = rbar# 5. Generalized sign test p_hat = np.mean(pos) z5 = (p_hat -0.5) / np.sqrt(0.25/ N) r['Z_GSign'] = z5 r['p_GSign'] =2*(1-stats.norm.cdf(abs(z5)))# 6. Sign test r['Z_Sign'] = z5 # Same formula with p0=0.5 r['p_Sign'] = r['p_GSign']# 7. Skewness-adjusted tif s_scar >0: zb = m_scar / s_scar gam = stats.skew(scars) t7 = np.sqrt(N) * (zb + gam*zb**2/3+ gam**2*zb**3/27+ gam/(6*N)) r['t_SkAdj'] = t7 r['p_SkAdj'] =2*(1-stats.t.cdf(abs(t7), N-1)) if np.isfinite(t7) else np.nan# 8. Wilcoxon signed-ranktry: w, pw = stats.wilcoxon(cars, alternative='two-sided') r['W_Wilcoxon'] = w r['p_Wilcoxon'] = pwexcept: r['W_Wilcoxon'] = r['p_Wilcoxon'] = np.nanreturn r results = [_stats(event_ar)]if group_col and group_col in event_ar.columns:for gv, gd in event_ar.groupby(group_col): s = _stats(gd, label=gv)if s: results.append(s)return pd.DataFrame([r for r in results if r isnotNone])def compute_daily_stats(daily_ar, id_col='symbol'):"""Compute test statistics at each event time t.""" rows = []for t, g in daily_ar.groupby('evttime'): n = g[id_col].nunique()if n <2:continue m_ar = g['AR'].mean() s_ar = g['AR'].std(ddof=1) t_ar = m_ar / (s_ar/np.sqrt(n)) if s_ar >0else np.nan rows.append({'evttime': t, 'N': n, 'mean_AR': m_ar,'mean_CAR': g['CAR'].mean(), 'mean_BHAR': g['BHAR'].mean(),'mean_cum_ret': g.get('cum_ret', pd.Series()).mean(),'t_AR': t_ar})return pd.DataFrame(rows).sort_values('evttime')```### Step 7: Publication-Ready Visualization```{python}#| label: visualization#| code-summary: "Event study plots"def plot_event_study(daily_stats, title="Cumulative Abnormal Returns Around Event Date", figsize=(12, 7), save_path=None):"""Publication-ready event study plot with CAR, BHAR, and daily AR panels.""" fig, axes = plt.subplots(2, 1, figsize=figsize, height_ratios=[3, 1], gridspec_kw={'hspace': 0.05}) ds = daily_stats.sort_values('evttime') t = ds['evttime'].values# Top: cumulative returns ax = axes[0] ax.plot(t, ds['mean_CAR']*100, color='#2166AC', lw=2.5, label='Mean CAR') ax.plot(t, ds['mean_BHAR']*100, color='#B2182B', lw=2, ls='--', label='Mean BHAR')if'mean_cum_ret'in ds.columns: ax.plot(t, ds['mean_cum_ret']*100, color='#666', lw=1.5, ls=':', label='Mean Cum. Return', alpha=0.7) ax.axvline(0, color='k', lw=0.8, alpha=0.5) ax.axhline(0, color='k', lw=0.5, alpha=0.3) ax.set_ylabel('Cumulative Return (%)', fontsize=12) ax.set_title(title, fontsize=14, fontweight='bold') ax.legend(loc='upper left', fontsize=10) ax.grid(True, alpha=0.2) ax.set_xticklabels([])# Bottom: daily AR bars ax2 = axes[1] colors = ['#2166AC'if v >=0else'#B2182B'for v in ds['mean_AR']] ax2.bar(t, ds['mean_AR']*100, color=colors, alpha=0.7, width=0.8)if't_AR'in ds.columns: sig = np.abs(ds['t_AR'].values) >1.96if sig.any(): ax2.scatter(t[sig], ds['mean_AR'].values[sig]*100, color='gold', s=40, marker='*', zorder=4, label='p<0.05') ax2.legend(fontsize=9) ax2.axvline(0, color='k', lw=0.8, alpha=0.5) ax2.axhline(0, color='k', lw=0.5, alpha=0.3) ax2.set_xlabel('Event Time (Trading Periods)', fontsize=12) ax2.set_ylabel('Mean AR (%)', fontsize=10) ax2.grid(True, alpha=0.2)for a in axes: a.spines['top'].set_visible(False) a.spines['right'].set_visible(False) plt.tight_layout()if save_path: fig.savefig(save_path, dpi=300, bbox_inches='tight')return figdef plot_car_distribution(event_ar, var='CAR', figsize=(12, 5)):"""Cross-sectional distribution of CARs with histogram and QQ plot.""" fig, (ax1, ax2) = plt.subplots(1, 2, figsize=figsize) data = event_ar[var].dropna() *100 ax1.hist(data, bins=50, density=True, alpha=0.6, color='#2166AC', edgecolor='white') ax1.axvline(data.mean(), color='k', ls='--', lw=1.5, label=f'Mean={data.mean():.2f}%') ax1.axvline(data.median(), color='gray', ls=':', lw=1.5, label=f'Median={data.median():.2f}%') ax1.set_xlabel(f'{var} (%)') ax1.set_ylabel('Density') ax1.set_title(f'Distribution of {var}', fontweight='bold') ax1.legend() ax1.spines['top'].set_visible(False) ax1.spines['right'].set_visible(False)# QQ plot (osm, osr), (slope, intercept, r) = stats.probplot(data, dist='norm') ax2.scatter(osm, osr, alpha=0.4, s=10, color='#2166AC') ax2.plot(osm, slope*np.array(osm)+intercept, 'r--', lw=1) ax2.set_xlabel('Theoretical Quantiles') ax2.set_ylabel('Sample Quantiles') ax2.set_title('Q-Q Plot (Normal)', fontweight='bold') ax2.spines['top'].set_visible(False) ax2.spines['right'].set_visible(False) plt.tight_layout()return fig```### The Master PipelineCombine all components into one function:```{python}#| label: master#| code-summary: "Complete event study pipeline"def run_event_study(events, prices, factors, config, id_col='symbol', date_col='date', ret_col='ret', event_date_col='event_date', mkt_col='mkt_excess', rf_col='risk_free', group_col=None, verbose=True):"""Run a complete event study from raw inputs to test statistics. This is the main entry point. Provide your events, price data, factor data, and configuration—get back everything you need. Parameters ---------- events : pd.DataFrame Columns: [id_col, event_date_col], optional 'group'. prices : pd.DataFrame Daily returns: [id_col, date_col, ret_col or 'ret_excess', rf_col]. factors : pd.DataFrame Factor returns: [date_col, mkt_col, 'smb', 'hml', ...]. config : EventStudyConfig Returns ------- dict with keys: 'config', 'daily_ar', 'event_ar', 'daily_stats', 'test_stats', 'params' """ config.validate()if verbose:print(f"═══ Event Study: {config.risk_model.value} model ═══")print(f" Windows: estimation={config.estimation_window}, "f"gap={config.gap}, event=({config.event_window_start},{config.event_window_end})")print(f" Min obs: {config.min_estimation_obs}\n")# 1. Trading calendarif verbose: print("Step 1: Building trading calendar...") trading_dates = pd.Series(sorted(prices[date_col].unique())) calendar = build_trading_calendar(trading_dates, config)if verbose: print(f" {len(calendar)} potential event dates\n")# 2. Align eventsif verbose: print("Step 2: Aligning events to trading calendar...") aligned = align_events(events, calendar, id_col, event_date_col)if verbose: print(f" {len(aligned)} aligned events\n")# 3. Extract returnsif verbose: print("Step 3: Extracting returns and merging factors...") evt_rets = extract_returns(aligned, prices, factors, config, id_col, date_col, ret_col, mkt_col, rf_col)if verbose: print()# 4. Estimate modelif verbose: print("Step 4: Estimating risk model parameters...") params = estimate_model(evt_rets, config, id_col, date_col, ret_col)if verbose: print()# 5. Compute abnormal returnsif verbose: print("Step 5: Computing abnormal returns...") daily_ar, event_ar = compute_abnormal_returns( evt_rets, params, config, id_col, date_col, ret_col)if verbose: print()# 6. Test statisticsif verbose: print("Step 6: Computing test statistics...") test_stats = compute_test_statistics(event_ar, params, group_col) daily_stats = compute_daily_stats(daily_ar, id_col)if verbose:print(f" Done.\n")print("═══ Results Summary ═══") cols = ['group', 'N', 'mean_CAR', 'mean_BHAR', 'pct_positive','t_CS', 'p_CS', 't_BMP', 'p_BMP', 't_KP', 'p_KP'] avail = [c for c in cols if c in test_stats.columns]print(test_stats[avail].to_string(index=False))return {'config': config,'params': params,'daily_ar': daily_ar,'event_ar': event_ar,'daily_stats': daily_stats,'test_stats': test_stats,'calendar': calendar, }print("Master pipeline ready.")```## Demonstration with Simulated DataSince we are building a general-purpose framework (the actual event data will be supplied later), we demonstrate the full pipeline with **realistic simulated data**.```{python}#| label: simulation#| code-summary: "Generate realistic simulated market data"#| fig-cap: "Event study results using simulated data with known abnormal returns"np.random.seed(2024)# --- Simulated trading calendar (Vietnamese market: ~245 days/year) ---dates = pd.bdate_range('2019-01-01', '2023-12-31', freq='B')# Remove Tet + national holidays (simplified)tet_holidays = pd.to_datetime(['2019-02-04','2019-02-05','2019-02-06','2019-02-07','2019-02-08','2020-01-23','2020-01-24','2020-01-27','2020-01-28','2020-01-29','2021-02-10','2021-02-11','2021-02-12','2021-02-15','2021-02-16','2022-01-31','2022-02-01','2022-02-02','2022-02-03','2022-02-04','2023-01-20','2023-01-23','2023-01-24','2023-01-25','2023-01-26',])dates = dates.difference(tet_holidays)T =len(dates)# --- Simulated factors (realistic Vietnamese market parameters) ---rf_daily =0.04/252# ~4% annual risk-freemkt_excess = np.random.normal(0.0003, 0.012, T) # ~7.5% annual, ~19% volsmb = np.random.normal(0.0001, 0.006, T)hml = np.random.normal(0.0001, 0.005, T)rmw = np.random.normal(0.00005, 0.004, T)cma = np.random.normal(0.00005, 0.004, T)factors_sim = pd.DataFrame({'date': dates, 'mkt_excess': mkt_excess, 'smb': smb, 'hml': hml,'rmw': rmw, 'cma': cma, 'risk_free': rf_daily})# --- 100 simulated stocks ---n_stocks =100symbols = [f'SIM{i:03d}'for i inrange(n_stocks)]betas = np.random.uniform(0.5, 1.5, n_stocks)alphas = np.random.normal(0, 0.0002, n_stocks)idio_vols = np.random.uniform(0.015, 0.035, n_stocks)price_rows = []for i, sym inenumerate(symbols): eps = np.random.normal(0, idio_vols[i], T) rets = alphas[i] + betas[i] * mkt_excess +0.3*smb +0.2*hml + epsfor j inrange(T): price_rows.append({'symbol': sym, 'date': dates[j], 'ret': rets[j],'ret_excess': rets[j] - rf_daily,'risk_free': rf_daily,'mktcap': np.random.uniform(100, 5000), })prices_sim = pd.DataFrame(price_rows)# --- Simulated events: 50 random firm-dates with KNOWN positive AR ---event_indices = np.random.choice(range(250, T-50), 50, replace=False)event_firms = np.random.choice(symbols, 50, replace=True)event_dates_sim = [dates[i] for i in event_indices]# Inject abnormal returns on event date (2% positive shock)for firm, edate inzip(event_firms, event_dates_sim): mask = (prices_sim['symbol'] == firm) & (prices_sim['date'] == edate) prices_sim.loc[mask, 'ret'] +=0.02 prices_sim.loc[mask, 'ret_excess'] +=0.02events_sim = pd.DataFrame({'symbol': event_firms,'event_date': event_dates_sim,'group': np.random.choice([1, 2], 50)})print(f"Simulated data: {n_stocks} stocks × {T} days = {len(prices_sim):,} obs")print(f"Events: {len(events_sim)} firm-event pairs")print(f"Injected abnormal return: +2% on event date")```### Running the Full Pipeline```{python}#| label: run-pipeline#| code-summary: "Execute the event study"config = EventStudyConfig( estimation_window=150, event_window_start=-10, event_window_end=10, gap=15, min_estimation_obs=120, risk_model=RiskModel.FF3)results = run_event_study( events=events_sim, prices=prices_sim, factors=factors_sim, config=config, group_col='group')```### Visualizing Results```{python}#| label: fig-car-dynamics#| fig-cap: "Dynamics of cumulative abnormal returns (CARs) and buy-and-hold abnormal returns (BHARs) around the event date. The positive jump at t=0 reflects the injected 2% abnormal return."fig1 = plot_event_study( results['daily_stats'], title="Event Study: FF3 Model — Simulated Vietnamese Market")plt.show()``````{python}#| label: fig-car-distribution#| fig-cap: "Cross-sectional distribution of cumulative abnormal returns. The rightward shift from zero and positive skewness are consistent with the injected positive event effect."fig2 = plot_car_distribution(results['event_ar'], 'CAR')plt.show()```### Complete Test Statistics```{python}#| label: tbl-test-results#| tbl-cap: "Event study test statistics for the full sample and by subgroup"# Format for displayts = results['test_stats'].copy()# Select key columnsdisplay_cols = ['group', 'N', 'mean_CAR', 'mean_BHAR', 'pct_positive','t_CS', 'p_CS', 'Z_Patell', 'p_Patell','t_BMP', 'p_BMP', 't_KP', 'p_KP','Z_GSign', 'p_GSign', 't_SkAdj', 'p_SkAdj']avail = [c for c in display_cols if c in ts.columns]display_df = ts[avail].copy()# Formatfor c in display_df.columns:if c in ['N']: display_df[c] = display_df[c].astype(int)elif c.startswith('p_'): display_df[c] = display_df[c].map(lambda x: f'{x:.4f}'if pd.notna(x) else'')elif c in ['mean_CAR', 'mean_BHAR']: display_df[c] = display_df[c].map(lambda x: f'{x:.4%}'if pd.notna(x) else'')elif c =='pct_positive': display_df[c] = display_df[c].map(lambda x: f'{x:.1%}'if pd.notna(x) else'')elifisinstance(display_df[c].iloc[0], (int, float, np.floating)): display_df[c] = display_df[c].map(lambda x: f'{x:.3f}'if pd.notna(x) else'')print(display_df.to_string(index=False))```### Running Multiple Models for RobustnessA key best practice is to report results across multiple risk models. If conclusions are robust across models, this strengthens the findings:```{python}#| label: multi-model#| code-summary: "Run event study across all available models"models_to_run = [ ("Market-Adjusted", RiskModel.MARKET_ADJ), ("Market Model", RiskModel.MARKET_MODEL), ("Fama-French 3", RiskModel.FF3), ("Fama-French 5", RiskModel.FF5),]robustness = []for name, mdl in models_to_run: cfg = EventStudyConfig( estimation_window=150, event_window_start=-10, event_window_end=10, gap=15, min_estimation_obs=120, risk_model=mdl ) res = run_event_study(events_sim, prices_sim, factors_sim, cfg, verbose=False) ts = res['test_stats'] full = ts[ts['group'] =='All'].iloc[0] robustness.append({'Model': name,'N': int(full['N']),'Mean CAR': f"{full['mean_CAR']:.4%}",'Mean BHAR': f"{full['mean_BHAR']:.4%}",'% Positive': f"{full['pct_positive']:.1%}",'t (CS)': f"{full['t_CS']:.2f}",'t (BMP)': f"{full['t_BMP']:.2f}",'t (KP)': f"{full.get('t_KP', np.nan):.2f}", })rob_df = pd.DataFrame(robustness)print("Robustness Across Risk Models:")print(rob_df.to_string(index=False))```## How to Use This Framework with Your Data### Required Data FormatTo run the event study on real Vietnamese market data, prepare three inputs:**1. Stock Returns** (`prices` DataFrame):| Column | Description | Example ||-----------------------|------------------------|--------------||`symbol`| Stock ticker |`'VNM'`||`date`| Trading date |`2023-06-15`||`ret` or `ret_excess`| Daily return (decimal) |`0.0123`||`risk_free`| Daily risk-free rate |`0.000159`|**2. Factor Returns** (`factors` DataFrame):| Column | Description ||--------------|----------------------------||`date`| Trading date ||`mkt_excess`| Market excess return ||`smb`| Size factor (FF3/FF5) ||`hml`| Value factor (FF3/FF5) ||`rmw`| Profitability factor (FF5) ||`cma`| Investment factor (FF5) ||`risk_free`| Risk-free rate |**3. Event File** (`events` DataFrame):| Column | Description | Example ||--------------|---------------------|--------------||`symbol`| Stock ticker |`'VNM'`||`event_date`| Event date |`2023-03-15`||`group`| (Optional) subgroup |`1`|### Minimal Usage Example``` python# Load your dataprices = pd.read_csv('prices_daily.csv', parse_dates=['date'])factors = pd.read_csv('factors_ff3_daily.csv', parse_dates=['date'])events = pd.read_csv('my_events.csv', parse_dates=['event_date'])# Configureconfig = EventStudyConfig( estimation_window=150, event_window_start=-5, event_window_end=5, gap=15, min_estimation_obs=120, risk_model=RiskModel.FF3)# Runresults = run_event_study(events, prices, factors, config)# Access outputsresults['test_stats'] # Test statisticsresults['event_ar'] # Firm-level CARs/BHARsresults['daily_ar'] # Daily abnormal returnsresults['daily_stats'] # Event-time aggregates# Plotplot_event_study(results['daily_stats'], title="My Event Study")```## Demonstration with Vietnamese Market DataWe now demonstrate the full event study pipeline using actual Vietnamese stock market data. The datasets available are:- `prices_daily`: `symbol`, `date`, `ret_excess`, `mktcap`, `mktcap_lag`, `risk_free`- `prices_monthly`: same structure- `factors_ff3_daily`: `date`, `smb`, `hml`, `mkt_excess`, `risk_free`- `factors_ff3_monthly` — monthly frequency version- `factors_ff5_daily`: `date`, `smb`, `hml`, `mkt_excess`, `risk_free`, `rmw`, `cma`- `factors_ff5_monthly`Since our data provides `ret_excess` rather than raw returns, we recover raw returns as $R_{it} = R^e_{it} + R_{f,t}$, and the market return as $R_{m,t} = R^e_{m,t} + R_{f,t}$. The `extract_event_returns()` function handles this automatically.### Loading the Data```{python}#| label: load-data#| code-summary: "Load Vietnamese market data"# --- Recover raw returns ---# ret = ret_excess + risk_freeprices_daily['ret'] = prices_daily['ret_excess'] + prices_daily['risk_free']prices_monthly['ret'] = prices_monthly['ret_excess'] + prices_monthly['risk_free']# --- Inspect the data ---print("="*70)print("VIETNAMESE MARKET DATA SUMMARY")print("="*70)print(f"\nprices_daily: {prices_daily.shape[0]:,} rows, "f"{prices_daily['symbol'].nunique()} stocks, "f"{prices_daily['date'].min().date()} to {prices_daily['date'].max().date()}")print(f"prices_monthly: {prices_monthly.shape[0]:,} rows, "f"{prices_monthly['symbol'].nunique()} stocks")print(f"\nfactors_ff3_daily: {factors_ff3_daily.shape[0]:,} trading days")print(f" Columns: {list(factors_ff3_daily.columns)}")print(f"factors_ff5_daily: {factors_ff5_daily.shape[0]:,} trading days")print(f" Columns: {list(factors_ff5_daily.columns)}")print(f"\nSample daily returns:")print(prices_daily[['symbol', 'date', 'ret_excess', 'ret', 'risk_free', 'mktcap']] .head(5).to_string(index=False))print(f"\nSample daily factors:")print(factors_ff3_daily.head(5).to_string(index=False))```### Creating Sample EventsFor this demonstration, we create a sample event file. In practice, events would come from corporate announcements (earnings, M&A, dividends), regulatory changes, or other information shocks. Here we select 50 large-cap Vietnamese stocks and assign random event dates from the most recent two years of data to illustrate the pipeline mechanics.```{python}#| label: create-events#| code-summary: "Create sample event file for demonstration"np.random.seed(2024)# Select the 50 largest stocks by median market caplargest = (prices_daily.groupby('symbol')['mktcap'] .median() .nlargest(50) .index.tolist())# Date range for events: last 2 years of data, with buffer for windowsdate_range = prices_daily['date'].sort_values().unique()n_dates =len(date_range)# Events from the middle portion (need room for estimation + event windows)event_eligible = date_range[int(n_dates *0.3):int(n_dates *0.85)]# Generate 50 random firm-event pairsevent_firms = np.random.choice(largest, 50, replace=True)event_dates = np.random.choice(event_eligible, 50, replace=False)events_demo = pd.DataFrame({'symbol': event_firms,'event_date': pd.to_datetime(event_dates),'group': np.random.choice(['Group_A', 'Group_B'], 50)})# Remove any duplicate firm-date pairsevents_demo = events_demo.drop_duplicates(subset=['symbol', 'event_date'])print(f"Sample event file: {len(events_demo)} firm-event observations")print(f"Unique firms: {events_demo['symbol'].nunique()}")print(f"Date range: {events_demo['event_date'].min().date()} to "f"{events_demo['event_date'].max().date()}")print(f"\nGroup distribution:")print(events_demo['group'].value_counts().to_string())print(f"\nFirst 10 events:")print(events_demo.sort_values('event_date').head(10).to_string(index=False))```### Daily Event Study: Fama-French 3-Factor Model```{python}#| label: run-daily-ff3#| code-summary: "Run daily event study with FF3 model"config_ff3 = EventStudyConfig( estimation_window=150, event_window_start=-10, event_window_end=10, gap=15, min_estimation_obs=120, risk_model=RiskModel.FF3)results_ff3 = run_event_study( events=events_demo, prices=prices_daily, factors=factors_ff3_daily, config=config_ff3, group_col='group')```### Visualizing Daily Results```{python}#| label: fig-daily-car#| fig-cap: "Cumulative abnormal returns around event dates for Vietnamese stocks using the Fama-French 3-factor model. The event window spans [-10, +10] trading days."fig1 = plot_event_study( results_ff3['daily_stats'], title="Event Study: Fama-French 3-Factor Model — Vietnamese Market (Daily)")plt.show()``````{python}#| label: fig-daily-dist#| fig-cap: "Cross-sectional distribution of cumulative abnormal returns (CARs) across firm-events. The histogram and Q-Q plot assess normality assumptions underlying parametric tests."fig2 = plot_car_distribution(results_ff3['event_ar'], 'CAR')plt.show()```### Complete Test Statistics (Daily)```{python}#| label: tbl-daily-tests#| tbl-cap: "Event study test statistics for the full sample and by subgroup — Daily frequency, FF3 model"ts = results_ff3['test_stats'].copy()display_cols = ['group', 'N', 'mean_CAR', 'median_CAR', 'mean_BHAR', 'pct_positive','t_CS', 'p_CS', 'Z_Patell', 'p_Patell','t_BMP', 'p_BMP', 't_KP', 'p_KP','Z_GSign', 'p_GSign', 't_SkAdj', 'p_SkAdj','W_Wilcoxon', 'p_Wilcoxon']avail = [c for c in display_cols if c in ts.columns]display_df = ts[avail].copy()for c in display_df.columns:if c in ['N']: display_df[c] = display_df[c].astype(int)elif c =='group':continueelif c.startswith('p_'): display_df[c] = display_df[c].map(lambda x: f'{x:.4f}'if pd.notna(x) else'')elif c in ['mean_CAR', 'median_CAR', 'mean_BHAR']: display_df[c] = display_df[c].map(lambda x: f'{x:.4%}'if pd.notna(x) else'')elif c =='pct_positive': display_df[c] = display_df[c].map(lambda x: f'{x:.1%}'if pd.notna(x) else'')elifisinstance(display_df[c].iloc[0], (int, float, np.floating)): display_df[c] = display_df[c].map(lambda x: f'{x:.3f}'if pd.notna(x) else'')print(display_df.to_string(index=False))```### Robustness: Multiple Risk Models (Daily)```{python}#| label: tbl-robustness-daily#| tbl-cap: "Robustness of event study results across risk models — Daily frequency"#| code-summary: "Run event study across all available daily models"models_daily = [ ("Market-Adjusted", RiskModel.MARKET_ADJ, factors_ff3_daily), ("Market Model", RiskModel.MARKET_MODEL, factors_ff3_daily), ("Fama-French 3", RiskModel.FF3, factors_ff3_daily), ("Fama-French 5", RiskModel.FF5, factors_ff5_daily),]robustness_daily = []for name, mdl, facs in models_daily: cfg = EventStudyConfig( estimation_window=150, event_window_start=-10, event_window_end=10, gap=15, min_estimation_obs=120, risk_model=mdl ) res = run_event_study(events_demo, prices_daily, facs, cfg, verbose=False) ts = res['test_stats'] full = ts[ts['group'] =='All'].iloc[0] robustness_daily.append({'Model': name,'N': int(full['N']),'Mean CAR': f"{full['mean_CAR']:.4%}",'Median CAR': f"{full['median_CAR']:.4%}",'Mean BHAR': f"{full['mean_BHAR']:.4%}",'% Positive': f"{full['pct_positive']:.1%}",'t (CS)': f"{full['t_CS']:.3f}",'p (CS)': f"{full['p_CS']:.4f}",'t (BMP)': f"{full['t_BMP']:.3f}",'p (BMP)': f"{full['p_BMP']:.4f}",'t (KP)': f"{full.get('t_KP', np.nan):.3f}",'p (KP)': f"{full.get('p_KP', np.nan):.4f}", })rob_daily_df = pd.DataFrame(robustness_daily)print("Robustness Across Risk Models (Daily Frequency)")print("="*100)print(rob_daily_df.to_string(index=False))```### Robustness: Multiple Event WindowsA key practice is to examine sensitivity to the event window specification:```{python}#| label: tbl-robustness-windows#| tbl-cap: "Sensitivity of results to event window specification"#| code-summary: "Test across different event window widths"windows = [ ("(-1, +1)", -1, 1), ("(-3, +3)", -3, 3), ("(-5, +5)", -5, 5), ("(-10, +10)", -10, 10), ("(-1, +5)", -1, 5), ("(-5, +1)", -5, 1), ("(0, 0)", 0, 0),]window_results = []for label, ws, we in windows: cfg = EventStudyConfig( estimation_window=150, event_window_start=ws, event_window_end=we, gap=15, min_estimation_obs=120, risk_model=RiskModel.FF3 ) res = run_event_study(events_demo, prices_daily, factors_ff3_daily, cfg, verbose=False) ts = res['test_stats'] full = ts[ts['group'] =='All'].iloc[0] window_results.append({'Window': label,'Days': we - ws +1,'N': int(full['N']),'Mean CAR': f"{full['mean_CAR']:.4%}",'Mean BHAR': f"{full['mean_BHAR']:.4%}",'% Positive': f"{full['pct_positive']:.1%}",'t (CS)': f"{full['t_CS']:.3f}",'t (BMP)': f"{full['t_BMP']:.3f}",'p (BMP)': f"{full['p_BMP']:.4f}", })win_df = pd.DataFrame(window_results)print("Sensitivity to Event Window Specification (FF3 Model)")print("="*90)print(win_df.to_string(index=False))```### Monthly Event Study: Fama-French 3-Factor ModelFor longer-horizon studies, monthly frequency is appropriate. Note that the estimation window is specified in months rather than days:```{python}#| label: run-monthly-ff3#| code-summary: "Run monthly event study with FF3 model"# Create monthly events aligned to the monthly data# Map daily event dates to the corresponding month-endevents_monthly = events_demo.copy()events_monthly['event_date'] = events_monthly['event_date'].dt.to_period('M').dt.to_timestamp('M')# Use month-end dates from monthly pricesmonthly_dates = prices_monthly['date'].sort_values().unique()# Filter events to dates present in monthly dataevents_monthly = events_monthly[events_monthly['event_date'].isin(monthly_dates)]events_monthly = events_monthly.drop_duplicates(subset=['symbol', 'event_date'])config_monthly = EventStudyConfig( estimation_window=36, # 36 months event_window_start=-3, # 3 months before event_window_end=3, # 3 months after gap=3, # 3-month gap min_estimation_obs=24, # At least 24 months risk_model=RiskModel.FF3)iflen(events_monthly) >0: results_monthly = run_event_study( events=events_monthly, prices=prices_monthly, factors=factors_ff3_monthly, config=config_monthly, group_col='group' )print("\n--- Monthly Test Statistics ---") ts_m = results_monthly['test_stats'] mcols = ['group', 'N', 'mean_CAR', 'mean_BHAR', 'pct_positive','t_CS', 'p_CS', 't_BMP', 'p_BMP'] mavail = [c for c in mcols if c in ts_m.columns]print(ts_m[mavail].to_string(index=False))else:print("No monthly events could be aligned. Skipping monthly study.")``````{python}#| label: fig-monthly-car#| fig-cap: "Monthly cumulative abnormal returns around event dates. Wider windows capture slower information incorporation typical of emerging markets."iflen(events_monthly) >0and'daily_stats'in results_monthly: fig3 = plot_event_study( results_monthly['daily_stats'], title="Event Study: FF3 Model — Vietnamese Market (Monthly)" ) plt.show()```### Daily Event Study: Fama-French 5-Factor Model```{python}#| label: run-daily-ff5#| code-summary: "Run daily event study with FF5 model"config_ff5 = EventStudyConfig( estimation_window=150, event_window_start=-10, event_window_end=10, gap=15, min_estimation_obs=120, risk_model=RiskModel.FF5)results_ff5 = run_event_study( events=events_demo, prices=prices_daily, factors=factors_ff5_daily, config=config_ff5, group_col='group')```### Comparing FF3 vs FF5 Estimation Quality```{python}#| label: tbl-model-comparison#| tbl-cap: "Comparison of estimation quality between FF3 and FF5 models"params_ff3 = results_ff3['params']params_ff5 = results_ff5['params']print("Model Estimation Diagnostics")print("="*60)print(f"\n{'Metric':<30}{'FF3':>12}{'FF5':>12}")print("-"*54)print(f"{'Firm-events estimated':<30}{len(params_ff3):>12}{len(params_ff5):>12}")print(f"{'Mean R^2':<30}{params_ff3['r_squared'].mean():>12.4f}{params_ff5['r_squared'].mean():>12.4f}")print(f"{'Median R^2':<30}{params_ff3['r_squared'].median():>12.4f}{params_ff5['r_squared'].median():>12.4f}")print(f"{'Mean σ(ε)':<30}{params_ff3['sigma'].mean():>12.6f}{params_ff5['sigma'].mean():>12.6f}")print(f"{'Mean |α|':<30}{params_ff3['alpha'].abs().mean():>12.6f}{params_ff5['alpha'].abs().mean():>12.6f}")print(f"{'Mean β(MKT)':<30}{params_ff3['beta_mkt_excess'].mean():>12.4f}{params_ff5['beta_mkt_excess'].mean():>12.4f}")if'beta_smb'in params_ff3.columns:print(f"{'Mean β(SMB)':<30}{params_ff3['beta_smb'].mean():>12.4f}{params_ff5['beta_smb'].mean():>12.4f}")if'beta_hml'in params_ff3.columns:print(f"{'Mean β(HML)':<30}{params_ff3['beta_hml'].mean():>12.4f}{params_ff5['beta_hml'].mean():>12.4f}")if'beta_rmw'in params_ff5.columns:print(f"{'Mean β(RMW)':<30}{'—':>12}{params_ff5['beta_rmw'].mean():>12.4f}")if'beta_cma'in params_ff5.columns:print(f"{'Mean β(CMA)':<30}{'—':>12}{params_ff5['beta_cma'].mean():>12.4f}")```### Event-Level Detail```{python}#| label: tbl-event-detail#| tbl-cap: "Event-level detail: CARs and BHARs for each firm-event (FF3 model)"detail = results_ff3['event_ar'].copy()detail_cols = ['symbol', 'evtdate', 'CAR', 'BHAR', 'SCAR', 'sigma','nobs', 'alpha', 'beta_mkt_excess']detail_avail = [c for c in detail_cols if c in detail.columns]detail_show = detail[detail_avail].copy()detail_show['CAR'] = detail_show['CAR'].map(lambda x: f'{x:.4%}')detail_show['BHAR'] = detail_show['BHAR'].map(lambda x: f'{x:.4%}')detail_show['SCAR'] = detail_show['SCAR'].map(lambda x: f'{x:.3f}')print("Event-Level Results (first 20 firm-events)")print("="*100)print(detail_show.head(20).to_string(index=False))```### Daily Abnormal Return Dynamics```{python}#| label: tbl-daily-dynamics#| tbl-cap: "Daily dynamics of mean abnormal returns and test statistics within the event window"ds = results_ff3['daily_stats'].copy()ds_cols = ['evttime', 'N', 'mean_AR', 'mean_CAR', 'mean_BHAR', 't_AR_CS', 't_AR_BMP']ds_avail = [c for c in ds_cols if c in ds.columns]ds_show = ds[ds_avail].copy()for c in ['mean_AR', 'mean_CAR', 'mean_BHAR']:if c in ds_show.columns: ds_show[c] = ds_show[c].map(lambda x: f'{x:.4%}')for c in ['t_AR_CS', 't_AR_BMP']:if c in ds_show.columns: ds_show[c] = ds_show[c].map(lambda x: f'{x:.3f}'if pd.notna(x) else'')print("Daily Event-Window Dynamics (FF3 Model)")print("="*80)print(ds_show.to_string(index=False))```### Summary of Key Findings```{python}#| label: summary#| code-summary: "Summarize key findings"print("="*70)print("EVENT STUDY RESULTS SUMMARY")print("="*70)ff3_all = results_ff3['test_stats'][results_ff3['test_stats']['group'] =='All'].iloc[0]print(f"\nSample: {int(ff3_all['N'])} firm-event observations")print(f"Frequency: Daily")print(f"Primary Model: Fama-French 3-Factor")print(f"Estimation Window: {config_ff3.estimation_window} trading days")print(f"Event Window: ({config_ff3.event_window_start}, {config_ff3.event_window_end})")print(f"Gap: {config_ff3.gap} trading days")print(f"\n--- Abnormal Return Measures ---")print(f"Mean CAR({config_ff3.event_window_start},{config_ff3.event_window_end}): "f"{ff3_all['mean_CAR']:.4%}")print(f"Median CAR: {ff3_all['median_CAR']:.4%}")print(f"Mean BHAR: {ff3_all['mean_BHAR']:.4%}")print(f"Fraction positive CARs: {ff3_all['pct_positive']:.1%}")print(f"\n--- Statistical Significance ---")print(f"Cross-Sectional t: {ff3_all['t_CS']:.3f} (p = {ff3_all['p_CS']:.4f})")print(f"Patell Z: {ff3_all['Z_Patell']:.3f} (p = {ff3_all['p_Patell']:.4f})")print(f"BMP t: {ff3_all['t_BMP']:.3f} (p = {ff3_all['p_BMP']:.4f})")print(f"Kolari-Pynnönen t: {ff3_all['t_KP']:.3f} (p = {ff3_all['p_KP']:.4f})")print(f"Generalized Sign Z: {ff3_all['Z_GSign']:.3f} (p = {ff3_all['p_GSign']:.4f})")sig_005 =sum(1for k in ['p_CS','p_Patell','p_BMP','p_KP','p_GSign','p_SkAdj','p_Wilcoxon']if k in ff3_all and pd.notna(ff3_all[k]) and ff3_all[k] <0.05)total_tests =sum(1for k in ['p_CS','p_Patell','p_BMP','p_KP','p_GSign','p_SkAdj','p_Wilcoxon']if k in ff3_all and pd.notna(ff3_all[k]))print(f"\n{sig_005}/{total_tests} tests significant at 5% level")# Robustness noteprint(f"\nRobustness: Results checked across {len(models_daily)} risk models "f"and {len(windows)} event windows")```## Market Reactions to Macroeconomic News and Belief Overreaction {#sec-event-belief-overreaction}The event studies in this chapter measure how one firm's price responds to one firm's news. The aggregate market responds to a different kind of event: scheduled macroeconomic releases, central bank decisions, and the clustered earnings announcements of large firms. Whether those responses are rational, excessive, or too small is a long-standing question, and the standard tool for answering it, a regression of survey forecast errors on forecast revisions, has two weaknesses. It says nothing about *which* news investors overreact to, and in real-time data it often finds no reliable relation at all.@bianchi2026hundreds take a different route. They estimate a structural asset-pricing model in which a representative investor's beliefs about several macroeconomic shocks may be distorted, and they let the data choose the direction and size of the distortion. The rational benchmark is supplied by a machine-learning forecaster that uses only information available in real time and beats survey forecasts out of sample. They then filter how the investor's perceptions of each shock were revised around hundreds of specific news events (macroeconomic data releases, earnings announcements, and Federal Reserve communications) and compare the market's actual reaction with the reaction a rational investor would have had.Three findings stand out.- **Investors overreact to every perceived shock.** The estimated distortion parameter, in the spirit of diagnostic expectations, is $\theta = 1.58$, well above zero. Inattention, which would imply underreaction, is allowed by the model and rejected by the data. Investors also over-extrapolate news about the payout share of output.- **Overreaction to each shock does not imply overreaction to each event.** Most real news moves perceptions of several shocks at once, often in directions with opposing implications for prices. Because the shocks differ in volatility and persistence, overreaction to each can net out to a market response that is *smaller* than the rational one.- **Belief distortion stabilized the market when it mattered.** The authors estimate that this compositional underreaction describes several post-2000 episodes, most notably the global financial crisis. Over the post-2000 period as a whole, a rational benchmark with the estimated shocks would have produced a *more* volatile market than observed, a puzzle of excess stability rather than excess volatility.The mechanism can be seen in the paper's simplified model, which is small enough to reproduce here. Log payout growth is the sum of output growth $y_t$ and the change in the log payout share $k_t$, both autoregressive:$$\Delta d_{t+1} = y_{t+1} + k_{t+1} - k_t, \qquady_{t+1} = \rho_y y_t + \varepsilon_{y,t+1}, \qquadk_{t+1} = \rho_k k_t + \varepsilon_{k,t+1}.$$ {#eq-event-blm-payout}A rise in output growth is persistent good news. A fall in the payout share is transitory, so it implies catch-up growth later and, under rational expectations, barely moves the price. With the Campbell-Shiller approximation and a constant discount rate, the price-payout ratio loads on the two states with coefficients $a_y = \rho_y/(1-\rho\rho_y) > 0$ and $a_k = (\rho_k - 1)/(1-\rho\rho_k) < 0$. Diagnostic beliefs inflate the perceived news in each innovation by the factor $1 + \theta$, so the return on impact of an event that moves perceptions by $(\varepsilon_y, \varepsilon_k)$ is$$r = \left[1 + a_y(1+\theta)\right]\varepsilon_y + \left[1 + a_k(1+\theta)\right]\varepsilon_k ,$$ {#eq-event-blm-response}which reduces to the rational response at $\theta = 0$. Because $a_k$ is negative, overreaction to a payout-share shock pushes the price in the *opposite* direction to overreaction to an output shock of the same sign. The code below evaluates @eq-event-blm-response for every direction of news and compares the distorted with the rational response. The persistence values are illustrative, not the authors' estimates; $\theta = 1.58$ is their estimate.```{python}#| label: belief-overreaction-model#| code-summary: "Rational and distorted market responses to news"def news_response(eps_y, eps_k, theta, rho_y=0.2, rho_k=0.9, rho=0.997):""" Impact return of a news event in the simplified model of Bianchi, Ludvigson, and Ma: payout growth = output growth + change in the log payout share, both AR(1), priced with the Campbell-Shiller identity. eps_y, eps_k : perceived innovations to output growth and the payout share theta : diagnostic distortion (0 = rational expectations) Returns the log return on impact (price-payout change plus payout growth). """ a_y = rho_y / (1- rho * rho_y) # price-payout loading on output growth a_k = (rho_k -1) / (1- rho * rho_k) # loading on the payout share (< 0)return ((1+ a_y * (1+ theta)) * eps_y+ (1+ a_k * (1+ theta)) * eps_k)angles = np.linspace(-np.pi, np.pi, 721)news = pd.DataFrame({"angle": angles,"eps_y": np.cos(angles), "eps_k": np.sin(angles)})news["re"] = news_response(news["eps_y"], news["eps_k"], theta=0.0)frames = []for theta in [0.5, 1.58]: de = news_response(news["eps_y"], news["eps_k"], theta=theta) frames.append(news.assign(theta=theta, de=de, ratio=np.abs(de) / np.abs(news["re"])))overreaction = pd.concat(frames, ignore_index=True)# Share of news compositions for which the market underreacts despite theta > 0print(overreaction.assign(under=overreaction["ratio"] <1) .groupby("theta")["under"].mean().round(3))``````{python}#| label: fig-belief-overreaction#| fig-cap: "Distorted relative to rational market response to a news event, by the composition of perceived output and payout-share news, in the simplified model of Bianchi, Ludvigson, and Ma. Values below one are underreaction."#| fig-alt: "Line chart of the ratio of the distorted to the rational response, on a log scale, against the angle of the news vector. The ratio is above one for most compositions but falls well below one in two regions where output and payout-share news have the same sign, and spikes where the rational response is near zero."plot_df = overreaction.copy()plot_df["angle_deg"] = np.degrees(plot_df["angle"])# Mask the points where the rational response is essentially zeroplot_df["ratio_plot"] = plot_df["ratio"].where(plot_df["ratio"].between(0.02, 50))fig, ax = plt.subplots(figsize=(10, 4.5))for (theta, grp), color inzip(plot_df.groupby("theta"), ["#5B8BD0", "#2E5090"]): ax.plot(grp["angle_deg"], grp["ratio_plot"], color=color, lw=1.8, label=f"Diagnostic distortion θ = {theta:g}")ax.axhline(1, color="#C0392B", ls="--", lw=1, label="Rational response")for x0, x1, txt in [(-180, -90, "bad output,\nbad payout share"), (-90, 0, "good output,\nbad payout share"), (0, 90, "good output,\ngood payout share"), (90, 180, "bad output,\ngood payout share")]: ax.text((x0 + x1) /2, 40, txt, ha="center", va="top", fontsize=8, color="grey")ax.set_yscale("log")ax.set_ylim(0.02, 50)ax.set_xticks([-180, -90, 0, 90, 180])ax.set_xlabel("Composition of perceived news (angle of the shock vector, degrees)")ax.set_ylabel("|Distorted response| / |rational response|")ax.legend(loc="lower right", frameon=False)plt.tight_layout()plt.show()```@fig-belief-overreaction shows both regimes. When an event's news is mostly about output, or when output and payout-share news point in opposite directions, the distorted response exceeds the rational one: the textbook overreaction that amplifies volatility. Near pure payout-share news the rational response is close to zero while the distorted one is not, so the ratio explodes. But for most compositions in which the two shocks have the same sign (bad output growth together with a fall in the payout share, or the mirror image), the overreaction to the transitory payout-share news offsets the overreaction to the output news, and the market moves *less* than it rationally should. For roughly a quarter to a third of all possible news compositions in this example, a market that overreacts to every shock underreacts to the event.### What This Means for Vietnamese Research {#sec-event-belief-overreaction-vietnam}The full structural-AI synthesis requires real-time vintages of hundreds of macroeconomic series, survey expectations of investors and analysts, and futures prices, most of which do not exist for Vietnam. Its central insight transfers nonetheless, and in one respect Vietnam is a better laboratory than the United States.**Vietnamese macro news arrives bundled.** The General Statistics Office publishes inflation, industrial production, retail sales, trade, and investment together in a single report on a pre-announced schedule. Every release day is therefore a multi-shock event in the sense of @eq-event-blm-response, with frequent conflicting signals (higher inflation alongside stronger output, for example). The compositional prediction is testable directly: the market's response to a release should be dampened, relative to a model fitted on releases with consistent signals, when the components of the news have counteracting implications.**State Bank decisions are unscheduled.** Changes to policy rates and credit-growth targets are announced without a fixed meeting calendar, so their timing is itself news. They are natural events for this design but require care in defining the event day.**The rational benchmark must be real-time.** The paper's machine forecaster uses only data available at each date. Vietnamese macroeconomic series are revised, and historical vintages are rarely archived, so a benchmark built from today's revised data overstates what investors could have known and inflates measured belief distortions. Archive releases as published, or restrict the benchmark to series that are not revised.**Daily data limit the event window.** Intraday index data allow windows of minutes around a release; with daily data, other news on the same day contaminates the response, and price limits can truncate it on large-surprise days (@sec-price-limit-distortion).The code below sets up the reduced-form version of the exercise. It builds a real-time machine forecast of each indicator from information released before each date, measures surprises, estimates the VN-Index response on release days, and tests the two predictions that matter: that responses reverse when they reflect overreaction, and that responses are dampened when a release delivers conflicting signals. The release calendar, a file of release dates and first-print values, has to be assembled from GSO publications.```{python}#| label: macro-news-event-study#| eval: false#| code-summary: "Real-time surprises and the VN-Index response to GSO releases"from sklearn.linear_model import ElasticNetCVfrom datacore import DataCoreClientclient = DataCoreClient()# Release calendar assembled from GSO reports: one row per release date and# indicator, holding the value as first published on that datereleases = pd.read_csv("data/gso_releases.csv", parse_dates=["release_date"])panel = (releases.pivot(index="release_date", columns="indicator", values="value") .sort_index())indicators =list(panel.columns)def real_time_surprises(panel, n_lags=6, min_train=36):"""First print minus an elastic-net forecast fitted only on earlier releases.""" lagged = pd.concat({f"{c}_lag{l}": panel[c].shift(l)for c in panel.columns for l inrange(1, n_lags +1)}, axis=1) surprise = pd.DataFrame(index=panel.index, columns=panel.columns, dtype=float)for i inrange(n_lags + min_train, len(panel)): train = lagged.iloc[n_lags:i].dropna() x_now = lagged.iloc[[i]]if x_now.isna().any(axis=None):continuefor c in panel.columns: model = ElasticNetCV(l1_ratio=[0.1, 0.5, 0.9], cv=5, max_iter=10000) model.fit(train, panel[c].loc[train.index]) surprise.iloc[i, panel.columns.get_loc(c)] = ( panel[c].iloc[i] - model.predict(x_now)[0])return surprise / surprise.std() # standardized surprisessurprises = real_time_surprises(panel).dropna()vn = client.get_index_returns("VNINDEX", frequency="daily", start_date="2010-01-01", end_date="2024-12-31")vn["date"] = pd.to_datetime(vn["date"])ret = vn.set_index("date")["return"].sort_index()# Event day: first trading day on or after the release. Check GSO's release# time; a release after the close moves the event to the next trading day.pos = ret.index.searchsorted(surprises.index)keep = pos <len(ret)events = surprises[keep].copy()events["event_day"] = ret.index[pos[keep]]events["r0"] = ret.reindex(events["event_day"]).valuespost = ret[::-1].rolling(5).sum()[::-1].shift(-1) # return over days +1..+5events["r_post"] = post.reindex(events["event_day"]).valuesevents = events.dropna()# 1. Release-day response to each indicator's surpriseresponse = sm.OLS(events["r0"], sm.add_constant(events[indicators])).fit(cov_type="HC1")# 2. Composition: how much of the news pushes against its net directioncontrib = events[indicators] * response.params[indicators]gross = contrib.abs().sum(axis=1)events["news_index"] = contrib.sum(axis=1)events["conflict"] = np.minimum(contrib.clip(lower=0).sum(axis=1),-contrib.clip(upper=0).sum(axis=1)) / gross# 3. Reversal versus continuation. A negative slope of r_post on r0 indicates# overreaction; the interaction asks whether releases with conflicting# signals behave differently, as the compositional mechanism predicts.events["r0_x_conflict"] = events["r0"] * events["conflict"]reversal = sm.OLS(events["r_post"], sm.add_constant(events[["r0", "conflict", "r0_x_conflict"]]) ).fit(cov_type="HC1")print(response.summary().tables[1])print(reversal.summary().tables[1])```Read the output in two steps. In the reversal regression, a negative coefficient on the release-day return means release-day moves partly unwind over the following week, the signature of overreaction; a positive coefficient means they continue, the signature of underreaction. The compositional mechanism predicts a positive interaction: releases whose components conflict should show less reversal, or outright continuation, than releases whose components agree. With about a dozen GSO releases a year, statistical power is the binding constraint. Pooling them with State Bank decisions and the clustered quarterly earnings announcements of VN30 constituents raises the number of events, at the cost of mixing news types that the structural model would treat separately.## Practical RecommendationsBased on the literature and our implementation experience:1. **Estimation window**: Use 150 trading days (\~7 months) for daily studies. This balances parameter precision against structural breaks. For monthly studies, 60 months is standard [@kothari2007econometrics].2. **Gap**: 15 trading days is standard. Increase to 30 if information leakage is a concern.3. **Event window**: Start with (-1, +1) for short-window tests, then expand to (-5, +5) and (-10, +10) for robustness. Report all windows.4. **Model choice**: Always report market model as the baseline. Add FF3 or FF5 for robustness. For Vietnam, local factors are preferable to global factors.5. **Test statistics**: Report at minimum: cross-sectional t (for ease of interpretation), BMP (robust to event-induced variance), and one non-parametric test (sign or Wilcoxon). Report Kolari-Pynnönen if events cluster in calendar time.6. **Thin trading**: For Vietnamese small-caps, consider @dimson1979risk with 1 lead/lag or increase `min_estimation_obs` to filter out illiquid stocks.7. **Multiple testing**: If testing multiple event windows or subgroups, apply Bonferroni or Holm corrections to control family-wise error rate.