Commit 636e498d authored by Dr.李's avatar Dr.李

update example

parent 09dc52e9
...@@ -3,7 +3,9 @@ ...@@ -3,7 +3,9 @@
{ {
"cell_type": "code", "cell_type": "code",
"execution_count": null, "execution_count": null,
"metadata": {}, "metadata": {
"collapsed": true
},
"outputs": [], "outputs": [],
"source": [ "source": [
"%matplotlib inline\n", "%matplotlib inline\n",
...@@ -28,10 +30,12 @@ ...@@ -28,10 +30,12 @@
{ {
"cell_type": "code", "cell_type": "code",
"execution_count": null, "execution_count": null,
"metadata": {}, "metadata": {
"collapsed": true
},
"outputs": [], "outputs": [],
"source": [ "source": [
"ref_date = '2018-02-08'\n", "ref_date = '2018-01-08'\n",
"engine = SqlEngine('postgres+psycopg2://postgres:we083826@192.168.0.102/alpha')\n", "engine = SqlEngine('postgres+psycopg2://postgres:we083826@192.168.0.102/alpha')\n",
"universe = Universe('custom', ['zz800'])" "universe = Universe('custom', ['zz800'])"
] ]
...@@ -39,24 +43,28 @@ ...@@ -39,24 +43,28 @@
{ {
"cell_type": "code", "cell_type": "code",
"execution_count": null, "execution_count": null,
"metadata": {}, "metadata": {
"collapsed": true
},
"outputs": [], "outputs": [],
"source": [ "source": [
"codes = engine.fetch_codes(ref_date, universe)\n", "codes = engine.fetch_codes(ref_date, universe)\n",
"total_data = engine.fetch_data(ref_date, 'ep_q', codes, 905, industry='sw_adj')\n", "total_data = engine.fetch_data(ref_date, 'ep_q', codes, 906, industry='sw_adj', risk_model='day')\n",
"all_styles = risk_styles + industry_styles + ['COUNTRY']" "all_styles = risk_styles + industry_styles + ['COUNTRY']"
] ]
}, },
{ {
"cell_type": "code", "cell_type": "code",
"execution_count": null, "execution_count": null,
"metadata": {}, "metadata": {
"collapsed": true
},
"outputs": [], "outputs": [],
"source": [ "source": [
"risk_cov = total_data['risk_cov'][all_styles].values\n", "risk_cov = total_data['risk_cov'][all_styles].values\n",
"factor = total_data['factor']\n", "factor = total_data['factor']\n",
"risk_exposure = factor[all_styles].values\n", "risk_exposure = factor[all_styles].values\n",
"special_risk = factor['s_srisk'].values" "special_risk = factor['d_srisk'].values"
] ]
}, },
{ {
...@@ -84,7 +92,9 @@ ...@@ -84,7 +92,9 @@
{ {
"cell_type": "code", "cell_type": "code",
"execution_count": null, "execution_count": null,
"metadata": {}, "metadata": {
"collapsed": true
},
"outputs": [], "outputs": [],
"source": [ "source": [
"er = factor['ep_q'].values\n", "er = factor['ep_q'].values\n",
...@@ -107,7 +117,7 @@ ...@@ -107,7 +117,7 @@
"source": [ "source": [
"# check the result\n", "# check the result\n",
"print(f\"total weight is {p_weight.sum(): .4f}\")\n", "print(f\"total weight is {p_weight.sum(): .4f}\")\n",
"print(f\"portfolio activate weight forecasting vol is {np.sqrt((p_weight - bm) @ sec_cov @ (p_weight - bm)):.2f}\")\n", "print(f\"portfolio activate weight forecasting vol is {np.sqrt((p_weight - bm) @ sec_cov @ (p_weight - bm)):.4f}\")\n",
"print(f\"portfolio expected return is {p_weight @ er:.4f} comparing with benchmark er {bm @ er:.4f}\")" "print(f\"portfolio expected return is {p_weight @ er:.4f} comparing with benchmark er {bm @ er:.4f}\")"
] ]
}, },
...@@ -122,29 +132,37 @@ ...@@ -122,29 +132,37 @@
{ {
"cell_type": "code", "cell_type": "code",
"execution_count": null, "execution_count": null,
"metadata": {}, "metadata": {
"collapsed": true
},
"outputs": [], "outputs": [],
"source": [ "source": [
"\"\"\"\n", "\"\"\"\n",
"Back test parameter settings\n", "Back test parameter settings\n",
"\"\"\"\n", "\"\"\"\n",
"\n", "\n",
"start_date = '2011-01-01'\n", "start_date = '2010-01-01'\n",
"end_date = '2018-02-14'\n", "end_date = '2018-03-08'\n",
"\n", "\n",
"freq = '10b'\n", "freq = '10b'\n",
"industry_lower = 1.0\n", "neutralized_risk = industry_styles\n",
"industry_upper = 1.0\n",
"neutralized_risk = ['SIZE'] + industry_styles\n",
"industry_name = 'sw_adj'\n", "industry_name = 'sw_adj'\n",
"industry_level = 1\n", "industry_level = 1\n",
"risk_model = 'short'\n",
"batch = 0\n", "batch = 0\n",
"horizon = map_freq(freq)\n", "horizon = map_freq(freq)\n",
"universe = Universe(\"custom\", ['zz500'])\n", "universe = Universe(\"custom\", ['zz800'])\n",
"data_source = 'postgres+psycopg2://postgres:we083826@192.168.0.102/alpha'\n", "data_source = 'postgres+psycopg2://postgres:we083826@192.168.0.102/alpha'\n",
"benchmark_code = 905\n", "benchmark_code = 906\n",
"target_vol = 0.05\n", "target_vol = 0.05\n",
"\n", "\n",
"if risk_model == 'day':\n",
" risk_model_name = 'd_srisk'\n",
"elif risk_model == 'short':\n",
" risk_model_name = 's_srisk'\n",
"else:\n",
" risk_model_name = 'l_srisk'\n",
"\n",
"executor = NaiveExecutor()\n", "executor = NaiveExecutor()\n",
"ref_dates = makeSchedule(start_date, end_date, freq, 'china.sse')\n", "ref_dates = makeSchedule(start_date, end_date, freq, 'china.sse')\n",
"engine = SqlEngine(data_source)" "engine = SqlEngine(data_source)"
...@@ -153,14 +171,16 @@ ...@@ -153,14 +171,16 @@
{ {
"cell_type": "code", "cell_type": "code",
"execution_count": null, "execution_count": null,
"metadata": {}, "metadata": {
"collapsed": true
},
"outputs": [], "outputs": [],
"source": [ "source": [
"\"\"\"\n", "\"\"\"\n",
"Factor Model\n", "Factor Model\n",
"\"\"\"\n", "\"\"\"\n",
"\n", "\n",
"alpha_factors = {'f01': LAST('ep_q')}\n", "alpha_factors = {'f01': CSRank(LAST('ep_q'))}\n",
"\n", "\n",
"weights = dict(f01=1.)\n", "weights = dict(f01=1.)\n",
"\n", "\n",
...@@ -203,7 +223,9 @@ ...@@ -203,7 +223,9 @@
{ {
"cell_type": "code", "cell_type": "code",
"execution_count": null, "execution_count": null,
"metadata": {}, "metadata": {
"collapsed": true
},
"outputs": [], "outputs": [],
"source": [ "source": [
"\"\"\"\n", "\"\"\"\n",
...@@ -225,14 +247,16 @@ ...@@ -225,14 +247,16 @@
"bounds = create_box_bounds(total_risk_names, b_type, l_val, u_val)\n", "bounds = create_box_bounds(total_risk_names, b_type, l_val, u_val)\n",
"industry_total = engine.fetch_industry_matrix_range(universe, dates=ref_dates, category=industry_name, level=industry_level)\n", "industry_total = engine.fetch_industry_matrix_range(universe, dates=ref_dates, category=industry_name, level=industry_level)\n",
"benchmark_total = engine.fetch_benchmark_range(dates=ref_dates, benchmark=benchmark_code)\n", "benchmark_total = engine.fetch_benchmark_range(dates=ref_dates, benchmark=benchmark_code)\n",
"risk_cov_total, risk_exposure_total = engine.fetch_risk_model_range(universe, dates=ref_dates)\n", "risk_cov_total, risk_exposure_total = engine.fetch_risk_model_range(universe, dates=ref_dates, risk_model=risk_model)\n",
"index_return = engine.fetch_dx_return_index_range(benchmark_code, start_date, end_date, horizon=horizon, offset=1).set_index('trade_date')" "index_return = engine.fetch_dx_return_index_range(benchmark_code, start_date, end_date, horizon=horizon, offset=1).set_index('trade_date')"
] ]
}, },
{ {
"cell_type": "code", "cell_type": "code",
"execution_count": null, "execution_count": null,
"metadata": {}, "metadata": {
"collapsed": true
},
"outputs": [], "outputs": [],
"source": [ "source": [
"# rebalance\n", "# rebalance\n",
...@@ -260,7 +284,7 @@ ...@@ -260,7 +284,7 @@
" \n", " \n",
" risk_exposure = total_data[all_styles].values\n", " risk_exposure = total_data[all_styles].values\n",
" risk_cov = risk_cov[all_styles].values\n", " risk_cov = risk_cov[all_styles].values\n",
" special_risk = total_data['s_srisk'].values\n", " special_risk = total_data[risk_model_name].values\n",
" sec_cov = risk_exposure @ risk_cov @ risk_exposure.T / 10000 + np.diag(special_risk ** 2) / 10000\n", " sec_cov = risk_exposure @ risk_cov @ risk_exposure.T / 10000 + np.diag(special_risk ** 2) / 10000\n",
"\n", "\n",
" benchmark_w = total_data.weight.values\n", " benchmark_w = total_data.weight.values\n",
...@@ -272,7 +296,7 @@ ...@@ -272,7 +296,7 @@
" constraints = LinearConstraints(bounds, total_risk_exp, benchmark_w)\n", " constraints = LinearConstraints(bounds, total_risk_exp, benchmark_w)\n",
" \n", " \n",
" lbound = np.zeros(len(total_data))\n", " lbound = np.zeros(len(total_data))\n",
" ubound = 0.05 + benchmark_w\n", " ubound = np.ones(len(total_data)) * 0.1\n",
"\n", "\n",
" er = predicts[i].loc[codes].values.flatten()\n", " er = predicts[i].loc[codes].values.flatten()\n",
" cons_mat = np.ones((len(er), 1))\n", " cons_mat = np.ones((len(er), 1))\n",
...@@ -280,7 +304,7 @@ ...@@ -280,7 +304,7 @@
" \n", " \n",
" try:\n", " try:\n",
" target_pos, _ = er_portfolio_analysis(er,\n", " target_pos, _ = er_portfolio_analysis(er,\n",
" industry_matrix.industry_name.values,\n", " total_data.industry_name.values,\n",
" None,\n", " None,\n",
" constraints,\n", " constraints,\n",
" False,\n", " False,\n",
...@@ -348,14 +372,9 @@ ...@@ -348,14 +372,9 @@
{ {
"cell_type": "code", "cell_type": "code",
"execution_count": null, "execution_count": null,
"metadata": {}, "metadata": {
"outputs": [], "collapsed": true
"source": [] },
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [], "outputs": [],
"source": [] "source": []
} }
...@@ -376,7 +395,36 @@ ...@@ -376,7 +395,36 @@
"name": "python", "name": "python",
"nbconvert_exporter": "python", "nbconvert_exporter": "python",
"pygments_lexer": "ipython3", "pygments_lexer": "ipython3",
"version": "3.6.4" "version": "3.6.3"
},
"varInspector": {
"cols": {
"lenName": 16,
"lenType": 16,
"lenVar": 40
},
"kernels_config": {
"python": {
"delete_cmd_postfix": "",
"delete_cmd_prefix": "del ",
"library": "var_list.py",
"varRefreshCmd": "print(var_dic_list())"
},
"r": {
"delete_cmd_postfix": ") ",
"delete_cmd_prefix": "rm(",
"library": "var_list.r",
"varRefreshCmd": "cat(var_dic_list()) "
}
},
"types_to_exclude": [
"module",
"function",
"builtin_function_or_method",
"instance",
"_Feature"
],
"window_display": false
} }
}, },
"nbformat": 4, "nbformat": 4,
......
{
"cells": [
{
"cell_type": "markdown",
"metadata": {
"collapsed": true
},
"source": [
"* 比较不同组合组合优化器在不同规模问题上的性能;\n",
"\n",
"* 下面的结果主要比较``alphamind``和``sicpy``中内置优化器的性能差别;\n",
"\n",
"* 由于``scipy``在``ashare_ex``上面性能太差,所以一般忽略``scipy``在这个股票池上的表现;\n",
"\n",
"* 时间单位都是毫秒。"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"collapsed": true
},
"outputs": [],
"source": [
"import timeit\n",
"import numpy as np\n",
"import pandas as pd\n",
"from scipy.optimize import linprog\n",
"from scipy.optimize import minimize\n",
"from alphamind.api import *\n",
"from alphamind.portfolio.linearbuilder import linear_builder\n",
"from alphamind.portfolio.meanvariancebuilder import mean_variance_builder\n",
"from alphamind.portfolio.meanvariancebuilder import target_vol_builder\n",
"\n",
"pd.options.display.float_format = '{:,.2f}'.format"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"## 0. 数据准备\n",
"------------------"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"collapsed": true
},
"outputs": [],
"source": [
"ref_date = '2018-02-08'\n",
"u_names = ['sh50', 'hs300', 'zz500', 'zz800', 'ashare_ex']\n",
"b_codes = [16, 300, 905, 906, None]\n",
"risk_model = 'short'\n",
"lb = 0.0\n",
"ub = 0.1\n",
"data_source = 'postgres+psycopg2://postgres:we083826@localhost/alpha'\n",
"engine = SqlEngine(data_source)\n",
"\n",
"universes = [Universe('custom', [u_name]) for u_name in u_names]\n",
"codes_set = [engine.fetch_codes(ref_date, universe=universe) for universe in universes]\n",
"data_set = [engine.fetch_data(ref_date, 'ep_q', codes, benchmark=b_code, risk_model=risk_model) for codes, b_code in zip(codes_set, b_codes)]"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"## 1. 线性优化(带线性限制条件)\n",
"---------------------------------"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"df = pd.DataFrame(columns=u_names, index=['scipy', 'alphamind'])\n",
"\n",
"number = 1\n",
"\n",
"for u_name, sample_data in zip(u_names, data_set):\n",
" factor_data = sample_data['factor']\n",
" er = factor_data['ep_q'].values\n",
" lbound = np.ones(len(er)) * lb\n",
" ubound = np.ones(len(er)) * ub\n",
"\n",
" risk_constraints = np.ones((len(er), 1))\n",
" risk_target = (np.array([1.]), np.array([1.]))\n",
"\n",
" status, y, x1 = linear_builder(er, lbound, ubound, risk_constraints, risk_target)\n",
" elasped_time1 = timeit.timeit(\"linear_builder(er, lbound, ubound, risk_constraints, risk_target)\", number=number, globals=globals()) / number * 1000\n",
"\n",
" c = -er\n",
" A_eq = risk_constraints.T\n",
" b_eq = np.array([1.])\n",
" \n",
" if u_name != 'ashare_ex':\n",
" res = linprog(c, A_ub=None, b_ub=None, A_eq=A_eq, b_eq=b_eq, bounds=list(zip(lbound, ubound)))\n",
" elasped_time2 = timeit.timeit(\"linprog(c, A_ub=None, b_ub=None, A_eq=A_eq, b_eq=b_eq, bounds=list(zip(lbound, ubound)))\",\n",
" number=number, globals=globals()) / number * 1000\n",
" x2 = res['x']\n",
" np.testing.assert_array_almost_equal(x1, x2, 4)\n",
" else:\n",
" elasped_time2 = np.nan\n",
"\n",
" df.loc['alphamind', u_name] = elasped_time1\n",
" df.loc['scipy', u_name] = elasped_time2\n",
" alpha_logger.info(f\"{u_name} is finished\")"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"df"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"## 2. 线性优化(带L1限制条件)\n",
"-----------------------"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"df = pd.DataFrame(columns=u_names, index=['alphamind'])\n",
"turn_over_target = 0.5\n",
"number = 1\n",
"\n",
"for u_name, sample_data in zip(u_names[:2], data_set):\n",
" factor_data = sample_data['factor']\n",
" er = factor_data['ep_q'].values\n",
" lbound = np.ones(len(er)) * lb\n",
" ubound = np.ones(len(er)) * ub\n",
" \n",
" if 'weight' in factor_data:\n",
" current_position = factor_data.weight.values\n",
" else:\n",
" current_position = np.ones_like(er) / len(er)\n",
"\n",
" risk_constraints = np.ones((len(er), 1))\n",
" risk_target = (np.array([1.]), np.array([1.]))\n",
"\n",
" status, y, x1 = linear_builder(er, lbound, ubound, risk_constraints, risk_target, turn_over_target=turn_over_target, current_position=current_position)\n",
" elasped_time1 = timeit.timeit(\"linear_builder(er, lbound, ubound, risk_constraints, risk_target, turn_over_target=turn_over_target, current_position=current_position)\", number=number, globals=globals()) / number * 1000\n",
"\n",
" np.testing.assert_almost_equal(np.abs(x1 - current_position).sum(), 0.5)\n",
"\n",
" df.loc['alphamind', u_name] = elasped_time1\n",
" alpha_logger.info(f\"{u_name} is finished\")"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"df"
]
},
{
"cell_type": "markdown",
"metadata": {
"collapsed": true
},
"source": [
"## 3. Mean - Variance 优化 (无约束)\n",
"-----------------------"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"df = pd.DataFrame(columns=u_names, index=['alphamind', 'direct'])\n",
"number = 10\n",
"\n",
"for u_name, sample_data in zip(u_names, data_set):\n",
" all_styles = risk_styles + industry_styles + ['COUNTRY']\n",
" factor_data = sample_data['factor']\n",
" risk_cov = sample_data['risk_cov'][all_styles].values\n",
" risk_exposure = factor_data[all_styles].values\n",
" special_risk = factor_data['s_srisk'].values\n",
" sec_cov = risk_exposure @ risk_cov @ risk_exposure.T / 10000 + np.diag(special_risk ** 2) / 10000\n",
" er = factor_data['ep_q'].values\n",
"\n",
" bm = np.zeros(len(er))\n",
" lbound = -np.ones(len(er)) * np.inf\n",
" ubound = np.ones(len(er)) * np.inf\n",
"\n",
" status, y, x1 = mean_variance_builder(er, sec_cov, bm, lbound, ubound, None, None, lam=1)\n",
" elasped_time1 = timeit.timeit(\"mean_variance_builder(er, sec_cov, bm, lbound, ubound, None, None, lam=1)\",\n",
" number=number, globals=globals()) / number * 1000\n",
" x2 = np.linalg.inv(sec_cov) @ er\n",
" elasped_time2 = timeit.timeit(\"np.linalg.inv(sec_cov) @ er\",\n",
" number=number, globals=globals()) / number * 1000\n",
"\n",
" np.testing.assert_array_almost_equal(x1, x2, 4)\n",
"\n",
" df.loc['alphamind', u_name] = elasped_time1\n",
" df.loc['direct', u_name] = elasped_time2\n",
" alpha_logger.info(f\"{u_name} is finished\")"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"df"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"## 4. Mean - Variance 优化 (Box约束以及线性约束)"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"def func(x):\n",
" return 0.5 * x @ sec_cov @ x - er @ x\n",
"\n",
"def con_func(x):\n",
" return x.sum() - 1.\n",
"\n",
"df = pd.DataFrame(columns=u_names, index=['alphamind', 'scipy'])\n",
"number = 1\n",
"\n",
"for u_name, sample_data in zip(u_names, data_set):\n",
" all_styles = risk_styles + industry_styles + ['COUNTRY']\n",
" factor_data = sample_data['factor']\n",
" risk_cov = sample_data['risk_cov'][all_styles].values\n",
" risk_exposure = factor_data[all_styles].values\n",
" special_risk = factor_data['s_srisk'].values\n",
" sec_cov = risk_exposure @ risk_cov @ risk_exposure.T / 10000 + np.diag(special_risk ** 2) / 10000\n",
" er = factor_data['ep_q'].values\n",
" \n",
" bm = np.zeros(len(er))\n",
" lbound = np.zeros(len(er))\n",
" ubound = np.ones(len(er)) * 0.1\n",
" \n",
" risk_constraints = np.ones((len(er), 1))\n",
" risk_target = (np.array([1.]), np.array([1.]))\n",
"\n",
" status, y, x1 = mean_variance_builder(er, sec_cov, bm, lbound, ubound, risk_constraints, risk_target, lam=1)\n",
" elasped_time1 = timeit.timeit(\"mean_variance_builder(er, sec_cov, bm, lbound, ubound, None, None, lam=1)\",\n",
" number=number, globals=globals()) / number * 1000\n",
" \n",
" cons = [dict(type='eq', fun=con_func)]\n",
" \n",
" if u_name != 'ashare_ex':\n",
" res = minimize(func, np.zeros(len(er)), bounds=list(zip(lbound, ubound)), constraints=cons, tol=1e-12)\n",
" x2 = res['x']\n",
" elasped_time2 = timeit.timeit(\"minimize(func, np.zeros(len(er)), bounds=list(zip(lbound, ubound)), constraints=cons, tol=1e-12)\",\n",
" number=number, globals=globals()) / number * 1000\n",
"\n",
" np.testing.assert_array_almost_equal(x1, x2, 4)\n",
" else:\n",
" elasped_time2 = np.nan\n",
"\n",
" df.loc['alphamind', u_name] = elasped_time1\n",
" df.loc['scipy', u_name] = elasped_time2\n",
" alpha_logger.info(f\"{u_name} is finished\")"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"df"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"## 5. 线性优化(带二次限制条件)\n",
"-------------------------"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"df = pd.DataFrame(columns=u_names, index=['alphamind', 'scipy'])\n",
"number = 1\n",
"target_vol = 0.1\n",
"\n",
"def func(x):\n",
" return - er @ x\n",
"\n",
"def con_func(x):\n",
" return x.sum()\n",
"\n",
"def ieq_func(x):\n",
" return target_vol * target_vol - x @ sec_cov @ x\n",
"\n",
"for u_name, sample_data in zip(u_names, data_set):\n",
" all_styles = risk_styles + industry_styles + ['COUNTRY']\n",
" factor_data = sample_data['factor']\n",
" risk_cov = sample_data['risk_cov'][all_styles].values\n",
" risk_exposure = factor_data[all_styles].values\n",
" special_risk = factor_data['s_srisk'].values\n",
" sec_cov = risk_exposure @ risk_cov @ risk_exposure.T / 10000 + np.diag(special_risk ** 2) / 10000\n",
" er = factor_data['ep_q'].values\n",
" \n",
" if 'weight' in factor_data:\n",
" bm = factor_data.weight.values\n",
" else:\n",
" bm = np.ones_like(er) / len(er)\n",
" lbound = np.zeros(len(er))\n",
" ubound = np.ones(len(er)) * 0.1\n",
" \n",
" risk_constraints = np.ones((len(er), 1))\n",
" risk_target = (np.array([bm.sum()]), np.array([bm.sum()]))\n",
"\n",
" status, y, x1 = target_vol_builder(er, sec_cov, bm, lbound, ubound, risk_constraints, risk_target, vol_low=0, vol_high=target_vol)\n",
" elasped_time1 = timeit.timeit(\"mean_variance_builder(er, sec_cov, bm, lbound, ubound, None, None, lam=1)\",\n",
" number=number, globals=globals()) / number * 1000\n",
" \n",
" cons = [dict(type='eq', fun=con_func), dict(type='ineq', fun=ieq_func)]\n",
" \n",
" if u_name != 'ashare_ex':\n",
" res = minimize(func, bm, bounds=list(zip(lbound - bm, ubound-bm)), constraints=cons, tol=1e-12)\n",
" x2 = res['x'] + bm\n",
" elasped_time2 = timeit.timeit(\"minimize(func, np.zeros(len(er)), bounds=list(zip(lbound-bm, ubound-bm)), constraints=cons, tol=1e-12)\",\n",
" number=number, globals=globals()) / number * 1000\n",
"\n",
" np.testing.assert_array_almost_equal(x1, x2, 4)\n",
" else:\n",
" elasped_time2 = np.nan\n",
"\n",
" df.loc['alphamind', u_name] = elasped_time1\n",
" df.loc['scipy', u_name] = elasped_time2\n",
" alpha_logger.info(f\"{u_name} is finished\")"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"collapsed": true
},
"outputs": [],
"source": []
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"collapsed": true
},
"outputs": [],
"source": []
}
],
"metadata": {
"kernelspec": {
"display_name": "Python 3",
"language": "python",
"name": "python3"
},
"language_info": {
"codemirror_mode": {
"name": "ipython",
"version": 3
},
"file_extension": ".py",
"mimetype": "text/x-python",
"name": "python",
"nbconvert_exporter": "python",
"pygments_lexer": "ipython3",
"version": "3.6.3"
},
"varInspector": {
"cols": {
"lenName": 16,
"lenType": 16,
"lenVar": 40
},
"kernels_config": {
"python": {
"delete_cmd_postfix": "",
"delete_cmd_prefix": "del ",
"library": "var_list.py",
"varRefreshCmd": "print(var_dic_list())"
},
"r": {
"delete_cmd_postfix": ") ",
"delete_cmd_prefix": "rm(",
"library": "var_list.r",
"varRefreshCmd": "cat(var_dic_list()) "
}
},
"position": {
"height": "819px",
"left": "1947px",
"right": "20px",
"top": "156px",
"width": "504px"
},
"types_to_exclude": [
"module",
"function",
"builtin_function_or_method",
"instance",
"_Feature"
],
"window_display": false
}
},
"nbformat": 4,
"nbformat_minor": 2
}
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