Creating Custom Widgets Displayed in the Jupyter Notebook
1. Built-in Magic Commands
Magic commands are supported by the IPython kernel. They are prefixed by the
%% characters. These magic commands are designed to solve common problems in data analysis and control the behavior of IPython itself. The magic command used to create custom widgets are:
%%htmlis used to render and define HTML templates and cascading style sheets for widgets
In the next section, I will use this knowledge including CSS bootstrap and jQuery to create a Quote widget displaying real-time financial data in the Jupyter notebook.
Quote Widget is a widget that displays real-time financial data in the Jupyter notebook.
There are three steps to implement this quote widget. All code is written in the Jupyter notebook (QuoteWidget.ipynb).
1. Python Widget Class
The first step is defining a Python class inheriting from the
DOMWidget base class. The
DOMWidget class defined in the
ipywidgets package represents a widget that is displayed on the page as an HTML DOM element.
QuoteWidget class contains several traitlets properties. The
_view_name properties define the
Backbone.js view class for the model. The
name are the properties of the model. The
name property contains the unique name of the quote widget. It represents a unique ID in the HTML DOM element. The
status property contains a text representing the status of the quote widget. The
payload property contains real-time financial data in the field list format.
The data in the quote widget will be updated when the value of the
payload property has been changed. The
sync=True keyword argument tells the widget framework to synchronize the value to the Backbone.js front end.
2. HTML Template
The next step is using the
%%html built-in magic command to define an HTML template and styles of the quote widget. The template is defined inside the script tag with the text/template type. The ID of the template is quote-template. This template will be loaded by the Backbone.js front end. It uses the Bootstrap CSS framework to create a layout of the widget.
Credit: Source link