<commit_before>{
 "cells": [
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## MiFID II classification of trades using the RTS 2 Annex 3 taxonomy.\n",
    "\n",
    "Governments would prefer to avoid another financial crisis like the one in 2008 and beleive that making the big players operate in a more open and transparent way will help avoid another crash.\n",
    "\n",
    "Markets in Financial Instruments Directive II (MiFID II) is an EU law which has market transparency as its key objective.  The predecessor law, MiFID I, only looked at a part of what banking firms do.  MiFID II aims to cover most mainstream activity.\n",
    "\n",
    "Governments rely on regulators to make sure that their laws are being followed.  For MiFID II the primary regulator is ESMA.  ESMA have produced a number of Regulatory Technical Standard (RTS) documents which aim to explain what banking firms must do to comply with the MiFID II law.\n",
    "\n",
    "One of the RTS documents, RTS 2, explains how different kinds of trading activity can be identified.  Having a clear way to say what has been traded is an important part of making the markets more transparent.\n",
    "\n",
    "Some kinds of trading activity is already pretty transparent, for example buying and selling shares in a public company.  Trades of this kind are mostly done using a public exchange, such as the New York or London stock exchanges.  The 'price' for a given stock is simply the amount of money paid in the most recent trade and this price is made public by the exchange so everyone can see what the latest price is.  It is pretty easy to identify what has been traded because each stock has a identifier, e.g. 'AAPL' identifies Apple Inc. shares.\n",
    "\n",
    "Not all trades happen on public exchanges.  Many trades happen directly between two parties and these are known as over the counter (OTC) trades.  Each OTC trade can be fine tuned, for example setting payment dates and interest rates.  The fine tuning of OTC deals makes it hard to identify what has been traded, but this is where RTS 2 comes in. \n",
    "\n",
    "The easyest way to understand what RTS 2 is all about is to use it to classify some trades, and you can do just that below.\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 191,
   "metadata": {
    "collapsed": false
   },
   "outputs": [],
   "source": [
    "#import sys\n",
    "#sys.path.append('/home/bbadger/bag/data/dev/mifid2-rts/mifid2-rts/rts')\n",
    "import rts2_annex3\n",
    "import datetime"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 192,
   "metadata": {
    "collapsed": false
   },
   "outputs": [],
   "source": [
    "class SampleTrade(object):\n",
    "    pass\n",
    "\n",
    "sample_trade = SampleTrade()\n",
    "sample_trade.asset_class_name = 'Foreign Exchange Derivatives'\n",
    "sample_trade.sub_asset_class_name= 'Deliverable FX options (DO)'\n",
    "sample_trade.underlying_currency_pair = ('GBP', 'USD')\n",
    "sample_trade.from_date = datetime.date(2017, 8, 13)\n",
    "sample_trade.to_date = datetime.date(2017, 10, 12)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 193,
   "metadata": {
    "collapsed": true
   },
   "outputs": [],
   "source": [
    "sample_classification = rts2_annex3.class_root.classification_for(sample_trade)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 194,
   "metadata": {
    "collapsed": false
   },
   "outputs": [
    {
     "data": {
      "text/plain": [
       "{'Asset class': 'Foreign Exchange Derivatives',\n",
       " 'RTS2 version': 'Brussels, 14.7.2016 C(2016) 4301 final ANNEXES 1 to 4',\n",
       " 'Segmentation criterion 1': \"('GBP', 'USD')\",\n",
       " 'Segmentation criterion 1 description': 'underlying currency pair defined as combination of the two currencies underlying the derivative contract',\n",
       " 'Segmentation criterion 2': 'Maturity bucket 2: 1 week to 3 months',\n",
       " 'Segmentation criterion 2 description': 'time to maturity bucket of the swap defined as follows:',\n",
       " 'Sub-asset class': 'Deliverable FX options (DO)'}"
      ]
     },
     "execution_count": 194,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "sample_classification.classification_dict()"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 195,
   "metadata": {
    "collapsed": true
   },
   "outputs": [],
   "source": [
    "import ipywidgets as widgets"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 196,
   "metadata": {
    "collapsed": false
   },
   "outputs": [],
   "source": [
    "asset_classes = rts2_annex3.class_root.asset_classes\n",
    "asset_class_names = [an_asset_class.name for an_asset_class in asset_classes]\n",
    "asset_class_dict = dict([\n",
    "        (an_asset_class.name, an_asset_class) \n",
    "        for an_asset_class \n",
    "        in asset_classes])"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 197,
   "metadata": {
    "collapsed": false
   },
   "outputs": [],
   "source": [
    "asset_class_widget = widgets.Dropdown(\n",
    "    options=asset_class_dict,\n",
    "    # value=asset_class_dict[asset_class_names[0]],\n",
    "    description='Asset Classes:',\n",
    "    disabled=False,\n",
    ")\n",
    "asset_class_widget"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 198,
   "metadata": {
    "collapsed": false
   },
   "outputs": [],
   "source": [
    "#selected_asset_class = rts2_annex3.class_root.asset_class_by_name(asset_class_widget.value)\n",
    "selected_asset_class = asset_class_widget.value\n",
    "sub_asset_class_names = [\n",
    "    sub_asset_class.name \n",
    "    for sub_asset_class \n",
    "    in selected_asset_class.sub_asset_classes]\n",
    "sub_asset_class_dict = dict([\n",
    "    (sub_asset_class.name, sub_asset_class) \n",
    "    for sub_asset_class \n",
    "    in selected_asset_class.sub_asset_classes])"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 199,
   "metadata": {
    "collapsed": false
   },
   "outputs": [],
   "source": [
    "sub_asset_class_widget = widgets.Dropdown(\n",
    "    options=sub_asset_class_dict,\n",
    "    # value=sub_asset_class_names[0],\n",
    "    description='Sub-asset Classes:',\n",
    "    disabled=False,\n",
    ")\n",
    "sub_asset_class_widget"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 200,
   "metadata": {
    "collapsed": false
   },
   "outputs": [],
   "source": [
    "criteria_vbox = widgets.VBox([])"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 201,
   "metadata": {
    "collapsed": true
   },
   "outputs": [],
   "source": [
    "from IPython.display import display"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 202,
   "metadata": {
    "collapsed": false
   },
   "outputs": [],
   "source": [
    "def criteria_widgets(sub_asset_class):\n",
    "    # OK, in here I need to look up the criteria for the\n",
    "    # sub-asset class and build the widgets in rows of HBox es\n",
    "    return [\n",
    "        widgets.Label(sub_asset_class.name + \" L1\"),\n",
    "        widgets.Label(sub_asset_class.name + \" L2\")\n",
    "    ]\n",
    "    \n",
    "def asset_class_changed(change):\n",
    "    if change['type'] == 'change' and change['name'] == 'value':\n",
    "        selected_asset_class = change['new']\n",
    "        sub_asset_class_names = [sub_asset_class.name for sub_asset_class in selected_asset_class.sub_asset_classes]\n",
    "        sub_asset_class_dict = dict([\n",
    "            (sub_asset_class.name, sub_asset_class) \n",
    "            for sub_asset_class \n",
    "            in selected_asset_class.sub_asset_classes])\n",
    "        sub_asset_class_widget.options = sub_asset_class_dict\n",
    "        \n",
    "def sub_asset_class_changed(change):\n",
    "    if change['type'] == 'change' and change['name'] == 'value':\n",
    "        selected_sub_asset_class = change['new']\n",
    "        criteria_vbox.children = criteria_widgets(selected_sub_asset_class)\n",
    "\n",
    "asset_class_widget.observe(asset_class_changed)\n",
    "sub_asset_class_widget.observe(sub_asset_class_changed)\n",
    "display(asset_class_widget)\n",
    "display(sub_asset_class_widget)\n",
    "criteria_vbox.children = criteria_widgets(sub_asset_class_widget.value)\n",
    "display(criteria_vbox)\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 203,
   "metadata": {
    "collapsed": false
   },
   "outputs": [],
   "source": [
    "# help(widgets.VBox)\n",
    "# help(widgets.Label)\n",
    "l_1 = widgets.Label(\"L1\")\n",
    "vbox_1 = widgets.VBox([widgets.Label(\"xx\"), l_1])\n",
    "display(vbox_1)\n",
    "l_2 = widgets.Label(\"L2\")\n",
    "vbox_1.children = ([widgets.Label(\"yy\"), l_2])\n",
    "display(vbox_1)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 204,
   "metadata": {
    "collapsed": false
   },
   "outputs": [
    {
     "data": {
      "text/plain": [
       "'C10 derivatives'"
      ]
     },
     "execution_count": 204,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "sub_asset_class_widget.value.parent.name"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 205,
   "metadata": {
    "collapsed": false
   },
   "outputs": [
    {
     "data": {
      "text/plain": [
       "1"
      ]
     },
     "metadata": {},
     "output_type": "display_data"
    }
   ],
   "source": [
    "from ipywidgets import interact\n",
    "@interact(x=dict(a=1,b=2,c=3))\n",
    "def xx(x):\n",
    "    return x"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 206,
   "metadata": {
    "collapsed": false
   },
   "outputs": [],
   "source": [
    "from IPython.display import display\n",
    "button = widgets.Button(description=\"Click Me!\")\n",
    "display(button)\n",
    "\n",
    "def on_button_clicked(b):\n",
    "    print(\"Button clicked.\")\n",
    "\n",
    "button.on_click(on_button_clicked)"
   ]
  }
 ],
 "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.5.3"
  },
  "widgets": {
   "state": {
    "01b8b86bbea744f7a29f252141efbba1": {
     "views": [
      {
       "cell_index": 12
      }
     ]
    },
    "058478d9f1404574b561808860fcef95": {
     "views": [
      {
       "cell_index": 9
      },
      {
       "cell_index": 12
      }
     ]
    },
    "09d3cbce75ab4863aebfaf4177cf662d": {
     "views": [
      {
       "cell_index": 13
      }
     ]
    },
    "102f1426a0c749638caaedf3d07abb54": {
     "views": [
      {
       "cell_index": 13
      }
     ]
    },
    "130e9042771f4f688a8aeb89ef10046b": {
     "views": [
      {
       "cell_index": 15
      }
     ]
    },
    "322b090c052142d2aef61b3eadf80fc5": {
     "views": [
      {
       "cell_index": 11
      }
     ]
    },
    "3e6b0f69c25b445d80b995b019e2673d": {
     "views": [
      {
       "cell_index": 11
      },
      {
       "cell_index": 11
      }
     ]
    },
    "67d80b9785d64516b85d417583f46fe0": {
     "views": [
      {
       "cell_index": 12
      }
     ]
    },
    "6ed3ef3611594db19e871e736800bd50": {
     "views": [
      {
       "cell_index": 11
      },
      {
       "cell_index": 12
      },
      {
       "cell_index": 12
      },
      {
       "cell_index": 12
      },
      {
       "cell_index": 12
      }
     ]
    },
    "74ba98a0876249b5aa28b625ca475b1c": {
     "views": [
      {
       "cell_index": 11
      },
      {
       "cell_index": 11
      }
     ]
    },
    "768d9ac85fba42b5acd4e8369c25543e": {
     "views": [
      {
       "cell_index": 11
      }
     ]
    },
    "7b0c5a5910e64b84be0eb30c7868c873": {
     "views": [
      {
       "cell_index": 11
      }
     ]
    },
    "8f0be33a3d7547f4901e92d36966055e": {
     "views": [
      {
       "cell_index": 12
      }
     ]
    },
    "ae5ab0b3138d487b8701ce7729c72608": {
     "views": [
      {
       "cell_index": 11
      }
     ]
    },
    "bae985c696534f109ded7b5321db6778": {
     "views": [
      {
       "cell_index": 7
      },
      {
       "cell_index": 12
      }
     ]
    },
    "bb914744f9c94a7783e2d90587c308f9": {
     "views": [
      {
       "cell_index": 12
      }
     ]
    },
    "c67bba9db54043309dd06a19348048a9": {
     "views": [
      {
       "cell_index": 13
      }
     ]
    },
    "c6c682a6437e47a796a53493af64c56d": {
     "views": [
      {
       "cell_index": 12
      }
     ]
    },
    "cbb6d574bcfb43abaa3c4f8af076c5c4": {
     "views": [
      {
       "cell_index": 13
      }
     ]
    },
    "dac4a9c76cc7488f80ec645a8de6dc8f": {
     "views": [
      {
       "cell_index": 12
      }
     ]
    },
    "e4cec7311af84354a24a04d085d54ac0": {
     "views": [
      {
       "cell_index": 16
      }
     ]
    },
    "e7b6d217912a41ebbc7d9e0bf09a61e1": {
     "views": [
      {
       "cell_index": 11
      },
      {
       "cell_index": 11
      }
     ]
    },
    "f6625cb5ae2242abb928d1a72aa2d614": {
     "views": [
      {
       "cell_index": 13
      },
      {
       "cell_index": 13
      }
     ]
    }
   },
   "version": "1.2.0"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 2<commit_msg>Slowly extending the Jupyter example.<commit_after>{
 "cells": [
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Read me\n",
    "\n",
    "This page is a Jupyter notebook.  It is a combination of a document and some live software which you can execute if you are running your own jupyter-notebook server.  If you are not running a Jupyter server you can still read the document and see the code examples - you just can't run them.\n",
    "\n",
    "\n",
    "## MiFID II classification of trades using the RTS 2 Annex 3 taxonomy.\n",
    "\n",
    "Governments would prefer to avoid another financial crisis like the one in 2008 and beleive that making the big players operate in a more open and transparent way will help avoid another crash.\n",
    "\n",
    "Markets in Financial Instruments Directive II (MiFID II) is an EU law which has market transparency as its key objective.  The predecessor law, MiFID I, only looked at a part of what banking firms do.  MiFID II aims to cover most mainstream activity.\n",
    "\n",
    "Governments rely on regulators to make sure that their laws are being followed.  For MiFID II the primary regulator is ESMA.  ESMA have produced a number of Regulatory Technical Standard (RTS) documents which aim to explain what banking firms must do to comply with the MiFID II law.\n",
    "\n",
    "One of the RTS documents, RTS 2, explains how different kinds of trading activity can be identified.  Having a clear way to say what has been traded is an important part of making the markets more transparent.\n",
    "\n",
    "Some kinds of trading activity is already pretty transparent, for example buying and selling shares in a public company.  Trades of this kind are mostly done using a public exchange, such as the New York or London stock exchanges.  The 'price' for a given stock is simply the amount of money paid in the most recent trade and this price is made public by the exchange so everyone can see what the latest price is.  It is pretty easy to identify what has been traded because each stock has a identifier, e.g. 'AAPL' identifies Apple Inc. shares.\n",
    "\n",
    "Not all trades happen on public exchanges.  Many trades happen directly between two parties and these are known as over the counter (OTC) trades.  Each OTC trade can be fine tuned, for example setting payment dates and interest rates.  The fine tuning of OTC deals makes it hard to identify what has been traded, but this is where RTS 2 comes in. \n",
    "\n",
    "The easyest way to understand what RTS 2 is all about is to use it to classify some trades, and you can do just that below.\n",
    "\n",
    "### A Python Implementaion of RTS 2 Annex 3\n",
    "\n",
    "It would be nice if ESMA published a working software implememtation of the RTS rules along with some test data so people can see exactly how the rules are supposed to work, and how reports are supposed to look.  But ESMA don't do that.  Each participant must somehow get an implementation of the RTS rules, either by writing it themselves or buying an implementation.\n",
    "\n",
    "One market participant implemented the RTS rules themselves and have now released part of that implementaion under an open source license, the BSD license, so anyone can see the implementaion and use it.  This document forms a part of that release.\n",
    "\n",
    "Hopefully this software will encourage ESMA to produce reference implementaions of their rules in future.  They could even take this software as a starting point.\n",
    "\n",
    "The software here is written in the Python programming language.  This was done because Python is ubiquitous, that is it can be used easily and immediately on most modern computers; everything from a Raspberry Pi to the largest of big data clusters.\n",
    "\n",
    "### Running a really simple initial classification\n",
    "\n",
    "The box below contains python code which runs the classification sofware.  If you are just viewing this page then you won't be able to run the code, but if you start the page using your own local Jupyter notebook server then the code will really run if you select the box below and press control+enter\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 1,
   "metadata": {
    "collapsed": false
   },
   "outputs": [
    {
     "data": {
      "text/plain": [
       "{'Asset class': 'Foreign Exchange Derivatives',\n",
       " 'RTS2 version': 'Brussels, 14.7.2016 C(2016) 4301 final ANNEXES 1 to 4',\n",
       " 'Segmentation criterion 1': \"('GBP', 'USD')\",\n",
       " 'Segmentation criterion 1 description': 'underlying currency pair defined as combination of the two currencies underlying the derivative contract',\n",
       " 'Segmentation criterion 2': 'Maturity bucket 2: 1 week to 3 months',\n",
       " 'Segmentation criterion 2 description': 'time to maturity bucket of the swap defined as follows:',\n",
       " 'Sub-asset class': 'Deliverable FX options (DO)'}"
      ]
     },
     "execution_count": 1,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "# Import the RTS 2 module and the Python date & time tools module\n",
    "import rts2_annex3\n",
    "import datetime\n",
    "\n",
    "# Create a simple Python object to represent a trade.\n",
    "class SampleTrade(object):\n",
    "    pass\n",
    "sample_trade = SampleTrade()\n",
    "sample_trade.asset_class_name = 'Foreign Exchange Derivatives'\n",
    "sample_trade.sub_asset_class_name= 'Deliverable FX options (DO)'\n",
    "sample_trade.underlying_currency_pair = ('GBP', 'USD')\n",
    "sample_trade.from_date = datetime.date(2017, 8, 13)\n",
    "sample_trade.to_date = datetime.date(2017, 10, 12)\n",
    "\n",
    "# Now classify the trade\n",
    "sample_classification = rts2_annex3.class_root.classification_for(sample_trade)\n",
    "\n",
    "# Lastly, display the classificaton\n",
    "sample_classification.classification_dict()"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### Understanding a classification\n",
    "\n",
    "If you were able to run code above you would have seen something like this displayed, though the order of the results might not be the same:\n",
    "\n",
    "```python\n",
    "{\n",
    " 'RTS2 version': 'Brussels, 14.7.2016 C(2016) 4301 final ANNEXES 1 to 4',\n",
    "\n",
    " 'Asset class': 'Foreign Exchange Derivatives',\n",
    "\n",
    "'Sub-asset class': 'Deliverable FX options (DO)', \n",
    "\n",
    "'Segmentation criterion 1 description': 'underlying currency pair defined as combination of the two currencies underlying the derivative contract',\n",
    " 'Segmentation criterion 1': \"('GBP', 'USD')\",\n",
    "\n",
    "'Segmentation criterion 2 description': 'time to maturity bucket of the swap defined as follows:',\n",
    " 'Segmentation criterion 2': 'Maturity bucket 2: 1 week to 3 months', \n",
    "}\n",
    "```\n",
    "\n",
    "To a large degree, the classification is simply repeating the information we gave our trade object in the code above, but information has been checked and other information added.\n",
    "\n",
    "This implementation first confirms the identity of the RTS document the classification is based upon.  The RTS rules may change over time, so it is important to know which version of the RTS a particular classification is based upon.\n",
    "\n",
    "Next we see the Asset class and Sub-asset class, which is repeating just what we said above.  When classifying a trade there are some things you just have to know.  There will be some help on how to choose Asset classes and Sun-asset classes below.\n",
    "\n",
    "Then we see something we didn't include in our trade object.  The RTS 2 Annex 3 document defines a number of criteria for each kind of Sub-asset class.  The Sub-asset class in this case has two criteria, and the classification included the description, the exact text, from the RTS document to explain what the crieria mean.\n",
    "\n",
    "The values for the criteria do come from the values on our object, but some involve calculation.  The currencly pair criterion, criterion 1, is simply the name of underlying_currency_pair value we provided.  Criterion 2 gets its value from date calculations which use the from and to dates we gave, the resulting value is a date bucket, bucket 2 in this case.\n",
    "\n",
    "### RTS 2 Annex 3 defines a taxonomy.  A Tree.\n",
    "\n",
    "To understand how the classification process works we need to look at what the RTS says.\n",
    "\n",
    "The RTS 2 Annex 3 taxonomy is made up of Asset classes which get broken down into Sub-asset classes which are further broken down by combinations of criteria values.\n",
    "\n",
    "Here is some code to list the names of the asset classes:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 2,
   "metadata": {
    "collapsed": false
   },
   "outputs": [
    {
     "data": {
      "text/plain": [
       "['Bonds (all bond types except ETCs and ETNs)',\n",
       " 'Structured Finance Products (SFPs)',\n",
       " 'Securitised Derivatives',\n",
       " 'Interest Rate Derivatives',\n",
       " 'Equity Derivatives',\n",
       " 'Commodity Derivatives',\n",
       " 'Foreign Exchange Derivatives',\n",
       " 'Credit Derivatives',\n",
       " 'C10 derivatives',\n",
       " 'Financial contracts for differences (CFDs)',\n",
       " 'Emission allowances',\n",
       " 'Emission allowance derivatives']"
      ]
     },
     "execution_count": 2,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "# The root of the taxonomy is rts2_annex3.class_root.  This code asks the\n",
    "# root for the asset classes, and for each asset class gets the name.\n",
    "[asset_class.name for asset_class in rts2_annex3.class_root.asset_classes]"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Again, just in case you can't run the code here is what the list of Asset class names looks like:\n",
    "\n",
    "```python\n",
    "['Bonds (all bond types except ETCs and ETNs)',\n",
    " 'Structured Finance Products (SFPs)',\n",
    " 'Securitised Derivatives',\n",
    " 'Interest Rate Derivatives',\n",
    " 'Equity Derivatives',\n",
    " 'Commodity Derivatives',\n",
    " 'Foreign Exchange Derivatives',\n",
    " 'Credit Derivatives',\n",
    " 'C10 derivatives',\n",
    " 'Financial contracts for differences (CFDs)',\n",
    " 'Emission allowances',\n",
    " 'Emission allowance derivatives']\n",
    "```\n",
    "There are exactly the names of the Asset classes you'll see in the RTS document.\n",
    "\n",
    "Each asset class is broken down into Sub-asset classes.  Here is some code to list the Sub-asset classes for one of the Asset classes named above:\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 3,
   "metadata": {
    "collapsed": false
   },
   "outputs": [
    {
     "data": {
      "text/plain": [
       "['Non-deliverable forward (NDF)',\n",
       " 'Deliverable forward (DF)',\n",
       " 'Non-Deliverable FX options (NDO)',\n",
       " 'Deliverable FX options (DO)',\n",
       " 'Non-Deliverable FX swaps (NDS)',\n",
       " 'Deliverable FX swaps (DS)',\n",
       " 'FX futures',\n",
       " 'Other Foreign Exchange Derivatives']"
      ]
     },
     "execution_count": 3,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "fx_asset_class = rts2_annex3.class_root.asset_class_by_name('Foreign Exchange Derivatives')\n",
    "[sub_asset_class.name for sub_asset_class in fx_asset_class.children]"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "... and we can then ask one of these Foreign Exchange Derivatives Sub-asset classes for the description of its criteria:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 4,
   "metadata": {
    "collapsed": false
   },
   "outputs": [
    {
     "data": {
      "text/plain": [
       "['underlying currency pair defined as combination of the two currencies underlying the derivative contract',\n",
       " 'time to maturity bucket of the swap defined as follows:']"
      ]
     },
     "execution_count": 4,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "fx_do_sub_asset_class = fx_asset_class.sub_asset_class_by_name('Deliverable FX options (DO)')\n",
    "[criterion.description for criterion in fx_do_sub_asset_class.criteria]"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 5,
   "metadata": {
    "collapsed": true
   },
   "outputs": [],
   "source": [
    "import ipywidgets as widgets"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 6,
   "metadata": {
    "collapsed": false
   },
   "outputs": [],
   "source": [
    "asset_classes = rts2_annex3.class_root.asset_classes\n",
    "asset_class_names = [an_asset_class.name for an_asset_class in asset_classes]\n",
    "asset_class_dict = dict([\n",
    "        (an_asset_class.name, an_asset_class) \n",
    "        for an_asset_class \n",
    "        in asset_classes])"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 7,
   "metadata": {
    "collapsed": false
   },
   "outputs": [],
   "source": [
    "asset_class_widget = widgets.Dropdown(\n",
    "    options=asset_class_dict,\n",
    "    # value=asset_class_dict[asset_class_names[0]],\n",
    "    description='Asset Classes:',\n",
    "    disabled=False,\n",
    ")\n",
    "asset_class_widget"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 8,
   "metadata": {
    "collapsed": false
   },
   "outputs": [],
   "source": [
    "#selected_asset_class = rts2_annex3.class_root.asset_class_by_name(asset_class_widget.value)\n",
    "selected_asset_class = asset_class_widget.value\n",
    "sub_asset_class_names = [\n",
    "    sub_asset_class.name \n",
    "    for sub_asset_class \n",
    "    in selected_asset_class.sub_asset_classes]\n",
    "sub_asset_class_dict = dict([\n",
    "    (sub_asset_class.name, sub_asset_class) \n",
    "    for sub_asset_class \n",
    "    in selected_asset_class.sub_asset_classes])"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 9,
   "metadata": {
    "collapsed": false
   },
   "outputs": [],
   "source": [
    "sub_asset_class_widget = widgets.Dropdown(\n",
    "    options=sub_asset_class_dict,\n",
    "    # value=sub_asset_class_names[0],\n",
    "    description='Sub-asset Classes:',\n",
    "    disabled=False,\n",
    ")\n",
    "sub_asset_class_widget"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 10,
   "metadata": {
    "collapsed": false
   },
   "outputs": [],
   "source": [
    "criteria_vbox = widgets.VBox([])"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 11,
   "metadata": {
    "collapsed": true
   },
   "outputs": [],
   "source": [
    "from IPython.display import display"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 13,
   "metadata": {
    "collapsed": false
   },
   "outputs": [],
   "source": [
    "def criteria_widgets(sub_asset_class):\n",
    "    # OK, in here I need to look up the criteria for the\n",
    "    # sub-asset class and build the widgets in rows of HBox es\n",
    "    return [widgets.Label(criterion.display(prefix=\"\"))\n",
    "            for criterion\n",
    "            in sub_asset_class.criteria]\n",
    "    \n",
    "def asset_class_changed(change):\n",
    "    if change['type'] == 'change' and change['name'] == 'value':\n",
    "        selected_asset_class = change['new']\n",
    "        sub_asset_class_names = [sub_asset_class.name for sub_asset_class in selected_asset_class.sub_asset_classes]\n",
    "        sub_asset_class_dict = dict([\n",
    "            (sub_asset_class.name, sub_asset_class) \n",
    "            for sub_asset_class \n",
    "            in selected_asset_class.sub_asset_classes])\n",
    "        sub_asset_class_widget.options = sub_asset_class_dict\n",
    "        \n",
    "def sub_asset_class_changed(change):\n",
    "    if change['type'] == 'change' and change['name'] == 'value':\n",
    "        selected_sub_asset_class = change['new']\n",
    "        criteria_vbox.children = criteria_widgets(selected_sub_asset_class)\n",
    "\n",
    "asset_class_widget.observe(asset_class_changed)\n",
    "sub_asset_class_widget.observe(sub_asset_class_changed)\n",
    "display(asset_class_widget)\n",
    "display(sub_asset_class_widget)\n",
    "criteria_vbox.children = criteria_widgets(sub_asset_class_widget.value)\n",
    "display(criteria_vbox)\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "collapsed": false
   },
   "outputs": [],
   "source": [
    "from ipywidgets import interact\n",
    "@interact(x=dict(a=1,b=2,c=3))\n",
    "def xx(x):\n",
    "    return x"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "collapsed": false
   },
   "outputs": [],
   "source": [
    "from IPython.display import display\n",
    "button = widgets.Button(description=\"Click Me!\")\n",
    "display(button)\n",
    "\n",
    "def on_button_clicked(b):\n",
    "    print(\"Button clicked.\")\n",
    "\n",
    "button.on_click(on_button_clicked)"
   ]
  }
 ],
 "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.5.3"
  },
  "widgets": {
   "state": {
    "058478d9f1404574b561808860fcef95": {
     "views": [
      {
       "cell_index": 12
      }
     ]
    },
    "09d3cbce75ab4863aebfaf4177cf662d": {
     "views": [
      {
       "cell_index": 13
      }
     ]
    },
    "0b123a9d0cc748f589498ba1c7e81693": {
     "views": [
      {
       "cell_index": 11
      }
     ]
    },
    "102f1426a0c749638caaedf3d07abb54": {
     "views": [
      {
       "cell_index": 13
      }
     ]
    },
    "322b090c052142d2aef61b3eadf80fc5": {
     "views": [
      {
       "cell_index": 11
      }
     ]
    },
    "3c811f236bf4414e9bda49ba4a008ca3": {
     "views": [
      {
       "cell_index": 12
      }
     ]
    },
    "3e6b0f69c25b445d80b995b019e2673d": {
     "views": [
      {
       "cell_index": 11
      }
     ]
    },
    "437e5ed8a31d4cf495f1e6113b140cb8": {
     "views": [
      {
       "cell_index": 10
      },
      {
       "cell_index": 15
      }
     ]
    },
    "67d80b9785d64516b85d417583f46fe0": {
     "views": [
      {
       "cell_index": 12
      }
     ]
    },
    "6ac47ed365384a2fa8c55a8c07ebca20": {
     "views": [
      {
       "cell_index": 15
      },
      {
       "cell_index": 15
      }
     ]
    },
    "6ed3ef3611594db19e871e736800bd50": {
     "views": [
      {
       "cell_index": 11
      },
      {
       "cell_index": 12
      },
      {
       "cell_index": 12
      }
     ]
    },
    "74ba98a0876249b5aa28b625ca475b1c": {
     "views": [
      {
       "cell_index": 11
      },
      {
       "cell_index": 11
      }
     ]
    },
    "841860703cb24f2a869632eee51ffc4d": {
     "views": [
      {
       "cell_index": 12
      },
      {
       "cell_index": 15
      },
      {
       "cell_index": 15
      }
     ]
    },
    "92a02693fd214fa199e07708e7dc7d19": {
     "views": [
      {
       "cell_index": 15
      }
     ]
    },
    "bc4de7c803674aa3bded0a31c3f52386": {
     "views": [
      {
       "cell_index": 15
      }
     ]
    },
    "c67bba9db54043309dd06a19348048a9": {
     "views": [
      {
       "cell_index": 13
      }
     ]
    },
    "c6c682a6437e47a796a53493af64c56d": {
     "views": [
      {
       "cell_index": 12
      }
     ]
    },
    "e7b6d217912a41ebbc7d9e0bf09a61e1": {
     "views": [
      {
       "cell_index": 11
      }
     ]
    },
    "ea82ec5f1cae416aa7f507972e8755a3": {
     "views": [
      {
       "cell_index": 15
      }
     ]
    }
   },
   "version": "1.2.0"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 2
{'fraction_non_alphanumeric': 0.1417136781167853, 'fraction_numerical': 0.03715627492099123, 'mean_word_length': 2.5509176717357107, 'pattern_counts': {'":': 414, '<': 3, '<?xml version=': 0, '>': 3, 'https://': 0, 'lorem ipsum': 0, 'www.': 0, 'xml': 0}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 0, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'dir': 'git-commits-cleaned', 'id': '1185167', 'n_tokens_mistral': 12578, 'n_tokens_neox': 11548, 'n_words': 2938}