【问题标题】:Getting the minimum value by using lambda through numpy Array Python通过numpy Array Python使用lambda获取最小值
【发布时间】:2021-08-01 17:02:24
【问题描述】:

下面的代码计算从 $100 开始的 Compounding 值和百分比收益 gains。下面的代码从整个增益数组[20,3,4,55,6.5,-10, 20,-60,5] 开始,最后得到96.25,然后取出第一个索引并重新计算复合值[3,4,55,6.5,-10, 20,-60,5],得到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] 导致复合输出 105 没有低于 100 的值,所以它是 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])

预期输出:

[91.67, 76.37, 74.164, 71.312, 46.008, 43.2, 48., 40., None]

【问题讨论】:

    标签: python arrays numpy indexing lambda


    【解决方案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]
    

    【讨论】:

    • 谢谢它的工作原理有没有办法我可以在result 中返回每次迭代的最后一个索引并获得像这样的值96.25120203, 80.20933502, 77.8731408, 74.87802, 48.3084 ,45.36, 50.4, 42, 105
    • result[:, -1]],结果的最后一列。
    猜你喜欢
    • 2021-08-13
    • 1970-01-01
    • 2021-08-16
    • 2017-10-25
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-05-31
    • 2019-02-02
    相关资源
    最近更新 更多