Skip to content

Instantly share code, notes, and snippets.

@Palpatineli
Created July 29, 2020 18:33
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save Palpatineli/9f9180e7090a8484157835825794b53f to your computer and use it in GitHub Desktop.
Save Palpatineli/9f9180e7090a8484157835825794b53f to your computer and use it in GitHub Desktop.
cumulative annual return
from collections import deque
import numpy as np
def cumulative_return(x: np.ndarray) -> np.ndarray:
"""Calculate the cumulative annual return from monthly fluctuations
Args:
x: an 1D array, each item is a float showing proportion of change of investment in that month
Returns:
an 1D array, each item is the annual rate of change (return) for the 12 previous months
"""
x1 = x + 1
window = deque([x1[0]], maxlen=12)
result = [x1[0]]
for item in x1[1:]:
if len(window) == 12:
past = window.popleft()
result.append(result[-1] * item / past)
else:
result.append(result[-1] * item)
window.append(item)
return np.subtract(result, 1)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment