BookmarkSubscribeRSS Feed
lior
Calcite | Level 5

Hallow, does the SAS have the ability to make arithmetic calculations that involved figures from different rows?

For example if I have daily data on share prices and I want to calculate daily return of the shares, I need to take the share price,  subtract the share price at the former day   (from the upper row) and dived it by the share price at the former day. 

This is very easy  to do in the excel and I wondered if the SAS able to do this kind of calculation as well. thanks, Lior

DateShare PriceShare Daily Return
01/01/20124
02/01/201250.25 = ( 5 - 4 ) / 4
03/01/2012101 = ( 10- 5 ) / 5
04/01/20128-0.2 = ( 8 - 10 ) / 10
4 REPLIES 4
KachiM
Rhodochrosite | Level 12

There are several ways to do this. There is lag() function that can be used. Here, even that is not needed for the present data set. Just hold the current value as PREV and use it in calcuations.

data need;

retain prev;

   set have;

   if prev then do;

      return = (Price - prev) / prev;

      prev = Price;

    end;

   if _n_ = 1 then prev = Price;

drop prev;

run;

RW9
Diamond | Level 26 RW9
Diamond | Level 26

Lag() however would shrink your code somewhat, note also that both examples assume that all data is present, i.e. if you were missing 03/01/2012 then 04 would be compared to 02/01/2012.

Lag:

data need;

     set have;

     return=(price - lag(price)) /lag(price);

run;

My suggestion however would be to explicitly merge the previous day on the current day to avoid missing data:

proc sql;

     create table NEED as

     select     A.*,

                   case     when B.PRICE is not null then (A.PRICE - B.PRICE) / B.PRICE

                                else . end as RETURN  /* Only calculate if previous record is present */

     from       HAVE A

     left join   HAVE B

     on           A.DATE=(B.DATE + 1);   /* Assumes date is numeric like date9. */

quit;

lior
Calcite | Level 5

In my research , if 03/01/2012 price data is missing (because for example its turn to be Saterday and no price data  been public), I would want the 04/01/2012 to be compared to 02/01/2012 data  . so there no problem in that aspect.

Thank you,

Lior

lior
Calcite | Level 5

Thank you, I will try it.

Lior

hackathon24-white-horiz.png

The 2025 SAS Hackathon has begun!

It's finally time to hack! Remember to visit the SAS Hacker's Hub regularly for news and updates.

Latest Updates

How to Concatenate Values

Learn how use the CAT functions in SAS to join values from multiple variables into a single value.

Find more tutorials on the SAS Users YouTube channel.

SAS Training: Just a Click Away

 Ready to level-up your skills? Choose your own adventure.

Browse our catalog!

Discussion stats
  • 4 replies
  • 1549 views
  • 0 likes
  • 3 in conversation