11-17-2014 03:15 AM
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
|Date||Share Price||Share Daily Return|
|02/01/2012||5||0.25 = ( 5 - 4 ) / 4|
|03/01/2012||10||1 = ( 10- 5 ) / 5|
|04/01/2012||8||-0.2 = ( 8 - 10 ) / 10|
11-17-2014 04:37 AM
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.
if prev then do;
return = (Price - prev) / prev;
prev = Price;
if _n_ = 1 then prev = Price;
11-17-2014 04:56 AM
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.
return=(price - lag(price)) /lag(price);
My suggestion however would be to explicitly merge the previous day on the current day to avoid missing data:
create table NEED as
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. */
11-17-2014 06:24 AM
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.