data crsp; set work.daily_return; format date mmddyy10.; month=month(date); keep permno date month ret; run; data have ; set crsp; ret=input(ret,?? best32.); drop Returns; monyy=intnx('month',Date,0); format monyy yymmn6.; run; proc sort data=have; by PERMNO monyy Date; run; data want; if _n_=1 then do; if 0 then set have(rename=(ret=_ret)); declare hash h(multidata:'y'); h.definekey('Date'); h.definedata('_ret'); h.definedone(); /**********/ declare hash m(); m.definekey('_monyy'); m.definedata('_ret'); m.definedone(); /**********/ end; array x{100} _temporary_; do until(last.PERMNO); set have; by PERMNO; _ret=ret;h.add(); end; do until(last.PERMNO); set have; by PERMNO; n=0;call missing(of x{*}); m.clear(); /**<---***/ do i=intnx('month',monyy,-3) to intnx('month',monyy,-1,'e'); rc=h.find(key:i); do while(rc=0); if not missing(_RET) then do;n+1;x{n}=_ret; _monyy=intnx('month',i,0); m.replace(); end; /**<---***/ rc=h.find_next(key:i); end; end; std=std(of x{*}); if n<5 then std=.; /**<-----****/ if m.num_items<3 then std=.; /**<----EDIT HERE-****/ output; end; h.clear(); drop i _ret n rc; run; data trim; set want; date2=intnx('month',date,1)-1; date1=intnx('month',date2,0); date_of=intnx('month',date1,-3); year=year(date); format date1 date2 date_of date9.; drop date1 monyy _monyy ret; run; proc sort data=trim; by permno month year; run; data monthly; set trim; by permno month year; firstpermno=first.permno; lastpermno=last.permno; firstyear=first.year; lastyear=last.year; *firstmonth=first.month; *lastmonth=last.month; if lastyear=1; run; proc sort data=monthly; by permno date; run; data sigma; set monthly; if month=1 then date=mdy(month,31,year(date)); if month=2 and year(date)in ('2000','2004','2008','2012','2016') then date=mdy(2,29,year(date)); else if month=2 and year(date) not in ('2000','2004','2008','2012','2016') then date=mdy(2,28,year(date)); if month=3 then date=mdy(month,31,year(date)); if month=4 then date=mdy(month,30,year(date)); if month=5 then date=mdy(month,31,year(date)); if month=6 then date=mdy(month,30,year(date)); if month=7 then date=mdy(month,31,year(date)); if month=8 then date=mdy(month,31,year(date)); if month=9 then date=mdy(month,30,year(date)); if month=10 then date=mdy(month,31,year(date)); if month=11 then date=mdy(month,30,year(date)); if month=12 then date=mdy(month,31,year(date)); drop firstpermno lastpermno lastyear firstyear; by permno date; run; /* Annualizing Sigma */ Data Sigma2; Set Sigma; Sigma_Annualized= sqrt(252/(64-1))*three months rolling volatility; run;