{
 "cells": [
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "collapsed": true
   },
   "outputs": [],
   "source": [
    "import dautil as dl\n",
    "import ch7util\n",
    "import numpy as np\n",
    "import matplotlib.pyplot as plt\n",
    "import statsmodels.api as sm\n",
    "from IPython.display import HTML"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "collapsed": false
   },
   "outputs": [],
   "source": [
    "context = dl.nb.Context('autoregressive_test')\n",
    "lr = dl.nb.LatexRenderer(chapter=7, start=13, context=context)\n",
    "lr.render(r'X_t = c + \\sum_{i=1}^p \\varphi_i X_{t-i}+ \\varepsilon_t')\n",
    "lr.render(r'X_t = c + \\varepsilon_t')\n",
    "lr.render(r'Market Effciency = 1 -  \\frac{  R_{Restricted} ^{2} }{R_{Unrestricted} ^{2}}')"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "collapsed": false
   },
   "outputs": [],
   "source": [
    "ohlc = dl.data.OHLC()\n",
    "efficiencies = []\n",
    "restricted_r2 = []\n",
    "unrestricted_r2 = []\n",
    "\n",
    "for stock in ch7util.STOCKS:\n",
    "    rets = ch7util.log_rets(ohlc.get(stock)['Adj Close'])\n",
    "    restricted = sm.OLS(rets, rets.mean() * np.ones_like(rets)).fit()\n",
    "    rets_1 = rets[3:-1]\n",
    "    rets_2 = rets[2:-2]\n",
    "    rets_3 = rets[1:-3]\n",
    "    rets_4 = rets[:-4]\n",
    "    x = np.vstack((rets_1, rets_2, rets_3, rets_4)).T\n",
    "    x = sm.add_constant(x)\n",
    "    y = rets[4:]\n",
    "    unrestricted = sm.OLS(y, x).fit()\n",
    "    restricted_r2.append(restricted.rsquared)\n",
    "    unrestricted_r2.append(unrestricted.rsquared)\n",
    "    efficiencies.append(1 - restricted.rsquared/unrestricted.rsquared)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "collapsed": false
   },
   "outputs": [],
   "source": [
    "%matplotlib inline\n",
    "dl.options.mimic_seaborn()\n",
    "dl.nb.RcWidget(context)\n",
    "dl.nb.LabelWidget(2, 1, context)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "collapsed": false
   },
   "outputs": [],
   "source": [
    "sp = dl.plotting.Subplotter(2, 1, context)\n",
    "dl.plotting.bar(sp.ax, ch7util.STOCKS, efficiencies)\n",
    "sp.label()\n",
    "dl.plotting.plot_text(sp.next_ax(), unrestricted_r2, np.array(restricted_r2)/10 ** -16,\n",
    "                      ch7util.STOCKS, add_scatter=True)\n",
    "sp.label()\n",
    "HTML(sp.exit())"
   ]
  }
 ],
 "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.4.3"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 0
}
