In [1]:
import datetime as dt
import numpy as np
import cvxpy
from alphamind.portfolio.linearbuilder import linear_builder
In [10]:
def time_function(py_callable, n):
start = dt.datetime.now()
result = py_callable(n)
elapsed = (dt.datetime.now() - start).total_seconds()
return elapsed, result
def cvxpy_lp(n):
w = cvxpy.Variable(n)
bndl = np.zeros(n)
bndu = 0.01 * np.ones(n)
risk_constraints1 = np.ones((n,1))
risk_constraints2 = np.zeros((n,1))
risk_constraints2[0][0] = 1.
risk_constraints2[1][0] = 1.
risk_constraints = np.concatenate((risk_constraints1, risk_constraints2), axis=1)
curr_risk_exposure = risk_constraints.T @ w
risk_targets = np.array([1., 0.015])
constraints = [w >= bndl,
w <= bndu,
curr_risk_exposure >= risk_targets,
curr_risk_exposure <= risk_targets]
np.random.seed(1)
er = np.random.randn(n)
objective = cvxpy.Minimize(-w.T * er)
prob = cvxpy.Problem(objective, constraints)
prob.solve(solver='ECOS')
return w, prob
In [11]:
print("{0:<8}{1:>12}{2:>12}{3:>12}{4:>12}{5:>12}{6:>15}".format('Scale(n)', 'time(ms)', 'feval', 'min(x)', 'max(x)', 'sum(x)', 'x(0) + x(1)'))
for n in range(200, 3200, 200):
elapsed, result = time_function(cvxpy_lp, n)
s = np.array(result[0].value).flatten()
print("{0:<8}{1:>12.2f}{2:>12.2f}{3:>12f}{4:>12f}{5:>12f}{6:>15}".format(n, elapsed*1000, result[1].value, s.min(), s.max(), s.sum(), s[0] + s[1]))
In [4]:
def clp_lp(n):
np.random.seed(1)
er = np.random.randn(n)
bndl = np.zeros(n)
bndu = 0.01 * np.ones(n)
risk_constraints1 = np.ones((n,1))
risk_constraints2 = np.zeros((n,1))
risk_constraints2[0][0] = 1.
risk_constraints2[1][0] = 1.
risk_constraints = np.concatenate((risk_constraints1, risk_constraints2), axis=1)
risk_target = np.array([1., 0.015]), np.array([1., 0.015])
result = linear_builder(er, bndl, bndu, risk_constraints, risk_target)
return result
In [5]:
print("{0:<8}{1:>12}{2:>12}{3:>12}{4:>12}{5:>12}{6:>15}".format('Scale(n)', 'time(ms)', 'feval', 'min(x)', 'max(x)', 'sum(x)', 'x(0) + x(1)'))
for n in range(200, 3200, 200):
elapsed, result = time_function(clp_lp, n)
s = result[2]
print("{0:<8}{1:>12.2f}{2:>12.2f}{3:>12f}{4:>12f}{5:>12f}{6:>15}".format(n, elapsed*1000, result[1], s.min(), s.max(), s.sum(), s[0] + s[1]))
In [ ]: