Beispiel #1
0
def test_plot():
    class MockOrder:
        def __init__(self, reason_code):
            self.reason_code = reason_code

    class MockTrade:
        def __init__(self, timestamp, qty, price, reason_code):
            self.timestamp = timestamp
            self.qty = qty
            self.price = price
            self.order = MockOrder(reason_code)

        def __repr__(self):
            return f'{self.date} {self.qty} {self.price}'

    set_defaults()

    timestamps = 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]')
    pnl_timestamps = 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]')

    positions = (pnl_timestamps, np.array([0., 5., 0., -10.]))

    trade_timestamps = np.array(
        ['2018-01-09 14:00:00', '2018-01-10 15:00:00', '2018-01-15 15:00:00'],
        dtype='M8[ns]')
    trade_price = [9., 10., 9.5]
    trade_qty = [5, -5, -10]
    reason_codes = [
        ReasonCode.ENTER_LONG, ReasonCode.EXIT_LONG, ReasonCode.ENTER_SHORT
    ]
    trades = [
        MockTrade(trade_timestamps[i], trade_qty[i], trade_price[i],
                  reason_codes[i]) for i, d in enumerate(trade_timestamps)
    ]

    ind_subplot = Subplot([
        TimeSeries('slow_support',
                   timestamps=timestamps,
                   values=np.array([8.9, 8.9, 9.1, 9.1]),
                   line_type='--'),
        TimeSeries('fast_support',
                   timestamps=timestamps,
                   values=np.array([8.9, 9.0, 9.1, 9.2]),
                   line_type='--'),
        TimeSeries('slow_resistance',
                   timestamps=timestamps,
                   values=np.array([9.2, 9.2, 9.4, 9.4]),
                   line_type='--'),
        TimeSeries('fast_resistance',
                   timestamps=timestamps,
                   values=np.array([9.2, 9.3, 9.4, 9.5]),
                   line_type='--'),
        TimeSeries('secondary_y_test',
                   timestamps=timestamps,
                   values=np.array([150, 160, 162, 135]),
                   line_type='--'),
        TradeBarSeries('price',
                       timestamps=timestamps,
                       o=np.array([8.9, 9.1, 9.3, 8.6]),
                       h=np.array([9.0, 9.3, 9.4, 8.7]),
                       l=np.array([8.8, 9.0, 9.2, 8.4]),
                       c=np.array([8.95, 9.2, 9.35, 8.5]),
                       v=np.array([200, 100, 150, 300]),
                       vwap=np.array([8.9, 9.15, 9.3, 8.55]))
    ] + trade_sets_by_reason_code(trades),
                          secondary_y=['secondary_y_test'],
                          ylabel="Price",
                          height_ratio=0.3)

    sig_subplot = Subplot(TimeSeries('trend',
                                     timestamps=timestamps,
                                     values=np.array([1, 1, -1, -1])),
                          height_ratio=0.1,
                          ylabel='Trend')

    equity_subplot = Subplot(
        TimeSeries('equity',
                   timestamps=pnl_timestamps,
                   values=[1.0e6, 1.1e6, 1.2e6, 1.3e6]),
        height_ratio=0.1,
        ylabel='Equity',
        date_lines=[
            DateLine(date=np.datetime64('2018-01-09 14:00:00'),
                     name='drawdown',
                     color='red'),
            DateLine(date=np.datetime64('2018-01-10 15:00:00'), color='red')
        ],
        horizontal_lines=[HorizontalLine(y=0, name='zero', color='green')])

    pos_subplot = Subplot(TimeSeries('position',
                                     timestamps=positions[0],
                                     values=positions[1],
                                     plot_type='filled_line'),
                          height_ratio=0.1,
                          ylabel='Position')

    annual_returns_subplot = Subplot(BucketedValues(
        'annual returns', ['2017', '2018'],
        bucket_values=[
            np.random.normal(0, 1, size=(250, )),
            np.random.normal(0, 1, size=(500, ))
        ]),
                                     height_ratio=0.1,
                                     ylabel='Annual Returns')

    x = np.random.rand(10)
    y = np.random.rand(10)
    xy_subplot = Subplot(XYData('2d test',
                                x,
                                y,
                                plot_type='scatter',
                                marker='X'),
                         xlabel='x',
                         ylabel='y',
                         height_ratio=0.2,
                         title='XY Plot')

    z = x**2 + y**2
    xyz_subplot = Subplot(XYZData(
        '3d test',
        x,
        y,
        z,
    ),
                          xlabel='x',
                          ylabel='y',
                          zlabel='z',
                          height_ratio=0.3)

    subplot_list = [
        ind_subplot, sig_subplot, pos_subplot, equity_subplot,
        annual_returns_subplot, xy_subplot, xyz_subplot
    ]
    plot = Plot(subplot_list, figsize=(20, 20), title='Plot Test', hspace=0.35)
    plot.draw()

    plot = Plot(subplot_list, figsize=(20, 20), title='Plot Test', hspace=0.35)
    plot.draw()
Beispiel #2
0
import matplotlib.dates as mdates
import matplotlib.ticker as mtick
import matplotlib.lines as mlines
import matplotlib.patches as mptch
import matplotlib.gridspec as gridspec
import matplotlib.path as path
from mpl_toolkits import mplot3d
from mpl_toolkits.mplot3d import Axes3D
import matplotlib.cm as cm
from scipy.interpolate import griddata

from mpl_toolkits.axes_grid1 import make_axes_locatable
from IPython.display import display
from pyqstrat.pq_utils import set_defaults, ReasonCode, series_to_array, strtup2date, has_display, resample_ts, resample_trade_bars

set_defaults()

_VERBOSE = False


class DateFormatter(mtick.Formatter):
    '''
    Formats timestamps on plot axes.  See matplotlib Formatter
    '''
    def __init__(self, timestamps, fmt):
        self.timestamps = timestamps
        self.fmt = fmt

    def __call__(self, x, pos=0):
        'Return the label for time x at position pos'
        ind = int(np.round(x))