Hi,
I have the following code and I am trying to calculate the weekly stock return of firm i from the last trading day in week t-1 to the last trading day in week t. According to my data, the week starts Sunday and ends Thursday. Unfortunately, the code does not give me the right output. Also, it does not give me the cumulative returns for each firm per week.
Your assistance is highly appreciated.
data Returns_1;
set Returns;
by stk date;
retain week_count 0 week_total 0;
if first.stk then do; week_count = 0; week_total = 0; end;
if weekday(date) = 1 /* assuming sunday */
then do; week_count + 1; week_total = 0; end;
week_total = week_total + ret;
run;
data Returns_2;
set Returns_1;
by stk week_count;
if last.week_count;
run;
Please provide, in the form of a working data step, a sample of the data you are starting with, and the erroneous results your program generates from that sample.
Help us help you.
You may be doing a lot of extra work.
If you apply the correct format to a date value you get a calendar week. So if you want a total of some value by calendar week you might try
proc summary data=Returns nway; class stk date; format date weeku5.; var ret; output out=work.weeksummary (drop=_type_) sum=Week_total; run;
The weekU format will display values in yyWww, 21W03 would be the third week of 2021 for example.
Formats can create groups that will be honored by the analysis, reporting and graphing procedures (most of the time).
The underlying value of the date variable in the output will be the first date of the week encountered in the data so would mostly be Mondays except for days there is no data. You can check that by printing a few records with a different format.
If you do not like the appearance change the format. You can also create a custom date format with Proc Format and a Picture statement if you want the year/ week combination displayed differently.
Are you ready for the spotlight? We're accepting content ideas for SAS Innovate 2025 to be held May 6-9 in Orlando, FL. The call is open until September 16. Read more here about why you should contribute and what is in it for you!
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.