{
  "cells": [
    {
      "cell_type": "code",
      "execution_count": 1,
      "metadata": {},
      "outputs": [
        {
          "name": "stdout",
          "output_type": "stream",
          "text": [
            "Requirement already satisfied: pip in ./venv/lib/python3.10/site-packages (23.2.1)\n",
            "Note: you may need to restart the kernel to use updated packages.\n"
          ]
        }
      ],
      "source": [
        "%pip install --upgrade pip"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": 2,
      "metadata": {
        "colab": {
          "base_uri": "https://localhost:8080/"
        },
        "id": "yLacqQR2O_8l",
        "outputId": "a46a4c1e-a8a3-44c2-a5da-b6833ec35687"
      },
      "outputs": [
        {
          "name": "stdout",
          "output_type": "stream",
          "text": [
            "Note: you may need to restart the kernel to use updated packages.\n",
            "Note: you may need to restart the kernel to use updated packages.\n",
            "Note: you may need to restart the kernel to use updated packages.\n",
            "Note: you may need to restart the kernel to use updated packages.\n",
            "Note: you may need to restart the kernel to use updated packages.\n"
          ]
        }
      ],
      "source": [
        "%pip install numpy -q\n",
        "%pip install pandas -q\n",
        "%pip install yfinance -q\n",
        "%pip install mosek -q\n",
        "%pip install riskfolio-lib -q"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": 126,
      "metadata": {
        "colab": {
          "base_uri": "https://localhost:8080/"
        },
        "id": "AXkX5PxyPP6u",
        "outputId": "c11a8d3b-8413-48a2-cbae-ab200a405332"
      },
      "outputs": [
        {
          "name": "stdout",
          "output_type": "stream",
          "text": [
            "[*********************100%***********************]  45 of 45 completed\n"
          ]
        }
      ],
      "source": [
        "import numpy as np\n",
        "import pandas as pd\n",
        "import yfinance as yf\n",
        "import riskfolio as rp\n",
        "\n",
        "# Tickers of assets\n",
        "tickers = [\n",
        "    \"ABCB4.SA\", \"ALUP11.SA\", \"B3SA3.SA\", \"BRSR6.SA\", \"BBSE3.SA\", \"BRAP4.SA\", \"BBAS3.SA\", \"AGRO3.SA\", \"CMIG3.SA\",\n",
        "    \"CMIG4.SA\", \"CSMG3.SA\", \"CPLE6.SA\", \"CPFE3.SA\", \"CMIN3.SA\", \"CURY3.SA\", \"DIRR3.SA\", \"ENAT3.SA\", \"EGIE3.SA\",\n",
        "    \"FESA4.SA\", \"GGBR4.SA\", \"GOAU4.SA\", \"MYPK3.SA\", \"RANI3.SA\", \"ITSA4.SA\", \"JBSS3.SA\", \"JHSF3.SA\", \"KEPL3.SA\",\n",
        "    \"LAVV3.SA\", \"MRFG3.SA\", \"BEEF3.SA\", \"PETR3.SA\", \"PETR4.SA\", \"PSSA3.SA\", \"RAPT4.SA\", \"ROMI3.SA\", \"SANB11.SA\",\n",
        "    \"CSNA3.SA\", \"TAEE11.SA\", \"VIVT3.SA\", \"TRPL4.SA\", \"TRIS3.SA\", \"UNIP6.SA\", \"USIM5.SA\", \"VALE3.SA\", \"VBBR3.SA\"\n",
        "]\n",
        "\n",
        "tickers.sort()\n",
        "\n",
        "# Downloading the data\n",
        "data = yf.download(tickers, start=start, end=end)\n",
        "data = data.loc[:, ('Adj Close', slice(None))]\n",
        "data.columns = tickers\n",
        "assets = data.pct_change().dropna()\n",
        "\n",
        "Y = assets\n",
        "\n",
        "# Creating the Portfolio Object\n",
        "port = rp.Portfolio(returns=Y)\n",
        "\n",
        "# To display dataframes values in percentage format\n",
        "pd.options.display.float_format = '{:.4%}'.format\n",
        "\n",
        "# Choose the risk measure\n",
        "rm = 'MSV'  # Semi Standard Deviation\n",
        "\n",
        "# Estimate inputs of the model (historical estimates)\n",
        "# Method to estimate expected returns based on historical data.\n",
        "method_mu = 'hist'\n",
        "# Method to estimate covariance matrix based on historical data.\n",
        "method_cov = 'hist'\n",
        "\n",
        "port.assets_stats(method_mu=method_mu, method_cov=method_cov, d=0.94)\n",
        "\n",
        "# Estimate the portfolio that maximizes the risk adjusted return ratio\n",
        "w1 = port.optimization(model='Classic', rm=rm,\n",
        "                       obj='Sharpe', rf=0.0, l=0, hist=True)\n",
        "\n",
        "# Estimate points in the efficient frontier mean - semi standard deviation\n",
        "ws = port.efficient_frontier(\n",
        "    model='Classic', rm=rm, points=20, rf=0, hist=True)\n",
        "\n",
        "# Estimate the risk parity portfolio for semi standard deviation\n",
        "w2 = port.rp_optimization(model='Classic', rm=rm, rf=0, b=None, hist=True)"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": 138,
      "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>weights</th>\n",
              "    </tr>\n",
              "  </thead>\n",
              "  <tbody>\n",
              "    <tr>\n",
              "      <th>PETR3.SA</th>\n",
              "      <td>32.5183%</td>\n",
              "    </tr>\n",
              "    <tr>\n",
              "      <th>CMIG3.SA</th>\n",
              "      <td>18.4078%</td>\n",
              "    </tr>\n",
              "    <tr>\n",
              "      <th>CPLE6.SA</th>\n",
              "      <td>12.6776%</td>\n",
              "    </tr>\n",
              "    <tr>\n",
              "      <th>RANI3.SA</th>\n",
              "      <td>11.1030%</td>\n",
              "    </tr>\n",
              "    <tr>\n",
              "      <th>TAEE11.SA</th>\n",
              "      <td>10.3605%</td>\n",
              "    </tr>\n",
              "    <tr>\n",
              "      <th>FESA4.SA</th>\n",
              "      <td>9.1889%</td>\n",
              "    </tr>\n",
              "    <tr>\n",
              "      <th>UNIP6.SA</th>\n",
              "      <td>5.7439%</td>\n",
              "    </tr>\n",
              "    <tr>\n",
              "      <th>PSSA3.SA</th>\n",
              "      <td>0.0000%</td>\n",
              "    </tr>\n",
              "    <tr>\n",
              "      <th>KEPL3.SA</th>\n",
              "      <td>0.0000%</td>\n",
              "    </tr>\n",
              "    <tr>\n",
              "      <th>CURY3.SA</th>\n",
              "      <td>0.0000%</td>\n",
              "    </tr>\n",
              "    <tr>\n",
              "      <th>BBSE3.SA</th>\n",
              "      <td>0.0000%</td>\n",
              "    </tr>\n",
              "    <tr>\n",
              "      <th>BEEF3.SA</th>\n",
              "      <td>0.0000%</td>\n",
              "    </tr>\n",
              "    <tr>\n",
              "      <th>CPFE3.SA</th>\n",
              "      <td>0.0000%</td>\n",
              "    </tr>\n",
              "    <tr>\n",
              "      <th>CSMG3.SA</th>\n",
              "      <td>0.0000%</td>\n",
              "    </tr>\n",
              "    <tr>\n",
              "      <th>PETR4.SA</th>\n",
              "      <td>0.0000%</td>\n",
              "    </tr>\n",
              "    <tr>\n",
              "      <th>CMIG4.SA</th>\n",
              "      <td>0.0000%</td>\n",
              "    </tr>\n",
              "    <tr>\n",
              "      <th>GOAU4.SA</th>\n",
              "      <td>0.0000%</td>\n",
              "    </tr>\n",
              "    <tr>\n",
              "      <th>EGIE3.SA</th>\n",
              "      <td>0.0000%</td>\n",
              "    </tr>\n",
              "    <tr>\n",
              "      <th>ALUP11.SA</th>\n",
              "      <td>0.0000%</td>\n",
              "    </tr>\n",
              "    <tr>\n",
              "      <th>BBAS3.SA</th>\n",
              "      <td>0.0000%</td>\n",
              "    </tr>\n",
              "    <tr>\n",
              "      <th>AGRO3.SA</th>\n",
              "      <td>0.0000%</td>\n",
              "    </tr>\n",
              "    <tr>\n",
              "      <th>GGBR4.SA</th>\n",
              "      <td>0.0000%</td>\n",
              "    </tr>\n",
              "    <tr>\n",
              "      <th>TRPL4.SA</th>\n",
              "      <td>0.0000%</td>\n",
              "    </tr>\n",
              "    <tr>\n",
              "      <th>ABCB4.SA</th>\n",
              "      <td>0.0000%</td>\n",
              "    </tr>\n",
              "    <tr>\n",
              "      <th>VIVT3.SA</th>\n",
              "      <td>0.0000%</td>\n",
              "    </tr>\n",
              "    <tr>\n",
              "      <th>BRSR6.SA</th>\n",
              "      <td>0.0000%</td>\n",
              "    </tr>\n",
              "    <tr>\n",
              "      <th>DIRR3.SA</th>\n",
              "      <td>0.0000%</td>\n",
              "    </tr>\n",
              "    <tr>\n",
              "      <th>MYPK3.SA</th>\n",
              "      <td>0.0000%</td>\n",
              "    </tr>\n",
              "    <tr>\n",
              "      <th>ITSA4.SA</th>\n",
              "      <td>0.0000%</td>\n",
              "    </tr>\n",
              "    <tr>\n",
              "      <th>LAVV3.SA</th>\n",
              "      <td>0.0000%</td>\n",
              "    </tr>\n",
              "    <tr>\n",
              "      <th>JBSS3.SA</th>\n",
              "      <td>0.0000%</td>\n",
              "    </tr>\n",
              "    <tr>\n",
              "      <th>VALE3.SA</th>\n",
              "      <td>0.0000%</td>\n",
              "    </tr>\n",
              "    <tr>\n",
              "      <th>ENAT3.SA</th>\n",
              "      <td>0.0000%</td>\n",
              "    </tr>\n",
              "    <tr>\n",
              "      <th>MRFG3.SA</th>\n",
              "      <td>0.0000%</td>\n",
              "    </tr>\n",
              "    <tr>\n",
              "      <th>BRAP4.SA</th>\n",
              "      <td>0.0000%</td>\n",
              "    </tr>\n",
              "    <tr>\n",
              "      <th>SANB11.SA</th>\n",
              "      <td>0.0000%</td>\n",
              "    </tr>\n",
              "    <tr>\n",
              "      <th>RAPT4.SA</th>\n",
              "      <td>0.0000%</td>\n",
              "    </tr>\n",
              "    <tr>\n",
              "      <th>JHSF3.SA</th>\n",
              "      <td>0.0000%</td>\n",
              "    </tr>\n",
              "    <tr>\n",
              "      <th>B3SA3.SA</th>\n",
              "      <td>0.0000%</td>\n",
              "    </tr>\n",
              "    <tr>\n",
              "      <th>VBBR3.SA</th>\n",
              "      <td>0.0000%</td>\n",
              "    </tr>\n",
              "    <tr>\n",
              "      <th>ROMI3.SA</th>\n",
              "      <td>0.0000%</td>\n",
              "    </tr>\n",
              "    <tr>\n",
              "      <th>CMIN3.SA</th>\n",
              "      <td>0.0000%</td>\n",
              "    </tr>\n",
              "    <tr>\n",
              "      <th>TRIS3.SA</th>\n",
              "      <td>0.0000%</td>\n",
              "    </tr>\n",
              "    <tr>\n",
              "      <th>USIM5.SA</th>\n",
              "      <td>0.0000%</td>\n",
              "    </tr>\n",
              "    <tr>\n",
              "      <th>CSNA3.SA</th>\n",
              "      <td>0.0000%</td>\n",
              "    </tr>\n",
              "  </tbody>\n",
              "</table>\n",
              "</div>"
            ],
            "text/plain": [
              "           weights\n",
              "PETR3.SA  32.5183%\n",
              "CMIG3.SA  18.4078%\n",
              "CPLE6.SA  12.6776%\n",
              "RANI3.SA  11.1030%\n",
              "TAEE11.SA 10.3605%\n",
              "FESA4.SA   9.1889%\n",
              "UNIP6.SA   5.7439%\n",
              "PSSA3.SA   0.0000%\n",
              "KEPL3.SA   0.0000%\n",
              "CURY3.SA   0.0000%\n",
              "BBSE3.SA   0.0000%\n",
              "BEEF3.SA   0.0000%\n",
              "CPFE3.SA   0.0000%\n",
              "CSMG3.SA   0.0000%\n",
              "PETR4.SA   0.0000%\n",
              "CMIG4.SA   0.0000%\n",
              "GOAU4.SA   0.0000%\n",
              "EGIE3.SA   0.0000%\n",
              "ALUP11.SA  0.0000%\n",
              "BBAS3.SA   0.0000%\n",
              "AGRO3.SA   0.0000%\n",
              "GGBR4.SA   0.0000%\n",
              "TRPL4.SA   0.0000%\n",
              "ABCB4.SA   0.0000%\n",
              "VIVT3.SA   0.0000%\n",
              "BRSR6.SA   0.0000%\n",
              "DIRR3.SA   0.0000%\n",
              "MYPK3.SA   0.0000%\n",
              "ITSA4.SA   0.0000%\n",
              "LAVV3.SA   0.0000%\n",
              "JBSS3.SA   0.0000%\n",
              "VALE3.SA   0.0000%\n",
              "ENAT3.SA   0.0000%\n",
              "MRFG3.SA   0.0000%\n",
              "BRAP4.SA   0.0000%\n",
              "SANB11.SA  0.0000%\n",
              "RAPT4.SA   0.0000%\n",
              "JHSF3.SA   0.0000%\n",
              "B3SA3.SA   0.0000%\n",
              "VBBR3.SA   0.0000%\n",
              "ROMI3.SA   0.0000%\n",
              "CMIN3.SA   0.0000%\n",
              "TRIS3.SA   0.0000%\n",
              "USIM5.SA   0.0000%\n",
              "CSNA3.SA   0.0000%"
            ]
          },
          "execution_count": 138,
          "metadata": {},
          "output_type": "execute_result"
        }
      ],
      "source": [
        "w1.sort_values(\"weights\", ascending=False)"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "W1L6k2-QQS78"
      },
      "source": [
        "### Plot series"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": 128,
      "metadata": {
        "colab": {
          "base_uri": "https://localhost:8080/",
          "height": 607
        },
        "id": "fswmfBhTP3C_",
        "outputId": "256f0490-c901-4749-d554-107986845a7b"
      },
      "outputs": [
        {
          "data": {
            "image/png": "[encoded data, 293084 characters]",
            "text/plain": [
              "<Figure size 1000x600 with 1 Axes>"
            ]
          },
          "metadata": {},
          "output_type": "display_data"
        }
      ],
      "source": [
        "ax = rp.plot_series(returns=Y,\n",
        "                    w=ws,\n",
        "                    cmap='tab20',\n",
        "                    height=6,\n",
        "                    width=10,\n",
        "                    ax=None)"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "8GfCgRdeRG5v"
      },
      "source": [
        "### Gráfico de fronteira eficiente a partir de medida de risco especificado pelo usuário"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": 129,
      "metadata": {
        "colab": {
          "base_uri": "https://localhost:8080/",
          "height": 607
        },
        "id": "PndiInJDQUmf",
        "outputId": "ba39ae37-fb27-48c1-e25a-e5890047542f"
      },
      "outputs": [
        {
          "data": {
            "image/png": "[encoded data, 98868 characters]",
            "text/plain": [
              "<Figure size 1000x600 with 2 Axes>"
            ]
          },
          "metadata": {},
          "output_type": "display_data"
        }
      ],
      "source": [
        "label = 'Max Risk Adjusted Return Portfolio'\n",
        "mu = port.mu\n",
        "cov = port.cov\n",
        "returns = port.returns\n",
        "\n",
        "ax = rp.plot_frontier(w_frontier=ws,\n",
        "                      mu=mu,\n",
        "                      cov=cov,\n",
        "                      returns=returns,\n",
        "                      rm=rm,\n",
        "                      rf=0,\n",
        "                      alpha=0.05,\n",
        "                      cmap='viridis',\n",
        "                      w=w1,\n",
        "                      label=label,\n",
        "                      marker='*',\n",
        "                      s=16,\n",
        "                      c='r',\n",
        "                      height=6,\n",
        "                      width=10,\n",
        "                      t_factor=252,\n",
        "                      ax=None)"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "hmh1aWuORcpo"
      },
      "source": [
        "### Gráfico de pesos por ativo"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": 130,
      "metadata": {
        "colab": {
          "base_uri": "https://localhost:8080/",
          "height": 607
        },
        "id": "2XgCJ2eORMgb",
        "outputId": "67b0b013-2a2a-44a8-971d-f0d170af513e"
      },
      "outputs": [
        {
          "data": {
            "image/png": "[encoded data, 99612 characters]",
            "text/plain": [
              "<Figure size 1000x600 with 1 Axes>"
            ]
          },
          "metadata": {},
          "output_type": "display_data"
        }
      ],
      "source": [
        "ax = rp.plot_pie(w=w1,\n",
        "                 title='Portfolio',\n",
        "                 height=6,\n",
        "                 width=10,\n",
        "                 cmap=\"tab20\",\n",
        "                 ax=None)"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "82BPUuTnSPvE"
      },
      "source": [
        "### Gráfico de fronteira eficiente"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": 131,
      "metadata": {
        "colab": {
          "base_uri": "https://localhost:8080/",
          "height": 607
        },
        "id": "_Wo-Zo2lSN-Y",
        "outputId": "9be452e7-f3b6-4866-8d45-ca29955335da"
      },
      "outputs": [
        {
          "data": {
            "image/png": "[encoded data, 219412 characters]",
            "text/plain": [
              "<Figure size 1000x600 with 1 Axes>"
            ]
          },
          "metadata": {},
          "output_type": "display_data"
        }
      ],
      "source": [
        "ax = rp.plot_frontier_area(w_frontier=ws,\n",
        "                           cmap=\"tab20\",\n",
        "                           height=6,\n",
        "                           width=10,\n",
        "                           ax=None)"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "_DZcrCF-S6te"
      },
      "source": [
        "### Contribuição de risco por ativo"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": 132,
      "metadata": {
        "colab": {
          "base_uri": "https://localhost:8080/",
          "height": 607
        },
        "id": "_Ke_zpDhSUGI",
        "outputId": "2b25e639-b42c-49e9-fdcb-6339bf0aa5a6"
      },
      "outputs": [
        {
          "data": {
            "image/png": "[encoded data, 117036 characters]",
            "text/plain": [
              "<Figure size 1000x600 with 1 Axes>"
            ]
          },
          "metadata": {},
          "output_type": "display_data"
        }
      ],
      "source": [
        "ax = rp.plot_risk_con(w=w2,\n",
        "                      cov=cov,\n",
        "                      returns=returns,\n",
        "                      rm=rm,\n",
        "                      rf=0,\n",
        "                      alpha=0.05,\n",
        "                      color=\"tab:blue\",\n",
        "                      height=6,\n",
        "                      width=10,\n",
        "                      t_factor=252,\n",
        "                      ax=None)"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {},
      "outputs": [],
      "source": []
    }
  ],
  "metadata": {
    "colab": {
      "authorship_tag": "ABX9TyPHs9KgmNJona/3h+651ykJ",
      "provenance": []
    },
    "kernelspec": {
      "display_name": "Python 3",
      "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.10.11"
    }
  },
  "nbformat": 4,
  "nbformat_minor": 0
}
