1.不等式約束
前面咱們討論了等式約束下的狀況,那麼若是有不等式約束呢?好比,咱們不能作空股票,那麼就要求每個股票的權重都要大於1,或者對於特定的股票咱們給予特殊的權重的設定等等。
這裏,咱們就假設咱們設置兩個不等式約束:
不能作空
股票s2的權重要要大於等於0.1.
這個時候,咱們的約束條件就是:
html
其中,
固然,這個時候就沒有解析解了,咱們須要用到python的一個凸優化的包來解決這個問題。
2.cvxopt optmizer
你們能夠查看一下cvxopt這個包的官網,http://cvxopt.org/install/index.html
按照官網的方法按照cvxopt彷佛是不能夠的,咱們能夠在下面的網站下載wheel,而後安裝。
http://www.lfd.uci.edu/~gohlke/pythonlibs/#cvxopt
對於cvxopt這個包而言,他的優化通式是這樣的:
python
言下之意,就是咱們要構建這幾個矩陣:P,q,G,h,A,b
from cvxopt import matrix
from cvxopt import solvers
cvxopt 中自帶matrix數據結構,要注意,這個和咱們前面對矩陣的表達不同,這裏一個list表明的是一個列,而不是行。web
P = matrix([[0.100162,0.045864,0.005712],[0.045864,0.210773,0.028283],[0.005712,0.028283,0.066884]])
q = matrix([0.0,0.0,0.0])
A = matrix([[1.0,1.0,1.0], [0.100162,0.164244,0.182082]]).T
b = matrix([1.0, 0.15])
sol = solvers.qp(P,q,A=A,b=b)
print sol['x']
結果以下:
[ 3.83e-01]
[ 3.97e-02]
[ 5.77e-01]
咱們發現,優化器優化出來的結構和咱們前面的用拉格朗日乘子法算出來的是同樣的。而後,咱們來算不等式約束吧。數據結構
3.不等式優化
咱們根據一開始的情景來進行不等式優化。app
P = matrix([[0.100162,0.045864,0.005712],[0.045864,0.210773,0.028283],[0.005712,0.028283,0.066884]])
q = matrix([0.0,0.0,0.0])
G = matrix([[0.0,-1.0,0.0], [-1.0,0.0,0.0],[0.0,0.0,-1.0]])
h = matrix([-0.1,0.0,0.0])
A = matrix([[1.0,1.0,1.0], [0.100162,0.164244,0.182082]]).T
b = matrix([1.0, 0.15])
sol = solvers.qp(P,q,G=G, h=h, A=A,b=b)
print sol['x']
[ 3.70e-01]
[ 1.00e-01]
[ 5.30e-01]
結果如上,這就是咱們不等式條件下的優化結果。
既然如此,仍是老樣子,畫有效前沿吧。svg
return_list = list()
risk_list = list()
P = matrix([[0.100162,0.045864,0.005712],[0.045864,0.210773,0.028283],[0.005712,0.028283,0.066884]])
q = matrix([0.0,0.0,0.0])
G = matrix([[0.0,-1.0,0.0], [-1.0,0.0,0.0],[0.0,0.0,-1.0]])
h = matrix([-0.1,0.0,0.0])
A = matrix([[1.0,1.0,1.0], [0.100162,0.164244,0.182082]]).T
for i in range(1, 100):
up = i/1000.0
b = matrix([1.0, up])
sol = solvers.qp(P,q,G=G, h=h, A=A,b=b)
w = np.matrix([sol['x'][0], sol['x'][1], sol['x'][2]]).T
return_list.append((A_matrix * w)[1,0])
risk_list.append((w.T * cov_matrix * w)[0,0])
plot_df = pd.DataFrame()
plot_df['return'] = return_list
plot_df['risk'] = risk_list
plot_df.plot.scatter(x='risk', y='return')
結果以下:
咱們之因此要先講述組合構建和優化器,是由於,接下來咱們將進行最最具備藝術的兩個部分,就是咱們前面提到的收益率預測模型和股票直接協方差矩陣,也就是風險模型。優化
本文同步分享在 博客「錢塘小甲子」(CSDN)。
若有侵權,請聯繫 support@oschina.cn 刪除。
本文參與「OSC源創計劃」,歡迎正在閱讀的你也加入,一塊兒分享。網站