Commit 896a96c9 authored by Dr.李's avatar Dr.李

some codes refined

parent 00ab6bb5
...@@ -38,33 +38,32 @@ def benchmark_build_linear(n_samples: int, n_risks: int, n_loop: int) -> None: ...@@ -38,33 +38,32 @@ def benchmark_build_linear(n_samples: int, n_risks: int, n_loop: int) -> None:
ubound, ubound,
risk_exp, risk_exp,
risk_target=(risk_lbound, risk_target=(risk_lbound,
risk_ubound), risk_ubound))
solver='ECOS')
impl_model_time = dt.datetime.now() - start impl_model_time = dt.datetime.now() - start
print('{0:20s}: {1}'.format('Implemented model (ECOS)', impl_model_time)) print('{0:20s}: {1}'.format('Implemented model (ECOS)', impl_model_time))
c = - er c = - er
bounds = [(lbound, ubound) for _ in range(n_samples)] bounds = [(lbound, ubound) for _ in range(n_samples)]
A_eq = np.ones((1, n_samples)) a_eq = np.ones((1, n_samples))
A_eq = np.vstack((A_eq, risk_exp.T)) a_eq = np.vstack((a_eq, risk_exp.T))
b_eq = np.hstack((np.array([1.]), risk_exp.T @ bm)) b_eq = np.hstack((np.array([1.]), risk_exp.T @ bm))
start = dt.datetime.now() start = dt.datetime.now()
for _ in range(n_loop): for _ in range(n_loop):
res = linprog(c, A_eq=A_eq, b_eq=b_eq, bounds=bounds, options={'maxiter': 10000}) res = linprog(c, A_eq=a_eq, b_eq=b_eq, bounds=bounds, options={'maxiter': 10000})
benchmark_model_time = dt.datetime.now() - start benchmark_model_time = dt.datetime.now() - start
print('{0:20s}: {1}'.format('Benchmark model (scipy)', benchmark_model_time)) print('{0:20s}: {1}'.format('Benchmark model (scipy)', benchmark_model_time))
np.testing.assert_array_almost_equal(x, res['x']) np.testing.assert_array_almost_equal(x, res['x'])
c = matrix(-er) c = matrix(-er)
A = matrix(A_eq) aneq = matrix(a_eq)
b = matrix(b_eq) b = matrix(b_eq)
G = matrix(np.vstack((np.diag(np.ones(n_samples)), -np.diag(np.ones(n_samples))))) g = matrix(np.vstack((np.diag(np.ones(n_samples)), -np.diag(np.ones(n_samples)))))
h = matrix(np.hstack((ubound * np.ones(n_samples), -lbound * np.ones(n_samples)))) h = matrix(np.hstack((ubound * np.ones(n_samples), -lbound * np.ones(n_samples))))
solvers.lp(c, G, h, solver='glpk') solvers.lp(c, g, h, solver='glpk')
start = dt.datetime.now() start = dt.datetime.now()
for _ in range(n_loop): for _ in range(n_loop):
res2 = solvers.lp(c, G, h, A, b, solver='glpk') res2 = solvers.lp(c, g, h, aneq, b, solver='glpk')
benchmark_model_time = dt.datetime.now() - start benchmark_model_time = dt.datetime.now() - start
print('{0:20s}: {1}'.format('Benchmark model (glpk)', benchmark_model_time)) print('{0:20s}: {1}'.format('Benchmark model (glpk)', benchmark_model_time))
np.testing.assert_array_almost_equal(x, np.array(res2['x']).flatten()) np.testing.assert_array_almost_equal(x, np.array(res2['x']).flatten())
......
...@@ -1073,5 +1073,5 @@ if __name__ == '__main__': ...@@ -1073,5 +1073,5 @@ if __name__ == '__main__':
from sqlalchemy import create_engine from sqlalchemy import create_engine
engine = create_engine('postgresql+psycopg2://postgres:A12345678!@10.63.6.220/alpha') engine = create_engine('postgresql+psycopg2://user:pwd@host/alpha')
Base.metadata.create_all(engine) Base.metadata.create_all(engine)
...@@ -80,11 +80,12 @@ class SqlEngine(object): ...@@ -80,11 +80,12 @@ class SqlEngine(object):
def __init__(self, def __init__(self,
db_url: str): db_url: str):
self.engine = sa.create_engine(db_url) self.engine = sa.create_engine(db_url)
self.session = None
self.create_session() self.create_session()
def create_session(self): def create_session(self):
Session = orm.sessionmaker(bind=self.engine) db_session = orm.sessionmaker(bind=self.engine)
self.session = Session() self.session = db_session()
def fetch_factors_meta(self) -> pd.DataFrame: def fetch_factors_meta(self) -> pd.DataFrame:
query = self.session.query(FactorMaster) query = self.session.query(FactorMaster)
...@@ -207,9 +208,7 @@ class SqlEngine(object): ...@@ -207,9 +208,7 @@ class SqlEngine(object):
if __name__ == '__main__': if __name__ == '__main__':
db_url = 'mssql+pymssql://licheng:A12345678!@10.63.6.220/alpha?charset=cp936' db_url = 'mssql+pymssql://user:pwd@host/alpha?charset=cp936'
import datetime as dt
universe = Universe('custom', ['zz500']) universe = Universe('custom', ['zz500'])
engine = SqlEngine(db_url) engine = SqlEngine(db_url)
......
...@@ -13,6 +13,7 @@ from alphamind.analysis.riskanalysis import risk_analysis ...@@ -13,6 +13,7 @@ from alphamind.analysis.riskanalysis import risk_analysis
class TestRiskAnalysis(unittest.TestCase): class TestRiskAnalysis(unittest.TestCase):
@staticmethod
def test_risk_analysis(self): def test_risk_analysis(self):
n_samples = 36000 n_samples = 36000
n_dates = 20 n_dates = 20
......
...@@ -12,6 +12,7 @@ from alphamind.portfolio.constraints import Constraints ...@@ -12,6 +12,7 @@ from alphamind.portfolio.constraints import Constraints
class TestConstraints(unittest.TestCase): class TestConstraints(unittest.TestCase):
@staticmethod
def test_constraints(self): def test_constraints(self):
cons = Constraints() cons = Constraints()
......
...@@ -278,7 +278,3 @@ def aggregate(groups, x, func, ddof=1): ...@@ -278,7 +278,3 @@ def aggregate(groups, x, func, ddof=1):
raise ValueError('({0}) is not recognized as valid functor'.format(func)) raise ValueError('({0}) is not recognized as valid functor'.format(func))
return value_data return value_data
if __name__ == '__main__':
pass
\ No newline at end of file
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