使用蒙特卡洛进行投资组合优化,但必须满足约束条件

时间:2020-09-27 19:25:36

标签: python optimization montecarlo quantitative-finance portfolio

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

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

工具= [“固定收入”,“权益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)

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

反正有做吗?而且我必须通过蒙特卡罗做

感谢大家的帮助。

2 个答案:

答案 0 :(得分:2)

这是一种解决方案:

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)

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

答案 1 :(得分:0)

在我的 PoV 中,使用 montecarlo 模拟进行投资组合优化效率非常低,因为即使使用 sobol 序列,当您增加资产数量时问题也非常困难。

另一方面,大多数投资组合优化问题都是二次或线性规划问题,因此您可以使用 cvxpy 来解决它,但对每个问题进行建模都需要时间。最后,您可以尝试 Riskfolio-Lib 一个基于 cvxpy 的库,它简化了投资组合优化模型的实现,甚至有一种格式来实现您正在尝试实现的资产类别约束。

您可以查看此链接中的第一个示例:https://riskfolio-lib.readthedocs.io/en/latest/examples.html

相关问题