{
 "cells": [
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "* 请在环境变量中设置`DB_URI`指向数据库"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "%matplotlib inline\n",
    "import os\n",
    "import numpy as np\n",
    "import pandas as pd\n",
    "from PyFin.api import *\n",
    "from alphamind.api import *\n",
    "from alphamind.strategy.strategy import Strategy, RunningSetting\n",
    "from matplotlib import pyplot as plt\n",
    "\n",
    "plt.style.use('ggplot')"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "# Back test parameter settings\n",
    "start_date = '2016-01-01'\n",
    "end_date = '2018-03-30'\n",
    "\n",
    "freq = '10b'\n",
    "industry_name = 'sw'\n",
    "industry_level = 1\n",
    "turn_over_target = 0.4\n",
    "batch = 1\n",
    "horizon = map_freq(freq)\n",
    "weights_bandwidth = 0.01\n",
    "universe = Universe('zz800')\n",
    "data_source = os.environ['DB_URI']\n",
    "benchmark_code = 905\n",
    "method = 'risk_neutral'"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "# Model settings\n",
    "alpha_factors = {\n",
    "    'f01': CSQuantiles(LAST('EPS'), groups='sw1'),\n",
    "    'f02': CSQuantiles(LAST('ROE'), groups='sw1'),\n",
    "    }\n",
    "\n",
    "weights = dict(f01=1.,\n",
    "               f02=1.)\n",
    "\n",
    "alpha_model = ConstLinearModel(features=alpha_factors, weights=weights)\n",
    "\n",
    "data_meta = DataMeta(freq=freq,\n",
    "                     universe=universe,\n",
    "                     batch=1,\n",
    "                     neutralized_risk=None,\n",
    "                     pre_process=None,\n",
    "                     post_process=None,\n",
    "                     data_source=data_source)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "# Constraintes settings\n",
    "\n",
    "industry_names = industry_list(industry_name, industry_level)\n",
    "constraint_risk = ['SIZE', 'SIZENL', 'BETA']\n",
    "total_risk_names = constraint_risk + ['benchmark', 'total']\n",
    "all_styles = risk_styles + industry_styles + macro_styles\n",
    "\n",
    "b_type = []\n",
    "l_val = []\n",
    "u_val = []\n",
    "\n",
    "previous_pos = pd.DataFrame()\n",
    "rets = []\n",
    "turn_overs = []\n",
    "leverags = []\n",
    "\n",
    "for name in total_risk_names:\n",
    "    if name == 'benchmark':\n",
    "        b_type.append(BoundaryType.RELATIVE)\n",
    "        l_val.append(0.8)\n",
    "        u_val.append(1.0)\n",
    "    else:\n",
    "        b_type.append(BoundaryType.ABSOLUTE)\n",
    "        l_val.append(0.0)\n",
    "        u_val.append(0.0)\n",
    "\n",
    "bounds = create_box_bounds(total_risk_names, b_type, l_val, u_val)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "# Running settings\n",
    "running_setting = RunningSetting(weights_bandwidth=weights_bandwidth,\n",
    "                                 rebalance_method=method,\n",
    "                                 bounds=bounds,\n",
    "                                 turn_over_target=turn_over_target)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "# Strategy\n",
    "strategy = Strategy(alpha_model,\n",
    "                    data_meta,\n",
    "                    universe=universe,\n",
    "                    start_date=start_date,\n",
    "                    end_date=end_date,\n",
    "                    freq=freq,\n",
    "                    benchmark=benchmark_code)\n",
    "\n",
    "strategy.prepare_backtest_data()\n",
    "ret_df, positions = strategy.run(running_setting=running_setting)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "ret_df[['turn_over', 'excess_return']].cumsum().plot(figsize=(14, 7), secondary_y='turn_over')"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "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.5"
  },
  "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_minor": 2
}
