REIT Analysis: Can someone explain the syntax of the Numpy diff function

The solution code provides a definition of a daily rate of return function as follows:

(1) def simple_rate_of_return(adj_closings):
(2)…daily_simple_ror = np.diff(adj_closings)/adj_closings[:-1]
(3)…return daily_simple_ror

Can someone explain line (2) above? Specifically, how does the syntax of the np.diff() function work?
this is the first time I’ve seen this function. I understand how np.diff() works over a single array.
The “(adj_closings)/adj_closings[:-1]” part is what I’m looking to clarify.



np.diff() is just working on the single array.

line 2 could be split up to;
a = np.diff(adj_closings)
b = adj_closings[:-1]
daily_simple_ror = a/b

so ‘a’ is diff doing its thing on adj_closings,
‘b’ is then taking the original array and removing the last entry
the final line will then divide list a with b, index by index,
so the resulting list would be;
[ a[0]/b[0], a[1]/b[1]… ]
adj_closings = [2, 5, 9, 12]
a = [3, 4, 3]
b = [2, 5, 9]
daily_simple_ror = [3/2, 4/5, 3/9]

Hope that helps.


Thank you! Your response confirmed what I think I realized right after posting my question. That is, that the np.diff() function operates on the adj_closings array, AND THEN divides those differences over the closing price in the period prior to the price movement.

I remain somewhat iffy on manipulating arrays; i.e. I’m not completely facile with that yet, but practice makes progress.

Thanks again!

1 Like