Commit 99b252c3 authored by wegamekinglc's avatar wegamekinglc

added with new api

parent 2161714e
...@@ -72,7 +72,6 @@ cdef extern from "tvoptimizer.hpp" namespace "pfopt": ...@@ -72,7 +72,6 @@ cdef extern from "tvoptimizer.hpp" namespace "pfopt":
double*, double*,
double*, double*,
double, double,
double,
int, int,
double*, double*,
double*, double*,
...@@ -96,8 +95,7 @@ cdef class CVOptimizer: ...@@ -96,8 +95,7 @@ cdef class CVOptimizer:
cnp.ndarray[double, ndim=2] cons_matrix=None, cnp.ndarray[double, ndim=2] cons_matrix=None,
double[:] clbound=None, double[:] clbound=None,
double[:] cubound=None, double[:] cubound=None,
double target_low=0.0, double target_vol=1.0,
double target_high=1.0,
cnp.ndarray[double, ndim=2] factor_cov_matrix=None, cnp.ndarray[double, ndim=2] factor_cov_matrix=None,
cnp.ndarray[double, ndim=2] factor_loading_matrix=None, cnp.ndarray[double, ndim=2] factor_loading_matrix=None,
double[:] idsync_risk=None): double[:] idsync_risk=None):
...@@ -123,8 +121,7 @@ cdef class CVOptimizer: ...@@ -123,8 +121,7 @@ cdef class CVOptimizer:
&cons[0], &cons[0],
&clbound[0], &clbound[0],
&cubound[0], &cubound[0],
target_low, target_vol,
target_high,
self.f, self.f,
&factor_cov[0] if factor_cov is not None else NULL, &factor_cov[0] if factor_cov is not None else NULL,
&factor_loading[0] if factor_loading is not None else NULL, &factor_loading[0] if factor_loading is not None else NULL,
...@@ -139,8 +136,7 @@ cdef class CVOptimizer: ...@@ -139,8 +136,7 @@ cdef class CVOptimizer:
NULL, NULL,
NULL, NULL,
NULL, NULL,
target_low, target_vol,
target_high,
self.f, self.f,
&factor_cov[0] if factor_cov is not None else NULL, &factor_cov[0] if factor_cov is not None else NULL,
&factor_loading[0] if factor_loading is not None else NULL, &factor_loading[0] if factor_loading is not None else NULL,
......
Subproject commit ffaf2153dfdce380c3d8aa1a69b328ab77665ad3 Subproject commit b78ad8a55855c448a866f91a3876a271a52d68a1
...@@ -109,7 +109,6 @@ def target_vol_builder(er: np.ndarray, ...@@ -109,7 +109,6 @@ def target_vol_builder(er: np.ndarray,
cons_mat, cons_mat,
clbound, clbound,
cubound, cubound,
0.,
vol_target, vol_target,
risk_model['factor_cov'], risk_model['factor_cov'],
risk_model['factor_loading'], risk_model['factor_loading'],
......
...@@ -23,6 +23,7 @@ from alphamind.data.engines.sqlengine import industry_styles ...@@ -23,6 +23,7 @@ from alphamind.data.engines.sqlengine import industry_styles
from alphamind.data.engines.sqlengine import macro_styles from alphamind.data.engines.sqlengine import macro_styles
from alphamind.data.processing import factor_processing from alphamind.data.processing import factor_processing
from alphamind.analysis.factoranalysis import er_portfolio_analysis from alphamind.analysis.factoranalysis import er_portfolio_analysis
from alphamind.exceptions.exceptions import PortfolioBuilderException
all_styles = risk_styles + industry_styles + macro_styles all_styles = risk_styles + industry_styles + macro_styles
...@@ -190,7 +191,7 @@ class Strategy(object): ...@@ -190,7 +191,7 @@ class Strategy(object):
current_position = None current_position = None
else: else:
previous_pos.set_index('code', inplace=True) previous_pos.set_index('code', inplace=True)
remained_pos = previous_pos.loc[codes] remained_pos = previous_pos.reindex(codes)
remained_pos.fillna(0., inplace=True) remained_pos.fillna(0., inplace=True)
current_position = remained_pos.weight.values current_position = remained_pos.weight.values
...@@ -254,6 +255,7 @@ class Strategy(object): ...@@ -254,6 +255,7 @@ class Strategy(object):
def _calculate_pos(self, running_setting, er, data, constraints, benchmark_w, lbound, ubound, risk_model, def _calculate_pos(self, running_setting, er, data, constraints, benchmark_w, lbound, ubound, risk_model,
current_position): current_position):
more_opts = running_setting.more_opts more_opts = running_setting.more_opts
try:
target_pos, _ = er_portfolio_analysis(er, target_pos, _ = er_portfolio_analysis(er,
industry=data.industry_name.values, industry=data.industry_name.values,
dx_return=None, dx_return=None,
...@@ -267,6 +269,19 @@ class Strategy(object): ...@@ -267,6 +269,19 @@ class Strategy(object):
target_vol=more_opts.get('target_vol'), target_vol=more_opts.get('target_vol'),
risk_model=risk_model, risk_model=risk_model,
turn_over_target=more_opts.get('turn_over_target')) turn_over_target=more_opts.get('turn_over_target'))
except PortfolioBuilderException:
alpha_logger.warning("Not able to fit the constraints. Using full re-balance.")
target_pos, _ = er_portfolio_analysis(er,
industry=data.industry_name.values,
dx_return=None,
constraints=constraints,
detail_analysis=False,
benchmark=benchmark_w,
method=running_setting.rebalance_method,
lbound=lbound,
ubound=ubound,
target_vol=more_opts.get('target_vol'),
risk_model=risk_model)
return target_pos return target_pos
...@@ -291,27 +306,22 @@ if __name__ == '__main__': ...@@ -291,27 +306,22 @@ if __name__ == '__main__':
mpl.rcParams['font.sans-serif'] = ['SimHei'] mpl.rcParams['font.sans-serif'] = ['SimHei']
mpl.rcParams['axes.unicode_minus'] = False mpl.rcParams['axes.unicode_minus'] = False
# Back test parameter settings """
start_date = '2016-01-01' Back test parameter settings
end_date = '2018-06-11' """
benchmark_code = 905
universe = Universe('zz800') + Universe('cyb')
start_date = '2011-01-01'
end_date = '2011-05-04'
freq = '10b' freq = '10b'
industry_name = 'sw_adj' neutralized_risk = None
industry_level = 1
turn_over_target = 0.4
batch = 1
horizon = map_freq(freq)
weights_bandwidth = 0.02
universe = Universe('zz800')
data_source = os.environ['DB_URI']
benchmark_code = 300
method = 'risk_neutral'
# Model settings
alpha_factors = { alpha_factors = {
'ep_q_cs': CSQuantiles(LAST('ep_q'), groups='sw1_adj'), 'ep_q_cs': CSQuantiles(LAST('ep_q'), groups='sw1_adj'),
'roe_q_cs': CSQuantiles(LAST('roe_q'), groups='sw1_adj'), 'roe_q_cs': CSQuantiles(LAST('roe_q'), groups='sw1_adj'),
'SGRO_cs': CSQuantiles(LAST('SGRO'), groups='sw1_adj'), 'OperatingRevenueGrowRate_cs': CSQuantiles(LAST('OperatingRevenueGrowRate'), groups='sw1_adj'),
'GREV_cs': CSQuantiles(LAST('GREV'), groups='sw1_adj'), 'GREV_cs': CSQuantiles(LAST('GREV'), groups='sw1_adj'),
'con_peg_rolling_cs': CSQuantiles(LAST('con_peg_rolling'), groups='sw1_adj'), 'con_peg_rolling_cs': CSQuantiles(LAST('con_peg_rolling'), groups='sw1_adj'),
'con_pe_rolling_order_cs': CSQuantiles(LAST('con_pe_rolling_order'), groups='sw1_adj'), 'con_pe_rolling_order_cs': CSQuantiles(LAST('con_pe_rolling_order'), groups='sw1_adj'),
...@@ -322,10 +332,10 @@ if __name__ == '__main__': ...@@ -322,10 +332,10 @@ if __name__ == '__main__':
weights = dict(ep_q_cs=1., weights = dict(ep_q_cs=1.,
roe_q_cs=1., roe_q_cs=1.,
SGRO_cs=0.0, OperatingRevenueGrowRate_cs=1.,
GREV_cs=0.0, GREV_cs=0.5,
con_peg_rolling_cs=-0.25, con_peg_rolling_cs=-0.25,
con_pe_rolling_order_cs=-0.25, con_pe_rolling_order_cs=-0.5,
IVR_cs=0.5, IVR_cs=0.5,
ILLIQUIDITY_cs=0.5, ILLIQUIDITY_cs=0.5,
DividendPaidRatio_cs=0.5) DividendPaidRatio_cs=0.5)
...@@ -338,86 +348,71 @@ if __name__ == '__main__': ...@@ -338,86 +348,71 @@ if __name__ == '__main__':
neutralized_risk=None, neutralized_risk=None,
pre_process=None, pre_process=None,
post_process=None, post_process=None,
data_source=data_source) data_source=os.environ['DB_URI'])
strategy = Strategy(alpha_model,
data_meta,
universe=universe,
start_date=start_date,
end_date=end_date,
freq=freq,
benchmark=benchmark_code)
strategy.prepare_backtest_data()
# Constraintes settings
industry_names = industry_list(industry_name, industry_level) def create_scenario(weights_bandwidth=0.02, target_vol=0.01, method='risk_neutral'):
constraint_risk = ['SIZE', 'BETA'] industry_names = industry_list('sw_adj', 1)
total_risk_names = constraint_risk + ['benchmark', 'total'] constraint_risk = ['EARNYILD', 'LIQUIDTY', 'GROWTH', 'SIZE', 'BETA', 'MOMENTUM']
all_styles = risk_styles + industry_names + macro_styles total_risk_names = constraint_risk + industry_names + ['benchmark', 'total']
b_type = [] b_type = []
l_val = [] l_val = []
u_val = [] u_val = []
previous_pos = pd.DataFrame()
rets = []
turn_overs = []
leverags = []
for name in total_risk_names: for name in total_risk_names:
if name == 'benchmark': if name == 'benchmark':
b_type.append(BoundaryType.RELATIVE) b_type.append(BoundaryType.RELATIVE)
l_val.append(0.8) l_val.append(0.8)
u_val.append(1.0) u_val.append(1.001)
elif name == 'total': elif name == 'total':
b_type.append(BoundaryType.ABSOLUTE) b_type.append(BoundaryType.ABSOLUTE)
l_val.append(.0) l_val.append(-0.001)
u_val.append(.0) u_val.append(.001)
elif name == 'EARNYILD': elif name == 'EARNYILD':
b_type.append(BoundaryType.ABSOLUTE) b_type.append(BoundaryType.ABSOLUTE)
l_val.append(0.00) l_val.append(-0.001)
u_val.append(0.60) u_val.append(0.60)
elif name == 'GROWTH': elif name == 'GROWTH':
b_type.append(BoundaryType.ABSOLUTE) b_type.append(BoundaryType.ABSOLUTE)
l_val.append(-0.05) l_val.append(-0.20)
u_val.append(0.05) u_val.append(0.20)
elif name == 'MOMENTUM': elif name == 'MOMENTUM':
b_type.append(BoundaryType.ABSOLUTE) b_type.append(BoundaryType.ABSOLUTE)
l_val.append(0.20) l_val.append(-0.10)
u_val.append(0.20) u_val.append(0.20)
elif name == 'SIZE': elif name == 'SIZE':
b_type.append(BoundaryType.ABSOLUTE) b_type.append(BoundaryType.ABSOLUTE)
l_val.append(-0.05) l_val.append(-0.20)
u_val.append(0.05) u_val.append(0.20)
elif name == 'LIQUIDTY': elif name == 'LIQUIDTY':
b_type.append(BoundaryType.ABSOLUTE) b_type.append(BoundaryType.ABSOLUTE)
l_val.append(-0.40) l_val.append(-0.25)
u_val.append(-0.0) u_val.append(0.25)
elif benchmark_code == 905 and name not in ["计算机", "医药生物", "国防军工", "信息服务", "机械设备"] and name in industry_names:
b_type.append(BoundaryType.RELATIVE)
l_val.append(0.8)
u_val.append(1.0)
elif benchmark_code == 300 and name in ["银行", "保险", "证券", "多元金融"]:
b_type.append(BoundaryType.RELATIVE)
l_val.append(0.70)
u_val.append(0.90)
elif name in ["计算机", "医药生物", "国防军工", "信息服务", "机械设备"]:
b_type.append(BoundaryType.ABSOLUTE)
l_val.append(0.0)
u_val.append(0.05)
else: else:
b_type.append(BoundaryType.ABSOLUTE) b_type.append(BoundaryType.ABSOLUTE)
l_val.append(-0.002) l_val.append(-0.01)
u_val.append(0.002) u_val.append(0.01)
bounds = create_box_bounds(total_risk_names, b_type, l_val, u_val) bounds = create_box_bounds(total_risk_names, b_type, l_val, u_val)
# Running settings
running_setting = RunningSetting(weights_bandwidth=weights_bandwidth, running_setting = RunningSetting(weights_bandwidth=weights_bandwidth,
rebalance_method=method, rebalance_method=method,
bounds=bounds, bounds=bounds,
turn_over_target=turn_over_target) target_vol=target_vol,
turn_over_target=0.4)
# Strategy ret_df, positions = strategy.run(running_setting)
strategy = Strategy(alpha_model, return ret_df
data_meta,
universe=universe,
start_date=start_date,
end_date=end_date,
freq=freq,
benchmark=benchmark_code)
strategy.prepare_backtest_data()
ret_df, positions = strategy.run(running_setting=running_setting) create_scenario(0.01, target_vol=0.02, method='tv')
\ No newline at end of file \ No newline at end of file
...@@ -116,7 +116,6 @@ class TestOptimizers(unittest.TestCase): ...@@ -116,7 +116,6 @@ class TestOptimizers(unittest.TestCase):
None, None,
None, None,
None, None,
target_vol,
target_vol) target_vol)
# check against known good result # check against known good result
...@@ -144,7 +143,6 @@ class TestOptimizers(unittest.TestCase): ...@@ -144,7 +143,6 @@ class TestOptimizers(unittest.TestCase):
cons, cons,
clbound, clbound,
cubound, cubound,
target_vol,
target_vol) target_vol)
# check against known good result # check against known good result
...@@ -173,7 +171,6 @@ class TestOptimizers(unittest.TestCase): ...@@ -173,7 +171,6 @@ class TestOptimizers(unittest.TestCase):
cons, cons,
clbound, clbound,
cubound, cubound,
0.,
target_vol, target_vol,
factor_var, factor_var,
factor_load, factor_load,
...@@ -204,7 +201,6 @@ class TestOptimizers(unittest.TestCase): ...@@ -204,7 +201,6 @@ class TestOptimizers(unittest.TestCase):
cons, cons,
clbound, clbound,
cubound, cubound,
0.,
target_vol) target_vol)
# check against known good result # check against known good result
......
...@@ -57,6 +57,9 @@ class TestMeanVarianceBuild(unittest.TestCase): ...@@ -57,6 +57,9 @@ class TestMeanVarianceBuild(unittest.TestCase):
status, _, x = mean_variance_builder(er, model, bm, lbound, ubound, None, None, lam=1) status, _, x = mean_variance_builder(er, model, bm, lbound, ubound, None, None, lam=1)
np.testing.assert_array_almost_equal(x, np.linalg.inv(cov) @ er) np.testing.assert_array_almost_equal(x, np.linalg.inv(cov) @ er)
def test_mean_variance_builder_without_constraints_with_factor_model(self):
pass
def test_mean_variance_builder_with_none_unity_lambda(self): def test_mean_variance_builder_with_none_unity_lambda(self):
er = np.array([0.01, 0.02, 0.03]) er = np.array([0.01, 0.02, 0.03])
cov = np.array([[0.02, 0.01, 0.02], cov = np.array([[0.02, 0.01, 0.02],
......
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