options errorabend;

libname perm '../data';
libname crsp '../data/raw';
%include "modules/Macro Repository.sas";

/* Restrict to newest sample */
proc import datafile = "../data/rest_regs.dta"
	out = rest
	dbms = dta
	replace;
run;

proc sort data = rest out = tempret (keep = permno disclosure_date bearish_engage bearish_engage_2 bearish_priority prin_sir bearish_engage_q5 bearish_engage_2_q5 bearish_priority_q5 prin_sir_q5 event_id) nodupkey; by permno disclosure_date;
run;

proc sql;
	create table ret_2 as select
	a.*, b.date, b.ret
	from tempret as a left join crsp.dsf as b
	on a.permno = b.permno
	and intnx('weekday',a.disclosure_date,-3) le b.date le intnx('weekday',a.disclosure_date,60);
quit;

*Get delisting returns;
proc sql;
	create table ret_3 as select
	a.*, max(b.dlret) as dlret
	from ret_2 as a left join crsp.dse as b
	on a.permno = b.permno
	and a.date = b.date
	group by a.permno, a.date
;
quit;

*Get value-weighted returns;
proc sql;
	create table ret_3b as select
	a.*, b.vwretd
	from ret_3 as a left join crsp.dsi as b
	on a.date = b.date;
quit;

data ret_3b; set ret_3b;
if dlret = . then dlret = 0;
run;

proc sort data = ret_3b nodupkey; by permno disclosure_date date;
run;

data ret_4; set ret_3b; by permno disclosure_date;
abret = ret+dlret-vwretd;
retain car;
if first.disclosure_date then car = abret;
else car + abret;
t = intck('weekday',disclosure_date,date);
run;

data perm.gl_returns; set ret_4;
run;

proc sql;
	create table rets_plot as select distinct
	t, mean(car) as car, count(car) as N, std(car) as std_car
	from ret_4 group by t;
quit;

proc sql;
	create table rets_plot2 as select distinct
	t, bearish_engage_q5, mean(car) as car, count(car) as N, std(car) as std_car, mean(bearish_engage) as bearish_engage
	from ret_4 group by t, bearish_engage_q5;
quit;

proc sql;
	create table rets_plot3 as select distinct
	t, bearish_engage_2_q5, mean(car) as car, count(car) as N, std(car) as std_car, mean(bearish_engage_2) as bearish_engage_2
	from ret_4 group by t, bearish_engage_2_q5;
quit;

proc sql;
	create table rets_plot4 as select distinct
	t, bearish_priority_q5, mean(car) as car, count(car) as N, std(car) as std_car, mean(bearish_priority) as bearish_priority
	from ret_4 group by t, bearish_priority_q5;
quit;

proc sql;
	create table rets_plot4 as select distinct
	t, prin_sir_q5, mean(car) as car, count(car) as N, std(car) as std_car, mean(prin_sir) as prin_sir
	from ret_4 group by t, prin_sir_q5;
quit;
