Commit 95f794be authored by Dr.李's avatar Dr.李

fixed bug

parent 76350d78
......@@ -29,7 +29,7 @@ cdef class LPOptimizer:
cnp.ndarray[double] ubound,
cnp.ndarray[double] objective):
self.cobj = new LpOptimizer(cons_matrix.flatten().tolist(),
self.cobj = new LpOptimizer(cons_matrix.flatten(),
lbound,
ubound,
objective)
......
......@@ -8,34 +8,58 @@ Created on 2017-5-5
import numpy as np
from typing import Tuple
from typing import Union
import cvxpy
from cvxopt import solvers
solvers.options['glpk'] = {'msg_lev': 'GLP_MSG_OFF'}
from alphamind.cython.lpoptimizer import LPOptimizer
def linear_build(er: np.ndarray,
lbound: Union[np.ndarray, float],
ubound: Union[np.ndarray, float],
risk_constraints: np.ndarray,
risk_target: Tuple[np.ndarray, np.ndarray],
solver: str=None) -> Tuple[str, np.ndarray, np.ndarray]:
n, m = risk_constraints.shape
w = cvxpy.Variable(n)
risk_target: Tuple[np.ndarray, np.ndarray]) -> Tuple[str, np.ndarray, np.ndarray]:
curr_risk_exposure = risk_constraints.T @ w
n, m = risk_constraints.shape
if not risk_target:
constraints = [w >= lbound,
w <= ubound]
risk_lbound = -np.inf * np.ones(m)
risk_ubound = np.inf * np.ones(m)
cons_matrix = np.concatenate((risk_constraints.T, risk_lbound.reshape((-1, 1)), risk_ubound.reshape((-1, 1))),
axis=1)
else:
constraints = [w >= lbound,
w <= ubound,
curr_risk_exposure >= risk_target[0],
curr_risk_exposure <= risk_target[1]]
objective = cvxpy.Minimize(-w.T * er)
prob = cvxpy.Problem(objective, constraints)
prob.solve(solver=solver)
return prob.status, prob.value, np.array(w.value).flatten()
cons_matrix = np.concatenate((risk_constraints.T, risk_target[0].reshape((-1, 1)), risk_target[1].reshape((-1, 1))),
axis=1)
if isinstance(lbound, float):
lbound = np.ones(n) * lbound
if isinstance(ubound, float):
ubound = np.ones(n) * ubound
opt = LPOptimizer(cons_matrix, lbound, ubound, -er)
status = opt.status()
if status == 0:
status = 'optimal'
return status, opt.feval(), opt.x_value()
if __name__ == '__main__':
n = 200
lb = np.zeros(n)
ub = 0.01 * np.ones(n)
er = np.random.randn(n)
cons = np.zeros((2, n+2))
cons[0] = np.ones(n+2)
cons[1][0] = 1.
cons[1][1] = 1.
cons[1][-2] = 0.015
cons[1][-1] = 0.015
opt = LPOptimizer(cons, lb, ub, er)
print(opt.status())
x = opt.x_value()
print(x[0], x[1])
......@@ -59,7 +59,7 @@ class TestLinearBuild(unittest.TestCase):
self.assertTrue(np.all(w >= -eplson))
calc_risk = (w - bm) @ self.risk_exp / np.abs(bm @ self.risk_exp)
self.assertTrue(np.all(np.abs(calc_risk) <= 1e-2))
self.assertTrue(np.all(np.abs(calc_risk) <= 1.0001e-2))
if __name__ == '__main__':
......
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment