{ "worksheets": [ { "cells": [ { "cell_type": "markdown", "metadata": {}, "source": [ "# Example of using the rlab helper classes\n", "the rlab package provides a simple way to create complex pdfs. It provides the following pieces. \n", "\n", "- components: provide wrappers to pdf components so they can dynamically scale themselves based on available space\n", "- table: numpy indexing to provide formatting\n", "- builder: manage the building of a pdf and defining grid based templates\n", "\n", "Below I will show the following simplified example. For each security (MSFT, CSCO, INTC), we want to generate 2 pdf pages, one page has images and the other has tabular data. " ] }, { "cell_type": "code", "metadata": {}, "outputs": [], "input": [ "import tia.rlab as rlab\n", "import matplotlib.pyplot as plt\n", "from tia.rlab.table import PercentFormatter, MillionsFormatter, mdYFormatter" ], "language": "python", "prompt_number": 1 }, { "cell_type": "heading", "metadata": {}, "level": 3, "source": [ "Get some financial data" ] }, { "cell_type": "code", "metadata": {}, "outputs": [], "input": [ "# get some real data to plot and build tables for\n", "from pandas.io.data import get_data_yahoo\n", "pxs = get_data_yahoo(['MSFT', 'INTC', 'CSCO'])" ], "language": "python", "prompt_number": 2 }, { "cell_type": "heading", "metadata": {}, "level": 3, "source": [ "Define the builder and templates" ] }, { "cell_type": "code", "metadata": {}, "outputs": [], "input": [ "# - Generate a pdf path\n", "# - define a cover page\n", "# - Create a Pdf Builder\n", "# - Define the templates and register with the builder\n", "#\n", "# TEMPLATE_1\n", "# |-------------------------|\n", "# | HEADER | \n", "# |-------------------------|\n", "# | | |\n", "# | | |\n", "# | | |\n", "# | IMG_1 | IMG_2 |\n", "# | | |\n", "# | | |\n", "# | | |\n", "# |-------------------------|\n", "#\n", "# TEMPLATE_2\n", "# |-------------------------|\n", "# | HEADER | \n", "# |-------------------------|\n", "# | | |\n", "# | | TBL_2 |\n", "# | | |\n", "# | TBL_1 |------------|\n", "# | | |\n", "# | | TBL_3 |\n", "# | | |\n", "# |-------------------------|\n", "\n", "pdfpath = 'rlab_usage.pdf'\n", "\n", "coverpage = rlab.CoverPage('SecurityOverview', 'Reported on Jan-20-2015')\n", "pdf = rlab.PdfBuilder(pdfpath, coverpage=coverpage, showBoundary=0)\n", "\n", "# Define TEMPLATE_1\n", "template = rlab.GridTemplate('TEMPLATE_1', nrows=100, ncols=100)\n", "# uses numpy style slicing to define the dimensions\n", "template.define_frames({\n", " 'HEADER': template[:10, :],\n", " 'IMG_1': template[10:, :50],\n", " 'IMG_2': template[10:, 50:]\n", "})\n", "template.register(pdf)\n", "\n", "# Define TEMPLATE_2\n", "template = rlab.GridTemplate('TEMPLATE_2', nrows=100, ncols=100)\n", "template.define_frames({\n", " 'HEADER': template[:10, :],\n", " 'TBL_1': template[10:, :50],\n", " 'TBL_2': template[10:55, 50:],\n", " 'TBL_3': template[55:, 50:]\n", "})\n", "template.register(pdf)" ], "language": "python", "prompt_number": 3 }, { "cell_type": "heading", "metadata": {}, "level": 3, "source": [ "Define a style and method for building a header" ] }, { "cell_type": "code", "metadata": {}, "outputs": [], "input": [ "from reportlab.platypus.flowables import HRFlowable\n", "from reportlab.lib.colors import HexColor\n", "from reportlab.lib.styles import ParagraphStyle, TA_CENTER\n", "\n", "# Add a stylesheet to the pdf\n", "tb = ParagraphStyle('TitleBar', parent=pdf.stylesheet['Normal'], fontName='Helvetica-Bold', fontSize=14, \n", " leading=14, alignment=TA_CENTER)\n", "\n", "\n", "'TitleBar' not in pdf.stylesheet and pdf.stylesheet.add(tb)\n", "\n", "\n", "def title_bar(pdf, title):\n", " # Build a title bar for top of page\n", " w, t, c = '100%', 2, HexColor('#404040')\n", " title = '{0}'.format(title) \n", " return [HRFlowable(width=w, thickness=t, color=c, spaceAfter=5, vAlign='MIDDLE', lineCap='square'),\n", " pdf.new_paragraph(title, 'TitleBar'),\n", " HRFlowable(width=w, thickness=t, color=c, spaceBefore=5, vAlign='MIDDLE', lineCap='square')]" ], "language": "python", "prompt_number": 4 }, { "cell_type": "heading", "metadata": {}, "level": 3, "source": [ "Define method to convert a dataframe to a formatted pdf table object" ] }, { "cell_type": "code", "metadata": {}, "outputs": [], "input": [ "def to_pdf_table(frame):\n", " table = pdf.table_formatter(frame, inc_header=1, inc_index=1)\n", " # use the default style to add a bit of color\n", " table.apply_basic_style() \n", " # apply a percent formatter to the return column\n", " table.cells.match_column_labels('return').apply_number_format(PercentFormatter)\n", " # apply a millions formatter to volumn column\n", " table.cells.match_column_labels('Volume').apply_number_format(MillionsFormatter)\n", " table.index.apply_format(mdYFormatter)\n", " return table.build(vAlign='MIDDLE')" ], "language": "python", "prompt_number": 6 }, { "cell_type": "heading", "metadata": {}, "level": 3, "source": [ "Create generic method which builds a graph and tables for the specified security" ] }, { "cell_type": "code", "metadata": {}, "outputs": [], "input": [ "# Define a matplotlib helper to store images by key\n", "from tia.util.mplot import FigureHelper\n", "figures = FigureHelper()\n", "\n", "def add_security_to_report(sid, pxframe):\n", " # build the images\n", " with plt.style.context('fivethirtyeight'):\n", " plt.rcParams['lines.linewidth'] = 1.5\n", " img1_key = '{0}_open_pxs'.format(sid)\n", " img2_key = '{0}_close_pxs'.format(sid)\n", " pxframe['Open'].plot(title='{0} Open Price'.format(sid)) \n", " figures.savefig(key=img1_key)\n", " pxframe['Close'].plot(title='{0} Close Price'.format(sid))\n", " figures.savefig(key=img2_key)\n", " # build the tables\n", " pxframe['return'] = pxframe.Close.pct_change()\n", " tbl1 = to_pdf_table(pxframe[['Open', 'High', 'Low', 'Close']].tail(40))\n", " tbl2 = to_pdf_table(pxframe.iloc[:10])\n", " tbl3 = to_pdf_table(pxframe.iloc[-10:])\n", " \n", " # Marry the template with the components\n", " pdf.build_page('TEMPLATE_1', {\n", " 'HEADER': title_bar(pdf, '{0} Images'.format(sid)),\n", " 'IMG_1': rlab.DynamicPdfImage(figures[img1_key]),\n", " 'IMG_2': rlab.DynamicPdfImage(figures[img2_key]), \n", " })\n", " \n", " pdf.build_page('TEMPLATE_2', {\n", " 'HEADER': title_bar(pdf, '{0} Tables'.format(sid)),\n", " 'TBL_1': tbl1,\n", " 'TBL_2': tbl2,\n", " 'TBL_3': tbl3,\n", " })" ], "language": "python", "prompt_number": 7 }, { "cell_type": "heading", "metadata": {}, "level": 3, "source": [ "For each security, add to the pdf" ] }, { "cell_type": "code", "metadata": {}, "outputs": [], "input": [ "for sid in pxs.minor_axis:\n", " add_security_to_report(sid, pxs.minor_xs(sid))\n", "pdf.save()" ], "language": "python", "prompt_number": 8 }, { "cell_type": "heading", "metadata": {}, "level": 3, "source": [ "Focusing on function and not form (working on better default style, check table example for nicer one) " ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "[Click ME](https://github.com/bpsmith/tia/raw/master/examples/rlab_usage.pdf)." ] }, { "cell_type": "code", "metadata": {}, "outputs": [], "input": [ "" ], "language": "python" } ] } ], "cells": [], "metadata": { "name": "", "signature": "sha256:bdd1c284c1b0d5738c9dd4193adafe3739bbc8dc4a52e9b9f2ae3509dbc21603" }, "nbformat": 3, "nbformat_minor": 0 }