{
 "cells": [
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "collapsed": true
   },
   "outputs": [],
   "source": [
    "import dautil as dl\n",
    "import ch7util\n",
    "import pandas as pd\n",
    "import numpy as np\n",
    "import seaborn as sns\n",
    "import matplotlib.pyplot as plt"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "collapsed": false
   },
   "outputs": [],
   "source": [
    "context = dl.nb.Context('portfolio_optimization')\n",
    "lr = dl.nb.LatexRenderer(chapter=7, start=16, context=context)\n",
    "lr.render(r'''\\operatorname{E}(R_p) =  w_A \\operatorname{E}(R_A) +\n",
    "w_B \\operatorname{E}(R_B) = w_A \\operatorname{E}(R_A) + (1 - w_A) \\operatorname{E}(R_B)''')\n",
    "lr.render(r'\\sigma_p^2  = w_A^2 \\sigma_A^2  + w_B^2 \\sigma_B^2 + 2w_Aw_B  \\sigma_{A} \\sigma_{B} \\rho_{AB}')"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "collapsed": true
   },
   "outputs": [],
   "source": [
    "def expected_return(stocka, stockb, means):\n",
    "    return 0.5 * (means[stocka] + means[stockb])"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "collapsed": true
   },
   "outputs": [],
   "source": [
    "def variance_return(stocka, stockb, stds):\n",
    "    ohlc = dl.data.OHLC()\n",
    "    dfa = ohlc.get(stocka)\n",
    "    dfb = ohlc.get(stockb)\n",
    "    merged = pd.merge(left=dfa, right=dfb,\n",
    "                      right_index=True, left_index=True,\n",
    "                      suffixes=('_A', '_B')).dropna()\n",
    "    retsa = ch7util.log_rets(merged['Adj Close_A'])\n",
    "    retsb = ch7util.log_rets(merged['Adj Close_B'])\n",
    "    corr = np.corrcoef(retsa, retsb)[0][1]\n",
    "\n",
    "    return 0.25 * (stds[stocka] ** 2 + stds[stockb] ** 2 +\n",
    "                   2 * stds[stocka] * stds[stockb] * corr)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "collapsed": true
   },
   "outputs": [],
   "source": [
    "def calc_ratio(stocka, stockb, means, stds, ratios):\n",
    "    if stocka == stockb:\n",
    "        return np.nan\n",
    "\n",
    "    key = stocka + '_' + stockb\n",
    "    ratio = ratios.get(key, None)\n",
    "\n",
    "    if ratio:\n",
    "        return ratio\n",
    "\n",
    "    expected = expected_return(stocka, stockb, means)\n",
    "    var = variance_return(stocka, stockb, stds)\n",
    "    ratio = expected/var\n",
    "    ratios[key] = ratio\n",
    "\n",
    "    return ratio"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "collapsed": true
   },
   "outputs": [],
   "source": [
    "means = {}\n",
    "stds = {}\n",
    "\n",
    "ohlc = dl.data.OHLC()\n",
    "\n",
    "for stock in ch7util.STOCKS:\n",
    "    close = ohlc.get(stock)['Adj Close']\n",
    "    rets = ch7util.log_rets(close)\n",
    "    means[stock] = rets.mean()\n",
    "    stds[stock] = rets.std()"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "collapsed": false
   },
   "outputs": [],
   "source": [
    "pairs = dl.collect.grid_list(ch7util.STOCKS)\n",
    "sorted_pairs = [[sorted(row[i]) for row in pairs]\n",
    "                for i in range(len(ch7util.STOCKS))]\n",
    "ratios = {}\n",
    "\n",
    "grid = [[calc_ratio(row[i][0], row[i][1], means, stds, ratios)\n",
    "        for row in sorted_pairs] for i in range(len(ch7util.STOCKS))]"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "collapsed": false
   },
   "outputs": [],
   "source": [
    "%matplotlib inline\n",
    "plt.title('Expected Return/Return Variance for 2 Asset Portfolio')\n",
    "sns.heatmap(grid, xticklabels=ch7util.STOCKS, yticklabels=ch7util.STOCKS)"
   ]
  }
 ],
 "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
}
