{
 "cells": [
  {
   "cell_type": "code",
   "execution_count": 1,
   "metadata": {
    "ExecuteTime": {
     "end_time": "2018-10-26T21:47:34.137660Z",
     "start_time": "2018-10-26T21:47:32.731872Z"
    },
    "run_control": {
     "frozen": false,
     "read_only": false
    }
   },
   "outputs": [],
   "source": [
    "from collections import defaultdict\n",
    "from functools import reduce\n",
    "import pandas as pd\n",
    "import numpy as np\n",
    "import matplotlib.pyplot as plt\n",
    "import matplotlib.dates as mdates\n",
    "import matplotlib.ticker as mtick\n",
    "import matplotlib.lines as mlines\n",
    "import matplotlib.patches as mptch\n",
    "import matplotlib.gridspec as gridspec\n",
    "import matplotlib.path as path\n",
    "from mpl_toolkits import mplot3d\n",
    "from mpl_toolkits.mplot3d import Axes3D\n",
    "import matplotlib.cm as cm\n",
    "from scipy.interpolate import griddata\n",
    "\n",
    "from mpl_toolkits.axes_grid1 import make_axes_locatable\n",
    "from IPython.display import display\n",
    "from pyqstrat.pq_utils import *\n",
    "\n",
    "set_defaults()"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 9,
   "metadata": {
    "ExecuteTime": {
     "end_time": "2018-10-26T22:01:18.176304Z",
     "start_time": "2018-10-26T22:01:16.073413Z"
    },
    "run_control": {
     "frozen": false,
     "read_only": false
    },
    "scrolled": false
   },
   "outputs": [
    {
     "data": {
      "image/png": "[encoded data, 240232 characters]\n",
      "text/plain": [
       "<Figure size 1440x1440 with 9 Axes>"
      ]
     },
     "metadata": {},
     "output_type": "display_data"
    }
   ],
   "source": [
    "\n",
    "_VERBOSE = False\n",
    "\n",
    "class DateFormatter(mtick.Formatter):\n",
    "    '''\n",
    "    Formats dates on plot axes.  See matplotlib Formatter\n",
    "    '''\n",
    "    def __init__(self, dates, fmt):\n",
    "        self.dates = dates\n",
    "        self.fmt = fmt\n",
    "\n",
    "    def __call__(self, x, pos = 0):\n",
    "        'Return the label for time x at position pos'\n",
    "        ind = int(np.round(x))\n",
    "        if ind >= len(self.dates) or ind < 0: return ''\n",
    "        return mdates.num2date(self.dates[ind]).strftime(self.fmt)\n",
    "    \n",
    "class HorizontalLine:\n",
    "    '''Draws a horizontal line on a subplot'''\n",
    "    def __init__(self, y, name = None, line_type = 'dashed', color = None):\n",
    "        self.y = y\n",
    "        self.name = name\n",
    "        self.line_type = line_type\n",
    "        self.color = color\n",
    "    \n",
    "class VerticalLine:\n",
    "    '''Draws a vertical line on a subplot where x axis is not a date-time axis'''\n",
    "    def __init__(self, x, name = None, line_type = 'dashed', color = None):\n",
    "        self.x = x\n",
    "        self.name = name\n",
    "        self.line_type = line_type\n",
    "        self.color = color\n",
    "    \n",
    "class DateLine:\n",
    "    '''Draw a vertical line on a plot with a datetime x-axis'''\n",
    "    def __init__(self, date, name = None, line_type = 'dashed', color = None):\n",
    "        self.date = date\n",
    "        self.name = name\n",
    "        self.line_type = line_type\n",
    "        self.color = color\n",
    "        \n",
    "        \n",
    "class BucketedValues:\n",
    "    '''Data in a subplot where x axis is a categorical we summarize properties of a numpy array.  For example, drawing a boxplot with percentiles.'''\n",
    "    def __init__(self, name, bucket_names, bucket_values, proportional_widths = True, show_means = True, show_all = True, show_outliers = False, notched = False):\n",
    "        '''\n",
    "        Args:\n",
    "            name: name used for this data in a plot legend\n",
    "            bucket_names: list of strings used on x axis labels\n",
    "            bucket_values: list of numpy arrays that are summarized in this plot\n",
    "            proportional_widths: if set to True, the width each box in the boxplot will be proportional to the number of items in its corresponding array\n",
    "            show_means: Whether to display a marker where the mean is for each array\n",
    "            show_outliers: Whether to show markers for outliers that are outside the whiskers.  \n",
    "              Box is at Q1 = 25%, Q3 = 75% quantiles, whiskers are at Q1 - 1.5 * (Q3 - Q1), Q3 + 1.5 * (Q3 - Q1)\n",
    "            notched: Whether to show notches indicating the confidence interval around the median\n",
    "        '''\n",
    "        assert isinstance(bucket_names, list) and isinstance(bucket_values, list) and len(bucket_names) == len(bucket_values)\n",
    "        self.name = name\n",
    "        self.bucket_names = bucket_names\n",
    "        self.bucket_values = series_to_array(bucket_values)\n",
    "        self.plot_type = 'boxplot'\n",
    "        self.proportional_widths = proportional_widths\n",
    "        self.show_means = show_means\n",
    "        self.show_all = show_all\n",
    "        self.show_outliers = show_outliers\n",
    "        self.notched = notched\n",
    "        self.time_plot = False\n",
    "        \n",
    "class XYData:\n",
    "    '''\n",
    "    Data in a subplot that has x and y values that are both arrays of floats\n",
    "    \n",
    "    '''\n",
    "    def __init__(self, name, x, y, plot_type = 'line', line_type = 'solid', line_width = None, color = None, marker = None, marker_size = 50,\n",
    "                 marker_color = 'red'):\n",
    "        '''\n",
    "        Args:\n",
    "            x: pandas series or numpy array of floats\n",
    "            y: pandas series or numpy arry of floats\n",
    "        '''\n",
    "        self.name = name\n",
    "        self.x = series_to_array(x)\n",
    "        self.y = series_to_array(y)\n",
    "        self.plot_type = plot_type\n",
    "        if plot_type == 'scatter' and marker is None: marker = 'X'\n",
    "        self.line_type = line_type\n",
    "        self.line_width = line_width\n",
    "        self.color = color\n",
    "        self.marker = marker\n",
    "        self.marker_size = marker_size\n",
    "        self.marker_color = marker_color\n",
    "        self.time_plot = False\n",
    "        \n",
    "class XYZData:\n",
    "    '''Data in a subplot that has x, y and z values that are all floats'''\n",
    "    def __init__(self, name, x, y, z, plot_type = 'surface', marker = 'X', marker_size = 50, marker_color = 'red', interpolation = 'linear',  cmap = 'viridis'):\n",
    "        '''\n",
    "        Args:\n",
    "            x: pandas series or numpy array of floats\n",
    "            y: pandas series or numpy array of floats\n",
    "            z: pandas series or numpy array of floats\n",
    "            plot_type: surface or contour (default surface)\n",
    "            marker: Adds a marker to each point in x, y, z to show the actual data used for interpolation.  You can set this to None to turn markers off.\n",
    "            interpolation: Can be ‘linear’, ‘nearest’ or ‘cubic’ for plotting z points between the ones passed in.  See scipy.interpolate.griddata for details\n",
    "            cmap: Colormap to use (default viridis).  See matplotlib colormap for details\n",
    "        '''\n",
    "        self.name = name\n",
    "        self.x = x\n",
    "        self.y = y\n",
    "        self.z = z\n",
    "        self.plot_type = plot_type\n",
    "        self.marker = marker\n",
    "        self.marker_size = marker_size\n",
    "        self.marker_color = marker_color\n",
    "        self.interpolation = interpolation\n",
    "        self.cmap = cmap\n",
    "        self.time_plot = False\n",
    "    \n",
    "class TimeSeries:\n",
    "    '''Data in a subplot where x is an array of numpy datetimes and y is a numpy array of floats'''\n",
    "    def __init__(self, name, dates, values, plot_type = 'line', line_type = 'solid', line_width = None, color = None, marker = None, marker_size = 50,\n",
    "                 marker_color = 'red'):\n",
    "        '''Args:\n",
    "            name: Name to show in plot legend\n",
    "            dates: pandas Series or numpy array of datetime64\n",
    "            values: pandas Series or numpy array of floats\n",
    "            plot_type: 'line' or 'scatter'\n",
    "            marker: If set, show a marker at each value in values.  See matplotlib marker types\n",
    "        '''\n",
    "        self.name = name\n",
    "        self.dates = series_to_array(dates)\n",
    "        self.values = series_to_array(values)\n",
    "        self.plot_type = plot_type\n",
    "        self.line_type = line_type\n",
    "        self.color = color\n",
    "        self.line_width = line_width\n",
    "        if plot_type == 'scatter' and marker is None: raise Exception('marker must be set for plot_type scatter')\n",
    "        self.marker = marker\n",
    "        self.marker_size = marker_size\n",
    "        self.marker_color = marker_color\n",
    "        self.time_plot = True\n",
    "        \n",
    "    def reindex(self, dates, fill):\n",
    "        '''Reindex this series given a new array of dates, forward filling holes if fill is set to True'''\n",
    "        s = pd.Series(self.values, index = self.dates)\n",
    "        s = s.reindex(dates, method = 'ffill' if fill else None)\n",
    "        self.dates = s.index.values\n",
    "        self.values = s.values\n",
    "        \n",
    "class OHLC:\n",
    "    '''\n",
    "    Data in a subplot that contains open, high, low, close, volume bars.  volume is optional.\n",
    "    '''\n",
    "    def __init__(self, name, dates, o, h, l, c, v = None, vwap = None, colorup='darkgreen', colordown='#F2583E'):\n",
    "        '''\n",
    "        Args:\n",
    "            name: Name to show in a legend\n",
    "            colorup: Color for bars where close >= open.  Default \"darkgreen\"\n",
    "            colordown: Color for bars where open < close.  Default \"#F2583E\"\n",
    "        '''\n",
    "        self.name = name\n",
    "        self.dates = dates\n",
    "        self.o = o\n",
    "        self.h = h\n",
    "        self.l = l\n",
    "        self.c = c\n",
    "        self.v = np.ones(len(self.dates), dtype = np.float64) * np.nan if v is None else v\n",
    "        self.vwap = np.ones(len(self.dates), dtype = np.float64) * np.nan if vwap is None else vwap\n",
    "        self.plot_type = 'candlestick'\n",
    "        self.colorup = colorup\n",
    "        self.colordown = colordown\n",
    "        self.time_plot = True\n",
    "        \n",
    "    def df(self):\n",
    "        return pd.DataFrame({'o' : self.o, 'h' : self.h, 'l' : self.l, 'c' : self.c, 'v' : self.v, 'vwap' : self.vwap}, index = self.dates)[['o', 'h', 'l', 'c', 'v', 'vwap']]\n",
    "        \n",
    "    def reindex(self, all_dates):\n",
    "        df = self.df()\n",
    "        df = df.reindex(all_dates)\n",
    "        self.dates = all_dates\n",
    "        for col in df.columns:\n",
    "            setattr(self, col, df[col].values)\n",
    "                \n",
    "class TradeSet:\n",
    "    '''Data for subplot that contains a set of trades along with marker properties for these trades'''\n",
    "    def __init__(self, name, trades, marker = 'P', marker_color = None, marker_size = 50):\n",
    "        '''\n",
    "        Args:\n",
    "            name: String to display in a subplot legend\n",
    "            trades: List of Trade objects to plot\n",
    "        '''\n",
    "        self. name = name\n",
    "        self.trades = trades\n",
    "        self.plot_type = 'scatter'\n",
    "        self.marker = marker\n",
    "        self.marker_color = marker_color\n",
    "        self.marker_size = marker_size\n",
    "        self.dates = np.array([trade.date for trade in trades], dtype = 'M8[ns]')\n",
    "        self.values = np.array([trade.price for trade in trades], dtype = np.float)\n",
    "        self.time_plot = True\n",
    "        \n",
    "    def reindex(self, all_dates, fill):\n",
    "        s = pd.Series(self.values, index = self.dates)\n",
    "        s = s.reindex(all_dates, method = 'ffill' if fill else None)\n",
    "        self.dates = s.index.values\n",
    "        self.values = s.values\n",
    "        \n",
    "    def __repr__(self):\n",
    "        s = ''\n",
    "        for trade in self.trades:\n",
    "            s += f'{trade.date} {trade.qty} {trade.price}\\n'\n",
    "        return s\n",
    "    \n",
    "def draw_poly(ax, left, bottom, top, right, facecolor, edgecolor, zorder):\n",
    "    '''Draw a set of polygrams given parrallel numpy arrays of left, bottom, top, right points'''\n",
    "    XY = np.array([[left, left, right, right], [bottom, top, top, bottom]]).T\n",
    "\n",
    "    barpath = path.Path.make_compound_path_from_polys(XY)\n",
    "    \n",
    "    # Clean path to get rid of 0, 0 points.  Seems to be a matplotlib bug.  If we don't ylim lower bound is set to 0\n",
    "    v = []\n",
    "    c = []\n",
    "    for seg in barpath.iter_segments():\n",
    "        vertices, command = seg\n",
    "        if not (vertices[0] == 0. and vertices[1] == 0.):\n",
    "            v.append(vertices)\n",
    "            c.append(command)\n",
    "    cleaned_path = path.Path(v, c)\n",
    "\n",
    "    patch = mptch.PathPatch(cleaned_path, facecolor = facecolor, edgecolor = edgecolor, zorder = zorder)\n",
    "    ax.add_patch(patch)\n",
    "\n",
    "\n",
    "def draw_candlestick(ax, index, o, h, l, c, v, vwap, colorup='darkgreen', colordown='#F2583E'):\n",
    "    '''Draw candlesticks given parrallel numpy arrays of o, h, l, c, v values.  v is optional.  See OHLC class __init__ for argument descriptions.'''\n",
    "    width = 0.5\n",
    "                \n",
    "    if v is not None and not np.isnan(v).all(): # Have to do volume first because of a mpl bug with axes fonts if we use make_axes_locatable after plotting on top axis\n",
    "        divider = make_axes_locatable(ax)\n",
    "        vol_ax = divider.append_axes('bottom', size = '25%', sharex = ax)\n",
    "        _c = np.nan_to_num(c)\n",
    "        _o = np.nan_to_num(o)\n",
    "        pos = _c >= _o\n",
    "        neg = _c < _o\n",
    "        vol_ax.bar(index[pos], v[pos], color = colorup, width = width)\n",
    "        vol_ax.bar(index[neg], v[neg], color= colordown, width = width)\n",
    "    \n",
    "    offset = width / 2.0\n",
    "    \n",
    "    mask = ~np.isnan(c) & ~np.isnan(o)\n",
    "    mask[mask] &= c[mask] < o[mask]\n",
    "    \n",
    "    left = index - offset\n",
    "    bottom = np.where(mask, o, c)\n",
    "    top = np.where(mask, c, o)\n",
    "    right = left + width\n",
    "    \n",
    "    draw_poly(ax, left[mask], bottom[mask], top[mask], right[mask], colordown, 'k', 100)\n",
    "    draw_poly(ax, left[~mask], bottom[~mask], top[~mask], right[~mask], colorup, 'k', 100)\n",
    "    draw_poly(ax, left + offset, l, h, left + offset, 'k', 'k', 1)\n",
    "    if vwap is not None:\n",
    "        ax.scatter(index, vwap, marker = 'o', color = 'orange', zorder = 110)\n",
    "        \n",
    "def draw_boxplot(ax, names, values, proportional_widths = True, notched = False, show_outliers = True, show_means = True, show_all = True):\n",
    "    '''Draw a boxplot.  See BucketedValues class for explanation of arguments'''\n",
    "    outliers = None if show_outliers else ''\n",
    "    meanpointprops = dict(marker='D')\n",
    "    assert(isinstance(values, list) and isinstance(names, list) and len(values) == len(names))\n",
    "    widths = None\n",
    "    \n",
    "    if show_all:\n",
    "        all_values = np.concatenate(values)\n",
    "        values.append(all_values)\n",
    "        names.append('all')\n",
    "    \n",
    "    if proportional_widths:\n",
    "        counts = [len(v) for v in values]\n",
    "        total = float(sum(counts))\n",
    "        cases = len(counts)\n",
    "        widths = [c/total for c in counts]  \n",
    "    \n",
    "    ax.boxplot(values, notch = notched, sym = outliers, showmeans = show_means, meanprops=meanpointprops, widths = widths) #, widths = proportional_widths);\n",
    "    ax.set_xticklabels(names);\n",
    "    \n",
    "    \n",
    "def draw_3d_plot(ax, x, y, z, plot_type, marker = 'X', marker_size = 50, marker_color = 'red',\n",
    "                interpolation = 'linear', cmap = 'viridis'):\n",
    "\n",
    "    '''Draw a 3d plot.  See XYZData class for explanation of arguments\n",
    "    \n",
    "    >>> points = np.random.rand(1000, 2)\n",
    "    >>> x = np.random.rand(10)\n",
    "    >>> y = np.random.rand(10)\n",
    "    >>> z = x ** 2 + y ** 2\n",
    "    >>> if has_display():\n",
    "    ...    fig, ax = plt.subplots()\n",
    "    ...    draw_3d_plot(ax, x = x, y = y, z = z, plot_type = 'contour', interpolation = 'linear')\n",
    "    '''\n",
    "    xi = np.linspace(min(x), max(x))\n",
    "    yi = np.linspace(min(y), max(y))\n",
    "    X, Y = np.meshgrid(xi, yi)\n",
    "    Z = griddata((x, y), z, (xi[None,:], yi[:,None]), method=interpolation)\n",
    "    Z = np.nan_to_num(Z)\n",
    "\n",
    "    if plot_type == 'surface':\n",
    "        ax.plot_surface(X, Y, Z, cmap = cmap)\n",
    "        if marker is not None:\n",
    "            ax.scatter(x, y, z, marker = marker, s = marker_size, c = marker_color)\n",
    "    elif plot_type == 'contour':\n",
    "        cs = ax.contour(X, Y, Z, linewidths = 0.5, colors='k')\n",
    "        ax.clabel(cs, cs.levels[::2], fmt = \"%.3g\", inline=1)\n",
    "        ax.contourf(X, Y, Z, cmap = cmap)\n",
    "        if marker is not None:\n",
    "            ax.scatter(x, y, marker = marker, s = marker_size, c = marker_color, zorder=10)\n",
    "    else:\n",
    "        raise Exception(f'unknown plot type: {plot_type}')\n",
    "\n",
    "    m = cm.ScalarMappable(cmap = cmap)\n",
    "    m.set_array(Z)\n",
    "    plt.colorbar(m, ax = ax)\n",
    "    \n",
    "def _adjust_axis_limit(lim, values):\n",
    "    '''If values + 10% buffer are outside current xlim or ylim, return expanded xlim or ylim for subplot'''\n",
    "    min_val, max_val = min(values), max(values)\n",
    "    lim_min = min(values) - .1 * (max_val - min_val)\n",
    "    lim_max = max(values) + .1 * (max_val - min_val)\n",
    "    return (min(lim[0], lim_min), max(lim[1], lim_max))\n",
    "\n",
    "def _plot_data(ax, data):\n",
    "    \n",
    "    x, y = None, None\n",
    "    \n",
    "    if data.time_plot:\n",
    "        dates = data.dates\n",
    "        x = np.arange(len(dates))\n",
    "\n",
    "    if hasattr(data, 'x'): x = data.x\n",
    "    if hasattr(data, 'values'): y = data.values\n",
    "    elif hasattr(data, 'y'): y = data.y\n",
    "        \n",
    "    line = None\n",
    "    \n",
    "    if data.plot_type == 'line':\n",
    "        line, = ax.plot(x, y, linestyle = data.line_type, linewidth = data.line_width, color = data.color)\n",
    "        if data.marker is not None:\n",
    "            line = ax.scatter(x, y, marker = data.marker, c = data.marker_color, s = data.marker_size, zorder=100)\n",
    "    elif data.plot_type == 'scatter':\n",
    "        line = ax.scatter(x, y, marker = data.marker, c = data.marker_color, s = data.marker_size, zorder=100)\n",
    "    elif data.plot_type == 'bar':\n",
    "        line = ax.bar(index, y, color = data.color)\n",
    "    elif data.plot_type == 'filled_line':\n",
    "        values = np.nan_to_num(data.values)\n",
    "        pos_values = np.where(y > 0, y, 0)\n",
    "        neg_values = np.where(y < 0, y, 0)\n",
    "        ax.fill_between(x, pos_values, color='blue', step = 'post', linewidth = 0.0)\n",
    "        ax.fill_between(x, neg_values, color='red', step = 'post', linewidth = 0.0)\n",
    "        #ax.set_ylim(max(ylim[0], np.max(y) * 1.1), min(ylim[1], np.min(y) * 1.1))\n",
    "    elif data.plot_type == 'candlestick':\n",
    "        draw_candlestick(ax, x, data.o, data.h, data.l, data.c, data.v, data.vwap, colorup = data.colorup, colordown = data.colordown)\n",
    "    elif data.plot_type == 'boxplot':\n",
    "        draw_boxplot(ax, data.bucket_names, data.bucket_values, data.proportional_widths, data.notched, data.show_outliers, \n",
    "                     data.show_means, data.show_all)\n",
    "    elif data.plot_type in ['contour', 'surface']:\n",
    "        draw_3d_plot(ax, x, y, data.z, data.plot_type, data.marker, data.marker_size,\n",
    "                     data.marker_color, data.interpolation, data.cmap)\n",
    "    else:\n",
    "        raise Exception(f'unknown plot type: {data.plot_type}')\n",
    "        \n",
    "    # For scatter and filled line, xlim and ylim does not seem to get set automatically\n",
    "    if x is not None: ax.set_xlim(_adjust_axis_limit(ax.get_xlim(), x))\n",
    "    if y is not None: ax.set_ylim(_adjust_axis_limit(ax.get_ylim(), y))\n",
    "\n",
    "    return line\n",
    "\n",
    "def _draw_date_gap_lines(ax, plot_dates):\n",
    "    dates = mdates.date2num(plot_dates)\n",
    "    freq = np.nanmin(np.diff(dates))\n",
    "    if freq <= 0: raise Exception('could not infer date frequency')\n",
    "    date_index = np.arange(len(dates))\n",
    "    date_diff = np.diff(dates)\n",
    "    \n",
    "    xs = []\n",
    "\n",
    "    for i in date_index:\n",
    "        if i < len(date_diff) and date_diff[i] > (freq + 0.000000001):\n",
    "            xs.append(i + 0.5)\n",
    "            \n",
    "    if len(xs) > 20:\n",
    "        return # Too many lines will clutter the graph\n",
    "    \n",
    "    for x in xs:\n",
    "        ax.axvline(x, linestyle = 'dashed', color = '0.5')\n",
    "            \n",
    "def draw_date_line(ax, plot_dates, date, linestyle, color):\n",
    "    '''Draw vertical line on a subplot with datetime x axis'''\n",
    "    date_index = np.arange(len(plot_dates))\n",
    "    closest_index = (np.abs(plot_dates - date)).argmin()\n",
    "    return ax.axvline(x = closest_index, linestyle = linestyle, color = color)\n",
    "\n",
    "def draw_horizontal_line(ax, y, linestyle, color):\n",
    "    '''Draw horizontal line on a subplot'''\n",
    "    return ax.axhline(y = y, linestyle = linestyle, color = color)\n",
    "\n",
    "def draw_vertical_line(ax, x, linestyle, color):\n",
    "    '''Draw vertical line on a subplot'''\n",
    "    return ax.axvline(x = x, linestyle = linestyle, color = color)\n",
    "           \n",
    "def get_date_formatter(plot_dates, date_format):\n",
    "    '''Create an appropriate DateFormatter for x axis labels.  \n",
    "    If date_format is set to None, figures out an appropriate date format based on the range of dates passed in'''\n",
    "    num_dates = mdates.date2num(plot_dates)\n",
    "    if date_format is not None: return DateFormatter(num_dates, format = date_format)\n",
    "    date_range = num_dates[-1] - num_dates[0]\n",
    "    if date_range > 252:\n",
    "        date_format = '%d-%b-%Y'\n",
    "    elif date_range > 7:\n",
    "        date_format = '%b %d'\n",
    "    elif date_range > 1:\n",
    "        date_format = '%d %H:%M'\n",
    "    else:\n",
    "        date_format = '%H:%M:%S'\n",
    "        \n",
    "    formatter = DateFormatter(num_dates, fmt = date_format)\n",
    "    return formatter\n",
    "    \n",
    "class Subplot:\n",
    "    '''A top level plot contains a list of subplots, each of which contain a list of data objects to draw'''\n",
    "    def __init__(self, data_list, title = None, xlabel = None, ylabel = None, zlabel = None,\n",
    "                 date_lines = None, horizontal_lines = None, vertical_lines = None, xlim = None, ylim = None, \n",
    "                 height_ratio = 1.0, display_legend = True, legend_loc = 'best', log_y = False, y_tick_format = None):\n",
    "        \n",
    "        '''\n",
    "        Args:\n",
    "            data_list: A list of objects to draw.  Each element can contain XYData, XYZData, TimeSeries, OHLC, BucketedValues or TradeSet\n",
    "            title: Title to show for this subplot. Default None\n",
    "            zlabel: Only applicable to 3d subplots.  Default None\n",
    "            date_lines: A list of DateLine objects to draw as vertical lines.  Only applicable when x axis is datetime.  Default None\n",
    "            horizontal_lines: A list of HorizontalLine objects to draw on the plot.  Default None\n",
    "            vertical_lines: A list of VerticalLine objects to draw on the plot\n",
    "            xlim: x limits for the plot as a tuple of numpy datetime objects when x-axis is datetime, or tuple of floats. Default None\n",
    "            ylim: y limits for the plot.  Tuple of floats.  Default None\n",
    "            height_ratio: If you have more than one subplot on a plot, use height ratio to determine how high each subplot should be.\n",
    "                For example, if you set height_ratio = 0.75 for the first subplot and 0.25 for the second, \n",
    "                the first will be 3 times taller than the second one. Default 1.0\n",
    "            display_legend: Whether to show a legend on the plot.  Default True\n",
    "            legend_loc: Location for the legend. Default 'best'\n",
    "            log_y: whether the y axis should be logarithmic.  Default False\n",
    "            y_tick_format: Format string to use for y axis labels.  For example, you can decide to \n",
    "              use fixed notation instead of scientific notation or change number of decimal places shown.  Default None\n",
    "        '''\n",
    "        if not isinstance(data_list, list): data_list = [data_list]\n",
    "        self.time_plot = all([data.time_plot for data in data_list])\n",
    "        if self.time_plot and any([not data.time_plot for data in data_list]):\n",
    "            raise Exception('cannot add a non date subplot on a subplot which has time series plots')\n",
    "        if not self.time_plot and date_lines is not None: \n",
    "            raise Exception('date lines can only be specified on a time series subplot')\n",
    "        \n",
    "        self.is_3d = any([data.plot_type in ['surface'] for data in data_list])\n",
    "        if self.is_3d and any([data.plot_type not in ['surface'] for data in data_list]):\n",
    "            raise Exception('cannot add a 2d plot on a subplot which has a 3d plot')\n",
    "\n",
    "        self.data_list = data_list\n",
    "        self.date_lines = [] if date_lines is None else date_lines\n",
    "        self.horizontal_lines = [] if horizontal_lines is None else horizontal_lines\n",
    "        self.vertical_lines = [] if vertical_lines is None else vertical_lines\n",
    "        self.title = title\n",
    "        self.xlabel = xlabel\n",
    "        self.ylabel = ylabel\n",
    "        self.zlabel = zlabel\n",
    "        self.ylim = ylim\n",
    "        self.height_ratio = height_ratio\n",
    "        self.display_legend = display_legend\n",
    "        self.legend_loc = legend_loc\n",
    "        self.log_y = log_y\n",
    "        self.y_tick_format = y_tick_format\n",
    "        \n",
    "    def _resample(self, sampling_frequency):\n",
    "        dates, values = None, None\n",
    "        for data in self.data_list:\n",
    "            values = None\n",
    "            if isinstance(data, TimeSeries) or isinstance(data, TradeSet):\n",
    "                data.dates, data.values = resample_ts(data.dates, data.values, sampling_frequency)\n",
    "            elif isinstance(data, OHLC):\n",
    "                df_dict = {}\n",
    "                cols = ['dates', 'o', 'h', 'l' , 'c', 'v', 'vwap']\n",
    "                for col in cols:\n",
    "                    val = getattr(data, col)\n",
    "                    if val is not None:\n",
    "                        df_dict[col] = val\n",
    "                for k, v in df_dict.items():\n",
    "                    print(f'{k} len: {len(v)}')\n",
    "                df = pd.DataFrame(df_dict)\n",
    "                df.set_index('dates', inplace = True)\n",
    "                df = resample_ohlc(df, sampling_frequency)\n",
    "                for col in cols:\n",
    "                    if col in df:\n",
    "                        setattr(data, col, df[col].values)\n",
    "            else:\n",
    "                raise Exception(f'unknown type: {data}')\n",
    "        \n",
    "    def get_all_dates(self, date_range):\n",
    "        dates_list = [data.dates for data in self.data_list]\n",
    "        all_dates = np.array(reduce(np.union1d, dates_list))\n",
    "        if date_range: all_dates = all_dates[(all_dates >= date_range[0]) & (all_dates <= date_range[1])]\n",
    "        return all_dates\n",
    "    \n",
    "    def _reindex(self, all_dates):\n",
    "        for data in self.data_list:\n",
    "            if isinstance(data, OHLC):\n",
    "                data.reindex(all_dates)\n",
    "            else:\n",
    "                fill = not isinstance(data, TradeSet) and not data.plot_type == 'bar'\n",
    "                data.reindex(all_dates, fill = fill)\n",
    "            \n",
    "    def _draw(self, ax, plot_dates, date_formatter):\n",
    "        \n",
    "        if self.time_plot:\n",
    "            self._reindex(plot_dates)\n",
    "            ax.xaxis.set_major_formatter(date_formatter)\n",
    "            date_index = np.arange(len(plot_dates))\n",
    "        \n",
    "        lines = []\n",
    "        \n",
    "        for data in self.data_list:\n",
    "            if _VERBOSE: print(f'plotting data: {data.name}')\n",
    "            line  = _plot_data(ax, data)\n",
    "            lines.append(line)\n",
    "            \n",
    "        for date_line in self.date_lines: # vertical lines on time plot\n",
    "            line = draw_date_line(ax, plot_dates, date_line.date, date_line.line_type, date_line.color)\n",
    "            if date_line.name is not None: lines.append(line)\n",
    "                \n",
    "        for horizontal_line in self.horizontal_lines:\n",
    "            line = draw_horizontal_line(ax, horizontal_line.y, horizontal_line.line_type, horizontal_line.color)\n",
    "            if horizontal_line.name is not None: lines.append(line)\n",
    "                \n",
    "        for vertical_line in self.vertical_lines:\n",
    "            line = draw_vertical_line(ax, vertical_line.x, vertical_line.line_type, vertical_line.color)\n",
    "            if vertical_line.name is not None: lines.append(line)\n",
    "          \n",
    "        self.legend_names = [data.name for data in self.data_list]\n",
    "        self.legend_names += [date_line.name for date_line in self.date_lines if date_line.name is not None]\n",
    "        self.legend_names += [horizontal_line.name for horizontal_line in self.horizontal_lines if horizontal_line.name is not None]\n",
    "        self.legend_names += [vertical_line.name for vertical_line in self.vertical_lines if vertical_line.name is not None]\n",
    "        \n",
    "        if self.ylim: ax.set_ylim(self.ylim)\n",
    "        if (len(self.data_list) > 1 or len(self.date_lines)) and self.display_legend: \n",
    "            ax.legend([line for line in lines if line is not None],\n",
    "                      [self.legend_names[i] for i, line in enumerate(lines) if line is not None], loc = self.legend_loc)\n",
    " \n",
    "        if self.log_y: \n",
    "            ax.set_yscale('log')\n",
    "            ax.yaxis.set_major_locator(mtick.AutoLocator())\n",
    "        if self.y_tick_format:\n",
    "            ax.yaxis.set_major_formatter(mtick.StrMethodFormatter(self.y_tick_format))\n",
    "            \n",
    "        ax.relim()\n",
    "        ax.autoscale_view()\n",
    "        \n",
    "        if self.title: ax.set_title(self.title)\n",
    "        if self.xlabel: ax.set_xlabel(self.xlabel)\n",
    "        if self.ylabel: ax.set_ylabel(self.ylabel)\n",
    "        if self.zlabel: ax.set_zlabel(self.zlabel)\n",
    "            \n",
    "class Plot:\n",
    "    \n",
    "    '''Top level plot containing a list of subplots to draw'''\n",
    "    \n",
    "    def __init__(self, subplot_list,  title = None, figsize = (15, 8), date_range = None, date_format = None, \n",
    "                 sampling_frequency = None, show_grid = True, show_date_gaps = True, hspace = 0.15):\n",
    "        '''\n",
    "        Args:\n",
    "            subplot_list: List of Subplot objects to draw\n",
    "            title: Title for this plot.  Default None\n",
    "            figsize: Figure size.  Default (15, 8)\n",
    "            date_range: Tuple of strings or numpy datetime64 limiting dates to draw.  e.g. (\"2018-01-01 14:00\", \"2018-01-05\"). Default None\n",
    "            date_format: Date format to use for x-axis\n",
    "            sampling_frequency: Set this to downsample subplots that have a datetime x axis.  \n",
    "              For example, if you have minute bar data, you might want to subsample to hours if the plot is too crowded.\n",
    "              See pandas time frequency strings for possible values.  Default None\n",
    "            show_grid: If set to True, show a grid on the subplots.  Default True\n",
    "            show_date_gaps: If set to True, then when there is a gap between dates will draw a dashed vertical line. \n",
    "              For example, you may have minute bars and a gap between end of trading day and beginning of next day. \n",
    "              Even if set to True, this will turn itself off if there are too many gaps to avoid clutter.  Default True\n",
    "            hspace: Height (vertical) space between subplots.  Default 0.15\n",
    "        '''\n",
    "        if isinstance(subplot_list, Subplot): subplot_list = [subplot_list]\n",
    "        assert(len(subplot_list))\n",
    "        self.subplot_list = subplot_list\n",
    "        self.title = title\n",
    "        self.figsize = figsize\n",
    "        self.date_range = strtup2date(date_range)\n",
    "        self.date_format = date_format\n",
    "        self.sampling_frequency = sampling_frequency\n",
    "        self.show_date_gaps = show_date_gaps\n",
    "        self.show_grid = show_grid\n",
    "        self.hspace = hspace\n",
    "        \n",
    "    def _get_plot_dates(self):\n",
    "        dates_list = []\n",
    "        for subplot in self.subplot_list:\n",
    "            if not subplot.time_plot: continue\n",
    "            subplot._resample(self.sampling_frequency)\n",
    "            dates_list.append(subplot.get_all_dates(self.date_range))\n",
    "        if not len(dates_list): return None\n",
    "        plot_dates = np.array(reduce(np.union1d, dates_list))\n",
    "        return plot_dates\n",
    "        \n",
    "\n",
    "    def draw(self, check_data_size = True):\n",
    "        '''Draw the subplots.\n",
    "        \n",
    "        Args:\n",
    "            check_data_size: If set to True, will not plot if there are > 100K points to avoid locking up your computer for a long time.\n",
    "              Default True\n",
    "        '''\n",
    "        if not has_display():\n",
    "            print('no display found, cannot plot')\n",
    "            return\n",
    "        \n",
    "        plot_dates = self._get_plot_dates()\n",
    "        if check_data_size and plot_dates is not None and len(plot_dates) > 100000:\n",
    "            raise Exception(f'trying to plot large data set with {len(plot_dates)} points, reduce date range or turn check_data_size flag off')\n",
    "            \n",
    "        date_formatter = None\n",
    "        if plot_dates is not None: \n",
    "            date_formatter = get_date_formatter(plot_dates, self.date_format)\n",
    "        height_ratios = [subplot.height_ratio for subplot in self.subplot_list]\n",
    "        \n",
    "        fig = plt.figure(figsize = self.figsize)\n",
    "        gs = gridspec.GridSpec(len(self.subplot_list), 1, height_ratios= height_ratios, hspace = self.hspace)\n",
    "        axes = []\n",
    "        \n",
    "        for i, subplot in enumerate(self.subplot_list):\n",
    "            if subplot.is_3d:\n",
    "                ax = plt.subplot(gs[i], projection='3d')\n",
    "            else:\n",
    "                ax = plt.subplot(gs[i])\n",
    "            axes.append(ax)\n",
    "            \n",
    "        time_axes = [axes[i] for i, s in enumerate(self.subplot_list) if s.time_plot]\n",
    "        if len(time_axes):\n",
    "            time_axes[0].get_shared_x_axes().join(*time_axes)\n",
    "            \n",
    "        for i, subplot in enumerate(self.subplot_list):\n",
    "            subplot._draw(axes[i], plot_dates, date_formatter)\n",
    "            \n",
    "        if self.title: axes[0].set_title(self.title)\n",
    "\n",
    "        # We may have added new axes in candlestick plot so get list of axes again\n",
    "        ax_list = fig.axes\n",
    "        for ax in ax_list:\n",
    "            if self.show_grid: ax.grid(linestyle='dotted') #, color = 'grey', which = 'both', alpha = 0.5)\n",
    "                \n",
    "        for ax in ax_list:\n",
    "            if ax not in axes: time_axes.append(ax)\n",
    "                \n",
    "        for ax in time_axes:\n",
    "            if self.show_date_gaps and plot_dates is not None: _draw_date_gap_lines(ax, plot_dates)\n",
    "                \n",
    "        for ax in ax_list:\n",
    "            ax.relim()\n",
    "            ax.autoscale_view()\n",
    "                \n",
    "def _group_trades_by_reason_code(trades):\n",
    "    trade_groups = defaultdict(list)\n",
    "    for trade in trades:\n",
    "        trade_groups[trade.order.reason_code].append(trade)\n",
    "    return trade_groups\n",
    "\n",
    "def trade_sets_by_reason_code(trades, marker_props = ReasonCode.MARKER_PROPERTIES):\n",
    "    '''\n",
    "    Returns a list of TradeSet objects.  Each TradeSet contains trades with a different reason code.  The markers for each TradeSet\n",
    "    are set by looking up marker properties for each reason code using the marker_props argument:\n",
    "    \n",
    "    Args:\n",
    "        trades: List of Trade objects, each containing an order attribute which in turn contains a reason_code attribute\n",
    "        marker_props: Dictionary from reason code string -> dictionary of marker properties.  See ReasonCode.MARKER_PROPERTIES for example.\n",
    "          Default ReasonCode.MARKER_PROPERTIES\n",
    "     '''\n",
    "    trade_groups = _group_trades_by_reason_code(trades)\n",
    "    tradesets = []\n",
    "    for reason_code, trades in trade_groups.items():\n",
    "        if reason_code in marker_props:\n",
    "            mp = marker_props[reason_code]\n",
    "            tradeset = TradeSet(reason_code, trades, marker = mp['symbol'], marker_color = mp['color'], marker_size = mp['size'])\n",
    "        else:\n",
    "            tradeset = TradeSet(reason_code, trades)\n",
    "        tradesets.append(tradeset)\n",
    "    return tradesets \n",
    "\n",
    "def test_plot():\n",
    "    \n",
    "    class MockOrder:\n",
    "        def __init__(self, reason_code):\n",
    "            self.reason_code = reason_code\n",
    "    \n",
    "    class MockTrade:\n",
    "            \n",
    "        def __init__(self, date, qty, price, reason_code):\n",
    "            self.date = date\n",
    "            self.qty = qty\n",
    "            self.price = price\n",
    "            self.order = MockOrder(reason_code) \n",
    "            \n",
    "        def __repr__(self):\n",
    "            return f'{self.date} {self.qty} {self.price}'\n",
    "        \n",
    "    set_defaults()\n",
    "            \n",
    "    md_dates = np.array(['2018-01-08 15:00:00', '2018-01-09 15:00:00', '2018-01-10 15:00:00', '2018-01-11 15:00:00'], dtype = 'M8[ns]')\n",
    "    pnl_dates = np.array(['2018-01-08 15:00:00', '2018-01-09 14:00:00', '2018-01-10 15:00:00', '2018-01-15 15:00:00'], dtype = 'M8[ns]')\n",
    "    \n",
    "    positions = (pnl_dates, np.array([0., 5., 0.,-10.]))\n",
    "    \n",
    "    trade_dates = np.array(['2018-01-09 14:00:00', '2018-01-10 15:00:00', '2018-01-15 15:00:00'], dtype = 'M8[ns]')\n",
    "    trade_price = [9., 10., 9.5]\n",
    "    trade_qty =  [5, -5, -10]\n",
    "    reason_codes = [ReasonCode.ENTER_LONG, ReasonCode.EXIT_LONG, ReasonCode.ENTER_SHORT]\n",
    "    trades = [MockTrade(trade_dates[i], trade_qty[i], trade_price[i], reason_codes[i]) for i, d in enumerate(trade_dates)]\n",
    "\n",
    "    ind_subplot = Subplot([TimeSeries('slow_support', dates = md_dates, values = np.array([8.9, 8.9, 9.1, 9.1]), line_type = '--'),\n",
    "                           TimeSeries('fast_support', dates = md_dates, values = np.array([8.9, 9.0, 9.1, 9.2]), line_type = '--'),\n",
    "                           TimeSeries('slow_resistance', dates = md_dates, values = np.array([9.2, 9.2, 9.4, 9.4]), line_type = '--'),\n",
    "                           TimeSeries('fast_resistance', dates = md_dates, values = np.array([9.2, 9.3, 9.4, 9.5]), line_type = '--'), \n",
    "                           OHLC('price', dates = md_dates, \n",
    "                                o = np.array([8.9, 9.1, 9.3, 8.6]),\n",
    "                                h = np.array([9.0, 9.3, 9.4, 8.7]),\n",
    "                                l = np.array([8.8, 9.0, 9.2, 8.4]),\n",
    "                                c = np.array([8.95, 9.2, 9.35, 8.5]),\n",
    "                                v = np.array([200, 100, 150, 300]),\n",
    "                                vwap = np.array([8.9, 9.15, 9.3, 8.55]))\n",
    "                          ] + trade_sets_by_reason_code(trades), ylabel = \"Price\", height_ratio = 0.3)\n",
    "    \n",
    "    sig_subplot = Subplot(TimeSeries('trend', dates = md_dates, values = np.array([1, 1, -1, -1])), height_ratio=0.1, ylabel = 'Trend')\n",
    "    \n",
    "    equity_subplot = Subplot(TimeSeries('equity', dates= pnl_dates, values = [1.0e6, 1.1e6, 1.2e6, 1.3e6]), height_ratio = 0.1, ylabel = 'Equity', date_lines = \n",
    "                            [DateLine(date = np.datetime64('2018-01-09 14:00:00'), name = 'drawdown', color = 'red'),\n",
    "                             DateLine(date = np.datetime64('2018-01-10 15:00:00'), color = 'red')], \n",
    "                             horizontal_lines = [HorizontalLine(y = 0, name = 'zero', color = 'green')])\n",
    "    \n",
    "    pos_subplot = Subplot(TimeSeries('position', dates = positions[0], values = positions[1], plot_type = 'filled_line'), height_ratio = 0.1, ylabel = 'Position')\n",
    "    \n",
    "    annual_returns_subplot = Subplot(BucketedValues('annual returns', ['2017', '2018'], \n",
    "                                                    bucket_values = [np.random.normal(0, 1, size=(250,)), np.random.normal(0, 1, size=(500,))]),\n",
    "                                                   height_ratio = 0.1, ylabel = 'Annual Returns')\n",
    "    \n",
    "    x = np.random.rand(10)\n",
    "    y = np.random.rand(10)\n",
    "    xy_subplot = Subplot(XYData('2d test', x, y, plot_type = 'scatter', marker = 'X'), xlabel = 'x', ylabel = 'y', height_ratio = 0.2, title = 'XY Plot')\n",
    "    \n",
    "    z = x ** 2 + y ** 2\n",
    "    xyz_subplot = Subplot(XYZData('3d test', x, y, z, ), xlabel = 'x', ylabel = 'y', zlabel = 'z', height_ratio = 0.3)\n",
    "    \n",
    "    \n",
    "    subplot_list = [ind_subplot, sig_subplot, pos_subplot, equity_subplot, annual_returns_subplot, xy_subplot, xyz_subplot]\n",
    "    plot = Plot(subplot_list, figsize = (20,20), title = 'Plot Test', hspace = 0.35)\n",
    "    plot.draw()\n",
    "    \n",
    "    \n",
    "if __name__ == \"__main__\":\n",
    "    test_plot()"
   ]
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "Python 3",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.6.6"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 2
}
