## Stock return and do loop

Occasional Contributor
Posts: 6

# Stock return and do loop

Hi I have this code

%let K=6;

data thesis.test7;

set thesis.test2;

array returns SPY--AFL;

do i= 1+&K to dim(returns);

returns[i]=(returns[i]-lag(returns[i]))/lag(returns[i]);

end;

run;

I would like the return computation to start at row 1+K and have the previous rows blank but it starts at column 1+K with the stock prices shown for previous columns.

What am I doing wrong?

Super User
Posts: 13,542

## Re: Stock return and do loop

The automatic variable _n_ has the row number and can be used for such processing:

``````data thesis.test7;
set thesis.test2;
array returns SPY--AFL;
if _n_ > &k then do i= 1 to dim(returns);
returns[i]=(returns[i]-lag(returns[i]))/lag(return​s[i]);
end;
run;``````

HOWEVER, the lag function, when it executes for row 7 all the lagged values will be missing because that is the first time the lag function is called.

You might be better off creating an array of  non-conditional lagged values and reference that array instead of using lag(returns[i])

Occasional Contributor
Posts: 6

## Re: Stock return and do loop

Cool thanks I'll try that out. Just another quick question, I'm new to the language SAS uses,
is there a way to generalize
array returns SPY--AFL
i.e. take the first column to the last column?

Thank you for your time.
Super User
Posts: 13,542

## Re: Stock return and do loop

To you mean to reverse the order of processing (AFL first and SPY last)? Easiest would be to change the index of the do loop:

Do i = dim(returns) to 1 by (-1);

If you are thinking of something else you may need to go into more details and the reasons why. Preferrably in a separate topic.

Super User
Posts: 10,778

## Re: Stock return and do loop

```Better post your data as text , No one would like to type it for you .
And most important thing is post your output too .

```
Discussion stats
• 4 replies
• 310 views
• 0 likes
• 3 in conversation