"""Check the streaming job's output against a direct computation of the same numbers.
Both sides use the settings in src/common/study.py, but this script computes the
abnormal returns and CARs from clean/master.parquet all at once with numpy, with none
of the streaming machinery (Kafka, watermark, join state, per-ticker state). If the
stream handled late and out-of-order messages correctly, every value matches.
daily ar market model re-fitted every day, on the days ending ESTIMATION_GAP_DAYS earlier
event car one market model per event, on the days before day -5 (the batch study's method)
Run from anywhere after the job: python3 scripts/check_streaming.py [stream folder]
"""
import sys
import numpy as np
import pandas as pd
from common.contracts import MARKET_WIDE_TICKER, expand_events, parquet_columns, require_contract
from common.settings import STREAM_DIR, STREAM_SUBDIRS, clean_path
from common.study import (ESTIMATION_DAYS, ESTIMATION_GAP_DAYS, EVENT_WINDOW, MARKET_TICKER,
MIN_ESTIMATION_DAYS, STUDY_END_YEAR, STUDY_START_YEAR)
TOLERANCE = 1e-9
stream_dir = sys.argv[1] if len(sys.argv) > 1 else str(STREAM_DIR)
def read_stream(dataset):
"""One output of the job, after checking its files against the contract."""
folder = f'{stream_dir}/{STREAM_SUBDIRS[dataset]}'
require_contract(dataset, parquet_columns(folder))
return pd.read_parquet(folder)
def fit(ret, mkt, end):
"""(alpha, beta) by OLS on the ESTIMATION_DAYS rows before index `end`, or None."""
r, m = ret[max(0, end - ESTIMATION_DAYS):max(0, end)], mkt[max(0, end - ESTIMATION_DAYS):max(0, end)]
ok = ~np.isnan(r) & ~np.isnan(m)
if ok.sum() < MIN_ESTIMATION_DAYS:
return None
beta, alpha = np.polyfit(m[ok], r[ok], 1)
return alpha, beta
master = pd.read_parquet(clean_path('master'))
master['date'] = pd.to_datetime(master['date'])
market = master[master['ticker'] == MARKET_TICKER].set_index('date')['ret'].rename('mkt_ret')
stocks = master[master['ticker'] != MARKET_TICKER].join(market, on='date')
events = pd.DataFrame(expand_events(STUDY_START_YEAR, STUDY_END_YEAR))
events['event_date'] = pd.to_datetime(events['event_date'])
daily, cars = [], []
for ticker, g in stocks.sort_values('date').groupby('ticker'):
ret, mkt, dates = g['ret'].to_numpy(), g['mkt_ret'].to_numpy(), g['date'].to_numpy()
ar = np.full(len(g), np.nan)
for i in range(len(g)):
model = fit(ret, mkt, i - ESTIMATION_GAP_DAYS)
if model:
ar[i] = ret[i] - (model[0] + model[1] * mkt[i])
daily.append(pd.DataFrame({'ticker': ticker, 'date': dates, 'ar': ar}))
for e in events[events['ticker'].isin([MARKET_WIDE_TICKER, ticker])].itertuples():
if e.event_date < dates[0]:
continue
i0 = int(np.searchsorted(dates, np.datetime64(e.event_date))) # first trading day on or after
if i0 + EVENT_WINDOW[1] >= len(dates):
continue
start, stop = max(0, i0 + EVENT_WINDOW[0]), i0 + EVENT_WINDOW[1] + 1
model = fit(ret, mkt, start)
r, m = ret[start:stop], mkt[start:stop]
ok = ~np.isnan(r) & ~np.isnan(m)
n = int(ok.sum()) if model else 0
cars.append({'ticker': ticker, 'event_type': e.event_type, 'event_date': e.event_date,
'window_end': dates[stop - 1], 'n_days': n,
'car': (r[ok] - (model[0] + model[1] * m[ok])).sum() if n else np.nan})
batch_daily, batch_cars = pd.concat(daily), pd.DataFrame(cars)
stream_daily = read_stream('stream_signals')
stream_cars = read_stream('stream_event_car')
for df in (stream_daily, stream_cars):
for c in ('date', 'event_date'):
if c in df:
df[c] = pd.to_datetime(df[c])
last_day = stream_daily['date'].max()
failures = []
dupes = stream_daily.duplicated(['ticker', 'date']).sum() + stream_cars.duplicated(
['ticker', 'event_type', 'event_date']).sum()
if dupes:
failures.append(f'{dupes} duplicate rows in the stream output')
d = batch_daily.merge(stream_daily[['ticker', 'date', 'ar']], on=['ticker', 'date'],
how='left', suffixes=('_batch', '_stream'), indicator=True)
missing = d[d['_merge'] == 'left_only']
both = d[d['_merge'] == 'both']
nan_mismatch = (both['ar_batch'].isna() != both['ar_stream'].isna()).sum()
ar_diff = (both['ar_batch'] - both['ar_stream']).abs().max()
print(f'daily: {len(both)} rows in both, {len(missing)} only in batch '
f'(last trading day the stream processed: {last_day.date()})')
print(f' abnormal returns: largest difference {ar_diff:.2e}, {nan_mismatch} rows where only one side has a value')
if nan_mismatch or ar_diff > TOLERANCE:
failures.append('abnormal returns differ')
if len(missing) and missing['date'].min() <= last_day:
failures.append('the stream skipped days before its last processed day')
# Windows that close after the stream's last processed day cannot be in the stream yet.
batch_cars = batch_cars[batch_cars['window_end'] <= last_day]
c = batch_cars.merge(stream_cars[['ticker', 'event_type', 'event_date', 'car', 'n_days']],
on=['ticker', 'event_type', 'event_date'], how='outer',
suffixes=('_batch', '_stream'), indicator=True)
both = c[c['_merge'] == 'both']
car_diff = (both['car_batch'] - both['car_stream']).abs().max()
car_nan = (both['car_batch'].isna() != both['car_stream'].isna()).sum()
n_diff = (both['n_days_batch'] != both['n_days_stream']).sum()
print(f'event CAR: {len(both)} windows in both, {(c["_merge"] == "left_only").sum()} only in batch, '
f'{(c["_merge"] == "right_only").sum()} only in stream')
print(f' CAR: largest difference {car_diff:.2e}; n_days differs in {n_diff} windows, '
f'only one side has a CAR in {car_nan}')
if car_diff > TOLERANCE or n_diff or car_nan or (c['_merge'] != 'both').any():
failures.append('event CARs differ')
print('OK: the stream matches the direct computation' if not failures else 'FAILED: ' + '; '.join(failures))
sys.exit(1 if failures else 0)