Home > Blockchain >  How to make a random list with a sum of 1 with minimum and maximum limits for each element?
How to make a random list with a sum of 1 with minimum and maximum limits for each element?

Time:03-15

I'm currently working on a long-short portfolio optimization project with python.

The thing is that I have to generate a list that has a sum of 1 and each element of the list should be larger or equal to -1 and smaller and equal to 5.

The length of the list must be 5 and the elements should be floats.

Is there a way that I could make such a list?

CodePudding user response:

Due to the constraint that the weights must sum to 1, there are only really four sources of randomness here. So, generate potential weights for the first four assets:

weights = [random.uniform(-1, 5) for i in range(4)]

then infer if the final weight final_weight = 1 - sum(weights) meets requirements. So something like:

def generate_weights():
    while True:
        weights = [random.uniform(-1, 5) for i in range(4)]
        weights.append(1 - sum(weights))
        if -1 <= weights[-1] <= 5:
            return weights
        
  • Related