Numpy - 生成随机数组,限制数组中的单个值 - 投资组合优化
Numpy - generate random array with restrictions on individual values in array - Portfolio Optimisation
我正在使用蒙特卡洛模拟开发带有约束的投资组合优化代码。但是,我已经运行陷入了一个问题。我的问题如下:
我有一个工具列表 ["Multi"、"Equity 1"、"Equity 2"、"Equity 3"、"FI"、"Cash"]
我想为这些工具生成一个随机数列表,例如
权重(随机数)= [xx, xx, xx, xx, xx, xx]
但是,有多个约束,例如:
- 0.05 到 0.20 之间的所有权重。
- 说“现金”的权重必须在 0 到 0.10 之间(即 0<= 权重[-1] <= 0.10)
- “股权 1”的权重必须为 0.15(即权重[1] = 0.15)
我是否可以生成满足所有这些条件的随机数?当然,所有权重的总和必须等于一。
谢谢大家的帮助!
你可以一个一个生成数字,每一步计算你已经得到的权重的总和。
我将使用 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
我正在使用蒙特卡洛模拟开发带有约束的投资组合优化代码。但是,我已经运行陷入了一个问题。我的问题如下:
我有一个工具列表 ["Multi"、"Equity 1"、"Equity 2"、"Equity 3"、"FI"、"Cash"]
我想为这些工具生成一个随机数列表,例如
权重(随机数)= [xx, xx, xx, xx, xx, xx]
但是,有多个约束,例如:
- 0.05 到 0.20 之间的所有权重。
- 说“现金”的权重必须在 0 到 0.10 之间(即 0<= 权重[-1] <= 0.10)
- “股权 1”的权重必须为 0.15(即权重[1] = 0.15)
我是否可以生成满足所有这些条件的随机数?当然,所有权重的总和必须等于一。
谢谢大家的帮助!
你可以一个一个生成数字,每一步计算你已经得到的权重的总和。 我将使用 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