下面的代码计算从 $100 开始的 Compounding
值和百分比收益 gains
。下面的代码从一开始,整个增益数组 [20,3,4,55,6.5,-10, 20,-60,5]
导致 96.25
结束,然后去掉第一个索引并重新计算复合值 [3,4,55,6.5,-10, 20,-60,5]
导致 { {1}}。它会这样做直到增益数组 80.20
的末尾。我想编写一个代码来计算最大回撤,因为它正在计算 [5]
。这将是 f
f
的第一次迭代的复合结果,如果它低于初始资本 [120., 123.6 ,128.544, 199.243, 212.194008 190.9746072, 229.16952864, 91.66781146, 96.25120203]
值,我想记录一个值。因此,第一次迭代中的最小值为 Amount
,因此这将是输出,而在第二次迭代中,它将是 91.67
。由于在最后一次迭代中有 76.37
导致 [5]
的复合输出,因此没有低于 100 的值,因此它是 105
作为输出。我如何才能在下面的代码中实现这一点并获得预期的输出?
None
预期输出:
import numpy as np
Amount = 100
def moneyrisk(array):
f = lambda array: Amount*np.cumprod(array/100 + 1, 1)
rep = array[None].repeat(len(array), 0)
rep_t = np.triu(rep, k=0)
final = f(rep_t)[:, -1]
gains= np.array([20,3,4,55,6.5,-10, 20,-60,5])
答案 0 :(得分:1)
我想我已经理解了要求。在 np.triu
用 1 填充零后计算复合因子,这意味着 min
方法返回有效值。
import numpy as np
gains= np.array( [20,3,4,55,6.5,-10, 20,-60,5] ) # Gains in %
amount = 100
def moneyrisk( arr ):
rep = arr[ None ].repeat( len(arr), 0 )
rep_t = np.triu( rep, k = 0 )
rep_t = ( 1 + rep_t * .01 ) # Create factors to compound in rep_t
result = amount*(rep_t.cumprod( axis = 1 ).min( axis = 1 ))
# compound and find min value.
return [ x if x < amount else None for x in result ]
# Set >= amount to None in a list as numpy floats can't hold None
moneyrisk( gains )
# [91.667811456, 76.38984288, 74.164896, 71.3124, 46.008, 43.2, 48.0, 40.0, None]