python-pour-finance/09-Python-Finance-Fondamentaux/.ipynb_checkpoints/02-Optimisation-Portfolio-c...

1842 lines
300 KiB
Plaintext
Raw Normal View History

2023-08-21 15:12:19 +00:00
{
"cells": [
{
"cell_type": "markdown",
"metadata": {},
"source": [
"# Portfolio Optimization"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"“Modern Portfolio Theory (MPT), a hypothesis put forth by Harry Markowitz in his paper “Portfolio Selection,” (published in 1952 by the Journal of Finance) is an investment theory based on the idea that risk-averse investors can construct portfolios to optimize or maximize expected return based on a given level of market risk, emphasizing that risk is an inherent part of higher reward. It is one of the most important and influential economic theories dealing with finance and investment."
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"## Monte Carlo Simulation for Optimization Search\n",
"\n",
"\n",
"We could randomly try to find the optimal portfolio balance using Monte Carlo simulation"
]
},
{
"cell_type": "code",
"execution_count": 21,
"metadata": {
"collapsed": true
},
"outputs": [],
"source": [
"import numpy as np\n",
"import pandas as pd\n",
"import matplotlib.pyplot as plt\n",
"%matplotlib inline"
]
},
{
"cell_type": "code",
"execution_count": 22,
"metadata": {
"collapsed": true
},
"outputs": [],
"source": [
"# Download and get Daily Returns\n",
"aapl = pd.read_csv('AAPL_CLOSE',index_col='Date',parse_dates=True)\n",
"cisco = pd.read_csv('CISCO_CLOSE',index_col='Date',parse_dates=True)\n",
"ibm = pd.read_csv('IBM_CLOSE',index_col='Date',parse_dates=True)\n",
"amzn = pd.read_csv('AMZN_CLOSE',index_col='Date',parse_dates=True)"
]
},
{
"cell_type": "code",
"execution_count": 23,
"metadata": {
"collapsed": true
},
"outputs": [],
"source": [
"stocks = pd.concat([aapl,cisco,ibm,amzn],axis=1)\n",
"stocks.columns = ['aapl','cisco','ibm','amzn']"
]
},
{
"cell_type": "code",
"execution_count": 24,
"metadata": {},
"outputs": [
{
"data": {
"text/html": [
"<div>\n",
"<style>\n",
" .dataframe thead tr:only-child th {\n",
" text-align: right;\n",
" }\n",
"\n",
" .dataframe thead th {\n",
" text-align: left;\n",
" }\n",
"\n",
" .dataframe tbody tr th {\n",
" vertical-align: top;\n",
" }\n",
"</style>\n",
"<table border=\"1\" class=\"dataframe\">\n",
" <thead>\n",
" <tr style=\"text-align: right;\">\n",
" <th></th>\n",
" <th>aapl</th>\n",
" <th>cisco</th>\n",
" <th>ibm</th>\n",
" <th>amzn</th>\n",
" </tr>\n",
" <tr>\n",
" <th>Date</th>\n",
" <th></th>\n",
" <th></th>\n",
" <th></th>\n",
" <th></th>\n",
" </tr>\n",
" </thead>\n",
" <tbody>\n",
" <tr>\n",
" <th>2012-01-03</th>\n",
" <td>53.063218</td>\n",
" <td>15.752778</td>\n",
" <td>160.830881</td>\n",
" <td>179.03</td>\n",
" </tr>\n",
" <tr>\n",
" <th>2012-01-04</th>\n",
" <td>53.348386</td>\n",
" <td>16.057180</td>\n",
" <td>160.174781</td>\n",
" <td>177.51</td>\n",
" </tr>\n",
" <tr>\n",
" <th>2012-01-05</th>\n",
" <td>53.940658</td>\n",
" <td>15.997991</td>\n",
" <td>159.415086</td>\n",
" <td>177.61</td>\n",
" </tr>\n",
" <tr>\n",
" <th>2012-01-06</th>\n",
" <td>54.504543</td>\n",
" <td>15.938801</td>\n",
" <td>157.584912</td>\n",
" <td>182.61</td>\n",
" </tr>\n",
" <tr>\n",
" <th>2012-01-09</th>\n",
" <td>54.418089</td>\n",
" <td>16.040268</td>\n",
" <td>156.764786</td>\n",
" <td>178.56</td>\n",
" </tr>\n",
" </tbody>\n",
"</table>\n",
"</div>"
],
"text/plain": [
" aapl cisco ibm amzn\n",
"Date \n",
"2012-01-03 53.063218 15.752778 160.830881 179.03\n",
"2012-01-04 53.348386 16.057180 160.174781 177.51\n",
"2012-01-05 53.940658 15.997991 159.415086 177.61\n",
"2012-01-06 54.504543 15.938801 157.584912 182.61\n",
"2012-01-09 54.418089 16.040268 156.764786 178.56"
]
},
"execution_count": 24,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"stocks.head()"
]
},
{
"cell_type": "code",
"execution_count": 25,
"metadata": {},
"outputs": [
{
"data": {
"text/plain": [
"aapl 0.000750\n",
"cisco 0.000599\n",
"ibm 0.000081\n",
"amzn 0.001328\n",
"dtype: float64"
]
},
"execution_count": 25,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"mean_daily_ret = stocks.pct_change(1).mean()\n",
"mean_daily_ret"
]
},
{
"cell_type": "code",
"execution_count": 26,
"metadata": {},
"outputs": [
{
"data": {
"text/html": [
"<div>\n",
"<style>\n",
" .dataframe thead tr:only-child th {\n",
" text-align: right;\n",
" }\n",
"\n",
" .dataframe thead th {\n",
" text-align: left;\n",
" }\n",
"\n",
" .dataframe tbody tr th {\n",
" vertical-align: top;\n",
" }\n",
"</style>\n",
"<table border=\"1\" class=\"dataframe\">\n",
" <thead>\n",
" <tr style=\"text-align: right;\">\n",
" <th></th>\n",
" <th>aapl</th>\n",
" <th>cisco</th>\n",
" <th>ibm</th>\n",
" <th>amzn</th>\n",
" </tr>\n",
" </thead>\n",
" <tbody>\n",
" <tr>\n",
" <th>aapl</th>\n",
" <td>1.000000</td>\n",
" <td>0.301990</td>\n",
" <td>0.297498</td>\n",
" <td>0.235487</td>\n",
" </tr>\n",
" <tr>\n",
" <th>cisco</th>\n",
" <td>0.301990</td>\n",
" <td>1.000000</td>\n",
" <td>0.424672</td>\n",
" <td>0.284470</td>\n",
" </tr>\n",
" <tr>\n",
" <th>ibm</th>\n",
" <td>0.297498</td>\n",
" <td>0.424672</td>\n",
" <td>1.000000</td>\n",
" <td>0.258492</td>\n",
" </tr>\n",
" <tr>\n",
" <th>amzn</th>\n",
" <td>0.235487</td>\n",
" <td>0.284470</td>\n",
" <td>0.258492</td>\n",
" <td>1.000000</td>\n",
" </tr>\n",
" </tbody>\n",
"</table>\n",
"</div>"
],
"text/plain": [
" aapl cisco ibm amzn\n",
"aapl 1.000000 0.301990 0.297498 0.235487\n",
"cisco 0.301990 1.000000 0.424672 0.284470\n",
"ibm 0.297498 0.424672 1.000000 0.258492\n",
"amzn 0.235487 0.284470 0.258492 1.000000"
]
},
"execution_count": 26,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"stocks.pct_change(1).corr()"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"# Simulating Thousands of Possible Allocations"
]
},
{
"cell_type": "code",
"execution_count": 27,
"metadata": {},
"outputs": [
{
"data": {
"text/html": [
"<div>\n",
"<style>\n",
" .dataframe thead tr:only-child th {\n",
" text-align: right;\n",
" }\n",
"\n",
" .dataframe thead th {\n",
" text-align: left;\n",
" }\n",
"\n",
" .dataframe tbody tr th {\n",
" vertical-align: top;\n",
" }\n",
"</style>\n",
"<table border=\"1\" class=\"dataframe\">\n",
" <thead>\n",
" <tr style=\"text-align: right;\">\n",
" <th></th>\n",
" <th>aapl</th>\n",
" <th>cisco</th>\n",
" <th>ibm</th>\n",
" <th>amzn</th>\n",
" </tr>\n",
" <tr>\n",
" <th>Date</th>\n",
" <th></th>\n",
" <th></th>\n",
" <th></th>\n",
" <th></th>\n",
" </tr>\n",
" </thead>\n",
" <tbody>\n",
" <tr>\n",
" <th>2012-01-03</th>\n",
" <td>53.063218</td>\n",
" <td>15.752778</td>\n",
" <td>160.830881</td>\n",
" <td>179.03</td>\n",
" </tr>\n",
" <tr>\n",
" <th>2012-01-04</th>\n",
" <td>53.348386</td>\n",
" <td>16.057180</td>\n",
" <td>160.174781</td>\n",
" <td>177.51</td>\n",
" </tr>\n",
" <tr>\n",
" <th>2012-01-05</th>\n",
" <td>53.940658</td>\n",
" <td>15.997991</td>\n",
" <td>159.415086</td>\n",
" <td>177.61</td>\n",
" </tr>\n",
" <tr>\n",
" <th>2012-01-06</th>\n",
" <td>54.504543</td>\n",
" <td>15.938801</td>\n",
" <td>157.584912</td>\n",
" <td>182.61</td>\n",
" </tr>\n",
" <tr>\n",
" <th>2012-01-09</th>\n",
" <td>54.418089</td>\n",
" <td>16.040268</td>\n",
" <td>156.764786</td>\n",
" <td>178.56</td>\n",
" </tr>\n",
" </tbody>\n",
"</table>\n",
"</div>"
],
"text/plain": [
" aapl cisco ibm amzn\n",
"Date \n",
"2012-01-03 53.063218 15.752778 160.830881 179.03\n",
"2012-01-04 53.348386 16.057180 160.174781 177.51\n",
"2012-01-05 53.940658 15.997991 159.415086 177.61\n",
"2012-01-06 54.504543 15.938801 157.584912 182.61\n",
"2012-01-09 54.418089 16.040268 156.764786 178.56"
]
},
"execution_count": 27,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"stocks.head()"
]
},
{
"cell_type": "code",
"execution_count": 28,
"metadata": {},
"outputs": [
{
"data": {
"text/plain": [
"<matplotlib.axes._subplots.AxesSubplot at 0x2258d9c4668>"
]
},
"execution_count": 28,
"metadata": {},
"output_type": "execute_result"
},
{
"data": {
"image/png": "iVBORw0KGgoAAAANSUhEUgAAAXcAAAEICAYAAACktLTqAAAABHNCSVQICAgIfAhkiAAAAAlwSFlz\nAAALEgAACxIB0t1+/AAAIABJREFUeJzsnXd4VEXXwH+zJZveQ0ILIXRCb1JUgoIioiKigliwYX3V\nVwV91U+xYnsVERUR9RULNopSLCAgoCACAkqvIQkQQnpPdne+P+5mS7Ihm7BpML/nycO9M3Pnnt2E\nc889c+YcIaVEoVAoFGcXuoYWQKFQKBTeRyl3hUKhOAtRyl2hUCjOQpRyVygUirMQpdwVCoXiLEQp\nd4VCoTgLUcpdoVAozkKUclcoFIqzEKXcFQqF4izE0FA3joyMlHFxcQ11e4VCoWiSbNmy5ZSUMqq6\ncQ2m3OPi4ti8eXND3V6hUCiaJEKIJE/GKbeMQqFQnIUo5a5QKBRnIUq5KxQKxVlIg/nc3VFWVkZK\nSgrFxcUNLUq94uvrS6tWrTAajQ0tikKhOEtoVMo9JSWFoKAg4uLiEEI0tDj1gpSSjIwMUlJSaNu2\nbUOLo1AozhIalVumuLiYiIiIc0axAwghiIiIOOfeVhQKRd3SqJQ7cE4p9nLOxc+sUJyLlB07Rv7a\ntfVyr0an3BUKheJsJeVfD5A8+S5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oUQzb0ioUKhUNQhUkostlQiFcvdZXz4EYevGsOh\ny0eD2UyzRx5G6PV1Ikf5LlZzZpZX5vM0WmYGMBWoaj9sSyDZ6TzF1tbkGDx4MABr1qxh9OjR1YxW\nKBRNnaz589k3cBClycl
"text/plain": [
"<matplotlib.figure.Figure at 0x2258d9c4eb8>"
]
},
"metadata": {},
"output_type": "display_data"
}
],
"source": [
"stock_normed = stocks/stocks.iloc[0]\n",
"stock_normed.plot()"
]
},
{
"cell_type": "code",
"execution_count": 29,
"metadata": {},
"outputs": [
{
"data": {
"text/html": [
"<div>\n",
"<style>\n",
" .dataframe thead tr:only-child th {\n",
" text-align: right;\n",
" }\n",
"\n",
" .dataframe thead th {\n",
" text-align: left;\n",
" }\n",
"\n",
" .dataframe tbody tr th {\n",
" vertical-align: top;\n",
" }\n",
"</style>\n",
"<table border=\"1\" class=\"dataframe\">\n",
" <thead>\n",
" <tr style=\"text-align: right;\">\n",
" <th></th>\n",
" <th>aapl</th>\n",
" <th>cisco</th>\n",
" <th>ibm</th>\n",
" <th>amzn</th>\n",
" </tr>\n",
" <tr>\n",
" <th>Date</th>\n",
" <th></th>\n",
" <th></th>\n",
" <th></th>\n",
" <th></th>\n",
" </tr>\n",
" </thead>\n",
" <tbody>\n",
" <tr>\n",
" <th>2012-01-03</th>\n",
" <td>NaN</td>\n",
" <td>NaN</td>\n",
" <td>NaN</td>\n",
" <td>NaN</td>\n",
" </tr>\n",
" <tr>\n",
" <th>2012-01-04</th>\n",
" <td>0.005374</td>\n",
" <td>0.019324</td>\n",
" <td>-0.004079</td>\n",
" <td>-0.008490</td>\n",
" </tr>\n",
" <tr>\n",
" <th>2012-01-05</th>\n",
" <td>0.011102</td>\n",
" <td>-0.003686</td>\n",
" <td>-0.004743</td>\n",
" <td>0.000563</td>\n",
" </tr>\n",
" <tr>\n",
" <th>2012-01-06</th>\n",
" <td>0.010454</td>\n",
" <td>-0.003700</td>\n",
" <td>-0.011481</td>\n",
" <td>0.028152</td>\n",
" </tr>\n",
" <tr>\n",
" <th>2012-01-09</th>\n",
" <td>-0.001586</td>\n",
" <td>0.006366</td>\n",
" <td>-0.005204</td>\n",
" <td>-0.022178</td>\n",
" </tr>\n",
" </tbody>\n",
"</table>\n",
"</div>"
],
"text/plain": [
" aapl cisco ibm amzn\n",
"Date \n",
"2012-01-03 NaN NaN NaN NaN\n",
"2012-01-04 0.005374 0.019324 -0.004079 -0.008490\n",
"2012-01-05 0.011102 -0.003686 -0.004743 0.000563\n",
"2012-01-06 0.010454 -0.003700 -0.011481 0.028152\n",
"2012-01-09 -0.001586 0.006366 -0.005204 -0.022178"
]
},
"execution_count": 29,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"stock_daily_ret = stocks.pct_change(1)\n",
"stock_daily_ret.head()"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"## Log Returns vs Arithmetic Returns\n",
"\n",
"We will now switch over to using log returns instead of arithmetic returns, for many of our use cases they are almost the same,but most technical analyses require detrending/normalizing the time series and using log returns is a nice way to do that.\n",
"Log returns are convenient to work with in many of the algorithms we will encounter.\n",
"\n",
"For a full analysis of why we use log returns, check [this great article](https://quantivity.wordpress.com/2011/02/21/why-log-returns/).\n"
]
},
{
"cell_type": "code",
"execution_count": 30,
"metadata": {},
"outputs": [
{
"data": {
"text/html": [
"<div>\n",
"<style>\n",
" .dataframe thead tr:only-child th {\n",
" text-align: right;\n",
" }\n",
"\n",
" .dataframe thead th {\n",
" text-align: left;\n",
" }\n",
"\n",
" .dataframe tbody tr th {\n",
" vertical-align: top;\n",
" }\n",
"</style>\n",
"<table border=\"1\" class=\"dataframe\">\n",
" <thead>\n",
" <tr style=\"text-align: right;\">\n",
" <th></th>\n",
" <th>aapl</th>\n",
" <th>cisco</th>\n",
" <th>ibm</th>\n",
" <th>amzn</th>\n",
" </tr>\n",
" <tr>\n",
" <th>Date</th>\n",
" <th></th>\n",
" <th></th>\n",
" <th></th>\n",
" <th></th>\n",
" </tr>\n",
" </thead>\n",
" <tbody>\n",
" <tr>\n",
" <th>2012-01-03</th>\n",
" <td>NaN</td>\n",
" <td>NaN</td>\n",
" <td>NaN</td>\n",
" <td>NaN</td>\n",
" </tr>\n",
" <tr>\n",
" <th>2012-01-04</th>\n",
" <td>0.005360</td>\n",
" <td>0.019139</td>\n",
" <td>-0.004088</td>\n",
" <td>-0.008526</td>\n",
" </tr>\n",
" <tr>\n",
" <th>2012-01-05</th>\n",
" <td>0.011041</td>\n",
" <td>-0.003693</td>\n",
" <td>-0.004754</td>\n",
" <td>0.000563</td>\n",
" </tr>\n",
" <tr>\n",
" <th>2012-01-06</th>\n",
" <td>0.010400</td>\n",
" <td>-0.003707</td>\n",
" <td>-0.011547</td>\n",
" <td>0.027763</td>\n",
" </tr>\n",
" <tr>\n",
" <th>2012-01-09</th>\n",
" <td>-0.001587</td>\n",
" <td>0.006346</td>\n",
" <td>-0.005218</td>\n",
" <td>-0.022428</td>\n",
" </tr>\n",
" </tbody>\n",
"</table>\n",
"</div>"
],
"text/plain": [
" aapl cisco ibm amzn\n",
"Date \n",
"2012-01-03 NaN NaN NaN NaN\n",
"2012-01-04 0.005360 0.019139 -0.004088 -0.008526\n",
"2012-01-05 0.011041 -0.003693 -0.004754 0.000563\n",
"2012-01-06 0.010400 -0.003707 -0.011547 0.027763\n",
"2012-01-09 -0.001587 0.006346 -0.005218 -0.022428"
]
},
"execution_count": 30,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"log_ret = np.log(stocks/stocks.shift(1))\n",
"log_ret.head()"
]
},
{
"cell_type": "code",
"execution_count": 31,
"metadata": {},
"outputs": [
{
"data": {
"image/png": "iVBORw0KGgoAAAANSUhEUgAAA1gAAAGoCAYAAABbkkSYAAAABHNCSVQICAgIfAhkiAAAAAlwSFlz\nAAALEgAACxIB0t1+/AAAIABJREFUeJzt3X+0ZXdd3//nywQkJPxIjF6HJHVSG7GRWVS8IkpLrw1W\nJJShrSuNK9iJpmuWXYigozKB71rQr1++HZWgqdp2jYKOJR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jn0glGIj3K6cAZSb4CPBH4BHA1\nsNIs3wesAq+aRHCSpPligiVJmltVdSjJG4CPA18Cbq6qm5MsVdXhZrWHgKX1tk+yE9gJsLS0xOrq\n6hiiHs7Ro0enOr5xWaR62LXt2EmXL51x6nUWpa4Wab84FevihFHVhQmWJGluNddWbQcuBD4HvD3J\nS/vXqapKUuttX1V7gb0Ay8vLtbKyMtqAW1hdXWWa4xuXRaqHK08xeNGubce45sDJ/9U7eMVKhxFN\nr0XaL07FujhhVHVhgiVpaI5MqBnwfOBjVfVJgCTvBH4AeDjJlqo6nGQLcGSSQUqS5oeDXEiS5tnH\ngeckeWKSAJcAdwM3ATuadXYAN04oPknSnLEFS5I0t6rq1iTvAD4AHAM+SK/L31nADUmuAu4HLptc\nlJKkeWKCJUmaa1X1WuC1a2Y/Qq81S5KkTtlFUJIkSZI6YoIlSZIkSR0xwZIkSZKkjphgSZIkSVJH\nTLAkSZIkqSOOIihJkjQDvLm7NBtMsCRJkqaUSZU0e+wiKEmSJEkdMcGSJEmSpI7YRVCSJEnr6u+i\neHDPpROMRJodJliSxsKTtCRJWgR2EZQkSZKkjrRqwUryVOB3gGcABfwkcA/wNmArcBC4rKo+2ypK\nSVPDEa0kSZI21rYF61r
"text/plain": [
"<matplotlib.figure.Figure at 0x2258e3f8cc0>"
]
},
"metadata": {},
"output_type": "display_data"
}
],
"source": [
"log_ret.hist(bins=100,figsize=(12,6));\n",
"plt.tight_layout()"
]
},
{
"cell_type": "code",
"execution_count": 32,
"metadata": {},
"outputs": [
{
"data": {
"text/html": [
"<div>\n",
"<style>\n",
" .dataframe thead tr:only-child th {\n",
" text-align: right;\n",
" }\n",
"\n",
" .dataframe thead th {\n",
" text-align: left;\n",
" }\n",
"\n",
" .dataframe tbody tr th {\n",
" vertical-align: top;\n",
" }\n",
"</style>\n",
"<table border=\"1\" class=\"dataframe\">\n",
" <thead>\n",
" <tr style=\"text-align: right;\">\n",
" <th></th>\n",
" <th>count</th>\n",
" <th>mean</th>\n",
" <th>std</th>\n",
" <th>min</th>\n",
" <th>25%</th>\n",
" <th>50%</th>\n",
" <th>75%</th>\n",
" <th>max</th>\n",
" </tr>\n",
" </thead>\n",
" <tbody>\n",
" <tr>\n",
" <th>aapl</th>\n",
" <td>1257.0</td>\n",
" <td>0.000614</td>\n",
" <td>0.016466</td>\n",
" <td>-0.131875</td>\n",
" <td>-0.007358</td>\n",
" <td>0.000455</td>\n",
" <td>0.009724</td>\n",
" <td>0.085022</td>\n",
" </tr>\n",
" <tr>\n",
" <th>cisco</th>\n",
" <td>1257.0</td>\n",
" <td>0.000497</td>\n",
" <td>0.014279</td>\n",
" <td>-0.116091</td>\n",
" <td>-0.006240</td>\n",
" <td>0.000213</td>\n",
" <td>0.007634</td>\n",
" <td>0.118862</td>\n",
" </tr>\n",
" <tr>\n",
" <th>ibm</th>\n",
" <td>1257.0</td>\n",
" <td>0.000011</td>\n",
" <td>0.011819</td>\n",
" <td>-0.086419</td>\n",
" <td>-0.005873</td>\n",
" <td>0.000049</td>\n",
" <td>0.006477</td>\n",
" <td>0.049130</td>\n",
" </tr>\n",
" <tr>\n",
" <th>amzn</th>\n",
" <td>1257.0</td>\n",
" <td>0.001139</td>\n",
" <td>0.019362</td>\n",
" <td>-0.116503</td>\n",
" <td>-0.008534</td>\n",
" <td>0.000563</td>\n",
" <td>0.011407</td>\n",
" <td>0.146225</td>\n",
" </tr>\n",
" </tbody>\n",
"</table>\n",
"</div>"
],
"text/plain": [
" count mean std min 25% 50% 75% \\\n",
"aapl 1257.0 0.000614 0.016466 -0.131875 -0.007358 0.000455 0.009724 \n",
"cisco 1257.0 0.000497 0.014279 -0.116091 -0.006240 0.000213 0.007634 \n",
"ibm 1257.0 0.000011 0.011819 -0.086419 -0.005873 0.000049 0.006477 \n",
"amzn 1257.0 0.001139 0.019362 -0.116503 -0.008534 0.000563 0.011407 \n",
"\n",
" max \n",
"aapl 0.085022 \n",
"cisco 0.118862 \n",
"ibm 0.049130 \n",
"amzn 0.146225 "
]
},
"execution_count": 32,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"log_ret.describe().transpose()"
]
},
{
"cell_type": "code",
"execution_count": 33,
"metadata": {},
"outputs": [
{
"data": {
"text/plain": [
"aapl 0.154803\n",
"cisco 0.125291\n",
"ibm 0.002788\n",
"amzn 0.287153\n",
"dtype: float64"
]
},
"execution_count": 33,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"log_ret.mean() * 252"
]
},
{
"cell_type": "code",
"execution_count": 34,
"metadata": {},
"outputs": [
{
"data": {
"text/html": [
"<div>\n",
"<style>\n",
" .dataframe thead tr:only-child th {\n",
" text-align: right;\n",
" }\n",
"\n",
" .dataframe thead th {\n",
" text-align: left;\n",
" }\n",
"\n",
" .dataframe tbody tr th {\n",
" vertical-align: top;\n",
" }\n",
"</style>\n",
"<table border=\"1\" class=\"dataframe\">\n",
" <thead>\n",
" <tr style=\"text-align: right;\">\n",
" <th></th>\n",
" <th>aapl</th>\n",
" <th>cisco</th>\n",
" <th>ibm</th>\n",
" <th>amzn</th>\n",
" </tr>\n",
" </thead>\n",
" <tbody>\n",
" <tr>\n",
" <th>aapl</th>\n",
" <td>0.000271</td>\n",
" <td>0.000071</td>\n",
" <td>0.000057</td>\n",
" <td>0.000075</td>\n",
" </tr>\n",
" <tr>\n",
" <th>cisco</th>\n",
" <td>0.000071</td>\n",
" <td>0.000204</td>\n",
" <td>0.000072</td>\n",
" <td>0.000079</td>\n",
" </tr>\n",
" <tr>\n",
" <th>ibm</th>\n",
" <td>0.000057</td>\n",
" <td>0.000072</td>\n",
" <td>0.000140</td>\n",
" <td>0.000059</td>\n",
" </tr>\n",
" <tr>\n",
" <th>amzn</th>\n",
" <td>0.000075</td>\n",
" <td>0.000079</td>\n",
" <td>0.000059</td>\n",
" <td>0.000375</td>\n",
" </tr>\n",
" </tbody>\n",
"</table>\n",
"</div>"
],
"text/plain": [
" aapl cisco ibm amzn\n",
"aapl 0.000271 0.000071 0.000057 0.000075\n",
"cisco 0.000071 0.000204 0.000072 0.000079\n",
"ibm 0.000057 0.000072 0.000140 0.000059\n",
"amzn 0.000075 0.000079 0.000059 0.000375"
]
},
"execution_count": 34,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"# Compute pairwise covariance of columns\n",
"log_ret.cov()"
]
},
{
"cell_type": "code",
"execution_count": 35,
"metadata": {},
"outputs": [
{
"data": {
"text/html": [
"<div>\n",
"<style>\n",
" .dataframe thead tr:only-child th {\n",
" text-align: right;\n",
" }\n",
"\n",
" .dataframe thead th {\n",
" text-align: left;\n",
" }\n",
"\n",
" .dataframe tbody tr th {\n",
" vertical-align: top;\n",
" }\n",
"</style>\n",
"<table border=\"1\" class=\"dataframe\">\n",
" <thead>\n",
" <tr style=\"text-align: right;\">\n",
" <th></th>\n",
" <th>aapl</th>\n",
" <th>cisco</th>\n",
" <th>ibm</th>\n",
" <th>amzn</th>\n",
" </tr>\n",
" </thead>\n",
" <tbody>\n",
" <tr>\n",
" <th>aapl</th>\n",
" <td>0.068326</td>\n",
" <td>0.017854</td>\n",
" <td>0.014464</td>\n",
" <td>0.018986</td>\n",
" </tr>\n",
" <tr>\n",
" <th>cisco</th>\n",
" <td>0.017854</td>\n",
" <td>0.051381</td>\n",
" <td>0.018029</td>\n",
" <td>0.019956</td>\n",
" </tr>\n",
" <tr>\n",
" <th>ibm</th>\n",
" <td>0.014464</td>\n",
" <td>0.018029</td>\n",
" <td>0.035203</td>\n",
" <td>0.014939</td>\n",
" </tr>\n",
" <tr>\n",
" <th>amzn</th>\n",
" <td>0.018986</td>\n",
" <td>0.019956</td>\n",
" <td>0.014939</td>\n",
" <td>0.094470</td>\n",
" </tr>\n",
" </tbody>\n",
"</table>\n",
"</div>"
],
"text/plain": [
" aapl cisco ibm amzn\n",
"aapl 0.068326 0.017854 0.014464 0.018986\n",
"cisco 0.017854 0.051381 0.018029 0.019956\n",
"ibm 0.014464 0.018029 0.035203 0.014939\n",
"amzn 0.018986 0.019956 0.014939 0.094470"
]
},
"execution_count": 35,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"log_ret.cov()*252 # multiply by days"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"## Single Run for Some Random Allocation"
]
},
{
"cell_type": "code",
"execution_count": 36,
"metadata": {},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"Stocks\n",
"Index(['aapl', 'cisco', 'ibm', 'amzn'], dtype='object')\n",
"\n",
"\n",
"Creating Random Weights\n",
"[ 0.51639863 0.57066759 0.02847423 0.17152166]\n",
"\n",
"\n",
"Rebalance to sum to 1.0\n",
"[ 0.40122278 0.44338777 0.02212343 0.13326603]\n",
"\n",
"\n",
"Expected Portfolio Return\n",
"0.15599272049632004\n",
"\n",
"\n",
"Expected Volatility\n",
"0.185026495659\n",
"\n",
"\n",
"Sharpe Ratio\n",
"0.843083148393\n"
]
}
],
"source": [
"# Set seed (optional)\n",
"np.random.seed(101)\n",
"\n",
"# Stock Columns\n",
"print('Stocks')\n",
"print(stocks.columns)\n",
"print('\\n')\n",
"\n",
"# Create Random Weights\n",
"print('Creating Random Weights')\n",
"weights = np.array(np.random.random(4))\n",
"print(weights)\n",
"print('\\n')\n",
"\n",
"# Rebalance Weights\n",
"print('Rebalance to sum to 1.0')\n",
"weights = weights / np.sum(weights)\n",
"print(weights)\n",
"print('\\n')\n",
"\n",
"# Expected Return\n",
"print('Expected Portfolio Return')\n",
"exp_ret = np.sum(log_ret.mean() * weights) *252\n",
"print(exp_ret)\n",
"print('\\n')\n",
"\n",
"# Expected Variance\n",
"print('Expected Volatility')\n",
"exp_vol = np.sqrt(np.dot(weights.T, np.dot(log_ret.cov() * 252, weights)))\n",
"print(exp_vol)\n",
"print('\\n')\n",
"\n",
"# Sharpe Ratio\n",
"SR = exp_ret/exp_vol\n",
"print('Sharpe Ratio')\n",
"print(SR)\n"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"Great! Now we can just run this many times over!"
]
},
{
"cell_type": "code",
"execution_count": 37,
"metadata": {
"collapsed": true
},
"outputs": [],
"source": [
"num_ports = 15000\n",
"\n",
"all_weights = np.zeros((num_ports,len(stocks.columns)))\n",
"ret_arr = np.zeros(num_ports)\n",
"vol_arr = np.zeros(num_ports)\n",
"sharpe_arr = np.zeros(num_ports)\n",
"\n",
"for ind in range(num_ports):\n",
"\n",
" # Create Random Weights\n",
" weights = np.array(np.random.random(4))\n",
"\n",
" # Rebalance Weights\n",
" weights = weights / np.sum(weights)\n",
" \n",
" # Save Weights\n",
" all_weights[ind,:] = weights\n",
"\n",
" # Expected Return\n",
" ret_arr[ind] = np.sum((log_ret.mean() * weights) *252)\n",
"\n",
" # Expected Variance\n",
" vol_arr[ind] = np.sqrt(np.dot(weights.T, np.dot(log_ret.cov() * 252, weights)))\n",
"\n",
" # Sharpe Ratio\n",
" sharpe_arr[ind] = ret_arr[ind]/vol_arr[ind]"
]
},
{
"cell_type": "code",
"execution_count": 38,
"metadata": {},
"outputs": [
{
"data": {
"text/plain": [
"1.0303260551271067"
]
},
"execution_count": 38,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"sharpe_arr.max()"
]
},
{
"cell_type": "code",
"execution_count": 39,
"metadata": {},
"outputs": [
{
"data": {
"text/plain": [
"1419"
]
},
"execution_count": 39,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"sharpe_arr.argmax()"
]
},
{
"cell_type": "code",
"execution_count": 40,
"metadata": {},
"outputs": [
{
"data": {
"text/plain": [
"array([ 0.26188068, 0.20759516, 0.00110226, 0.5294219 ])"
]
},
"execution_count": 40,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"all_weights[1419,:]"
]
},
{
"cell_type": "code",
"execution_count": 41,
"metadata": {
"collapsed": true
},
"outputs": [],
"source": [
"max_sr_ret = ret_arr[1419]\n",
"max_sr_vol = vol_arr[1419]"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"## Plotting the data"
]
},
{
"cell_type": "code",
"execution_count": 42,
"metadata": {},
"outputs": [
{
"data": {
"text/plain": [
"<matplotlib.collections.PathCollection at 0x2258e24ac50>"
]
},
"execution_count": 42,
"metadata": {},
"output_type": "execute_result"
},
{
"data": {
"image/png": "iVBORw0KGgoAAAANSUhEUgAAAq0AAAHjCAYAAAAJ5iYqAAAABHNCSVQICAgIfAhkiAAAAAlwSFlz\nAAALEgAACxIB0t1+/AAAIABJREFUeJzsnXm8HGWVv59T1d13T272hQQSZBFQAWVxRhFRUdEZN5wB\nQQd3HUVU1EFGRx2Xn47LOKIIw6DgKO4rKoi4i8rIvioQCAECCdlzl16q6j2/P96q7url3iTk3uTe\n5Dx+2ttV9db7nmr9dH9z3rOIqmIYhmEYhmEYU5lgdxtgGIZhGIZhGNvCRKthGIZhGIYx5THRahiG\nYRiGYUx5TLQahmEYhmEYUx4TrYZhGIZhGMaUx0SrYRiGYRiGMeUx0WoYhmEYhmFMeUy0GoZhGIZh\nGFMeE62GYRiGYRjGlKewuw2YSObOnavLli3b3WYYhmEYhrGHcMMNN6xX1Xm7247nPLdXN2xIJnTO\nm2+sXaWqz5/QSSeRPUq0Llu2jOuvv353m2EYhmEYxh6CiKza3TYAbNiQ8Js/7TOhcw52rZw7oRNO\nMnuUaDUMwzAMw9gzEXDh7jZit2IxrYZhGIZhGMaUxzythmEYhmEYUx0FcbK7rditmKfVMAzDMAzD\nmPKYp9UwDMMwDGM6oHu3p9VEq2EYhmEYxhRHsPAACw8wDMMwDMMwpjzmaTUMwzAMw5jqKIjb3Ubs\nXszTahiGYRiGYUx5TLQahmEYhmFMB9wEv7YDEfmyiDwqIrePcV1E5DwRWSEit4rIkx/z820DE62G\nYRiGYRhTHQWZ4Nd2cinw/HGunwQcmL7eCFywM485HiZaDcMwDMMwjI6o6u+AjeMMeTHwv+q5FhgU\nkUWTYYslYhmGYRiGYUwDJiERa66IXJ87vkhVL9rBOfYBHswdP5See2RnjWvFRKthGIZhGMbeyXpV\nPWp3G7G9mGg1DMMwDMOYDrjtD0TdhawGluaOl6TnJhyLaTUMwz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Haqp0QtooQIIp/5c6ju67WkSx6LbQmXAXdMOcFSMl2R3cYJxP7mmZMWiKWqsYiciZwFRACX1bV\nO0Tkzen1C4EPAHOAL6Z9imNVPQpYAPwgPVcAvq6qP5ssWw3DMIzpTxLfSnX4XNT5beeg8Dd0938C\nCWY3xtRuIKn81rts2n6zI8LCsa0nd5AI3IbmU9phKS3jNl8Ig69pPh2tJln9NqjeBQQQziJc/Gmk\nd8c2G6X/6dApDEF6kMG/36G5dgbp3hcO/Rp6/8dg5BYI+mDh6cg+b9llNuxRTMPaqhPJpHbEUtUr\ngCtazl2Ye/964PUd7rsPOLz1vGEYhmF0wrm1VLa+mryn1MV/pDx0Bj0zLkdEUI2obnkLaLXhaBXx\n76VAsfdfkGBwJy0pQjBzzOz9ZqM3oZrgK0SCakKy6nSIH6GuTuJHSB58PeH+VyHFRdtthYQzkH0+\njq4+F+9djUFKyOCLkb6n7vhj7QTSdyhy2GW7dE1jz8TauBqGYRjTDtVhosp3SKLfEQSLUApAq2cx\nRpPVuPgmwuKTcdGNQIwoaIT3tgbqPaEuJuzdd6ftEhHCGW8l2fIZ0PL4gwtL6oIVQEf/BG4zbe40\nTXCbv0047+07ZEs4+Pdo71Ho1p+iySjBjBOQnifu0BzGFGKaJk9NJCZaDcMwjGmFui2Ut56MuvVA\nBVdPz+i8d6puNfBk6qLW+e16aWplqdQ2v5vu+Vcjwcydsi8ceBWqCW7zxwGFADTxgraOdBPO9o0i\nVWN0809wGy5q1DNtogbRQ4/JFiktQua2bWgaxrTERKthGIYxrYgql6LuUSCr/zleoF9CUDgUgKB4\nFJmrqmMKittCZc3f0b3gcl+gn2i7Gg644at969R4NVI6iGDuuyl0H0sU9YCOItmqQeomky4KC75A\n0PsMVB3JqjfDyJ+9Zzb
"text/plain": [
"<matplotlib.figure.Figure at 0x2258da3b710>"
]
},
"metadata": {},
"output_type": "display_data"
}
],
"source": [
"plt.figure(figsize=(12,8))\n",
"plt.scatter(vol_arr,ret_arr,c=sharpe_arr,cmap='plasma')\n",
"plt.colorbar(label='Sharpe Ratio')\n",
"plt.xlabel('Volatility')\n",
"plt.ylabel('Return')\n",
"\n",
"# Add red dot for max SR\n",
"plt.scatter(max_sr_vol,max_sr_ret,c='red',s=50,edgecolors='black')"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"# Mathematical Optimization\n",
"\n",
"There are much better ways to find good allocation weights than just guess and check! We can use optimization functions to find the ideal weights mathematically!"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"### Functionalize Return and SR operations"
]
},
{
"cell_type": "code",
"execution_count": 43,
"metadata": {
"collapsed": true
},
"outputs": [],
"source": [
"def get_ret_vol_sr(weights):\n",
" \"\"\"\n",
" Takes in weights, returns array or return,volatility, sharpe ratio\n",
" \"\"\"\n",
" weights = np.array(weights)\n",
" ret = np.sum(log_ret.mean() * weights) * 252\n",
" vol = np.sqrt(np.dot(weights.T, np.dot(log_ret.cov() * 252, weights)))\n",
" sr = ret/vol\n",
" return np.array([ret,vol,sr])"
]
},
{
"cell_type": "code",
"execution_count": 44,
"metadata": {
"collapsed": true
},
"outputs": [],
"source": [
"from scipy.optimize import minimize"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"To fully understand all the parameters, check out:\n",
"https://docs.scipy.org/doc/scipy/reference/generated/scipy.optimize.minimize.html"
]
},
{
"cell_type": "code",
"execution_count": 45,
"metadata": {},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"Help on function minimize in module scipy.optimize._minimize:\n",
"\n",
"minimize(fun, x0, args=(), method=None, jac=None, hess=None, hessp=None, bounds=None, constraints=(), tol=None, callback=None, options=None)\n",
" Minimization of scalar function of one or more variables.\n",
" \n",
" In general, the optimization problems are of the form::\n",
" \n",
" minimize f(x) subject to\n",
" \n",
" g_i(x) >= 0, i = 1,...,m\n",
" h_j(x) = 0, j = 1,...,p\n",
" \n",
" where x is a vector of one or more variables.\n",
" ``g_i(x)`` are the inequality constraints.\n",
" ``h_j(x)`` are the equality constrains.\n",
" \n",
" Optionally, the lower and upper bounds for each element in x can also be\n",
" specified using the `bounds` argument.\n",
" \n",
" Parameters\n",
" ----------\n",
" fun : callable\n",
" Objective function.\n",
" x0 : ndarray\n",
" Initial guess.\n",
" args : tuple, optional\n",
" Extra arguments passed to the objective function and its\n",
" derivatives (Jacobian, Hessian).\n",
" method : str or callable, optional\n",
" Type of solver. Should be one of\n",
" \n",
" - 'Nelder-Mead' :ref:`(see here) <optimize.minimize-neldermead>`\n",
" - 'Powell' :ref:`(see here) <optimize.minimize-powell>`\n",
" - 'CG' :ref:`(see here) <optimize.minimize-cg>`\n",
" - 'BFGS' :ref:`(see here) <optimize.minimize-bfgs>`\n",
" - 'Newton-CG' :ref:`(see here) <optimize.minimize-newtoncg>`\n",
" - 'L-BFGS-B' :ref:`(see here) <optimize.minimize-lbfgsb>`\n",
" - 'TNC' :ref:`(see here) <optimize.minimize-tnc>`\n",
" - 'COBYLA' :ref:`(see here) <optimize.minimize-cobyla>`\n",
" - 'SLSQP' :ref:`(see here) <optimize.minimize-slsqp>`\n",
" - 'dogleg' :ref:`(see here) <optimize.minimize-dogleg>`\n",
" - 'trust-ncg' :ref:`(see here) <optimize.minimize-trustncg>`\n",
" - custom - a callable object (added in version 0.14.0),\n",
" see below for description.\n",
" \n",
" If not given, chosen to be one of ``BFGS``, ``L-BFGS-B``, ``SLSQP``,\n",
" depending if the problem has constraints or bounds.\n",
" jac : bool or callable, optional\n",
" Jacobian (gradient) of objective function. Only for CG, BFGS,\n",
" Newton-CG, L-BFGS-B, TNC, SLSQP, dogleg, trust-ncg.\n",
" If `jac` is a Boolean and is True, `fun` is assumed to return the\n",
" gradient along with the objective function. If False, the\n",
" gradient will be estimated numerically.\n",
" `jac` can also be a callable returning the gradient of the\n",
" objective. In this case, it must accept the same arguments as `fun`.\n",
" hess, hessp : callable, optional\n",
" Hessian (matrix of second-order derivatives) of objective function or\n",
" Hessian of objective function times an arbitrary vector p. Only for\n",
" Newton-CG, dogleg, trust-ncg.\n",
" Only one of `hessp` or `hess` needs to be given. If `hess` is\n",
" provided, then `hessp` will be ignored. If neither `hess` nor\n",
" `hessp` is provided, then the Hessian product will be approximated\n",
" using finite differences on `jac`. `hessp` must compute the Hessian\n",
" times an arbitrary vector.\n",
" bounds : sequence, optional\n",
" Bounds for variables (only for L-BFGS-B, TNC and SLSQP).\n",
" ``(min, max)`` pairs for each element in ``x``, defining\n",
" the bounds on that parameter. Use None for one of ``min`` or\n",
" ``max`` when there is no bound in that direction.\n",
" constraints : dict or sequence of dict, optional\n",
" Constraints definition (only for COBYLA and SLSQP).\n",
" Each constraint is defined in a dictionary with fields:\n",
" \n",
" type : str\n",
" Constraint type: 'eq' for equality, 'ineq' for inequality.\n",
" fun : callable\n",
" The function defining the constraint.\n",
" jac : callable, optional\n",
" The Jacobian of `fun` (only for SLSQP).\n",
" args : sequence, optional\n",
" Extra arguments to be passed to the function and Jacobian.\n",
" \n",
" Equality constraint means that the constraint function result is to\n",
" be zero whereas inequality means that it is to be non-negative.\n",
" Note that COBYLA only supports inequality constraints.\n",
" tol : float, optional\n",
" Tolerance for termination. For detailed control, use solver-specific\n",
" options.\n",
" options : dict, optional\n",
" A dictionary of solver options. All methods accept the following\n",
" generic options:\n",
" \n",
" maxiter : int\n",
" Maximum number of iterations to perform.\n",
" disp : bool\n",
" Set to True to print convergence messages.\n",
" \n",
" For method-specific options, see :func:`show_options()`.\n",
" callback : callable, optional\n",
" Called after each iteration, as ``callback(xk)``, where ``xk`` is the\n",
" current parameter vector.\n",
" \n",
" Returns\n",
" -------\n",
" res : OptimizeResult\n",
" The optimization result represented as a ``OptimizeResult`` object.\n",
" Important attributes are: ``x`` the solution array, ``success`` a\n",
" Boolean flag indicating if the optimizer exited successfully and\n",
" ``message`` which describes the cause of the termination. See\n",
" `OptimizeResult` for a description of other attributes.\n",
" \n",
" \n",
" See also\n",
" --------\n",
" minimize_scalar : Interface to minimization algorithms for scalar\n",
" univariate functions\n",
" show_options : Additional options accepted by the solvers\n",
" \n",
" Notes\n",
" -----\n",
" This section describes the available solvers that can be selected by the\n",
" 'method' parameter. The default method is *BFGS*.\n",
" \n",
" **Unconstrained minimization**\n",
" \n",
" Method :ref:`Nelder-Mead <optimize.minimize-neldermead>` uses the\n",
" Simplex algorithm [1]_, [2]_. This algorithm is robust in many\n",
" applications. However, if numerical computation of derivative can be\n",
" trusted, other algorithms using the first and/or second derivatives\n",
" information might be preferred for their better performance in\n",
" general.\n",
" \n",
" Method :ref:`Powell <optimize.minimize-powell>` is a modification\n",
" of Powell's method [3]_, [4]_ which is a conjugate direction\n",
" method. It performs sequential one-dimensional minimizations along\n",
" each vector of the directions set (`direc` field in `options` and\n",
" `info`), which is updated at each iteration of the main\n",
" minimization loop. The function need not be differentiable, and no\n",
" derivatives are taken.\n",
" \n",
" Method :ref:`CG <optimize.minimize-cg>` uses a nonlinear conjugate\n",
" gradient algorithm by Polak and Ribiere, a variant of the\n",
" Fletcher-Reeves method described in [5]_ pp. 120-122. Only the\n",
" first derivatives are used.\n",
" \n",
" Method :ref:`BFGS <optimize.minimize-bfgs>` uses the quasi-Newton\n",
" method of Broyden, Fletcher, Goldfarb, and Shanno (BFGS) [5]_\n",
" pp. 136. It uses the first derivatives only. BFGS has proven good\n",
" performance even for non-smooth optimizations. This method also\n",
" returns an approximation of the Hessian inverse, stored as\n",
" `hess_inv` in the OptimizeResult object.\n",
" \n",
" Method :ref:`Newton-CG <optimize.minimize-newtoncg>` uses a\n",
" Newton-CG algorithm [5]_ pp. 168 (also known as the truncated\n",
" Newton method). It uses a CG method to the compute the search\n",
" direction. See also *TNC* method for a box-constrained\n",
" minimization with a similar algorithm.\n",
" \n",
" Method :ref:`dogleg <optimize.minimize-dogleg>` uses the dog-leg\n",
" trust-region algorithm [5]_ for unconstrained minimization. This\n",
" algorithm requires the gradient and Hessian; furthermore the\n",
" Hessian is required to be positive definite.\n",
" \n",
" Method :ref:`trust-ncg <optimize.minimize-trustncg>` uses the\n",
" Newton conjugate gradient trust-region algorithm [5]_ for\n",
" unconstrained minimization. This algorithm requires the gradient\n",
" and either the Hessian or a function that computes the product of\n",
" the Hessian with a given vector.\n",
" \n",
" **Constrained minimization**\n",
" \n",
" Method :ref:`L-BFGS-B <optimize.minimize-lbfgsb>` uses the L-BFGS-B\n",
" algorithm [6]_, [7]_ for bound constrained minimization.\n",
" \n",
" Method :ref:`TNC <optimize.minimize-tnc>` uses a truncated Newton\n",
" algorithm [5]_, [8]_ to minimize a function with variables subject\n",
" to bounds. This algorithm uses gradient information; it is also\n",
" called Newton Conjugate-Gradient. It differs from the *Newton-CG*\n",
" method described above as it wraps a C implementation and allows\n",
" each variable to be given upper and lower bounds.\n",
" \n",
" Method :ref:`COBYLA <optimize.minimize-cobyla>` uses the\n",
" Constrained Optimization BY Linear Approximation (COBYLA) method\n",
" [9]_, [10]_, [11]_. The algorithm is based on linear\n",
" approximations to the objective function and each constraint. The\n",
" method wraps a FORTRAN implementation of the algorithm. The\n",
" constraints functions 'fun' may return either a single number\n",
" or an array or list of numbers.\n",
" \n",
" Method :ref:`SLSQP <optimize.minimize-slsqp>` uses Sequential\n",
" Least SQuares Programming to minimize a function of several\n",
" variables with any combination of bounds, equality and inequality\n",
" constraints. The method wraps the SLSQP Optimization subroutine\n",
" originally implemented by Dieter Kraft [12]_. Note that the\n",
" wrapper handles infinite values in bounds by converting them into\n",
" large floating values.\n",
" \n",
" **Custom minimizers**\n",
" \n",
" It may be useful to pass a custom minimization method, for example\n",
" when using a frontend to this method such as `scipy.optimize.basinhopping`\n",
" or a different library. You can simply pass a callable as the ``method``\n",
" parameter.\n",
" \n",
" The callable is called as ``method(fun, x0, args, **kwargs, **options)``\n",
" where ``kwargs`` corresponds to any other parameters passed to `minimize`\n",
" (such as `callback`, `hess`, etc.), except the `options` dict, which has\n",
" its contents also passed as `method` parameters pair by pair. Also, if\n",
" `jac` has been passed as a bool type, `jac` and `fun` are mangled so that\n",
" `fun` returns just the function values and `jac` is converted to a function\n",
" returning the Jacobian. The method shall return an ``OptimizeResult``\n",
" object.\n",
" \n",
" The provided `method` callable must be able to accept (and possibly ignore)\n",
" arbitrary parameters; the set of parameters accepted by `minimize` may\n",
" expand in future versions and then these parameters will be passed to\n",
" the method. You can find an example in the scipy.optimize tutorial.\n",
" \n",
" .. versionadded:: 0.11.0\n",
" \n",
" References\n",
" ----------\n",
" .. [1] Nelder, J A, and R Mead. 1965. A Simplex Method for Function\n",
" Minimization. The Computer Journal 7: 308-13.\n",
" .. [2] Wright M H. 1996. Direct search methods: Once scorned, now\n",
" respectable, in Numerical Analysis 1995: Proceedings of the 1995\n",
" Dundee Biennial Conference in Numerical Analysis (Eds. D F\n",
" Griffiths and G A Watson). Addison Wesley Longman, Harlow, UK.\n",
" 191-208.\n",
" .. [3] Powell, M J D. 1964. An efficient method for finding the minimum of\n",
" a function of several variables without calculating derivatives. The\n",
" Computer Journal 7: 155-162.\n",
" .. [4] Press W, S A Teukolsky, W T Vetterling and B P Flannery.\n",
" Numerical Recipes (any edition), Cambridge University Press.\n",
" .. [5] Nocedal, J, and S J Wright. 2006. Numerical Optimization.\n",
" Springer New York.\n",
" .. [6] Byrd, R H and P Lu and J. Nocedal. 1995. A Limited Memory\n",
" Algorithm for Bound Constrained Optimization. SIAM Journal on\n",
" Scientific and Statistical Computing 16 (5): 1190-1208.\n",
" .. [7] Zhu, C and R H Byrd and J Nocedal. 1997. L-BFGS-B: Algorithm\n",
" 778: L-BFGS-B, FORTRAN routines for large scale bound constrained\n",
" optimization. ACM Transactions on Mathematical Software 23 (4):\n",
" 550-560.\n",
" .. [8] Nash, S G. Newton-Type Minimization Via the Lanczos Method.\n",
" 1984. SIAM Journal of Numerical Analysis 21: 770-778.\n",
" .. [9] Powell, M J D. A direct search optimization method that models\n",
" the objective and constraint functions by linear interpolation.\n",
" 1994. Advances in Optimization and Numerical Analysis, eds. S. Gomez\n",
" and J-P Hennart, Kluwer Academic (Dordrecht), 51-67.\n",
" .. [10] Powell M J D. Direct search algorithms for optimization\n",
" calculations. 1998. Acta Numerica 7: 287-336.\n",
" .. [11] Powell M J D. A view of algorithms for optimization without\n",
" derivatives. 2007.Cambridge University Technical Report DAMTP\n",
" 2007/NA03\n",
" .. [12] Kraft, D. A software package for sequential quadratic\n",
" programming. 1988. Tech. Rep. DFVLR-FB 88-28, DLR German Aerospace\n",
" Center -- Institute for Flight Mechanics, Koln, Germany.\n",
" \n",
" Examples\n",
" --------\n",
" Let us consider the problem of minimizing the Rosenbrock function. This\n",
" function (and its respective derivatives) is implemented in `rosen`\n",
" (resp. `rosen_der`, `rosen_hess`) in the `scipy.optimize`.\n",
" \n",
" >>> from scipy.optimize import minimize, rosen, rosen_der\n",
" \n",
" A simple application of the *Nelder-Mead* method is:\n",
" \n",
" >>> x0 = [1.3, 0.7, 0.8, 1.9, 1.2]\n",
" >>> res = minimize(rosen, x0, method='Nelder-Mead', tol=1e-6)\n",
" >>> res.x\n",
" array([ 1., 1., 1., 1., 1.])\n",
" \n",
" Now using the *BFGS* algorithm, using the first derivative and a few\n",
" options:\n",
" \n",
" >>> res = minimize(rosen, x0, method='BFGS', jac=rosen_der,\n",
" ... options={'gtol': 1e-6, 'disp': True})\n",
" Optimization terminated successfully.\n",
" Current function value: 0.000000\n",
" Iterations: 26\n",
" Function evaluations: 31\n",
" Gradient evaluations: 31\n",
" >>> res.x\n",
" array([ 1., 1., 1., 1., 1.])\n",
" >>> print(res.message)\n",
" Optimization terminated successfully.\n",
" >>> res.hess_inv\n",
" array([[ 0.00749589, 0.01255155, 0.02396251, 0.04750988, 0.09495377], # may vary\n",
" [ 0.01255155, 0.02510441, 0.04794055, 0.09502834, 0.18996269],\n",
" [ 0.02396251, 0.04794055, 0.09631614, 0.19092151, 0.38165151],\n",
" [ 0.04750988, 0.09502834, 0.19092151, 0.38341252, 0.7664427 ],\n",
" [ 0.09495377, 0.18996269, 0.38165151, 0.7664427, 1.53713523]])\n",
" \n",
" \n",
" Next, consider a minimization problem with several constraints (namely\n",
" Example 16.4 from [5]_). The objective function is:\n",
" \n",
" >>> fun = lambda x: (x[0] - 1)**2 + (x[1] - 2.5)**2\n",
" \n",
" There are three constraints defined as:\n",
" \n",
" >>> cons = ({'type': 'ineq', 'fun': lambda x: x[0] - 2 * x[1] + 2},\n",
" ... {'type': 'ineq', 'fun': lambda x: -x[0] - 2 * x[1] + 6},\n",
" ... {'type': 'ineq', 'fun': lambda x: -x[0] + 2 * x[1] + 2})\n",
" \n",
" And variables must be positive, hence the following bounds:\n",
" \n",
" >>> bnds = ((0, None), (0, None))\n",
" \n",
" The optimization problem is solved using the SLSQP method as:\n",
" \n",
" >>> res = minimize(fun, (2, 0), method='SLSQP', bounds=bnds,\n",
" ... constraints=cons)\n",
" \n",
" It should converge to the theoretical solution (1.4 ,1.7).\n",
"\n"
]
}
],
"source": [
"help(minimize)"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"Optimization works as a minimization function, since we actually want to maximize the Sharpe Ratio, we will need to turn it negative so we can minimize the negative sharpe (same as maximizing the postive sharpe)"
]
},
{
"cell_type": "code",
"execution_count": 46,
"metadata": {
"collapsed": true
},
"outputs": [],
"source": [
"def neg_sharpe(weights):\n",
" return get_ret_vol_sr(weights)[2] * -1"
]
},
{
"cell_type": "code",
"execution_count": 47,
"metadata": {
"collapsed": true
},
"outputs": [],
"source": [
"# Contraints\n",
"def check_sum(weights):\n",
" '''\n",
" Returns 0 if sum of weights is 1.0\n",
" '''\n",
" return np.sum(weights) - 1"
]
},
{
"cell_type": "code",
"execution_count": 48,
"metadata": {
"collapsed": true
},
"outputs": [],
"source": [
"# By convention of minimize function it should be a function that returns zero for conditions\n",
"cons = ({'type':'eq','fun': check_sum})"
]
},
{
"cell_type": "code",
"execution_count": 49,
"metadata": {
"collapsed": true
},
"outputs": [],
"source": [
"# 0-1 bounds for each weight\n",
"bounds = ((0, 1), (0, 1), (0, 1), (0, 1))"
]
},
{
"cell_type": "code",
"execution_count": 50,
"metadata": {
"collapsed": true
},
"outputs": [],
"source": [
"# Initial Guess (equal distribution)\n",
"init_guess = [0.25,0.25,0.25,0.25]"
]
},
{
"cell_type": "code",
"execution_count": 51,
"metadata": {
"collapsed": true
},
"outputs": [],
"source": [
"# Sequential Least SQuares Programming (SLSQP).\n",
"opt_results = minimize(neg_sharpe,init_guess,method='SLSQP',bounds=bounds,constraints=cons)"
]
},
{
"cell_type": "code",
"execution_count": 52,
"metadata": {},
"outputs": [
{
"data": {
"text/plain": [
" fun: -1.030716870334955\n",
" jac: array([ 5.64455986e-05, 4.18275595e-05, 3.39921728e-01,\n",
" -4.45097685e-05])\n",
" message: 'Optimization terminated successfully.'\n",
" nfev: 42\n",
" nit: 7\n",
" njev: 7\n",
" status: 0\n",
" success: True\n",
" x: array([ 2.66289778e-01, 2.04189819e-01, 9.24621165e-17,\n",
" 5.29520404e-01])"
]
},
"execution_count": 52,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"opt_results"
]
},
{
"cell_type": "code",
"execution_count": 53,
"metadata": {},
"outputs": [
{
"data": {
"text/plain": [
"array([ 2.66289778e-01, 2.04189819e-01, 9.24621165e-17,\n",
" 5.29520404e-01])"
]
},
"execution_count": 53,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"opt_results.x"
]
},
{
"cell_type": "code",
"execution_count": 54,
"metadata": {},
"outputs": [
{
"data": {
"text/plain": [
"array([ 0.21885915, 0.21233683, 1.03071687])"
]
},
"execution_count": 54,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"get_ret_vol_sr(opt_results.x)"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"# All Optimal Portfolios (Efficient Frontier)\n",
"\n",
"The efficient frontier is the set of optimal portfolios that offers the highest expected return for a defined level of risk or the lowest risk for a given level of expected return. Portfolios that lie below the efficient frontier are sub-optimal, because they do not provide enough return for the level of risk. Portfolios that cluster to the right of the efficient frontier are also sub-optimal, because they have a higher level of risk for the defined rate of return.\n",
"\n",
"Efficient Frontier http://www.investopedia.com/terms/e/efficientfrontier"
]
},
{
"cell_type": "code",
"execution_count": 55,
"metadata": {
"collapsed": true
},
"outputs": [],
"source": [
"# Our returns go from 0 to somewhere along 0.3\n",
"# Create a linspace number of points to calculate x on\n",
"frontier_y = np.linspace(0,0.3,100) # Change 100 to a lower number for slower computers!"
]
},
{
"cell_type": "code",
"execution_count": 56,
"metadata": {
"collapsed": true
},
"outputs": [],
"source": [
"def minimize_volatility(weights):\n",
" return get_ret_vol_sr(weights)[1] "
]
},
{
"cell_type": "code",
"execution_count": 57,
"metadata": {
"collapsed": true
},
"outputs": [],
"source": [
"frontier_volatility = []\n",
"\n",
"for possible_return in frontier_y:\n",
" # function for return\n",
" cons = ({'type':'eq','fun': check_sum},\n",
" {'type':'eq','fun': lambda w: get_ret_vol_sr(w)[0] - possible_return})\n",
" \n",
" result = minimize(minimize_volatility,init_guess,method='SLSQP',bounds=bounds,constraints=cons)\n",
" \n",
" frontier_volatility.append(result['fun'])"
]
},
{
"cell_type": "code",
"execution_count": 58,
"metadata": {},
"outputs": [
{
"data": {
"text/plain": [
"[<matplotlib.lines.Line2D at 0x2258fdefeb8>]"
]
},
"execution_count": 58,
"metadata": {},
"output_type": "execute_result"
},
{
"data": {
"image/png": "iVBORw0KGgoAAAANSUhEUgAAAq0AAAHjCAYAAAAJ5iYqAAAABHNCSVQICAgIfAhkiAAAAAlwSFlz\nAAALEgAACxIB0t1+/AAAIABJREFUeJzs3XmcHlWV8PHfqXqW3pfsO1lJiIQ1rAFR9hBkVcFtBBcE\nxREH1/edUV91Rh2dURQHhkFkdBBkVHY0sgUCYQnIloQkhOx7OuktvTxL1Xn/qHq2fp7udEh3upOc\n7+cT0k/VrVu3+vNJ9+HWueeKqmKMMcYYY8xg5gz0AIwxxhhjjNkTC1qNMcYYY8ygZ0GrMcYYY4wZ\n9CxoNcYYY4wxg54FrcYYY4wxZtCzoNUYY4wxxgx6FrQaY4wxxphBz4JWY4wxxhgz6FnQaowxxhhj\nBr3IQA+gLw0bNkwnTpw40MMwxhhjzEHil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7skgZ\nc8bPyb7uP2HsCZaTavqPLcQyxhhjDk1pP83Lm1/Ovu5/bv1zJLwEtfFaPnLkR3AdN9v2zElnEnWi\nnDj2RM6adBZnTjqTk8edTDwSH8AnMObQYUGrMcaYQ4aqsmLnCh575zEeW/0YC9YuoDXZWtSuOdHM\n37b8jRPGnpA9Nrp6NE3faKIiWrE/h2xMjm0uYIwxxhz8PN9j+s3TeafxnR7bTR86nbMmnUV1vLro\nnAWsZsAolh4w0AMwxhhj+lJ7qp1n1z/LuJpxzBw+M3vcdVzG144vClrH1YzjrElncdaks3j/pPcz\nrmbc/h6yMaYXLGg1xhhzQPPV59Utr/LY6uCVfyYv9csnf5l/P+/fC9qeM/kc/rblb5w56UzOnnQ2\n50w5h2lDpiFyaM9gmQO
"text/plain": [
"<matplotlib.figure.Figure at 0x2258fd7b208>"
]
},
"metadata": {},
"output_type": "display_data"
}
],
"source": [
"plt.figure(figsize=(12,8))\n",
"plt.scatter(vol_arr,ret_arr,c=sharpe_arr,cmap='plasma')\n",
"plt.colorbar(label='Sharpe Ratio')\n",
"plt.xlabel('Volatility')\n",
"plt.ylabel('Return')\n",
"\n",
"\n",
"\n",
"# Add frontier line\n",
"plt.plot(frontier_volatility,frontier_y,'g--',linewidth=3)"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"# Great Job!"
]
}
],
"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.6.1"
}
},
"nbformat": 4,
"nbformat_minor": 2
}