{
 "cells": [
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "collapsed": true
   },
   "outputs": [],
   "source": [
    "import numpy as np\n",
    "import dautil as dl\n",
    "import matplotlib.pyplot as plt\n",
    "import ch7util"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "collapsed": false
   },
   "outputs": [],
   "source": [
    "context = dl.nb.Context('sharpe_liquidity')\n",
    "lr = dl.nb.LatexRenderer(chapter=7, start=3, context=context)\n",
    "lr.render(r'S_a = \\frac{E[R_a-R_b]}{\\sigma_a} = \\frac{E[R_a-R_b]}{\\sqrt{\\mathrm{var}[R_a-R_b]}}')"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "collapsed": true
   },
   "outputs": [],
   "source": [
    "def calc_metrics(ticker, ohlc):\n",
    "    stock = ohlc.get(ticker)\n",
    "    sp500 = ohlc.get('^GSPC')\n",
    "    merged = ch7util.merge_sp500(stock, sp500)\n",
    "    rets_stock = ch7util.log_rets(merged['Adj Close_stock'])\n",
    "    rets_sp500 = ch7util.log_rets(merged['Adj Close_sp500'])\n",
    "    stock_sp500 = rets_stock - rets_sp500\n",
    "    sharpe_stock = stock_sp500.mean()/stock_sp500.std()\n",
    "    avg_vol = np.log(merged['Volume_stock'].mean())\n",
    "\n",
    "    return (sharpe_stock, avg_vol)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "collapsed": true
   },
   "outputs": [],
   "source": [
    "dfb = dl.report.DFBuilder(cols=['Ticker', 'Sharpe', 'Log(Average Volume)'])\n",
    "\n",
    "ohlc = dl.data.OHLC()\n",
    "\n",
    "for symbol in ch7util.STOCKS:\n",
    "    sharpe, vol = calc_metrics(symbol, ohlc)\n",
    "    dfb.row([symbol, sharpe, vol])\n",
    "\n",
    "df = dfb.build(index=ch7util.STOCKS)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "collapsed": false
   },
   "outputs": [],
   "source": [
    "%matplotlib inline\n",
    "dl.options.mimic_seaborn()\n",
    "_, ax = plt.subplots()\n",
    "ax.scatter(df['Log(Average Volume)'], df['Sharpe'])\n",
    "dl.plotting.plot_polyfit(ax, df['Log(Average Volume)'], df['Sharpe'])\n",
    "\n",
    "dl.plotting.plot_text(ax, df['Log(Average Volume)'],\n",
    "                      df['Sharpe'], ch7util.STOCKS)\n",
    "ax.set_xlabel('Log(Average Volume)')\n",
    "ax.set_ylabel('Sharpe')\n",
    "ax.set_title('Sharpe Ratio & Liquidity')"
   ]
  }
 ],
 "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
}
