Notebook

This notebook shows how to plot multiindexed data (like the pipeline output for multiple assets) in three different ways.

In [95]:
import numpy as np
import matplotlib.pyplot as plt
from quantopian.pipeline import Pipeline, CustomFactor
from quantopian.pipeline.data import Fundamentals
from quantopian.research import run_pipeline

from quantopian.pipeline.filters import StaticAssets
from quantopian.research import symbols
from quantopian.pipeline.data import USEquityPricing

import matplotlib.pyplot as plt
import pandas as pd
In [104]:
assets_screen = StaticAssets(symbols(['NKE', 'UAA']))
fundamentals = {
            'total_assets': Fundamentals.total_assets.latest,
            'total_liabilities': Fundamentals.total_liabilities.latest,
            'market_cap': Fundamentals.market_cap.latest    
                }


my_pipeline = Pipeline(columns=fundamentals, screen=assets_screen)
data = run_pipeline(my_pipeline, '2002-1-01', '2018-6-27', 90)
In [105]:
data.head()
Out[105]:
market_cap total_assets total_liabilities
2002-01-02 00:00:00+00:00 Equity(5328 [NKE]) 1.507380e+10 6.278100e+09 NaN
2002-01-03 00:00:00+00:00 Equity(5328 [NKE]) 1.507380e+10 6.278100e+09 NaN
2002-01-04 00:00:00+00:00 Equity(5328 [NKE]) 1.507380e+10 6.278100e+09 NaN
2002-01-07 00:00:00+00:00 Equity(5328 [NKE]) 1.507380e+10 6.278100e+09 NaN
2002-01-08 00:00:00+00:00 Equity(5328 [NKE]) 1.507380e+10 6.278100e+09 NaN
In [106]:
# Slice dataframe to get values for each stock
idx = pd.IndexSlice
data_1 = data.loc[idx[:, symbols('NKE')], :]
data_2 = data.loc[idx[:, symbols('UAA')], :]

2. Similar idea, cleaner code

In [107]:
# This constructs the same plot, but using cleaner code
columns = list(data.columns)
dates = data.index.levels[0]

# Iterate through columns and plot each one
for column in columns:
    plt.plot(dates, data_1[column], label='NKE '+str(column))
    plt.plot(dates, data_2[column], label='UAA '+str(column))
    
plt.legend()
plt.title('NKE & UAA  Balance Sheet Comparison (in 100s of billions)')
plt.show()

ValueErrorTraceback (most recent call last)
<ipython-input-107-64bef3cdaabf> in <module>()
      6 for column in columns:
      7     plt.plot(dates, data_1[column], label='NKE '+str(column))
----> 8     plt.plot(dates, data_2[column], label='UAA '+str(column))
      9 
     10 plt.legend()

/usr/local/lib/python2.7/dist-packages/matplotlib/pyplot.pyc in plot(*args, **kwargs)
   3152         ax.hold(hold)
   3153     try:
-> 3154         ret = ax.plot(*args, **kwargs)
   3155     finally:
   3156         ax.hold(washold)

/usr/local/lib/python2.7/dist-packages/matplotlib/__init__.pyc in inner(ax, *args, **kwargs)
   1810                     warnings.warn(msg % (label_namer, func.__name__),
   1811                                   RuntimeWarning, stacklevel=2)
-> 1812             return func(ax, *args, **kwargs)
   1813         pre_doc = inner.__doc__
   1814         if pre_doc is None:

/usr/local/lib/python2.7/dist-packages/matplotlib/axes/_axes.pyc in plot(self, *args, **kwargs)
   1422             kwargs['color'] = c
   1423 
-> 1424         for line in self._get_lines(*args, **kwargs):
   1425             self.add_line(line)
   1426             lines.append(line)

/usr/local/lib/python2.7/dist-packages/matplotlib/axes/_base.pyc in _grab_next_args(self, *args, **kwargs)
    384                 return
    385             if len(remaining) <= 3:
--> 386                 for seg in self._plot_args(remaining, kwargs):
    387                     yield seg
    388                 return

/usr/local/lib/python2.7/dist-packages/matplotlib/axes/_base.pyc in _plot_args(self, tup, kwargs)
    362             x, y = index_of(tup[-1])
    363 
--> 364         x, y = self._xy_from_xy(x, y)
    365 
    366         if self.command == 'plot':

/usr/local/lib/python2.7/dist-packages/matplotlib/axes/_base.pyc in _xy_from_xy(self, x, y)
    221         y = _check_1d(y)
    222         if x.shape[0] != y.shape[0]:
--> 223             raise ValueError("x and y must have same first dimension")
    224         if x.ndim > 2 or y.ndim > 2:
    225             raise ValueError("x and y can be no greater than 2-D")

ValueError: x and y must have same first dimension

3. Using QGrid

In [9]:
import qgrid

# Get data in Qgrid
qgrid_widget = qgrid.show_grid(data)
qgrid_widget

Failed to display Jupyter Widget of type QgridWidget.

If you're reading this message in the Jupyter Notebook or JupyterLab Notebook, it may mean that the widgets JavaScript is still loading. If this message persists, it likely means that the widgets JavaScript library is either not installed or not enabled. See the Jupyter Widgets Documentation for setup instructions.

If you're reading this message in another frontend (for example, a static rendering on GitHub or NBViewer), it may mean that your frontend doesn't currently support widgets.

In [10]:
# Filter the second index column to show only rows for T,
# then save the changed dataframe
T_data = qgrid_widget.get_changed_df()
In [11]:
# Filter the second index column to show only rows for VZ,
# then save the changed dataframe
VZ_data = qgrid_widget.get_changed_df()
In [12]:
T_data.head()
Out[12]:
net_income operating_expenses operating_gains_losses operating_income
2002-01-02 00:00:00+00:00 Equity(6653 [T]) 2.072000e+09 2.200000e+09 -219000000.0 2.822000e+09
Equity(21839 [VZ]) 1.883000e+09 3.402000e+09 -29000000.0 3.677000e+09
2002-01-03 00:00:00+00:00 Equity(6653 [T]) 2.072000e+09 2.200000e+09 -219000000.0 2.822000e+09
Equity(21839 [VZ]) 1.883000e+09 3.402000e+09 -29000000.0 3.677000e+09
2002-01-04 00:00:00+00:00 Equity(6653 [T]) 2.072000e+09 2.200000e+09 -219000000.0 2.822000e+09
In [13]:
VZ_data.head()
Out[13]:
net_income operating_expenses operating_gains_losses operating_income
2002-01-02 00:00:00+00:00 Equity(6653 [T]) 2.072000e+09 2.200000e+09 -219000000.0 2.822000e+09
Equity(21839 [VZ]) 1.883000e+09 3.402000e+09 -29000000.0 3.677000e+09
2002-01-03 00:00:00+00:00 Equity(6653 [T]) 2.072000e+09 2.200000e+09 -219000000.0 2.822000e+09
Equity(21839 [VZ]) 1.883000e+09 3.402000e+09 -29000000.0 3.677000e+09
2002-01-04 00:00:00+00:00 Equity(6653 [T]) 2.072000e+09 2.200000e+09 -219000000.0 2.822000e+09
In [14]:
# Now plot using the same code from above
columns = list(data.columns)
dates = data.index.levels[0]

plt.clf() # clears previous plot

# Iterate through columns and plot each one
for column in columns:
    plt.plot(dates, T_data[column], label='T '+str(column))
    plt.plot(dates, VZ_data[column], label='VZ '+str(column))
    
plt.legend()
plt.title('Historical T CashFlow (in billions)')
plt.show()

ValueErrorTraceback (most recent call last)
<ipython-input-14-a2fc340b15ac> in <module>()
      7 # Iterate through columns and plot each one
      8 for column in columns:
----> 9     plt.plot(dates, T_data[column], label='T '+str(column))
     10     plt.plot(dates, VZ_data[column], label='VZ '+str(column))
     11 

/usr/local/lib/python2.7/dist-packages/matplotlib/pyplot.pyc in plot(*args, **kwargs)
   3152         ax.hold(hold)
   3153     try:
-> 3154         ret = ax.plot(*args, **kwargs)
   3155     finally:
   3156         ax.hold(washold)

/usr/local/lib/python2.7/dist-packages/matplotlib/__init__.pyc in inner(ax, *args, **kwargs)
   1810                     warnings.warn(msg % (label_namer, func.__name__),
   1811                                   RuntimeWarning, stacklevel=2)
-> 1812             return func(ax, *args, **kwargs)
   1813         pre_doc = inner.__doc__
   1814         if pre_doc is None:

/usr/local/lib/python2.7/dist-packages/matplotlib/axes/_axes.pyc in plot(self, *args, **kwargs)
   1422             kwargs['color'] = c
   1423 
-> 1424         for line in self._get_lines(*args, **kwargs):
   1425             self.add_line(line)
   1426             lines.append(line)

/usr/local/lib/python2.7/dist-packages/matplotlib/axes/_base.pyc in _grab_next_args(self, *args, **kwargs)
    384                 return
    385             if len(remaining) <= 3:
--> 386                 for seg in self._plot_args(remaining, kwargs):
    387                     yield seg
    388                 return

/usr/local/lib/python2.7/dist-packages/matplotlib/axes/_base.pyc in _plot_args(self, tup, kwargs)
    362             x, y = index_of(tup[-1])
    363 
--> 364         x, y = self._xy_from_xy(x, y)
    365 
    366         if self.command == 'plot':

/usr/local/lib/python2.7/dist-packages/matplotlib/axes/_base.pyc in _xy_from_xy(self, x, y)
    221         y = _check_1d(y)
    222         if x.shape[0] != y.shape[0]:
--> 223             raise ValueError("x and y must have same first dimension")
    224         if x.ndim > 2 or y.ndim > 2:
    225             raise ValueError("x and y can be no greater than 2-D")

ValueError: x and y must have same first dimension