Reputation: 630
The code below calculates the Compounding
values starting from 100 and the percentage gains gains
. I want to write a code that goes start off with the entirety of the gains array [20,3,4,55,6.5]
resulting in 212.19
at the end and then takes off the first index and recalculates the compounding value [3,4,55,6.5]
resulting in 176.82
., It would do this until the end of the gains array [6.5]
. how would I be able to implement this to the code below and get the expected output?
import numpy as np
Amount = 100
def moneyrisk(array):
for counter,iterator in enumerate(array):
Compounding = Amount * np.cumprod(array / 100 + 1)
return Compounding
gains= np.array([20,3,4,55,6.5])
print(moneyrisk(gains))
Expected output:
[212.194008, 176.82834, 171.678, 165.075, 106.5]
Upvotes: 0
Views: 142
Reputation: 40638
You could repeat the array to make a squared matrix, then remove the lower triangle, apply your function on each row. And, finally extract the last column:
Your moneyrisk
function is given by:
>>> f = lambda x: 100*np.cumprod(x/100 + 1, 1) # notice the axis=1 option
Repeat rows:
>>> rep = gains[None].repeat(len(gains), 0)
array([[20. , 3. , 4. , 55. , 6.5],
[20. , 3. , 4. , 55. , 6.5],
[20. , 3. , 4. , 55. , 6.5],
[20. , 3. , 4. , 55. , 6.5],
[20. , 3. , 4. , 55. , 6.5]])
Use np.triu
to remove the lower triangle:
>>> rep_t = np.triu(rep, k=0)
array([[20. , 3. , 4. , 55. , 6.5],
[ 0. , 3. , 4. , 55. , 6.5],
[ 0. , 0. , 4. , 55. , 6.5],
[ 0. , 0. , 0. , 55. , 6.5],
[ 0. , 0. , 0. , 0. , 6.5]])
Apply f
and select the last column:
>>> f(rep_t)
array([[120. , 123.6 , 128.544 , 199.2432 , 212.194008],
[100. , 103. , 107.12 , 166.036 , 176.82834 ],
[100. , 100. , 104. , 161.2 , 171.678 ],
[100. , 100. , 100. , 155. , 165.075 ],
[100. , 100. , 100. , 100. , 106.5 ]])
>>> f(rep_t)[:, -1]
array([212.194008, 176.82834 , 171.678 , 165.075 , 106.5 ])
Upvotes: 1