Since you have a large number of data, I suggest to create other datasets that holds the data of different case.
For exampe, I modified code to output the data you added for 'sell - buy' to a dataset OTHERSTOCK (see output).
Then you can copy/paste/modify the code to fill the missing date values in OTHERSTOCK. To do so, you need to change the 'b' to 's' and 's' to 'b' in the if condition statement. Please note that the observation of Code=600039 is still in the dataset BuySell. Hope this would help.
modified code
data test;
input account $ trade $ code $ qtr Tdate : date9. price;
datalines;
1001 b 600001 1000 05JAN2007 5.00
1001 s 600001 1000 12APR2007 6.00
1001 b 600002 500 16APR2007 4.00
1001 s 600002 500 22JUN2007 3.00
1001 b 600005 3000 16APR2007 5.00
1001 s 600005 3000 24APR2007 7.00
1002 b 600001 500 24APR2007 3.00
1002 s 600001 500 26APR2007 4.00
1002 b 600018 1500 28JAN2007 5.00
1002 s 600018 1500 13JUN2007 7.00
1002 b 600039 5000 4JAN2007 7.00
1002 b 600039 2500 27FEB2007 9.00
1003 b 600002 600 5MAR2007 7.00
1003 s 600002 600 19JAN2007 6.00
1003 b 600108 200 31JAN2007 6.00
1003 s 600108 200 27MAR2007 8.00
1001 s 600001 1000 05JAN2007 5.0
1001 b 600001 1000 12APR2007 6.0
1001 s 600002 500 16APR2007 4.0
1001 b 600002 500 22JUN2007 3.0
;
run;
proc print data=test;
format tdate mmddyy10.;
run;
proc sort data=test out=datasorted;
by account code trade tdate;
run;
proc print data=datasorted;
format tdate date9.;
run;
data Buy_Sell (drop= i) OtherStock (drop=i SellDate BuyDate);
set datasorted;
by account code;
retain BuyDate;
if first.code and trade ='b' then
do;
if first.code ne last.code then
BuyDate = tdate;
output Buy_Sell;
end;
else if last.code and trade = 's' then
do; SellDate = tdate;
do i = BuyDate to SellDate-1;
tdate = i+1;
trade = 'h/s';
output Buy_Sell;
end;
end;
else output OtherStock;
run;
proc sort data=Buy_Sell nodup;
by account;
run;
proc print data=otherstock;
format tdate date9.;
run;
data of OtherStock
Obs account trade code qtr Tdate price
1 1001 b 600001 1000 12APR2007 6
2 1001 s 600001 1000 05JAN2007 5
3 1001 b 600002 500 22JUN2007 3
4 1001 s 600002 500 16APR2007 4
5 1002 b 600039 2500 27FEB2007 9