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

1933 lines
304 KiB
Plaintext
Raw Permalink Normal View History

2023-08-21 15:12:19 +00:00
{
"cells": [
{
"cell_type": "markdown",
"metadata": {},
"source": [
"# Optimisation du Portefeuille"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"\"Modern Portfolio Theory\" (MPT), une hypothèse avancée par Harry Markowitz dans son article \"Portfolio Selection\" (publié en 1952 par le Journal of Finance) est une théorie de l'investissement basée sur l'idée que les investisseurs peu enclins au risque peuvent construire des portefeuilles pour optimiser ou maximiser le rendement attendu en fonction d'un niveau de risque de marché donné, en soulignant que le risque est une partie inhérente à un rendement plus élevé. Il s'agit de l'une des théories économiques les plus importantes et les plus influentes en matière de finance et d'investissement.\n",
"\n",
"[Plus d'informations sur la théorie moderne du Portefeuille](https://fr.wikipedia.org/wiki/Th%C3%A9orie_moderne_du_portefeuille)"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"## Simulation Monte Carlo pour la recherche d'optimisation\n",
"\n",
"\n",
"Nous pourrions essayer de trouver au hasard l'équilibre optimal du portefeuille en utilisant la simulation de Monte Carlo"
]
},
{
"cell_type": "code",
"execution_count": 2,
"metadata": {},
"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": 3,
"metadata": {},
"outputs": [],
"source": [
"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": 4,
"metadata": {},
"outputs": [],
"source": [
"stocks = pd.concat([aapl,cisco,ibm,amzn],axis=1)\n",
"stocks.columns = ['aapl','cisco','ibm','amzn']"
]
},
{
"cell_type": "code",
"execution_count": 5,
"metadata": {},
"outputs": [
{
"data": {
"text/html": [
"<div>\n",
"<style scoped>\n",
" .dataframe tbody tr th:only-of-type {\n",
" vertical-align: middle;\n",
" }\n",
"\n",
" .dataframe tbody tr th {\n",
" vertical-align: top;\n",
" }\n",
"\n",
" .dataframe thead th {\n",
" text-align: right;\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>52.848787</td>\n",
" <td>15.617341</td>\n",
" <td>157.578371</td>\n",
" <td>179.03</td>\n",
" </tr>\n",
" <tr>\n",
" <th>2012-01-04</th>\n",
" <td>53.132802</td>\n",
" <td>15.919125</td>\n",
" <td>156.935540</td>\n",
" <td>177.51</td>\n",
" </tr>\n",
" <tr>\n",
" <th>2012-01-05</th>\n",
" <td>53.722681</td>\n",
" <td>15.860445</td>\n",
" <td>156.191208</td>\n",
" <td>177.61</td>\n",
" </tr>\n",
" <tr>\n",
" <th>2012-01-06</th>\n",
" <td>54.284287</td>\n",
" <td>15.801764</td>\n",
" <td>154.398046</td>\n",
" <td>182.61</td>\n",
" </tr>\n",
" <tr>\n",
" <th>2012-01-09</th>\n",
" <td>54.198183</td>\n",
" <td>15.902359</td>\n",
" <td>153.594506</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 52.848787 15.617341 157.578371 179.03\n",
"2012-01-04 53.132802 15.919125 156.935540 177.51\n",
"2012-01-05 53.722681 15.860445 156.191208 177.61\n",
"2012-01-06 54.284287 15.801764 154.398046 182.61\n",
"2012-01-09 54.198183 15.902359 153.594506 178.56"
]
},
"execution_count": 5,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"stocks.head()"
]
},
{
"cell_type": "code",
"execution_count": 6,
"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": 6,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"mean_daily_ret = stocks.pct_change(1).mean()\n",
"mean_daily_ret"
]
},
{
"cell_type": "code",
"execution_count": 7,
"metadata": {},
"outputs": [
{
"data": {
"text/html": [
"<div>\n",
"<style scoped>\n",
" .dataframe tbody tr th:only-of-type {\n",
" vertical-align: middle;\n",
" }\n",
"\n",
" .dataframe tbody tr th {\n",
" vertical-align: top;\n",
" }\n",
"\n",
" .dataframe thead th {\n",
" text-align: right;\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": 7,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"stocks.pct_change(1).corr()"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"# Simulation de milliers de répartitions possibles"
]
},
{
"cell_type": "code",
"execution_count": 8,
"metadata": {},
"outputs": [
{
"data": {
"text/html": [
"<div>\n",
"<style scoped>\n",
" .dataframe tbody tr th:only-of-type {\n",
" vertical-align: middle;\n",
" }\n",
"\n",
" .dataframe tbody tr th {\n",
" vertical-align: top;\n",
" }\n",
"\n",
" .dataframe thead th {\n",
" text-align: right;\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>52.848787</td>\n",
" <td>15.617341</td>\n",
" <td>157.578371</td>\n",
" <td>179.03</td>\n",
" </tr>\n",
" <tr>\n",
" <th>2012-01-04</th>\n",
" <td>53.132802</td>\n",
" <td>15.919125</td>\n",
" <td>156.935540</td>\n",
" <td>177.51</td>\n",
" </tr>\n",
" <tr>\n",
" <th>2012-01-05</th>\n",
" <td>53.722681</td>\n",
" <td>15.860445</td>\n",
" <td>156.191208</td>\n",
" <td>177.61</td>\n",
" </tr>\n",
" <tr>\n",
" <th>2012-01-06</th>\n",
" <td>54.284287</td>\n",
" <td>15.801764</td>\n",
" <td>154.398046</td>\n",
" <td>182.61</td>\n",
" </tr>\n",
" <tr>\n",
" <th>2012-01-09</th>\n",
" <td>54.198183</td>\n",
" <td>15.902359</td>\n",
" <td>153.594506</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 52.848787 15.617341 157.578371 179.03\n",
"2012-01-04 53.132802 15.919125 156.935540 177.51\n",
"2012-01-05 53.722681 15.860445 156.191208 177.61\n",
"2012-01-06 54.284287 15.801764 154.398046 182.61\n",
"2012-01-09 54.198183 15.902359 153.594506 178.56"
]
},
"execution_count": 8,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"stocks.head()"
]
},
{
"cell_type": "code",
"execution_count": 9,
"metadata": {},
"outputs": [
{
"data": {
"text/plain": [
"<matplotlib.axes._subplots.AxesSubplot at 0x115185a90>"
]
},
"execution_count": 9,
"metadata": {},
"output_type": "execute_result"
},
{
"data": {
"image/png": "iVBORw0KGgoAAAANSUhEUgAAAXQAAAEECAYAAAA4Qc+SAAAABHNCSVQICAgIfAhkiAAAAAlwSFlzAAALEgAACxIB0t1+/AAAADh0RVh0U29mdHdhcmUAbWF0cGxvdGxpYiB2ZXJzaW9uMy4xLjEsIGh0dHA6Ly9tYXRwbG90bGliLm9yZy8QZhcZAAAgAElEQVR4nOydd3hUxdrAf7Mlm0Z6Qksg9N6LNAUEaXIBKQroFbv42RW7guXa0asIiqh47R0FKRaaFEF6J9RQAgTSezbZ3fn+OJvNbrJJNrAhCczveXg458ycmfcE8p4577xFSClRKBQKRe1HV90CKBQKhcI7KIWuUCgUlwhKoSsUCsUlglLoCoVCcYmgFLpCoVBcIhiqa+KIiAgZGxtbXdMrFApFrWTr1q3JUspId23VptBjY2PZsmVLdU2vUCgUtRIhxPGy2pTJRaFQKC4RlEJXKBSKSwSl0BUKheISodps6O4oLCwkISGB/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B6MJTWVpJlvYWzYEENkpEPpekuZA+jDNIVuy8k57zEqI82DaIUrgty03Q6kSSmbCyEmAq8DN5y3VAqFQlENSCkdyhwgc+ky0r7/npw1awFo8PZbF7SCLo8izxZrWmoFPcvGIy8XIUQ0cC3wcRldRlNcR/RHYJAoL9yyBtPHvgmxevVqRo4cWUFvhUJR28n84w/2t25D4blz5Kxd69q2dKlDmQMYwquufnDRBqhf587nPYanbovvAI8DtjLaGwInAaSUFiADKFWeQwh
"text/plain": [
"<Figure size 432x288 with 1 Axes>"
]
},
"metadata": {
"needs_background": "light"
},
"output_type": "display_data"
}
],
"source": [
"stock_normed = stocks/stocks.iloc[0]\n",
"stock_normed.plot()"
]
},
{
"cell_type": "code",
"execution_count": 10,
"metadata": {},
"outputs": [
{
"data": {
"text/html": [
"<div>\n",
"<style scoped>\n",
" .dataframe tbody tr th:only-of-type {\n",
" vertical-align: middle;\n",
" }\n",
"\n",
" .dataframe tbody tr th {\n",
" vertical-align: top;\n",
" }\n",
"\n",
" .dataframe thead th {\n",
" text-align: right;\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": 10,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"stock_daily_ret = stocks.pct_change(1)\n",
"stock_daily_ret.head()"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"## Rendements logarithmiques vs. Rendements arithmétiques\n",
"\n",
"Nous allons maintenant passer à l'utilisation de rendements logarithmiques au lieu de rendements arithmétiques, pour beaucoup de nos cas d'utilisation ce sont presque les mêmes, mais la plupart des analyses techniques nécessitent de normaliser les séries temporelles et l'utilisation de rendements logarithmiques est une bonne façon de le faire.\n",
"Les rendements logarithmiques sont pratiques à utiliser dans la plupart des algorithmes que nous rencontrerons.\n",
"\n",
"\n",
"Pour une analyse complète des raisons pour lesquelles nous utilisons les rendements logarithmiques, consultez [ce super article](https://quantivity.wordpress.com/2011/02/21/why-log-returns/).\n"
]
},
{
"cell_type": "code",
"execution_count": 11,
"metadata": {},
"outputs": [
{
"data": {
"text/html": [
"<div>\n",
"<style scoped>\n",
" .dataframe tbody tr th:only-of-type {\n",
" vertical-align: middle;\n",
" }\n",
"\n",
" .dataframe tbody tr th {\n",
" vertical-align: top;\n",
" }\n",
"\n",
" .dataframe thead th {\n",
" text-align: right;\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": 11,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"log_ret = np.log(stocks/stocks.shift(1))\n",
"log_ret.head()"
]
},
{
"cell_type": "code",
"execution_count": 12,
"metadata": {},
"outputs": [
{
"data": {
"image/png": "iVBORw0KGgoAAAANSUhEUgAAA1cAAAGoCAYAAACqmR8VAAAABHNCSVQICAgIfAhkiAAAAAlwSFlzAAALEgAACxIB0t1+/AAAADh0RVh0U29mdHdhcmUAbWF0cGxvdGxpYiB2ZXJzaW9uMy4xLjEsIGh0dHA6Ly9tYXRwbG90bGliLm9yZy8QZhcZAAAgAElEQVR4nO3dfZRld13n+/fHtCEhAfIEZeiOdhgjI9LjAGVAuHpLggIGCHcMTpwMk0BcvWbGB5QeTYC5C5zRO42XgKiz5LZGDWuQBCJOMjCjxECN4ozRJDA0SYxpQpN00iY8JEgjAxZ87x9nN3W6Ut1Vdc4+T7ver7XOqnP22fuc7/6effau7/n99m+nqpAkSZIkDeebJh2AJEmSJHWBxZUkSZIktcDiSpIkSZJaYHElSZIkSS2wuJIkSZKkFlhcSZIkSVILLK6kGZNkIcmBScchSZKkI1lcSZIkSVILLK4kSZIkqQUWV9IIJbkiySeTfDHJHUn+r2b6P0jyoSSfS/LZJO9KckrfcvuTvK5Z5uEkv5PkhMmtiSSpK45xbLo0yZ8leVuSR5Lck+S5zfT7kjyU5JJm3icnOdR3+7sk1fc6H0nyluYY9qkkL57kOkvjYnEljdYnge8DngD8AvCfkpwJBPgPwJOB7wTOAt60YtmLgRcC/wD4DuDfjidkSVLHHe3YBPBs4OPA6cDvAdcA3wN8O/DPgV9PcnJVPVBVJx++AX/QzEvf69wFnAH8MnBVkox+1aTJsriSRqiq3tscgL5eVdcCdwPnVtW+qrqxqr5SVZ8B3gr8nysW//Wquq+qPg/8EvBjYw5fktRBRzs2NU9/qqp+p6q+BlxL78e/f9ccrz4IfJVeofUNSS4H/iHw6r7Jn66q32xe52rgTGButGsmTd6WSQcgdVmSfwG8FtjeTDoZOCPJk4BfpffL4ePo/dDx8IrF7+u7/2l6rVySJA3laMcm4GvAg32zfhmgqlZOO7nvtV4Mv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TV8Y3TZsrFrh1Lx3x+7sS15wE2Tb4207axFnOxrO1cWFxJkjopyanABcDZwCPAe4EXrzJrrbZ8Ve0B9gDMz8/XwsLCaAJtweLiItMc3zhtplxcusYgRbt2LHHl3rX/1dt/8UJLEU23zbRtrMVcLGs7FxZXkobmKISaUi8APlVVnwFI8j7gucApSbY0rVfbgAcmGKMkqUMc0EKS1FX3As9J8tgkAc4D7gA+DFzYzHMJcP2E4pMkdYzFlSSpk6rqZuA64DZgL71j3h7gcuC1SfYBpwNXTSxISVKn2C1QktRZVfVG4I0rJt8DnDuBcCRJHWfLlSRJkiS1wOJKkiRJklpgcSVJkiRJLbC4kiRJkqQWWFxJkiRJUgscLVCSJGlGeNF2abpZXEmSJE0piylpttgtUJIkSZJaYHElSZIkSS2wW6AkSZJW1d8tcf/u8ycYiTQbLK4kjc3Kcwc8UEuSpC6xW6AkSZIktWColqskpwC/BTwdKODVwF3AtcB2YD/wo1X18FBRSpoqjl4lSZL0aMO2XL0d+MOq+ofAdwN3AlcAN1XVOcBNzWNJkiRJ6rSBi6skjwe+H7gKoKq+WlWPABcAVzezXQ28fNggJUmSJGnaDdMt8CnAZ4DfSfLdwK3Aa4C5qjoIUFUHkzxptYWT7AR2AszNzbG4uDhEKN106NAh8zIkc3ikXTuWBlpu7sTBl+3P/8rX2EyfjduiJEndN0xxtQV4JvBTVXVzkrezgS6AVbUH2AMwPz9fCwsLQ4TSTYuLi5iX4ZjDI1064LlSu3YsceXewXYX+y9eOOr79z/XdW6LkiR13zDnXB0ADlTVzc3j6+gVWw8mOROg+fvQcCFKkiRJ0vQbuLiqqr8B7kvy1GbSecAdwA3AJc20S4Drh4pQkiRJkmbAsBcR/in
"text/plain": [
"<Figure size 864x432 with 4 Axes>"
]
},
"metadata": {
"needs_background": "light"
},
"output_type": "display_data"
}
],
"source": [
"log_ret.hist(bins=100,figsize=(12,6));\n",
"plt.tight_layout()"
]
},
{
"cell_type": "code",
"execution_count": 13,
"metadata": {},
"outputs": [
{
"data": {
"text/html": [
"<div>\n",
"<style scoped>\n",
" .dataframe tbody tr th:only-of-type {\n",
" vertical-align: middle;\n",
" }\n",
"\n",
" .dataframe tbody tr th {\n",
" vertical-align: top;\n",
" }\n",
"\n",
" .dataframe thead th {\n",
" text-align: right;\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": 13,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"log_ret.describe().transpose()"
]
},
{
"cell_type": "code",
"execution_count": 14,
"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": 14,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"log_ret.mean() * 252"
]
},
{
"cell_type": "code",
"execution_count": 15,
"metadata": {},
"outputs": [
{
"data": {
"text/html": [
"<div>\n",
"<style scoped>\n",
" .dataframe tbody tr th:only-of-type {\n",
" vertical-align: middle;\n",
" }\n",
"\n",
" .dataframe tbody tr th {\n",
" vertical-align: top;\n",
" }\n",
"\n",
" .dataframe thead th {\n",
" text-align: right;\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": 15,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"# Calculer la covariance des colonnes par paires\n",
"log_ret.cov()"
]
},
{
"cell_type": "code",
"execution_count": 16,
"metadata": {},
"outputs": [
{
"data": {
"text/html": [
"<div>\n",
"<style scoped>\n",
" .dataframe tbody tr th:only-of-type {\n",
" vertical-align: middle;\n",
" }\n",
"\n",
" .dataframe tbody tr th {\n",
" vertical-align: top;\n",
" }\n",
"\n",
" .dataframe thead th {\n",
" text-align: right;\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": 16,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"log_ret.cov()*252 # multiplier par les jours ouvrables"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"## Exécution pour une certaine répartition aléatoire"
]
},
{
"cell_type": "code",
"execution_count": 17,
"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.1559927204963252\n",
"\n",
"\n",
"Expected Volatility\n",
"0.1850264956590895\n",
"\n",
"\n",
"Sharpe Ratio\n",
"0.8430831483926556\n"
]
}
],
"source": [
"# Règlage du seed (optionnel)\n",
"np.random.seed(101)\n",
"\n",
"# Colonnes d'actions (Stocks)\n",
"print('Stocks')\n",
"print(stocks.columns)\n",
"print('\\n')\n",
"\n",
"# Créer des poids aléatoires\n",
"print('Creating Random Weights')\n",
"weights = np.array(np.random.random(4))\n",
"print(weights)\n",
"print('\\n')\n",
"\n",
"# Re-pondération des Poids\n",
"print('Rebalance to sum to 1.0')\n",
"weights = weights / np.sum(weights)\n",
"print(weights)\n",
"print('\\n')\n",
"\n",
"# Rendement attendu ou escompté\n",
"print('Expected Portfolio Return')\n",
"exp_ret = np.sum(log_ret.mean() * weights) *252\n",
"print(exp_ret)\n",
"print('\\n')\n",
"\n",
"# variance attendue ou escomptée\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",
"# Ratio de Sharpe\n",
"SR = exp_ret/exp_vol\n",
"print('Sharpe Ratio')\n",
"print(SR)\n"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"Super ! Maintenant, on peut l'éxécuter plein de fois !"
]
},
{
"cell_type": "code",
"execution_count": 18,
"metadata": {},
"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",
" # Créer des poids aléatoires\n",
" weights = np.array(np.random.random(4))\n",
"\n",
" # (re)Pondération des poids\n",
" weights = weights / np.sum(weights)\n",
" \n",
" # Sauvegarde des Poids\n",
" all_weights[ind,:] = weights\n",
"\n",
" # rendement attendu\n",
" ret_arr[ind] = np.sum((log_ret.mean() * weights) *252)\n",
"\n",
" # variance Attendue\n",
" vol_arr[ind] = np.sqrt(np.dot(weights.T, np.dot(log_ret.cov() * 252, weights)))\n",
"\n",
" # Ratio de Sharpe\n",
" sharpe_arr[ind] = ret_arr[ind]/vol_arr[ind]"
]
},
{
"cell_type": "code",
"execution_count": 19,
"metadata": {},
"outputs": [
{
"data": {
"text/plain": [
"1.030326055127131"
]
},
"execution_count": 19,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"sharpe_arr.max()"
]
},
{
"cell_type": "code",
"execution_count": 20,
"metadata": {},
"outputs": [
{
"data": {
"text/plain": [
"1419"
]
},
"execution_count": 20,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"sharpe_arr.argmax()"
]
},
{
"cell_type": "code",
"execution_count": 21,
"metadata": {},
"outputs": [
{
"data": {
"text/plain": [
"array([0.26188068, 0.20759516, 0.00110226, 0.5294219 ])"
]
},
"execution_count": 21,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"all_weights[1419,:]"
]
},
{
"cell_type": "code",
"execution_count": 22,
"metadata": {},
"outputs": [],
"source": [
"max_sr_ret = ret_arr[1419]\n",
"max_sr_vol = vol_arr[1419]"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"## Tracer les données"
]
},
{
"cell_type": "code",
"execution_count": 23,
"metadata": {},
"outputs": [
{
"data": {
"text/plain": [
"<matplotlib.collections.PathCollection at 0x115e86e10>"
]
},
"execution_count": 23,
"metadata": {},
"output_type": "execute_result"
},
{
"data": {
"image/png": "iVBORw0KGgoAAAANSUhEUgAAAq0AAAHgCAYAAACPclSEAAAABHNCSVQICAgIfAhkiAAAAAlwSFlzAAALEgAACxIB0t1+/AAAADh0RVh0U29mdHdhcmUAbWF0cGxvdGxpYiB2ZXJzaW9uMy4xLjEsIGh0dHA6Ly9tYXRwbG90bGliLm9yZy8QZhcZAAAgAElEQVR4nOydeZwdZZW/n1N1l97SnX2HhFVZXUBBEXFBBNefu4CKGzjujoOO28iIM+qoOK6oKIqCwigCwzgqroiiiIiAwyYhBEgC2dPd6b597616z++Pt+reultn607SyXn4VLpv1VtvnfcC935z3rOIqmIYhmEYhmEYezLB7jbAMAzDMAzDMLaGiVbDMAzDMAxjj8dEq2EYhmEYhrHHY6LVMAzDMAzD2OMx0WoYhmEYhmHs8ZhoNQzDMAzDMPZ4crvbgIli9uzZunTp0t1thmEYhmEYexF/+ctf1qvqnN1tx8mn9OiGDfGEznnbrZXrVPXUCZ10EtlrROvSpUu55ZZbdrcZhmEYhmHsRYjIg7vbBoANG2Ku/+OiCZ1zevGB2RM64SSz14hWwzAMwzCMvRcBF+5uI3YrFtNqGIZhGIZh7PGYp9UwDMMwDGNPR0Gc7G4rdivmaTUMwzAMwz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MK5E1MVwTB2N5NZPcAwDMMwJpxK6QLQIaCSnIno7IKqEoTeuxgWnkGnoEABNHqAytpXoVpGVfHNHMdHVYkH/4vqipOp3v9EolVvhMoywsKTkKgHqUAQJ49V9YcMkFtwKUHX41BXJl7+CvTR/4DKqvbLkCJ0PX6rthh7O+ITsSbymGKYaDUMwzCmFHH1D3TOSMl+EXeT6zoDCQb8lXA
"text/plain": [
"<Figure size 864x576 with 2 Axes>"
]
},
"metadata": {
"needs_background": "light"
},
"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",
"# Ajouter un point rouge pour le SR max\n",
"plt.scatter(max_sr_vol,max_sr_ret,c='red',s=50,edgecolors='black')"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"# Optimisation mathématique\n",
"\n",
"Il y a de bien meilleures façons de trouver de bons poids de répartition que de simplement deviner et vérifier ! Nous pouvons utiliser des fonctions d'optimisation pour trouver les poids idéaux mathématiquement !"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"### Fonctionnaliser les opérations de rendement et de SR"
]
},
{
"cell_type": "code",
"execution_count": 24,
"metadata": {},
"outputs": [],
"source": [
"def get_ret_vol_sr(weights):\n",
" \"\"\"\n",
" Prends en argument les poids, retourne un tableau de rendement,\n",
" volatilité et Ratio de Sharpe\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": 25,
"metadata": {},
"outputs": [],
"source": [
"from scipy.optimize import minimize"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"Pour bien comprendre tous les paramètres, regardez:\n",
"https://docs.scipy.org/doc/scipy/reference/generated/scipy.optimize.minimize.html"
]
},
{
"cell_type": "code",
"execution_count": 26,
"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",
" Parameters\n",
" ----------\n",
" fun : callable\n",
" The objective function to be minimized.\n",
" \n",
" ``fun(x, *args) -> float``\n",
" \n",
" where x is an 1-D array with shape (n,) and `args`\n",
" is a tuple of the fixed parameters needed to completely\n",
" specify the function.\n",
" x0 : ndarray, shape (n,)\n",
" Initial guess. Array of real elements of size (n,),\n",
" where 'n' is the number of independent variables.\n",
" args : tuple, optional\n",
" Extra arguments passed to the objective function and its\n",
" derivatives (`fun`, `jac` and `hess` functions).\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",
" - 'trust-constr':ref:`(see here) <optimize.minimize-trustconstr>`\n",
" - 'dogleg' :ref:`(see here) <optimize.minimize-dogleg>`\n",
" - 'trust-ncg' :ref:`(see here) <optimize.minimize-trustncg>`\n",
" - 'trust-exact' :ref:`(see here) <optimize.minimize-trustexact>`\n",
" - 'trust-krylov' :ref:`(see here) <optimize.minimize-trustkrylov>`\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 : {callable, '2-point', '3-point', 'cs', bool}, optional\n",
" Method for computing the gradient vector. Only for CG, BFGS,\n",
" Newton-CG, L-BFGS-B, TNC, SLSQP, dogleg, trust-ncg, trust-krylov,\n",
" trust-exact and trust-constr. If it is a callable, it should be a\n",
" function that returns the gradient vector:\n",
" \n",
" ``jac(x, *args) -> array_like, shape (n,)``\n",
" \n",
" where x is an array with shape (n,) and `args` is a tuple with\n",
" the fixed parameters. Alternatively, the keywords\n",
" {'2-point', '3-point', 'cs'} select a finite\n",
" difference scheme for numerical estimation of the gradient. Options\n",
" '3-point' and 'cs' are available only to 'trust-constr'.\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 gradient\n",
" will be estimated using '2-point' finite difference estimation.\n",
" hess : {callable, '2-point', '3-point', 'cs', HessianUpdateStrategy}, optional\n",
" Method for computing the Hessian matrix. Only for Newton-CG, dogleg,\n",
" trust-ncg, trust-krylov, trust-exact and trust-constr. If it is\n",
" callable, it should return the Hessian matrix:\n",
" \n",
" ``hess(x, *args) -> {LinearOperator, spmatrix, array}, (n, n)``\n",
" \n",
" where x is a (n,) ndarray and `args` is a tuple with the fixed\n",
" parameters. LinearOperator and sparse matrix returns are\n",
" allowed only for 'trust-constr' method. Alternatively, the keywords\n",
" {'2-point', '3-point', 'cs'} select a finite difference scheme\n",
" for numerical estimation. Or, objects implementing\n",
" `HessianUpdateStrategy` interface can be used to approximate\n",
" the Hessian. Available quasi-Newton methods implementing\n",
" this interface are:\n",
" \n",
" - `BFGS`;\n",
" - `SR1`.\n",
" \n",
" Whenever the gradient is estimated via finite-differences,\n",
" the Hessian cannot be estimated with options\n",
" {'2-point', '3-point', 'cs'} and needs to be\n",
" estimated using one of the quasi-Newton strategies.\n",
" Finite-difference options {'2-point', '3-point', 'cs'} and\n",
" `HessianUpdateStrategy` are available only for 'trust-constr' method.\n",
" hessp : callable, optional\n",
" Hessian of objective function times an arbitrary vector p. Only for\n",
" Newton-CG, trust-ncg, trust-krylov, trust-constr.\n",
" Only one of `hessp` or `hess` needs to be given. If `hess` is\n",
" provided, then `hessp` will be ignored. `hessp` must compute the\n",
" Hessian times an arbitrary vector:\n",
" \n",
" ``hessp(x, p, *args) -> ndarray shape (n,)``\n",
" \n",
" where x is a (n,) ndarray, p is an arbitrary vector with\n",
" dimension (n,) and `args` is a tuple with the fixed\n",
" parameters.\n",
" bounds : sequence or `Bounds`, optional\n",
" Bounds on variables for L-BFGS-B, TNC, SLSQP and\n",
" trust-constr methods. There are two ways to specify the bounds:\n",
" \n",
" 1. Instance of `Bounds` class.\n",
" 2. Sequence of ``(min, max)`` pairs for each element in `x`. None\n",
" is used to specify no bound.\n",
" \n",
" constraints : {Constraint, dict} or List of {Constraint, dict}, optional\n",
" Constraints definition (only for COBYLA, SLSQP and trust-constr).\n",
" Constraints for 'trust-constr' are defined as a single object or a\n",
" list of objects specifying constraints to the optimization problem.\n",
" Available constraints are:\n",
" \n",
" - `LinearConstraint`\n",
" - `NonlinearConstraint`\n",
" \n",
" Constraints for COBYLA, SLSQP are defined as a list of dictionaries.\n",
" Each 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. For 'trust-constr' it is a callable with\n",
" the signature:\n",
" \n",
" ``callback(xk, OptimizeResult state) -> bool``\n",
" \n",
" where ``xk`` is the current parameter vector. and ``state``\n",
" is an `OptimizeResult` object, with the same fields\n",
" as the ones from the return. If callback returns True\n",
" the algorithm execution is terminated.\n",
" For all the other methods, the signature is:\n",
" \n",
" ``callback(xk)``\n",
" \n",
" where ``xk`` is the 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",
" 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. Suitable for large-scale\n",
" problems.\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. Suitable for large-scale problems.\n",
" \n",
" Method :ref:`trust-krylov <optimize.minimize-trustkrylov>` uses\n",
" the Newton GLTR trust-region algorithm [14]_, [15]_ for unconstrained\n",
" 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. Suitable for large-scale problems.\n",
" On indefinite problems it requires usually less iterations than the\n",
" `trust-ncg` method and is recommended for medium and large-scale problems.\n",
" \n",
" Method :ref:`trust-exact <optimize.minimize-trustexact>`\n",
" is a trust-region method for unconstrained minimization in which\n",
" quadratic subproblems are solved almost exactly [13]_. This\n",
" algorithm requires the gradient and the Hessian (which is\n",
" *not* required to be positive definite). It is, in many\n",
" situations, the Newton method to converge in fewer iteraction\n",
" and the most recommended for small and medium-size problems.\n",
" \n",
" **Bound-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",
" **Constrained Minimization**\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",
" Method :ref:`trust-constr <optimize.minimize-trustconstr>` is a\n",
" trust-region algorithm for constrained optimization. It swiches\n",
" between two implementations depending on the problem definition.\n",
" It is the most versatile constrained minimization algorithm\n",
" implemented in SciPy and the most appropriate for large-scale problems.\n",
" For equality constrained problems it is an implementation of Byrd-Omojokun\n",
" Trust-Region SQP method described in [17]_ and in [5]_, p. 549. When\n",
" inequality constraints are imposed as well, it swiches to the trust-region\n",
" interior point method described in [16]_. This interior point algorithm,\n",
" in turn, solves inequality constraints by introducing slack variables\n",
" and solving a sequence of equality-constrained barrier problems\n",
" for progressively smaller values of the barrier parameter.\n",
" The previously described equality constrained SQP method is\n",
" used to solve the subproblems with increasing levels of accuracy\n",
" as the iterate gets closer to a solution.\n",
" \n",
" **Finite-Difference Options**\n",
" \n",
" For Method :ref:`trust-constr <optimize.minimize-trustconstr>`\n",
" the gradient and the Hessian may be approximated using\n",
" three finite-difference schemes: {'2-point', '3-point', 'cs'}.\n",
" The scheme 'cs' is, potentially, the most accurate but it\n",
" requires the function to correctly handles complex inputs and to\n",
" be differentiable in the complex plane. The scheme '3-point' is more\n",
" accurate than '2-point' but requires twice as much operations.\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",
" .. [13] Conn, A. R., Gould, N. I., and Toint, P. L.\n",
" Trust region methods. 2000. Siam. pp. 169-200.\n",
" .. [14] F. Lenders, C. Kirches, A. Potschka: \"trlib: A vector-free\n",
" implementation of the GLTR method for iterative solution of\n",
" the trust region problem\", https://arxiv.org/abs/1611.04718\n",
" .. [15] N. Gould, S. Lucidi, M. Roma, P. Toint: \"Solving the\n",
" Trust-Region Subproblem using the Lanczos Method\",\n",
" SIAM J. Optim., 9(2), 504--525, (1999).\n",
" .. [16] Byrd, Richard H., Mary E. Hribar, and Jorge Nocedal. 1999.\n",
" An interior point algorithm for large-scale nonlinear programming.\n",
" SIAM Journal on Optimization 9.4: 877-900.\n",
" .. [17] Lalee, Marucha, Jorge Nocedal, and Todd Plantega. 1998. On the\n",
" implementation of an algorithm for large-scale equality constrained\n",
" optimization. SIAM Journal on Optimization 8.3: 682-706.\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": [
"L'optimisation fonctionne comme une fonction de minimisation, puisque nous voulons en fait maximiser le ratio de Sharpe, nous devrons le rendre négatif afin de pouvoir minimiser le sharpe négatif (comme pour maximiser le sharpe positif)"
]
},
{
"cell_type": "code",
"execution_count": 27,
"metadata": {},
"outputs": [],
"source": [
"def neg_sharpe(weights):\n",
" return get_ret_vol_sr(weights)[2] * -1"
]
},
{
"cell_type": "code",
"execution_count": 28,
"metadata": {},
"outputs": [],
"source": [
"# Contraintes\n",
"def check_sum(weights):\n",
" '''\n",
" Retourne 0 si la somme des poids vaut 1.0\n",
" '''\n",
" return np.sum(weights) - 1"
]
},
{
"cell_type": "code",
"execution_count": 29,
"metadata": {},
"outputs": [],
"source": [
"# Par convention de fonction de minimisation, il devrait s'agir d'une fonction qui retourne zéro pour certaines conditions\n",
"cons = ({'type':'eq','fun': check_sum})"
]
},
{
"cell_type": "code",
"execution_count": 30,
"metadata": {},
"outputs": [],
"source": [
"# 0-1 pour chaque poids\n",
"bounds = ((0, 1), (0, 1), (0, 1), (0, 1))"
]
},
{
"cell_type": "code",
"execution_count": 31,
"metadata": {},
"outputs": [],
"source": [
"# Hypothèse initiale (répartition égale)\n",
"init_guess = [0.25,0.25,0.25,0.25]"
]
},
{
"cell_type": "code",
"execution_count": 32,
"metadata": {},
"outputs": [],
"source": [
"# Sequential Least Squares Programming (SLSQP)\n",
"# Programmation séquentielle des moindres carrés\n",
"opt_results = minimize(neg_sharpe,init_guess,method='SLSQP',bounds=bounds,constraints=cons)"
]
},
{
"cell_type": "code",
"execution_count": 33,
"metadata": {},
"outputs": [
{
"data": {
"text/plain": [
" fun: -1.0307168703356593\n",
" jac: array([ 5.64157963e-05, 4.18424606e-05, 3.39921728e-01, -4.44948673e-05])\n",
" message: 'Optimization terminated successfully.'\n",
" nfev: 42\n",
" nit: 7\n",
" njev: 7\n",
" status: 0\n",
" success: True\n",
" x: array([0.26628976, 0.20418983, 0. , 0.52952041])"
]
},
"execution_count": 33,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"opt_results"
]
},
{
"cell_type": "code",
"execution_count": 34,
"metadata": {},
"outputs": [
{
"data": {
"text/plain": [
"array([0.26628976, 0.20418983, 0. , 0.52952041])"
]
},
"execution_count": 34,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"opt_results.x"
]
},
{
"cell_type": "code",
"execution_count": 35,
"metadata": {},
"outputs": [
{
"data": {
"text/plain": [
"array([0.21885915, 0.21233683, 1.03071687])"
]
},
"execution_count": 35,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"get_ret_vol_sr(opt_results.x)"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"# Portefeuilles Optimaux (Frontière Efficiente)\n",
"\n",
"La frontière efficiente est l'ensemble des portefeuilles optimaux qui offrent le rendement attendu le plus élevé pour un niveau de risque défini ou le risque le plus faible pour un niveau de rendement attendu donné. Les portefeuilles qui se situent sous la frontière efficiente sont sous-optimaux, car ils n'offrent pas un rendement suffisant pour le niveau de risque. Les portefeuilles qui se regroupent à droite de la frontière efficiente sont également sous-optimaux, car ils présentent un niveau de risque plus élevé pour le taux de rendement défini.\n",
"\n",
"En résumé, la frontière efficiente est composée de l'ensemble des portefeuilles (combinaisons de titres) qui présentent la meilleure rentabilité pour un niveau de risque donné.\n",
"\n",
"Frontière Efficiente https://epargne.ooreka.fr/astuce/voir/678865/frontiere-efficiente"
]
},
{
"cell_type": "code",
"execution_count": 36,
"metadata": {},
"outputs": [],
"source": [
"# Nos rendements vont de 0 à 0.3\n",
"# Créer un nombre de points linéairement espacés pour calculer x dessus\n",
"frontier_y = np.linspace(0,0.3,100) # Changez 100 à un chiffre inférieur pour les ordinateurs plus lents !"
]
},
{
"cell_type": "code",
"execution_count": 37,
"metadata": {},
"outputs": [],
"source": [
"def minimize_volatility(weights):\n",
" return get_ret_vol_sr(weights)[1] "
]
},
{
"cell_type": "code",
"execution_count": 38,
"metadata": {},
"outputs": [],
"source": [
"frontier_volatility = []\n",
"\n",
"for possible_return in frontier_y:\n",
" # contraintes\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": 39,
"metadata": {},
"outputs": [
{
"data": {
"text/plain": [
"[<matplotlib.lines.Line2D at 0x115951ad0>]"
]
},
"execution_count": 39,
"metadata": {},
"output_type": "execute_result"
},
{
"data": {
"image/png": "iVBORw0KGgoAAAANSUhEUgAAAq0AAAHgCAYAAACPclSEAAAABHNCSVQICAgIfAhkiAAAAAlwSFlzAAALEgAACxIB0t1+/AAAADh0RVh0U29mdHdhcmUAbWF0cGxvdGxpYiB2ZXJzaW9uMy4xLjEsIGh0dHA6Ly9tYXRwbG90bGliLm9yZy8QZhcZAAAgAElEQVR4nOzdd3gd5ZX48e+Z29TlIvdesenFYMBgqglg6g8SSMImSyCkF5IsCdmE3c2GJJtOskkIYdNDQkiAmB4SMGAMpoPBBfeKLRfJliVd3Tsz5/fHzG26V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ncebYMzli8BFWvN+YTrKg1RhjjOmk9TvX88+V/+SJ1U/wxKonWL9zfcl2c1fPLQhaAf75gX8ypGqIBalm3yiIlbwyxhhjzJ588P4P8tvXf7vbNrWJWmaOmclhdYcVHRtWPay7hmbMIcGCVmOMMSbU1NbEM2ufIe2luXTKpQXHJg+YXNS+Ol7NzDEzs4/7jx16rOWkmu5jC7GMMcaYQ1PSTfL8+uezj/xf2PACru9y1OCjioLWc8afw9ef+TqnjT6Ns8eezTnjz+H4YccXLLgyxnQf+y/NGGPMIcNXn9c3vc7jKx/nHyv/wTNrnyHpJovaLaxfSH1zPYMrB2ffO3H4iTR8sYGyaNmBHLIxOba5gDHGGHPw29K8hSN+ekTJgv75jhlyDOeMOwfXdwvejzgRe/Rveo5i6QE9PQBjjDGmK+1I7mDu6rmcMPyEgoL8dRV1VMYri4LWSQMmcc64czh73NmcNe4s6irqDvSQjTGdYEGrMcaYPi3tpVmwYQG
"text/plain": [
"<Figure size 864x576 with 2 Axes>"
]
},
"metadata": {
"needs_background": "light"
},
"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",
"# Ajouter une ligne de frontière\n",
"plt.plot(frontier_volatility,frontier_y,'g--',linewidth=3)"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"# Bon Travail!"
]
}
],
"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.8.5-final"
}
},
"nbformat": 4,
"nbformat_minor": 2
}