{
 "cells": [
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "import datetime as dt\n",
    "import numpy as np\n",
    "import cvxpy\n",
    "from cvxopt import solvers\n",
    "from alphamind.portfolio.linearbuilder import linear_builder"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "solvers.options['glpk'] = {'msg_lev': 'GLP_MSG_OFF'}"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "def time_function(py_callable, n):\n",
    "    start = dt.datetime.now()\n",
    "    result = py_callable(n)\n",
    "    elapsed = (dt.datetime.now() - start).total_seconds()\n",
    "    return elapsed, result\n",
    "\n",
    "def cvxpy_lp(n):\n",
    "    w = cvxpy.Variable(n)\n",
    "\n",
    "    bndl = np.zeros(n)\n",
    "    bndu = 0.01 * np.ones(n)\n",
    "    risk_constraints1 = np.ones((n,1))\n",
    "    risk_constraints2 = np.zeros((n,1))\n",
    "    risk_constraints2[0][0] = 1.\n",
    "    risk_constraints2[1][0] = 1.\n",
    "    risk_constraints = np.concatenate((risk_constraints1, risk_constraints2), axis=1)\n",
    "\n",
    "    curr_risk_exposure = risk_constraints.T @ w\n",
    "    risk_targets = np.array([1., 0.015])\n",
    "\n",
    "    constraints = [w >= bndl,\n",
    "                   w <= bndu,\n",
    "                   curr_risk_exposure >= risk_targets,\n",
    "                   curr_risk_exposure <= risk_targets]\n",
    "    \n",
    "    np.random.seed(1)\n",
    "    er = np.random.randn(n)\n",
    "\n",
    "    objective = cvxpy.Minimize(-w.T * er)\n",
    "    prob = cvxpy.Problem(objective, constraints)\n",
    "    prob.solve()\n",
    "    return w, prob"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "print(\"{0:<8}{1:>12}{2:>12}{3:>12}{4:>12}{5:>12}{6:>15}\".format('Scale(n)', 'time(ms)', 'feval', 'min(x)', 'max(x)', 'sum(x)', 'x(0) + x(1)'))\n",
    "\n",
    "for n in range(200, 3200, 200):\n",
    "    elapsed, result = time_function(cvxpy_lp, n)\n",
    "    s = np.array(result[0].value).flatten()\n",
    "    print(\"{0:<8}{1:>12.2f}{2:>12.2f}{3:>12f}{4:>12f}{5:>12f}{6:>15}\".format(n, elapsed*1000, result[1].value, s.min(), s.max(), s.sum(), s[0] + s[1]))"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "def clp_lp(n):\n",
    "    np.random.seed(1)\n",
    "    er = np.random.randn(n)\n",
    "\n",
    "    bndl = np.zeros(n)\n",
    "    bndu = 0.01 * np.ones(n)\n",
    "    risk_constraints1 = np.ones((n,1))\n",
    "    risk_constraints2 = np.zeros((n,1))\n",
    "    risk_constraints2[0][0] = 1.\n",
    "    risk_constraints2[1][0] = 1.\n",
    "    risk_constraints = np.concatenate((risk_constraints1, risk_constraints2), axis=1)\n",
    "    risk_target = np.array([1., 0.015]), np.array([1., 0.015])\n",
    "    \n",
    "    result = linear_builder(er, bndl, bndu, risk_constraints, risk_target)\n",
    "    return result"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "print(\"{0:<8}{1:>12}{2:>12}{3:>12}{4:>12}{5:>12}{6:>15}\".format('Scale(n)', 'time(ms)', 'feval', 'min(x)', 'max(x)', 'sum(x)', 'x(0) + x(1)'))\n",
    "\n",
    "for n in range(200, 3200, 200):\n",
    "    elapsed, result = time_function(clp_lp, n)\n",
    "    s = result[2]\n",
    "    print(\"{0:<8}{1:>12.2f}{2:>12.2f}{3:>12f}{4:>12f}{5:>12f}{6:>15}\".format(n, elapsed*1000, result[1], s.min(), s.max(), s.sum(), s[0] + s[1]))"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": []
  },
  {
   "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
}
