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

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

import pybloqs as p
[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!”

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

Play around with alignment

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

Adding a title

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

Announcement

Hello World!

Writing out dataframes

[6]:
p.Block(df.head())
[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

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

Raw HTML output

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

Composing blocks

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

Announcement

Hello World!
this text is bold

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

[10]:
p.Block(["Block %s" % i for i in range(8)])
[10]:
Block 0
Block 1
Block 2
Block 3
Block 4
Block 5
Block 6
Block 7

Splitting composite blocks into columns

[11]:
p.Block(["Block %s" % i for i in range(8)], cols=4)
[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.

[12]:
p.Block(["Block %s" % i for i in range(8)], cols=4, text_align="right")
[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:

[13]:
p.Block([p.Paragraph("First paragraph."),
         p.Paragraph("Second paragraph."),
         p.Paragraph("Third paragraph.")], text_align="right")
[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.

[14]:
p.Pre("""
some:
  example:
    yaml: [1,2,3]
  data: "text"
""")
[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:

[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!")
[15]:
THIS HERE TEXT SHOULD LOOK LIKE SHOUTING!
[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

[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
[17]:
'two_page_report.pdf'