{
 "cells": [
  {
   "cell_type": "code",
   "execution_count": 60,
   "metadata": {},
   "outputs": [],
   "source": [
    "import json\n",
    "import requests\n",
    "import pandas as pd\n",
    "import portfolio_optimizer as po"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 61,
   "metadata": {},
   "outputs": [],
   "source": [
    "resp = requests.get(\"http://localhost:1323/available_etfs_as_filename\")\n",
    "eft_filenames = resp.json()\n",
    "resp = requests.get(\"http://localhost:1323/available_etfs\")\n",
    "eft_data = resp.json()"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 62,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "(['CBUSE{}MI{}LU1048317025{}italy{}UBS Barclays US Liquid Corporates UCITS hedged to EUR A-acc{}2014-06-20{}2023-01-05.json',\n",
       "  'CCEUAS{}MI{}IE00B58HMN42{}italy{}UBS (Irl) Fund Solutions plc – CMCI Composite SF UCITS ETF (hedged to EUR) A-acc{}2013-05-28{}2023-01-05.json'],\n",
       " [{'ticker': 'CBUSE',\n",
       "   'exchange': 'MI',\n",
       "   'isin': 'LU1048317025',\n",
       "   'country': 'italy',\n",
       "   'name': 'UBS Barclays US Liquid Corporates UCITS hedged to EUR A-acc',\n",
       "   'data_from': '2014-06-20',\n",
       "   'data_to': '2023-01-05'},\n",
       "  {'ticker': 'CCEUAS',\n",
       "   'exchange': 'MI',\n",
       "   'isin': 'IE00B58HMN42',\n",
       "   'country': 'italy',\n",
       "   'name': 'UBS (Irl) Fund Solutions plc – CMCI Composite SF UCITS ETF (hedged to EUR) A-acc',\n",
       "   'data_from': '2013-05-28',\n",
       "   'data_to': '2023-01-05'}])"
      ]
     },
     "execution_count": 62,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "eft_filenames[:2], eft_data[:2]"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 63,
   "metadata": {},
   "outputs": [],
   "source": [
    "def build_dataframe(eft_filenames, eft_datas, directory = \"downloaded_etf\" ):\n",
    "    dfs = [\n",
    "        (\n",
    "            f\"{data['ticker']}.{data['exchange']}.{data['isin']}\",\n",
    "            po.file_to_dataframe(f\"{directory}/{filename}\")\n",
    "        )\n",
    "        for data, filename\n",
    "        in zip(eft_datas, eft_filenames)\n",
    "    ]\n",
    "\n",
    "    for df in dfs:\n",
    "        df[1].rename(columns={\"adjusted_close\": df[0]}, inplace=True)\n",
    "\n",
    "\n",
    "    return pd.concat([\n",
    "        df[1]\n",
    "        for df in dfs\n",
    "    ], axis=1)\n",
    "\n",
    "\n",
    "data = build_dataframe(eft_filenames, eft_data)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 64,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "(0.09205940587725953, 0.01834119843040924)"
      ]
     },
     "execution_count": 64,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "# supperss warnings\n",
    "import warnings\n",
    "warnings.filterwarnings('ignore')\n",
    "optimizer = po.PortfolioOptimizer(\n",
    "    data, False\n",
    ")\n",
    "\n",
    "maxdata = optimizer.maximum_return()[1]['risk']\n",
    "mindata = optimizer.minimum_risk()[1]['risk']\n",
    "\n",
    "maxdata, mindata"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 65,
   "metadata": {},
   "outputs": [],
   "source": [
    "def convert_porfolio_distribution_to_dict_list(portfolio):\n",
    "    return [\n",
    "        {\n",
    "            \"n\": name,\n",
    "            \"p\": round(perc * 100,2)\n",
    "        }\n",
    "        for name, perc in portfolio.items()\n",
    "    ]\n",
    "\n",
    "\n",
    "    \n",
    "def stratify_portfolio(portfolio: po.PortfolioOptimizer, maxdata, mindata, n=10):\n",
    "    step = (maxdata - mindata) / n\n",
    "    return [\n",
    "        convert_porfolio_distribution_to_dict_list(\n",
    "            portfolio.efficient_risk(risk)[0]\n",
    "        )\n",
    "        for risk\n",
    "        in [mindata + step * i for i in range(n)]\n",
    "    ]\n",
    "\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 66,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "[{'n': 'CBUSE.MI.LU1048317025', 'p': 1.0},\n",
       " {'n': 'CCEUAS.MI.IE00B58HMN42', 'p': 1.0},\n",
       " {'n': 'EIMI.MI.IE00BKM4GZ66', 'p': 1.0},\n",
       " {'n': 'EM13.MI.LU1650487413', 'p': 36.81},\n",
       " {'n': 'EMBE.MI.IE00B9M6RS56', 'p': 1.0},\n",
       " {'n': 'EMH5.MI.IE00BP46NG52', 'p': 5.06},\n",
       " {'n': 'GGOV.PA.LU1437016204', 'p': 1.0},\n",
       " {'n': 'IBC5.XETRA.IE00BDZVH966', 'p': 1.0},\n",
       " {'n': 'IHYE.MI.IE00BF3N7102', 'p': 1.0},\n",
       " {'n': 'IWVL.MI.IE00BP3QZB59', 'p': 1.0},\n",
       " {'n': 'LCWD.MI.LU1781541179', 'p': 1.0},\n",
       " {'n': 'SGLD.MI.IE00B579F325', 'p': 21.11},\n",
       " {'n': 'SWDA.MI.IE00B4L5Y983', 'p': 16.2},\n",
       " {'n': 'U10H.MI.LU1407890976', 'p': 1.0},\n",
       " {'n': 'XBLC.MI.LU0478205379', 'p': 1.0},\n",
       " {'n': 'XEIN.MI.LU0290358224', 'p': 9.81}]"
      ]
     },
     "execution_count": 66,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "stratified = stratify_portfolio(optimizer, maxdata, mindata,7)\n",
    "s = stratified[3]\n",
    "s"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 67,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "[{'n': 'CBUSE.MI.LU1048317025', 'p': 1.0, 'shares': 4.6, 'euros': 73.2},\n",
       " {'n': 'CCEUAS.MI.IE00B58HMN42', 'p': 1.0, 'shares': 1.0, 'euros': 73.2},\n",
       " {'n': 'EIMI.MI.IE00BKM4GZ66', 'p': 1.0, 'shares': 2.6, 'euros': 73.2},\n",
       " {'n': 'EM13.MI.LU1650487413', 'p': 36.81, 'shares': 22.9, 'euros': 2694.49},\n",
       " {'n': 'EMBE.MI.IE00B9M6RS56', 'p': 1.0, 'shares': 1.1, 'euros': 73.2},\n",
       " {'n': 'EMH5.MI.IE00BP46NG52', 'p': 5.06, 'shares': 14.8, 'euros': 370.39},\n",
       " {'n': 'GGOV.PA.LU1437016204', 'p': 1.0, 'shares': 1.6, 'euros': 73.2},\n",
       " {'n': 'IBC5.XETRA.IE00BDZVH966', 'p': 1.0, 'shares': 14.4, 'euros': 73.2},\n",
       " {'n': 'IHYE.MI.IE00BF3N7102', 'p': 1.0, 'shares': 18.4, 'euros': 73.2},\n",
       " {'n': 'IWVL.MI.IE00BP3QZB59', 'p': 1.0, 'shares': 2.2, 'euros': 73.2},\n",
       " {'n': 'LCWD.MI.LU1781541179', 'p': 1.0, 'shares': 5.8, 'euros': 73.2},\n",
       " {'n': 'SGLD.MI.IE00B579F325', 'p': 21.11, 'shares': 9.2, 'euros': 1545.25},\n",
       " {'n': 'SWDA.MI.IE00B4L5Y983', 'p': 16.2, 'shares': 17.1, 'euros': 1185.84},\n",
       " {'n': 'U10H.MI.LU1407890976', 'p': 1.0, 'shares': 1.0, 'euros': 73.2},\n",
       " {'n': 'XBLC.MI.LU0478205379', 'p': 1.0, 'shares': 0.5, 'euros': 73.2},\n",
       " {'n': 'XEIN.MI.LU0290358224', 'p': 9.81, 'shares': 3.2, 'euros': 718.09}]"
      ]
     },
     "execution_count": 67,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "tot_soldi = 7320\n",
    "\n",
    "# € * % / prezzo\n",
    "last_prices = {\n",
    "    ticker: data[ticker].iloc[-1]\n",
    "    for ticker in data.columns\n",
    "}\n",
    "\n",
    "\n",
    "\n",
    "for t in s:\n",
    "    t['shares'] = round(tot_soldi * t['p'] / 100 / last_prices[t['n']], 1)\n",
    "    t['euros'] = round(tot_soldi * t['p'] / 100, 2)\n",
    "\n",
    "s\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": []
  }
 ],
 "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.10.6 (main, Nov 14 2022, 16:10:14) [GCC 11.3.0]"
  },
  "orig_nbformat": 4,
  "vscode": {
   "interpreter": {
    "hash": "916dbcbb3f70747c44a77c7bcd40155683ae19c65e1c03b4aa3499c5328201f1"
   }
  }
 },
 "nbformat": 4,
 "nbformat_minor": 2
}
