Contributor
Posts: 20

# Not sure how to write a macro for the following

Also, here is an example. Lhat_t = current loss_t * tmp2 + lhat_t-1 * tmp1

At each week lhat is calculated based on the lhat last week and the new current loss.

 tmp1= 0.986629 tmp2= 0.013371
 Weekid current Loss lhat 1 0.0120 0.0120 2 0.0050 0.0119 3 0.0000 0.0117 4 0.0230 0.0119

I am trying to write the code below as a loop.

data work.alldata_lhat;

set work.alldata_lhat;

by secid;

if count=1 then oldlhat=current_loss;

if count=1 then lhat=tmp1*oldlhat+tmp2*current_loss;

oldlhat=lag(lhat);if count> 1 then lhat=tmp1*oldlhat+tmp2*current_loss;

oldlhat=lag(lhat);if count> 2 then lhat=tmp1*oldlhat+tmp2*current_loss;

oldlhat=lag(lhat);if count> 3 then lhat=tmp1*oldlhat+tmp2*current_loss;

oldlhat=lag(lhat);if count> 4 then lhat=tmp1*oldlhat+tmp2*current_loss;

oldlhat=lag(lhat);if count> 5 then lhat=tmp1*oldlhat+tmp2*current_loss;

_loss;

Super Contributor
Posts: 334

## Re: Not sure how to write a macro for the following

If I am understanding what you need, I dont think you need a macro for this. I dont have access to SAS right this second to verify this but I think something like this will work:

data work.alldata_lhat;

set work.alldata_lhat;

by secid;

tmp1 = 0.986629;

tmp2 = 0.013371;

if first.secid then do;

oldhat=current_loss;

lhat=tmp1*oldlhat+tmp2*current_loss;

end;

else do;

oldhat=lhat;

lhat=tmp1*oldlhat+tmp2*current_loss;

end;

retain oldhat lhat;

run;

Super User
Posts: 8,114

## Re: Not sure how to write a macro for the following

What is the question?  The code looks really strange to me.  I would have expected to see something using a RETAIN statement to carry the value forward to use in calculating the new value.  You are not using the BY statement for anything.

data old;

input Weekid current_Loss want ;

secid=1;

cards;

1 0.0120 0.0120

2 0.0050 0.0119

3 0.0000 0.0117

4 0.0230 0.0119

;;;;

data new;

retain tmp1 0.986629 tmp2 0.013371 ;

set old;

by secid ;

if first.secid then oldhat=current_loss;

lhat = tmp1*oldhat + tmp2*current_loss;

output;

oldhat=lhat;

retain oldhat ;

run;

ID CURRENT_LOSS LHAT   WANT

1 0.012 0.012        0.012

2 0.005 0.011906403  0.0119

3 0     0.0117472025 0.0117

4 0.023 0.0118976636 0.0119

If you want to turn it into a macro then what part of the above changes?  Is it the constants used in the formula?

Contributor
Posts: 20

## Re: Not sure how to write a macro for the following

Thank you. I will try the code out. The example was for one secid. I have 25,000 secid where some of the secid have over 2400 weeks of loss information.

Discussion stats
• 3 replies
• 217 views
• 0 likes
• 3 in conversation