Contributor
Posts: 38

# Arithmetic calculations that involved figures from different rows

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
Super Contributor
Posts: 324

## Re: Arithmetic calculations that involved figures from different rows

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;

Super User
Posts: 9,599

## Re: Arithmetic calculations that involved figures from different rows

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;

Contributor
Posts: 38

## Re: Arithmetic calculations that involved figures from different rows

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

Contributor
Posts: 38

## Re: Arithmetic calculations that involved figures from different rows

Thank you, I will try it.

Lior

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