Created
July 29, 2020 18:33
-
-
Save Palpatineli/9f9180e7090a8484157835825794b53f to your computer and use it in GitHub Desktop.
cumulative annual return
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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