Problem: We have a table of stock returns with columns "Date", "Ticker", "Return", which is not handy to analyse. We need to convert this table to the format "Date", "Ticker1 Return", "Ticker2 Return", "Ticker3 Return" etc. Let's see how to do it in SAS.

* Let's assume there is a SAS data file stocks in the file library


/* Extracting data for Ticker1 */
data Ticker1;
    set file.stocks;
    if ticker = "Ticker1";
    Ticker1_Return = Return;
run;

proc sort data=Ticker1;
    by date;
run;

/* Extracting data for Ticker2 */
data Ticker2;
    set file.stocks;
    if ticker = "Ticker2";
    Ticker2_Return = Return;
run;

proc sort data=Ticker2;
    by date;
run;

/* Extracting data for Ticker3 */
data Ticker3;
    set file.stocks;
    if ticker = "Ticker3";
    Ticker3_Return = Return;
run;

proc sort data=Ticker3;
    by date;
run;

/* Merging the data for all tickers */
data alltickers;
    merge Ticker1(in=a) Ticker2(in=b) Ticker3(in=c);
    by date;
    if a or b or c; /* This line ensures only rows with at least one non-missing ticker are included */
run;

/* Exporting the combined data to a CSV file */
data _null_;
    set alltickers;
    file "~/alltickers.csv" dlm=',' lrecl=256;
    if _n_ = 1 then put "date, Ticker1_Return, Ticker2_Return, Ticker3_Return";
    put date Ticker1_Return Ticker2_Return Ticker3_Return;
run;