首页 > 解决方案 > 使用 Monte Carlo 进行投资组合优化,但必须满足约束条件

问题描述

我在尝试找到投资组合权重并在满足约束的同时优化它们时遇到了问题。我需要一些帮助来设计一个允许我在满足一系列约束的同时模拟多个权重数组的代码,请参见下面的示例以获取解释:

问题 - 在满足约束的同时模拟各种权重:

工具 = ['固定收益'、'权益 1'、'权益 2'、'多资产'、'现金']

约束:

  1. 每个权重在 0.1 和 0.4 之间
  2. 现金 = 0.05
  3. 权益 1 小于 0.3

目前我有代码:

import numpy as np:

instruments = ['Fixed Income', 'Equity 1', 'Equity 2', 'Multi-Asset', 'Cash']

weights = np.random.uniform(0.1, 0.4, len(instruments)) # random number generation
weights = weights / weights.sum() # normalise weights
# I have done test runs, and normalised weights always fit the constraints

if weights[-1] > 0.03:
   excess = weights[-1] - 0.03
   # distribute excess weights equally
   weights[:-1] = weights[:-1] + excess / (len(weights) - 1)

我被困住了,我也意识到当我分配多余的重量时,我有效地打破了我的约束。

有什么办法吗?我必须通过蒙特卡罗来做

感谢大家的帮助。

标签: pythonoptimizationmontecarloquantitative-financeportfolio

解决方案


这是一种解决方案:

import numpy as np
N = 1000000
instruments = ['Fixed Income', 'Equity 1', 'Equity 2', 'Multi-Asset', 'Cash']

# each row is set of weights in order of instruments above
weights = np.zeros(shape=(N, len(instruments)))

weights[:, -1] = 0.05
weights[:, 1] = np.random.uniform(0, 0.3, N)

cols = (0, 2, 3)

# fill columns with random numbers
for col in cols[0:-1]:
    w_remaining = 1 - np.sum(weights, axis=1)
    weights[:, col] = np.random.uniform(0.1, 0.4, N)

# the last column is constrained for normalization
weights[:, cols[-1]] = 1 - np.sum(weights, axis=1)

# select only rows that meet condition:
cond1 = np.all(0.1 <= weights[:, cols], axis=1)
cond2 = np.all(weights[:, cols] <= 0.4, axis=1)
valid_rows = cond1*cond2

weights = weights[valid_rows, :]

# verify sum of weights == 1:
np.testing.assert_allclose(np.sum(weights, axis=1), 1)

此解决方案是高性能的,但会丢弃不满足约束的生成示例。


推荐阅读