Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

The code below calculates the Compounding values starting from $100 and the percentage gains gains. The code below goes from the start off with the entirety of the gains array [20,3,4,55,6.5,-10, 20,-60,5] resulting in 96.25 at the end and then takes off the first index and recalculates the compounding value [3,4,55,6.5,-10, 20,-60,5] resulting in 80.20. It would do this until the end of the gains array [5]. I want to write a code that calculates maximum drawdown as it is calculating f. This would be the compounding results for the first iteration of f [120., 123.6 ,128.544, 199.243, 212.194008 190.9746072, 229.16952864, 91.66781146, 96.25120203] I want to record a value if it is lower than the initial capital Amount value. So the lowest value is 91.67 on the first iteration so that would be the output, and on the second iteration it would be 76.37. Since in the last iteration there is [5] which results in the compounding output of 105 there are no values that go below 100 so it is None as the output. 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):
    
    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])

Expected output:

[91.67, 76.37, 74.164, 71.312, 46.008, 43.2, 48., 40., None]
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
210 views
Welcome To Ask or Share your Answers For Others

1 Answer

I think I've understood the requirement. Calculating the compound factors after the np.triu fills the zeroes with ones which means the min method returns a valid value.

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]

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...