{
 "cells": [
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "* 方法参考自 The Barra China Equity Model (CNE5)'s 文档\n",
    "\n",
    "* 请在环境变量中设置`DB_URI`指向数据库"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "%matplotlib inline\n",
    "\n",
    "import os\n",
    "import numpy as np\n",
    "import pandas as pd\n",
    "from matplotlib import pyplot as plt\n",
    "import statsmodels.api as sm\n",
    "from alphamind.api import *\n",
    "from PyFin.api import *\n",
    "from alphamind.analysis.crosssetctions import cross_section_analysis\n",
    "\n",
    "plt.style.use('ggplot')"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "\"\"\"\n",
    "Back test parameter settings\n",
    "\"\"\"\n",
    "\n",
    "start_date = '2016-01-01'\n",
    "end_date = '2018-02-28'\n",
    "category = 'sw'\n",
    "level = 1\n",
    "freq = '20b'\n",
    "universe = Universe('ashare_ex')\n",
    "\n",
    "horizon = map_freq(freq)\n",
    "ref_dates = makeSchedule(start_date, end_date, freq, 'china.sse')"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "def risk_factor_analysis(factor_name):\n",
    "    data_source = os.environ['DB_URI']\n",
    "    engine = SqlEngine(data_source)\n",
    "    risk_names = list(set(risk_styles).difference({factor_name}))\n",
    "    industry_names = list(set(industry_styles).difference({factor_name}))\n",
    "    constraint_risk = risk_names + industry_names\n",
    "    \n",
    "    df = pd.DataFrame(columns=['ret', 'ic', 't.'], dtype=float)\n",
    "\n",
    "    for ref_date in ref_dates:\n",
    "        df.loc[ref_date, :] = cross_section_analysis(ref_date,\n",
    "                                                     factor_name,\n",
    "                                                     universe,\n",
    "                                                     horizon,\n",
    "                                                     constraint_risk,\n",
    "                                                     engine=engine)\n",
    "    df.index = pd.to_datetime(df.index)\n",
    "    return df"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "candidates_factors = ['BETA', 'SIZE']"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "%%time\n",
    "res = [risk_factor_analysis(factor) for factor in candidates_factors]"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "df = pd.DataFrame()\n",
    "\n",
    "for f_name, data in zip(candidates_factors, res):\n",
    "    data['factor'] = f_name\n",
    "    df = df.append(data)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "df['abs t.'] = np.abs(df['t.'])\n",
    "df[['factor', 'abs t.']].groupby('factor').mean().sort_values('abs t.', ascending=False).head()"
   ]
  },
  {
   "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()) "
    }
   },
   "position": {
    "height": "607px",
    "left": "1093px",
    "right": "20px",
    "top": "94px",
    "width": "756px"
   },
   "types_to_exclude": [
    "module",
    "function",
    "builtin_function_or_method",
    "instance",
    "_Feature"
   ],
   "window_display": false
  }
 },
 "nbformat": 4,
 "nbformat_minor": 2
}
