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 | |||
---|---|---|---|---|---|
01/01/2012 | 4 | ||||
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 |
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;
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;
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
Thank you, I will try it.
Lior
Don't miss out on SAS Innovate - Register now for the FREE Livestream!
Can't make it to Vegas? No problem! Watch our general sessions LIVE or on-demand starting April 17th. Hear from SAS execs, best-selling author Adam Grant, Hot Ones host Sean Evans, top tech journalist Kara Swisher, AI expert Cassie Kozyrkov, and the mind-blowing dance crew iLuminate! Plus, get access to over 20 breakout sessions.
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.