我正在尝试解决 cvxopt 中的二次问题,但似乎忽略了其中一项要求
我想解决这组方程:
G =
[-1.00e+00 -0.00e+00 -0.00e+00 -0.00e+00]
[-0.00e+00 -1.00e+00 -0.00e+00 -0.00e+00]
[-0.00e+00 -0.00e+00 -1.00e+00 -0.00e+00]
[-0.00e+00 -0.00e+00 -0.00e+00 -1.00e+00]
[ 1.00e+00 0.00e+00 0.00e+00 0.00e+00]
[ 0.00e+00 1.00e+00 0.00e+00 0.00e+00]
[ 0.00e+00 0.00e+00 1.00e+00 0.00e+00]
[ 0.00e+00 0.00e+00 0.00e+00 1.00e+00]
h =
[ 0.00]
[ 0.00]
[ 0.00]
[ 0.00]
[ 20.0]
[ 20.0]
[ 20.0]
[ 20.0]
G <= h
这是代码:
import numpy as np
import pandas as pd
import cvxopt as opt
from cvxopt import solvers
from pandas.io.data import DataReader
from pandas.io.data import DataFrame
def get_returns(stock_list, start_date, end_date, shift = 100):
raw_data = {}
for ticker in stock_list:
raw_data[ticker] = DataReader(ticker, 'yahoo', start_date, end_date)['Adj Close']
price = DataFrame({ tic: data for tic,
data in raw_data.iteritems()})
returns = price/price.shift(shift) - 1
returns = np.asmatrix(returns[shift:][:])
return returns.T
def print_portfolio(stock_list, portfolio):
for stock, weight in zip(stock_list, portfolio):
print('\t %s \t: %.4f.' % (stock,weight))
return
stock_list = ['AAPL','IBM','MSFT','ORCL']
start_date = '1/1/2011' # start of the historical data
end_date = '1/1/2012' # end of historical data
solvers.options['show_progress'] = False
returns = np.asmatrix(get_returns(stock_list, start_date, end_date))
n = len(returns)
N = 100
mus = [10**(5.0 * t/N - 1.0) for t in range(N)]
S = opt.matrix(np.cov(returns))
pbar = opt.matrix(np.mean(returns, axis=1))
G = -opt.matrix(np.eye(n))
G = opt.matrix(np.concatenate((G, -G), axis = 0))
print G
h = opt.matrix(np.concatenate((opt.matrix(0.0, (n ,1)), opt.matrix(0.20, (n ,1))), axis = 0))
print h
A = opt.matrix(1.0, (1, n)) #
b = opt.matrix(1.0)
portfolio = solvers.qp(S, -pbar, G, h, A, b)['x']
print_portfolio(stock_list, portfolio)
但我得到这样的结果:
AAPL : 0.0000.
IBM : 0.8000.
MSFT : 0.0000.
ORCL : 0.2000.
所以不满足 x <= 20 的要求。可能是什么原因?