{
 "cells": [
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "collapsed": true
   },
   "outputs": [],
   "source": [
    "import dautil as dl\n",
    "import ch7util\n",
    "import matplotlib.pyplot as plt\n",
    "from scipy.stats import skew\n",
    "from scipy.stats import kurtosis\n",
    "from pandas.tools.plotting import autocorrelation_plot\n",
    "import numpy as np\n",
    "from scipy.stats import norm\n",
    "from IPython.display import HTML"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "collapsed": false
   },
   "outputs": [],
   "source": [
    "ohlc = dl.data.OHLC()\n",
    "rets_dict = {}\n",
    "\n",
    "for i, symbol in enumerate(ch7util.STOCKS):\n",
    "    rets = ch7util.log_rets(ohlc.get(symbol)['Adj Close'])\n",
    "    rets_dict[symbol] = rets\n",
    "\n",
    "sp500 = ch7util.log_rets(ohlc.get('^GSPC')['Adj Close'])"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "collapsed": false
   },
   "outputs": [],
   "source": [
    "%matplotlib inline\n",
    "dl.options.mimic_seaborn()\n",
    "context = dl.nb.Context('rets_stats')\n",
    "dl.nb.RcWidget(context)\n",
    "dl.nb.LabelWidget(2, 2, context)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "collapsed": false
   },
   "outputs": [],
   "source": [
    "sp = dl.plotting.Subplotter(2, 2, context)\n",
    "sp.ax.set_xlim(-0.05, 0.05)\n",
    "_, bins, _ = sp.ax.hist(sp500, bins=dl.stats.sqrt_bins(sp500),\n",
    "                     alpha=0.6, normed=True)\n",
    "sp.ax.plot(bins, norm.pdf(bins, sp500.mean(), sp500.std()), lw=2)\n",
    "\n",
    "skews = [skew(rets_dict[s]) for s in ch7util.STOCKS]\n",
    "kurts = [kurtosis(rets_dict[s]) for s in ch7util.STOCKS]\n",
    "sp.label()\n",
    "\n",
    "sp.next_ax().scatter(skews, kurts)\n",
    "dl.plotting.plot_text(sp.ax, skews, kurts, ch7util.STOCKS)\n",
    "sp.label()\n",
    "\n",
    "autocorrelation_plot(sp500, ax=sp.next_ax())\n",
    "sp.label()\n",
    "\n",
    "# Negative returns\n",
    "counts, neg_rets = np.histogram(sp500[sp500 < 0])\n",
    "neg_rets = neg_rets[:-1] + (neg_rets[1] - neg_rets[0])/2\n",
    "# Adding 1 to avoid log(0)\n",
    "dl.plotting.plot_polyfit(sp.next_ax(), np.log(np.abs(neg_rets)),\n",
    "                         np.log(counts + 1), plot_points=True)\n",
    "sp.label()\n",
    "\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
}
