'How to make a random list with a sum of 1 with minimum and maximum limits for each element?
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?
Solution 1:[1]
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
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | donkopotamus |
