Composable Blocks & Interactive Charts

This notebook is a simple illustration of the python API for Blocks and Highcharts interactive charts.

What are Blocks? Blocks are composable layout elements for easily building HTML, PDF, PNG and JPG based reports. At the same time, all block constructs can be rendered in-line in IPython Notebooks (as will be shown later). This has practical benefits like a single backtest function that can be used for quick analysis during research work in a notebook, but also directly injected into more formal reports with having to fumble around with intermediate formats.

Practically all the functionality is based on HTML rendering. HTML is a declarative, tree based language that is easy to work with and fungible. Blocks are also declarative, composable into a tree and are meant to be dead simple. The match was thus quite natural.

The blocks do not try to match the power and precision of latex. Such an undertaking would be not only out of the scope of a simple library, but would mean the reinvention of latex with all the gnarliness that comes with it.

This notebook aims to showcase the functionality and offers some examples to help people get started.

Imports & Data


In [1]:
%%capture
import numpy as np
import pandas as pd
import pandas.util.testing as pt
from datetime import datetime

import pybloqs as p

In [2]:
df = pd.DataFrame((np.random.rand(200, 4)-0.5)/10,
                  columns=list("ABCD"),
                  index=pd.date_range(datetime(2000,1,1), periods=200))

df_cr = (df + 1).cumprod()

a = df_cr.A
b = df_cr.B
c = df_cr.C
c.name = "C"

Using Blocks

Obligatory "Hello World!"


In [3]:
p.Block("Hello World!")


Out[3]:
Hello World!

Play around with alignment


In [4]:
p.Block("Hello World!", h_align="left")


Out[4]:
Hello World!

Adding a title


In [5]:
p.Block("Hello World!", title="Announcement", h_align="left")


Out[5]:

Announcement

Hello World!

Writing out dataframes


In [6]:
p.Block(df.head())


Out[6]:
A B C D
2000-01-01 00:00:00 0.03 -0.02 -0.01 -0.04
2000-01-02 00:00:00 0.01 0.02 0.02 -0.05
2000-01-03 00:00:00 0.00 -0.04 -0.02 -0.03
2000-01-04 00:00:00 -0.02 0.04 0.01 -0.03
2000-01-05 00:00:00 -0.05 0.04 -0.04 -0.02

Writing out matplotlib plots


In [7]:
p.Block(df.A.plot())


Out[7]:

Raw HTML output


In [8]:
p.Block("<b>this text is bold</b>")


Out[8]:
this text is bold

Composing blocks


In [9]:
p.VStack([p.Block("Hello World!", title="Announcement"), p.Block("<b>this text is bold</b>")])


Out[9]:

Announcement

Hello World!
this text is bold

In most cases, one does not need to explicitly wrap elements in blocks


In [10]:
p.Block(["Block %s" % i for i in range(8)])


Out[10]:
Block 0
Block 1
Block 2
Block 3
Block 4
Block 5
Block 6
Block 7

Splitting composite blocks into columns


In [11]:
p.Block(["Block %s" % i for i in range(8)], cols=4)


Out[11]:
Block 0
Block 1
Block 2
Block 3
Block 4
Block 5
Block 6
Block 7

Layout styling is cascading - styles will cascade from parent blocks to child blocks by default. This behavior can be disabled by setting inherit_cfg to false on the child blocks, or simply specifying the desired settings explicitly.


In [12]:
p.Block(["Block %s" % i for i in range(8)], cols=4, text_align="right")


Out[12]:
Block 0
Block 1
Block 2
Block 3
Block 4
Block 5
Block 6
Block 7

Using specific block types is simple as well. As an example - the Paragraph block:


In [13]:
p.Block([p.Paragraph("First paragraph."),
         p.Paragraph("Second paragraph."),
         p.Paragraph("Third paragraph.")], text_align="right")


Out[13]:

First paragraph.

Second paragraph.

Third paragraph.

The Pre block preserves whitespace formatting and is rendered using a fixed width font. Useful for rendering code-like text.


In [14]:
p.Pre("""
some:
  example:
    yaml: [1,2,3]
  data: "text"
""")


Out[14]:
some:
  example:
    yaml: [1,2,3]
  data: "text"

Creating custom blocks is trivial. For the majority of the cases, one can just inherit from the Container block, which has most of the plumbing already in place:


In [15]:
class Capitalize(p.Raw):
    def __init__(self, contents, **kwargs):
        # Stringify and capitalize
        contents = str(contents).upper()

        super(Capitalize, self).__init__(contents, **kwargs)
        
Capitalize("this here text should look like shouting!")


Out[15]:
THIS HERE TEXT SHOULD LOOK LIKE SHOUTING!

In [16]:
# Emails a block (or a report consisting of many blocks). The emailing is independent of previous reports being saved (e.g. there is no need to call save
# before emailing).
from smtplib import SMTPServerDisconnected

try:
    p.Block('').email()
except SMTPServerDisconnected:
    print("Please create ~/.pybloqs.cfg with entry for 'smtp_server'. See README.md and pybloqs/config.py for details.")


Please create ~/.pybloqs.cfg with entry for 'smtp_server'. See README.md and pybloqs/config.py for details.

Page break


In [17]:
blocks = [p.Block("First page", styles={"page-break-after": "always"}),
          p.Block("Second page")]
r = p.VStack(blocks)
r.save("two_page_report.pdf")


['wkhtmltopdf', '--no-stop-slow-scripts', '--debug-javascript', '--javascript-delay', '200', '--page-size', 'A4', '--orientation', 'Portrait', '--enable-smart-shrinking', '/tmp/69e57e72c8.html', 'two_page_report.pdf'] returned:

None
Out[17]:
'two_page_report.pdf'