Numpy在阵列组合优化中生成对单个值有限制的随机阵列

2024-05-15 00:41:26 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在开发一个带有约束的投资组合优化代码,使用蒙特卡罗模拟。然而,我遇到了一个问题。我的问题如下:

我有一份工具清单[“多元”、“权益1”、“权益2”、“权益3”、“金融机构”、“现金”]

我想为这些仪器生成一个随机数列表,例如

权重(随机数)=[xx,xx,xx,xx,xx,xx]

但是,有多个约束,例如:

  1. 所有重量介于0.05和0.20之间
  2. “现金”的权重必须介于0和0.10之间(即0<;=权重[-1]<;=0.10)
  3. “权益1”的权重必须为0.15(即权重[1]=0.15)

我能生成满足所有这些条件的随机数吗?当然,所有权重之和必须等于一

谢谢大家的帮助


Tags: 工具代码lt列表条件仪器权重重量
1条回答
网友
1楼 · 发布于 2024-05-15 00:41:26

你可以一个接一个地生成数字,在每一步计算你已经得到的权重的总和。 我将使用random.randint函数进行演示

import random

weights_name = ["Multi", "Equity 1", "Equity 2", "Equity 3", "FI", "Cash"]
weights = [0] * 6

weights[1] = 0.15  # Equity 1 weight
remaining = 0.85 # the sum of the remaining weights

x = random.randint(0, 100)
weights[-1] = x/1000 # Cash weigth
remaining -= weights[-1]

所以对于剩余的重量,你必须生成随机值,这样最后一个不会大于0.2

last_weight = remaining
while last_weight > 0.2:
    last_weight = remaining
    for i in [0, 2, 3]:
        weights[i] = 0.05 + random.randint(0, 150)/1000 # generating a random no between 0.05 and 0.20
        last_weight -= weights[i]
weights[4] = last_weight
for w in weights:
    print(w)

我的输出:

0.2
0.15
0.176
0.196
0.18200000000000005
0.096

相关问题 更多 >

    热门问题