python random_sample 最小值

python random_sample minimum value

我目前正在使用 random_sample 为每行值加起来为 1 的 3 只股票生成权重分配。

for portfolio in range (10):
    weights = np.random.random_sample(3)
    weights  = weights/ np.sum(weights)
    print (weights)

[0.39055438 0.44055996 0.16888567]
[0.22401792 0.26961926 0.50636282]
[0.67856154 0.21523207 0.10620639]
[0.33449127 0.36491387 0.30059486]
[0.55274192 0.23291811 0.21433997]
[0.20980909 0.38639029 0.40380063]
[0.24600751 0.199761   0.5542315 ]
[0.50743661 0.26633377 0.22622962]
[0.1154567  0.36803903 0.51650427]
[0.29092731 0.34675988 0.36231281]

我可以做到,但有什么办法可以保证最小权重分配大于0.05?这意味着最小权重分配只能是 [0.05 0.9 0.05]

你可以忽略它们:

n = 0
while n < 10:
    weights = np.random.random_sample(3)
    weights  = weights/ np.sum(weights)
    if any(i < 0.05 for i in weights):
        continue
    n += 1
    print (weights)

看看 docs

Results are from the “continuous uniform” distribution over the stated interval. To sample Unif(a,b), b>a multiply the output of random_sample by (b-a) and add a.

在这种情况下,0.95 * weight + 0.05