Использование CVXOPT для оптимизации средней дисперсии - PullRequest
0 голосов
/ 26 февраля 2019

Я вижу, что этот вопрос задавался abc 4 года назад, но я все еще боролся с ответом, поэтому перепостил его.Коды вставлены ниже

, если, скажем, гипотетически, я должен был убедиться, что диапазон актива 1 составляет от 20% до 40%, а диапазон актива 2 <30%, и сказать, что актив 2 составляет 10-15%, чтоизменения я делаю в G и ч?то есть, какие будут значения для G и h в коде. </p>

Остальное легко понять, но немного борется с квадратичным оптимизатором.Цени любую помощь!

спасибо, PK

import numpy as np
import pandas as pd
from scipy import optimize
import cvxopt as opt
from cvxopt import blas, solvers
import matplotlib.pyplot as plt


np.random.seed(123)

# Turn off progress printing
solvers.options['show_progress'] = False

# Number of assets
n_assets = 4

# Number of observations
n_obs = 2000

## Generating random returns for our 4 securities
return_vec = np.random.randn(n_assets, n_obs)


def rand_weights(n):
    '''
    Produces n random weights that sum to 1
    '''
    k = np.random.rand(n)
    return k / sum(k)


def random_portfolio(returns):
    '''
    Returns the mean and standard deviation of returns for a random portfolio
    '''

    p = np.asmatrix(np.mean(returns, axis=1))
    w = np.asmatrix(rand_weights(returns.shape[0]))
    C = np.asmatrix(np.cov(returns))

    mu = w * p.T
    sigma = np.sqrt(w * C * w.T)

    # This recursion reduces outliers to keep plots pretty
    if sigma > 2:
        return random_portfolio(returns)
    return mu, sigma


def optimal_portfolios(returns):
    n = len(returns)
    returns = np.asmatrix(returns)

    N = 50000

    # Creating a list of returns to optimize the risk for
    mus = [10 ** (5.0 * t / N - 1.0) for t in range(N)]

    # Convert to cvxopt matrices
    S = opt.matrix(np.cov(returns))
    pbar = opt.matrix(np.mean(returns, axis=1))

    # Create constraint matrices
    G = -opt.matrix(np.eye(n))  # negative n x n identity matrix
    h = opt.matrix(0.0, (n, 1))
    A = opt.matrix(1.0, (1, n))
    b = opt.matrix(1.0)

    # Calculate efficient frontier weights using quadratic programming
    portfolios = [solvers.qp(mu * S, -pbar, G, h, A, b)['x']
                  for mu in mus]

    ## Calculate the risk and returns of the frontier
    returns = [blas.dot(pbar, x) for x in portfolios]
    risks = [np.sqrt(blas.dot(x, S * x)) for x in portfolios]

    return returns, risks


n_portfolios = 25000

means, stds = np.column_stack([random_portfolio(return_vec) for x in range(n_portfolios)])

returns, risks = optimal_portfolios(return_vec)
...