{
 "cells": [
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "collapsed": true
   },
   "outputs": [],
   "source": [
    "import dautil as dl\n",
    "import numpy as np\n",
    "import pandas as pd\n",
    "import ch7util\n",
    "import matplotlib.pyplot as plt"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "collapsed": false
   },
   "outputs": [],
   "source": [
    "context = dl.nb.Context('capm')\n",
    "lr = dl.nb.LatexRenderer(chapter=7, start=5, context=context)\n",
    "lr.render(r'r_{a,t} = \\alpha + \\beta r_{b,t} + \\varepsilon_t')"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "collapsed": true
   },
   "outputs": [],
   "source": [
    "def calc_beta(symbol):\n",
    "    ohlc = dl.data.OHLC()\n",
    "    sp500 = ohlc.get('^GSPC')['Adj Close']\n",
    "    stock = ohlc.get(symbol)['Adj Close']\n",
    "    df = pd.DataFrame({'SP500': sp500, symbol: stock}).dropna()\n",
    "    sp500_rets = ch7util.log_rets(df['SP500'])\n",
    "    rets = ch7util.log_rets(df[symbol])\n",
    "    beta, _ = np.polyfit(sp500_rets, rets, 1)\n",
    "\n",
    "    # annualize & percentify\n",
    "    return beta, 252 * rets.mean() * 100"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "collapsed": true
   },
   "outputs": [],
   "source": [
    "betas = []\n",
    "means = []\n",
    "\n",
    "for symbol in ch7util.STOCKS:\n",
    "    beta, ret_mean = calc_beta(symbol)\n",
    "    betas.append(beta)\n",
    "    means.append(ret_mean)"
   ]
  },
  {
   "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.plot_text(ax, betas, means, ch7util.STOCKS, add_scatter=True)\n",
    "dl.plotting.plot_polyfit(ax, betas, means)\n",
    "ax.set_title('Capital Asset Pricing Model')\n",
    "ax.set_xlabel('Beta')\n",
    "ax.set_ylabel('Mean annual return (%)')"
   ]
  }
 ],
 "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
}
