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":
double*,
double*,
double,
double,
int,
double*,
double*,
......@@ -96,8 +95,7 @@ cdef class CVOptimizer:
cnp.ndarray[double, ndim=2] cons_matrix=None,
double[:] clbound=None,
double[:] cubound=None,
double target_low=0.0,
double target_high=1.0,
double target_vol=1.0,
cnp.ndarray[double, ndim=2] factor_cov_matrix=None,
cnp.ndarray[double, ndim=2] factor_loading_matrix=None,
double[:] idsync_risk=None):
......@@ -123,8 +121,7 @@ cdef class CVOptimizer:
&cons[0],
&clbound[0],
&cubound[0],
target_low,
target_high,
target_vol,
self.f,
&factor_cov[0] if factor_cov is not None else NULL,
&factor_loading[0] if factor_loading is not None else NULL,
......@@ -139,8 +136,7 @@ cdef class CVOptimizer:
NULL,
NULL,
NULL,
target_low,
target_high,
target_vol,
self.f,
&factor_cov[0] if factor_cov 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,
cons_mat,
clbound,
cubound,
0.,
vol_target,
risk_model['factor_cov'],
risk_model['factor_loading'],
......
......@@ -23,6 +23,7 @@ from alphamind.data.engines.sqlengine import industry_styles
from alphamind.data.engines.sqlengine import macro_styles
from alphamind.data.processing import factor_processing
from alphamind.analysis.factoranalysis import er_portfolio_analysis
from alphamind.exceptions.exceptions import PortfolioBuilderException
all_styles = risk_styles + industry_styles + macro_styles
......@@ -190,7 +191,7 @@ class Strategy(object):
current_position = None
else:
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)
current_position = remained_pos.weight.values
......@@ -254,19 +255,33 @@ class Strategy(object):
def _calculate_pos(self, running_setting, er, data, constraints, benchmark_w, lbound, ubound, risk_model,
current_position):
more_opts = running_setting.more_opts
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,
current_position=current_position,
target_vol=more_opts.get('target_vol'),
risk_model=risk_model,
turn_over_target=more_opts.get('turn_over_target'))
try:
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,
current_position=current_position,
target_vol=more_opts.get('target_vol'),
risk_model=risk_model,
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
......@@ -291,27 +306,22 @@ if __name__ == '__main__':
mpl.rcParams['font.sans-serif'] = ['SimHei']
mpl.rcParams['axes.unicode_minus'] = False
# Back test parameter settings
start_date = '2016-01-01'
end_date = '2018-06-11'
"""
Back test parameter settings
"""
benchmark_code = 905
universe = Universe('zz800') + Universe('cyb')
start_date = '2011-01-01'
end_date = '2011-05-04'
freq = '10b'
industry_name = 'sw_adj'
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
neutralized_risk = None
alpha_factors = {
'ep_q_cs': CSQuantiles(LAST('ep_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'),
'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'),
......@@ -322,10 +332,10 @@ if __name__ == '__main__':
weights = dict(ep_q_cs=1.,
roe_q_cs=1.,
SGRO_cs=0.0,
GREV_cs=0.0,
OperatingRevenueGrowRate_cs=1.,
GREV_cs=0.5,
con_peg_rolling_cs=-0.25,
con_pe_rolling_order_cs=-0.25,
con_pe_rolling_order_cs=-0.5,
IVR_cs=0.5,
ILLIQUIDITY_cs=0.5,
DividendPaidRatio_cs=0.5)
......@@ -338,79 +348,8 @@ if __name__ == '__main__':
neutralized_risk=None,
pre_process=None,
post_process=None,
data_source=data_source)
# Constraintes settings
industry_names = industry_list(industry_name, industry_level)
constraint_risk = ['SIZE', 'BETA']
total_risk_names = constraint_risk + ['benchmark', 'total']
all_styles = risk_styles + industry_names + macro_styles
b_type = []
l_val = []
u_val = []
previous_pos = pd.DataFrame()
rets = []
turn_overs = []
leverags = []
for name in total_risk_names:
if name == 'benchmark':
b_type.append(BoundaryType.RELATIVE)
l_val.append(0.8)
u_val.append(1.0)
elif name == 'total':
b_type.append(BoundaryType.ABSOLUTE)
l_val.append(.0)
u_val.append(.0)
elif name == 'EARNYILD':
b_type.append(BoundaryType.ABSOLUTE)
l_val.append(0.00)
u_val.append(0.60)
elif name == 'GROWTH':
b_type.append(BoundaryType.ABSOLUTE)
l_val.append(-0.05)
u_val.append(0.05)
elif name == 'MOMENTUM':
b_type.append(BoundaryType.ABSOLUTE)
l_val.append(0.20)
u_val.append(0.20)
elif name == 'SIZE':
b_type.append(BoundaryType.ABSOLUTE)
l_val.append(-0.05)
u_val.append(0.05)
elif name == 'LIQUIDTY':
b_type.append(BoundaryType.ABSOLUTE)
l_val.append(-0.40)
u_val.append(-0.0)
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:
b_type.append(BoundaryType.ABSOLUTE)
l_val.append(-0.002)
u_val.append(0.002)
data_source=os.environ['DB_URI'])
bounds = create_box_bounds(total_risk_names, b_type, l_val, u_val)
# Running settings
running_setting = RunningSetting(weights_bandwidth=weights_bandwidth,
rebalance_method=method,
bounds=bounds,
turn_over_target=turn_over_target)
# Strategy
strategy = Strategy(alpha_model,
data_meta,
universe=universe,
......@@ -420,4 +359,60 @@ if __name__ == '__main__':
benchmark=benchmark_code)
strategy.prepare_backtest_data()
ret_df, positions = strategy.run(running_setting=running_setting)
\ No newline at end of file
def create_scenario(weights_bandwidth=0.02, target_vol=0.01, method='risk_neutral'):
industry_names = industry_list('sw_adj', 1)
constraint_risk = ['EARNYILD', 'LIQUIDTY', 'GROWTH', 'SIZE', 'BETA', 'MOMENTUM']
total_risk_names = constraint_risk + industry_names + ['benchmark', 'total']
b_type = []
l_val = []
u_val = []
for name in total_risk_names:
if name == 'benchmark':
b_type.append(BoundaryType.RELATIVE)
l_val.append(0.8)
u_val.append(1.001)
elif name == 'total':
b_type.append(BoundaryType.ABSOLUTE)
l_val.append(-0.001)
u_val.append(.001)
elif name == 'EARNYILD':
b_type.append(BoundaryType.ABSOLUTE)
l_val.append(-0.001)
u_val.append(0.60)
elif name == 'GROWTH':
b_type.append(BoundaryType.ABSOLUTE)
l_val.append(-0.20)
u_val.append(0.20)
elif name == 'MOMENTUM':
b_type.append(BoundaryType.ABSOLUTE)
l_val.append(-0.10)
u_val.append(0.20)
elif name == 'SIZE':
b_type.append(BoundaryType.ABSOLUTE)
l_val.append(-0.20)
u_val.append(0.20)
elif name == 'LIQUIDTY':
b_type.append(BoundaryType.ABSOLUTE)
l_val.append(-0.25)
u_val.append(0.25)
else:
b_type.append(BoundaryType.ABSOLUTE)
l_val.append(-0.01)
u_val.append(0.01)
bounds = create_box_bounds(total_risk_names, b_type, l_val, u_val)
running_setting = RunningSetting(weights_bandwidth=weights_bandwidth,
rebalance_method=method,
bounds=bounds,
target_vol=target_vol,
turn_over_target=0.4)
ret_df, positions = strategy.run(running_setting)
return ret_df
create_scenario(0.01, target_vol=0.02, method='tv')
\ No newline at end of file
......@@ -116,7 +116,6 @@ class TestOptimizers(unittest.TestCase):
None,
None,
None,
target_vol,
target_vol)
# check against known good result
......@@ -144,7 +143,6 @@ class TestOptimizers(unittest.TestCase):
cons,
clbound,
cubound,
target_vol,
target_vol)
# check against known good result
......@@ -173,7 +171,6 @@ class TestOptimizers(unittest.TestCase):
cons,
clbound,
cubound,
0.,
target_vol,
factor_var,
factor_load,
......@@ -204,7 +201,6 @@ class TestOptimizers(unittest.TestCase):
cons,
clbound,
cubound,
0.,
target_vol)
# check against known good result
......
......@@ -57,6 +57,9 @@ class TestMeanVarianceBuild(unittest.TestCase):
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)
def test_mean_variance_builder_without_constraints_with_factor_model(self):
pass
def test_mean_variance_builder_with_none_unity_lambda(self):
er = np.array([0.01, 0.02, 0.03])
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