{
 "cells": [
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "collapsed": true
   },
   "outputs": [],
   "source": [
    "import dautil as dl\n",
    "import numpy as np\n",
    "import matplotlib.pyplot as plt\n",
    "import ch7util"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "collapsed": false
   },
   "outputs": [],
   "source": [
    "context = dl.nb.Context('random_walk')\n",
    "lr = dl.nb.LatexRenderer(chapter=7, start=9, context=context)\n",
    "lr.render(r'''\\matrix{ {\\hat \\mu } & \\equiv & {{1 \\over {2n}}\\sum\\limits_{k = 1}^{2n} {({X_k} - {X_{k - 1}}) = {1 \\over {2n}}({X_{2n}}\n",
    "                              - {X_0})} } \\cr }''')\n",
    "lr.render(r'\\hat \\sigma _a^2 \\equiv {1 \\over {2n}}\\sum\\limits_{k = 1}^{2n} {{{({X_k} - {X_{k - 1}} - \\hat \\mu )}^2}}')\n",
    "lr.render(r'''\\hat \\sigma _b^2 \\equiv {1 \\over {2n}}\\sum\\limits_{k = 1}^n {{{({X_{2k}} - {X_{2k - 2}} - 2\\hat \\mu )}^2}}''')\n",
    "lr.render(r'''{{J}_{r}}\\equiv \\frac{\\hat{\\sigma }_{b}^{2}}{\\hat{\\sigma }_{a}^{2}}-1\\quad \\sqrt{2n}\\ {{J}_{r}}\\ \\underset{\\raise0.3em\\hbox{$\\smash{\\scriptscriptstyle\\thicksim}$}}{a}\\\n",
    "                              \\rm{N}(0,2)''')\n",
    "    "
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "collapsed": true
   },
   "outputs": [],
   "source": [
    "ratios = []\n",
    "\n",
    "for symbol in ch7util.STOCKS:\n",
    "    ohlc = dl.data.OHLC()\n",
    "    P = ohlc.get(symbol)['Adj Close'].values\n",
    "    N = len(P)\n",
    "    mu = (np.log(P[-1]) - np.log(P[0]))/N\n",
    "    var_a = 0\n",
    "    var_b = 0\n",
    "\n",
    "    for k in range(1, N):\n",
    "        var_a = (np.log(P[k]) - np.log(P[k - 1]) - mu) ** 2\n",
    "        var_a = var_a / N\n",
    "\n",
    "    for k in range(1, N//2):\n",
    "        var_b = (np.log(P[2 * k]) - np.log(P[2 * k - 2]) - 2 * mu) ** 2\n",
    "        var_b = var_b / N\n",
    "\n",
    "    ratios.append(np.sqrt(N) * (var_b/var_a - 1))"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "collapsed": false
   },
   "outputs": [],
   "source": [
    "%matplotlib inline\n",
    "dl.options.mimic_seaborn()\n",
    "_, ax = plt.subplots()\n",
    "dl.plotting.bar(ax, ch7util.STOCKS, ratios)\n",
    "ax.set_title('Random Walk Test')\n",
    "ax.set_ylabel('Ratio')"
   ]
  }
 ],
 "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
}
