Build a list of returns in a loop, then compound them into the return for the whole stretch.
A return is the change from yesterday’s price to today’s price, divided by yesterday’s price. A list of prices becomes a list of returns one day at a time.
In this lesson I build that list with a loop, run it on a week of closing prices, and compound the daily returns into the return for the whole week.
Step 1. Three prices, two returns
Start with an empty list. Each pass through the loop computes one return and appends it to the end.
The loop starts at position 1, not 0, because position 0 has no day before it.
closes = [100.0, 110.0, 99.0]returns = [] # the list I am going to fillfor i inrange(1, len(closes)): # i = 1, 2 r = (closes[i] - closes[i -1]) / closes[i -1] # today minus yesterday, over yesterday returns.append(r) # put it on the endprint(returns) # -> [0.1, -0.1]print(len(closes), "prices ->", len(returns), "returns")# -> 3 prices -> 2 returns
[0.1, -0.1]
3 prices -> 2 returns
The price went from 100 to 110, a gain of 10%, then from 110 to 99, a fall of 10%. Three prices give two returns.
Here is what position 0 would reach for:
i =0print(closes[i -1]) # -> 99.0 <- closes[-1] is the last price in the list
99.0
closes[-1] counts from the end of the list.
Step 2. A week of closes
Now the same loop on five closes with the dates they belong to. Each return sits on the later of the two days it was computed from, so dates[1:] drops Monday.