pyqstrat package

Submodules

pyqstrat.evaluator module

class pyqstrat.evaluator.Evaluator(initial_metrics)[source]

Bases: object

You add functions to the evaluator that are dependent on the outputs of other functions. The evaluator will call these functions in the right order so dependencies are computed first before the functions that need their output. You can retrieve the output of a metric using the metric member function

>>> evaluator = Evaluator(initial_metrics={'x' : np.array([1, 2, 3]), 'y' : np.array([3, 4, 5])})
>>> evaluator.add_metric('z', lambda x, y: sum(x, y), dependencies=['x', 'y'])
>>> evaluator.compute()
>>> evaluator.metric('z')
array([ 9, 10, 11])
__init__(initial_metrics)[source]

Inits Evaluator with a dictionary of initial metrics that are used to compute subsequent metrics

Parameters:initial_metrics – a dictionary of string name -> metric. metric can be any object including a scalar, an array or a tuple
add_metric(name, func, dependencies)[source]
compute(metric_names=None)[source]

Compute metrics using the internal dependency graph

Parameters:metric_names – an array of metric names. If not passed in, evaluator will compute and store all metrics
compute_metric(metric_name)[source]

Compute and store a single metric:

Parameters:metric_name – string representing the metric to compute
metric(metric_name)[source]

Return the value of a single metric given its name

metrics()[source]

Return a dictionary of metric name -> metric value

pyqstrat.evaluator.compute_amean(returns)[source]

Computes arithmetic mean of a return array, ignoring NaNs

Parameters:returns – a numpy array of floats representing returns at any frequency
Returns:a float
>>> compute_amean(np.array([3, 4, np.nan]))
3.5
pyqstrat.evaluator.compute_annual_returns(dates, returns, periods_per_year)[source]

Takes the output of compute_bucketed_returns and returns geometric mean of returns by year

Returns:A tuple with the first element being an array of years (integer) and the second element an array of annualized returns for those years
pyqstrat.evaluator.compute_bucketed_returns(dates, returns)[source]

Bucket returns by year

Returns:A tuple with the first element being a list of years and the second a list of numpy arrays containing returns for each corresponding year
pyqstrat.evaluator.compute_calmar(returns_3yr, periods_per_year, mdd_pct_3yr)[source]

Compute Calmar ratio, which is the annualized return divided by max drawdown over the last 3 years

pyqstrat.evaluator.compute_dates_3yr(dates)[source]

Given an array of numpy datetimes, return those that are within 3 years of the last date in the array

pyqstrat.evaluator.compute_equity(dates, starting_equity, returns)[source]

Given starting equity, dates and returns, create a numpy array of equity at each date

pyqstrat.evaluator.compute_gmean(returns, periods_per_year)[source]

Computes geometric mean of an array of returns

Parameters:
  • returns – a numpy array of returns
  • periods_per_year – number of trading periods per year
Returns:

a float

>>> round(compute_gmean(np.array([0.001, 0.002, 0.003]), 252.), 6)
0.654358
pyqstrat.evaluator.compute_mar(returns, periods_per_year, mdd_pct)[source]

Compute MAR ratio, which is annualized return divided by biggest drawdown since inception.

pyqstrat.evaluator.compute_maxdd_date(rolling_dd_dates, rolling_dd)[source]

Compute date of max drawdown given numpy array of dates, and corresponding rolling dd percentages

pyqstrat.evaluator.compute_maxdd_date_3yr(rolling_dd_3yr_dates, rolling_dd_3yr)[source]

Compute max drawdown date over the last 3 years

pyqstrat.evaluator.compute_maxdd_pct(rolling_dd)[source]

Compute max drawdown percentage given a numpy array of rolling drawdowns, ignoring NaNs

pyqstrat.evaluator.compute_maxdd_pct_3yr(rolling_dd_3yr)[source]

Compute max drawdown percentage over the last 3 years

pyqstrat.evaluator.compute_maxdd_start(rolling_dd_dates, rolling_dd, mdd_date)[source]

Compute date when max drawdown starts, given numpy array of dates, corresponding rolling dd percentages and date that max dd starts

pyqstrat.evaluator.compute_maxdd_start_3yr(rolling_dd_3yr_dates, rolling_dd_3yr, mdd_date_3yr)[source]

Comput max drawdown start date over the last 3 years

pyqstrat.evaluator.compute_periods_per_year(dates)[source]
Computes trading periods per year for an array of numpy datetime64’s.
E.g. if most of the dates are separated by 1 day, will return 252.
Parameters:dates – a numpy array of datetime64’s
Returns:a float
>>> compute_periods_per_year(np.array(['2018-01-01', '2018-01-02', '2018-01-03', '2018-01-09'], dtype = 'M8[D]'))
252.0
pyqstrat.evaluator.compute_return_metrics(dates, rets, starting_equity)[source]

Compute a set of common metrics using returns (for example, of an instrument or a portfolio)

Parameters:
  • dates – a numpy datetime array with one date per return
  • rets – a numpy float array of returns
  • starting_equity – starting equity value in your portfolio
Returns:

An Evaluator object containing computed metrics off the returns passed in. If needed, you can add your own metrics to this object based on the values of existing metrics and recompute the Evaluator. Otherwise, you can just use the output of the evaluator using the metrics function.

pyqstrat.evaluator.compute_returns_3yr(dates, returns)[source]

Given an array of numpy datetimes and an array of returns, return those that are within 3 years of the last date in the datetime array

pyqstrat.evaluator.compute_rolling_dd(dates, equity)[source]

Compute numpy array of rolling drawdown percentage

Parameters:
  • dates – numpy array of datetime64
  • equity – numpy array of equity
pyqstrat.evaluator.compute_rolling_dd_3yr(dates, equity)[source]

Compute rolling drawdowns over the last 3 years

pyqstrat.evaluator.compute_sharpe(returns, amean, periods_per_year)[source]

Note that this does not take into risk free returns so it’s really a sharpe0, i.e. assumes risk free returns are 0

Parameters:
  • returns – a numpy array of returns
  • amean – arithmetic mean of returns
  • periods_per_year – number of trading periods per year
>>> round(compute_sharpe(np.array([0.001, -0.001, 0.002]), 0.001, 252), 6)
12.727922
pyqstrat.evaluator.compute_sortino(returns, amean, periods_per_year)[source]

Note that this assumes target return is 0.

Parameters:
  • returns – a numpy array of returns
  • amean – arithmetic mean of returns
  • periods_per_year – number of trading periods per year
>>> round(compute_sortino(np.array([0.001, -0.001, 0.002]), 0.001, 252), 6)
33.674916
pyqstrat.evaluator.compute_std(returns)[source]

Computes standard deviation of an array of returns, ignoring nans

pyqstrat.evaluator.display_return_metrics(metrics, float_precision=3)[source]

Creates a dataframe making it convenient to view the output of the metrics obtained using the compute_return_metrics function.

Parameters:float_precision – Change if you want to display floats with more or less significant figures than the default, 3 significant figures.
Returns:A one row dataframe with formatted metrics.
pyqstrat.evaluator.plot_return_metrics(metrics, title=None)[source]

Plot equity, rolling drawdowns and and a boxplot of annual returns given the output of compute_return_metrics.

pyqstrat.evaluator.test_evaluator()[source]

pyqstrat.marketdata module

class pyqstrat.marketdata.MarketData(dates, c, o=None, h=None, l=None, v=None)[source]

Bases: object

Used to store OHLCV bars. You must at least supply dates and close prices. All other fields are optional.

dates

A numpy datetime array with the datetime for each bar. Must be monotonically increasing.

c

A numpy float array with close prices for the bar.

o

A numpy float array with open prices

h

A numpy float array with high prices

l

A numpy float array with high prices

v

A numpy integer array with volume for the bar

__init__(dates, c, o=None, h=None, l=None, v=None)[source]

Zeroes in o, h, l, c are set to nan

describe(warn_std=10, time_distribution_frequency='15 min', print_time_distribution=False)[source]

Describe the bars. Shows an overview, errors and warnings for the bar data. This is a good function to use before running any backtests on a set of bar data.

Parameters:
  • warn_std – See warning function
  • time_distribution_frequency – See time_distribution function
  • print_time_distribution – Whether to print the time distribution in addition to plotting it.
df(start_date=None, end_date=None)[source]
errors(display=True)[source]

Returns a dataframe indicating any highs that are lower than opens, closes, lows or lows that are higher than other columns Also includes any ohlcv values that are negative

freq_str()[source]
is_ohlc()[source]

Returns True if we have all ohlc columns and none are empty

overview(display=True)[source]

Returns a dataframe showing basic information about the data, including count, number and percent missing, min, max

Parameters:display – Whether to print out the warning dataframe as well as returning it
plot(figsize=(15, 8), date_range=None, sampling_frequency=None, title='Price / Volume')[source]

Plot a candlestick or line plot depending on whether we have ohlc data or just close prices

Parameters:
  • figsize – Size of the figure (default (15,8))
  • date_range – A tuple of strings or numpy datetimes for plotting a smaller sample of the data, e.g. (“2018-01-01”, “2018-01-06”)
  • sampling_frequency – Downsample before plotting. See pandas frequency strings for possible values.
  • title – Title of the graph, default “Price / Volume”
resample(sampling_frequency, inplace=False)[source]

Downsample the OHLCV data into a new bar frequency

Parameters:
  • sampling_frequency – See sampling frequency in pandas
  • inplace – If set to False, don’t modify this object, return a new object instead.
time_distribution(frequency='15 minutes', display=True, plot=True, figsize=None)[source]

Return a dataframe with the time distribution of the bars

Parameters:
  • frequency – The width of each bin (default “15 minutes”). You can use hours or days as well.
  • display – Whether to display the data in addition to returning it.
  • plot – Whether to plot the data in addition to returning it.
  • figsize – If plot is set, optional figure size for the plot (default (20,8))
valid_row(i)[source]

Return True if the row with index i has no nans in it.

warnings(warn_std=10, display=True)[source]

Returns a dataframe indicating any values where the bar over bar change is more than warn_std standard deviations.

Parameters:
  • warn_std – Number of standard deviations to use as a threshold (default 10)
  • display – Whether to print out the warning dataframe as well as returning it
pyqstrat.marketdata.roll_futures(md, date_func, condition_func, expiries=None, return_full_df=False)[source]

Construct a continuous futures dataframe with one row per datetime given rolling logic

Parameters:
  • md – A dataframe containing the columns ‘date’, ‘series’, and any other market data, for example, ohlcv data. Date can contain time for sub-daily bars. The series column must contain a different string name for each futures series, e.g. SEP2018, DEC2018, etc.
  • date_func – A function that takes the market data object as an input and returns a numpy array of booleans True indicates that the future should be rolled on this date if the condition specified in condition_func is met. This function can assume that we have all the columns in the original market data object plus the same columns suffixed with _next for the potential series to roll over to.
  • condition_func – A function that takes the market data object as input and returns a numpy array of booleans. True indicates that we should try to roll the future at that row.
  • expiries – An optional dataframe with 2 columns, ‘series’ and ‘expiry’. This should have one row per future series indicating that future’s expiry date. If you don’t pass this in, the function will assume that the expiry column is present in the original dataframe.
  • return_full_df – If set, will return the datframe without removing extra dates so you can use your own logic for rolling, including the _next columns and the roll flag
Returns:

A pandas DataFrame with one row per date, which contains the columns in the original md DataFrame and the same columns suffixed with _next

representing the series we want to roll to. There is also a column called roll_flag which is set to True whenever the date and roll condition functions are met.

>>> md = pd.DataFrame({'date' : np.concatenate((np.arange(np.datetime64('2018-03-11'), np.datetime64('2018-03-16')),
...                                            np.arange(np.datetime64('2018-03-11'), np.datetime64('2018-03-16')))),
...                    'c' : [10, 10.1, 10.2, 10.3, 10.4] + [10.35, 10.45, 10.55, 10.65, 10.75],
...                    'v' : [200, 200, 150, 100, 100] + [100, 50, 200, 250, 300],
...                    'series' : ['MAR2018'] * 5 + ['JUN2018'] * 5})[['date','series', 'c', 'v']]
>>> expiries = pd.Series(np.array(['2018-03-15', '2018-06-15'], dtype = 'M8[D]'), index = ['MAR2018', 'JUN2018'], name = "expiry")
>>> date_func = lambda md : md.expiry - md.date <= np.timedelta64(3, 'D')
>>> condition_func = lambda md : md.v_next > md.v
>>> df = roll_futures(md, date_func, condition_func, expiries)
>>> df[df.series == 'MAR2018'].date.max() == np.datetime64('2018-03-14')
True
>>> df[df.series == 'JUN2018'].date.max() == np.datetime64('2018-03-15')
True
pyqstrat.marketdata.test_marketdata()[source]

pyqstrat.optimize module

class pyqstrat.optimize.Experiment(suggestion, cost, other_costs)[source]

Bases: object

An Experiment stores a suggestion and its result

suggestion

A dictionary of variable name -> value

cost

A float representing output of the function we are testing with this suggestion as input.

other_costs

A dictionary of other results we want to store and look at later.

valid()[source]

Returns True if all suggestions and costs are finite, i.e not NaN or +/- Infinity

class pyqstrat.optimize.Optimizer(name, generator, cost_func, max_processes=None)[source]

Bases: object

Optimizer is used to optimize parameters for a strategy.

__init__(name, generator, cost_func, max_processes=None)[source]
Parameters:
  • name – string used to display title in plotting, etc.
  • generator – A generator (see Python Generators) that takes no inputs and yields a list of dictionaries with parameter name -> parameter value.
  • cost_func – A function that takes a dictionary of parameter name -> parameter value as input and outputs cost for that set of parameters.
  • max_processes – If not set, the Optimizer will look at the number of CPU cores on your machine to figure out how many processes to run.
df_experiments(sort_column='cost', ascending=True)[source]

Returns a dataframe containing experiment data, sorted by sort_column (default “cost”)

experiment_list(sort_order='lowest_cost')[source]

Returns the list of experiments we have run

Parameters:sort_order – Can be set to lowest_cost, highest_cost or sequence. If set to sequence, experiments are returned in the sequence in which they were run
plot_2d(x, y='all', plot_type='line', figsize=(15, 8), marker='X', marker_size=50, marker_color='r', xlim=None, hspace=None)[source]

Creates a 2D plot of the optimization output for plotting 1 parameter and costs.

Parameters:
  • x – Name of the parameter to plot on the x axis, corresponding to the same name in the generator.
  • y – Can be one of: “cost” The name of another cost variable corresponding to the output from the cost function “all”, which creates a subplot for cost plus all other costs
  • plot_type – line or scatter (default line)
  • figsize – Figure size
  • marker – Adds a marker to each point in x, y to show the actual data used for interpolation. You can set this to None to turn markers off.
  • hspace – Vertical space between subplots
plot_3d(x, y, z='all', plot_type='surface', figsize=(15, 15), interpolation='linear', cmap='viridis', marker='X', marker_size=50, marker_color='r', xlim=None, ylim=None, hspace=None)[source]

Creates a 3D plot of the optimization output for plotting 2 parameters and costs.

Parameters:
  • x – Name of the parameter to plot on the x axis, corresponding to the same name in the generator.
  • y – Name of the parameter to plot on the y axis, corresponding to the same name in the generator.
  • z – Can be one of: “cost” The name of another cost variable corresponding to the output from the cost function “all”, which creates a subplot for cost plus all other costs
  • plot_type – surface or contour (default surface)
  • figsize – Figure size
  • interpolation – Can be ‘linear’, ‘nearest’ or ‘cubic’ for plotting z points between the ones passed in. See scipy.interpolate.griddata for details
  • cmap – Colormap to use (default viridis). See matplotlib colormap for details
  • 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.
  • hspace – Vertical space between subplots
run(raise_on_error=False)[source]

Run the optimizer.

Parameters:raise_on_error – If set to True, even if we are running a multiprocess optimization, any Exceptions will bubble up and stop the Optimizer. This can be useful for debugging to see stack traces for Exceptions.
pyqstrat.optimize.test_optimize()[source]

pyqstrat.orders module

class pyqstrat.orders.LimitOrder(symbol, date, qty, limit_price, reason_code='none', status='open')[source]

Bases: object

__init__(symbol, date, qty, limit_price, reason_code='none', status='open')[source]
Parameters:
  • symbol – A string
  • date – A numpy datetime indicating the time the order was placed
  • qty – Number of contracts or shares. Use a negative quantity for sell orders
  • limit_price – Limit price (float)
  • reason_code – A string representing the reason this order was created. Prefer a predefined constant from the ReasonCode class if it matches your reason for creating this order.
  • status – Status of the order, “open”, “filled”, etc. (default “open”)
params()[source]
class pyqstrat.orders.MarketOrder(symbol, date, qty, reason_code='none', status='open')[source]

Bases: object

__init__(symbol, date, qty, reason_code='none', status='open')[source]
Parameters:
  • symbol – A string
  • date – A numpy datetime indicating the time the order was placed
  • qty – Number of contracts or shares. Use a negative quantity for sell orders
  • reason_code – A string representing the reason this order was created. Prefer a predefined constant from the ReasonCode class if it matches your reason for creating this order.
  • status – Status of the order, “open”, “filled”, etc. (default “open”)
params()[source]
class pyqstrat.orders.RollOrder(symbol, date, close_qty, reopen_qty, reason_code='roll future', status='open')[source]

Bases: object

A roll order is used to roll a future from one series to the next. It represents a sell of one future and the buying of another future.

__init__(symbol, date, close_qty, reopen_qty, reason_code='roll future', status='open')[source]
Parameters:
  • symbol – A string
  • date – A numpy datetime indicating the time the order was placed
  • close_qty – Quantity of the future you are rolling
  • reopen_qty – Quantity of the future you are rolling to
  • reason_code – A string representing the reason this order was created. Prefer a predefined constant from the ReasonCode class if it matches your reason for creating this order.
  • status – Status of the order, “open”, “filled”, etc. (default “open”)
params()[source]
class pyqstrat.orders.StopLimitOrder(symbol, date, qty, trigger_price, limit_price=nan, reason_code='none', status='open')[source]

Bases: object

Used for stop loss or stop limit orders. The order is triggered when price goes above or below trigger price, depending on whether this is a short or long order. Becomes either a market or limit order at that point, depending on whether you set the limit price or not.

__init__(symbol, date, qty, trigger_price, limit_price=nan, reason_code='none', status='open')[source]
Parameters:
  • symbol – A string
  • date – A numpy datetime indicating the time the order was placed
  • qty – Number of contracts or shares. Use a negative value for sell orders
  • trigger_price – Order becomes a market or limit order if price crosses trigger_price.
  • limit_price – If not set (default), order becomes a market order when price crosses trigger price. Otherwise it becomes a limit order
  • reason_code – A string representing the reason this order was created. Prefer a predefined constant from the ReasonCode class if it matches your reason for creating this order.
  • status – Status of the order, “open”, “filled”, etc. (default “open”)
params()[source]

pyqstrat.plot module

class pyqstrat.plot.BucketedValues(name, bucket_names, bucket_values, proportional_widths=True, show_means=True, show_all=True, show_outliers=False, notched=False)[source]

Bases: object

Data in a subplot where x axis is a categorical we summarize properties of a numpy array. For example, drawing a boxplot with percentiles.

__init__(name, bucket_names, bucket_values, proportional_widths=True, show_means=True, show_all=True, show_outliers=False, notched=False)[source]
Parameters:
  • name – name used for this data in a plot legend
  • bucket_names – list of strings used on x axis labels
  • bucket_values – list of numpy arrays that are summarized in this plot
  • 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
  • show_means – Whether to display a marker where the mean is for each array
  • show_outliers – Whether to show markers for outliers that are outside the whiskers. Box is at Q1 = 25%, Q3 = 75% quantiles, whiskers are at Q1 - 1.5 * (Q3 - Q1), Q3 + 1.5 * (Q3 - Q1)
  • notched – Whether to show notches indicating the confidence interval around the median
class pyqstrat.plot.DateFormatter(dates, fmt)[source]

Bases: matplotlib.ticker.Formatter

Formats dates on plot axes. See matplotlib Formatter

class pyqstrat.plot.DateLine(date, name=None, line_type='dashed', color=None)[source]

Bases: object

Draw a vertical line on a plot with a datetime x-axis

class pyqstrat.plot.HorizontalLine(y, name=None, line_type='dashed', color=None)[source]

Bases: object

Draws a horizontal line on a subplot

class pyqstrat.plot.OHLC(name, dates, o, h, l, c, v=None, colorup='darkgreen', colordown='#F2583E')[source]

Bases: object

Data in a subplot that contains open, high, low, close, volume bars. volume is optional.

__init__(name, dates, o, h, l, c, v=None, colorup='darkgreen', colordown='#F2583E')[source]
Parameters:
  • name – Name to show in a legend
  • colorup – Color for bars where close >= open. Default “darkgreen”
  • colordown – Color for bars where open < close. Default “#F2583E”
df()[source]
reindex(all_dates)[source]
class pyqstrat.plot.Plot(subplot_list, title=None, figsize=(15, 8), date_range=None, date_format=None, sampling_frequency=None, show_grid=True, show_date_gaps=True, hspace=0.15)[source]

Bases: object

Top level plot containing a list of subplots to draw

__init__(subplot_list, title=None, figsize=(15, 8), date_range=None, date_format=None, sampling_frequency=None, show_grid=True, show_date_gaps=True, hspace=0.15)[source]
Parameters:
  • subplot_list – List of Subplot objects to draw
  • title – Title for this plot. Default None
  • figsize – Figure size. Default (15, 8)
  • date_range – Tuple of strings or numpy datetime64 limiting dates to draw. e.g. (“2018-01-01 14:00”, “2018-01-05”). Default None
  • date_format – Date format to use for x-axis
  • sampling_frequency – Set this to downsample subplots that have a datetime x axis. For example, if you have minute bar data, you might want to subsample to hours if the plot is too crowded. See pandas time frequency strings for possible values. Default None
  • show_grid – If set to True, show a grid on the subplots. Default True
  • show_date_gaps – If set to True, then when there is a gap between dates will draw a dashed vertical line. For example, you may have minute bars and a gap between end of trading day and beginning of next day. Even if set to True, this will turn itself off if there are too many gaps to avoid clutter. Default True
  • hspace – Height (vertical) space between subplots. Default 0.15
draw(check_data_size=True)[source]

Draw the subplots.

Parameters: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. Default True
class pyqstrat.plot.Subplot(data_list, title=None, xlabel=None, ylabel=None, zlabel=None, date_lines=None, horizontal_lines=None, vertical_lines=None, xlim=None, ylim=None, height_ratio=1.0, display_legend=True, legend_loc='best', log_y=False, y_tick_format=None)[source]

Bases: object

A top level plot contains a list of subplots, each of which contain a list of data objects to draw

__init__(data_list, title=None, xlabel=None, ylabel=None, zlabel=None, date_lines=None, horizontal_lines=None, vertical_lines=None, xlim=None, ylim=None, height_ratio=1.0, display_legend=True, legend_loc='best', log_y=False, y_tick_format=None)[source]
Parameters:
  • data_list – A list of objects to draw. Each element can contain XYData, XYZData, TimeSeries, OHLC, BucketedValues or TradeSet
  • title – Title to show for this subplot. Default None
  • zlabel – Only applicable to 3d subplots. Default None
  • date_lines – A list of DateLine objects to draw as vertical lines. Only applicable when x axis is datetime. Default None
  • horizontal_lines – A list of HorizontalLine objects to draw on the plot. Default None
  • vertical_lines – A list of VerticalLine objects to draw on the plot
  • xlim – x limits for the plot as a tuple of numpy datetime objects when x-axis is datetime, or tuple of floats. Default None
  • ylim – y limits for the plot. Tuple of floats. Default None
  • height_ratio – If you have more than one subplot on a plot, use height ratio to determine how high each subplot should be. For example, if you set height_ratio = 0.75 for the first subplot and 0.25 for the second, the first will be 3 times taller than the second one. Default 1.0
  • display_legend – Whether to show a legend on the plot. Default True
  • legend_loc – Location for the legend. Default ‘best’
  • log_y – whether the y axis should be logarithmic. Default False
  • y_tick_format – Format string to use for y axis labels. For example, you can decide to use fixed notation instead of scientific notation or change number of decimal places shown. Default None
get_all_dates(date_range)[source]
class pyqstrat.plot.TimeSeries(name, dates, values, plot_type='line', line_type='solid', line_width=None, color=None, marker=None, marker_size=50, marker_color='red')[source]

Bases: object

Data in a subplot where x is an array of numpy datetimes and y is a numpy array of floats

__init__(name, dates, values, plot_type='line', line_type='solid', line_width=None, color=None, marker=None, marker_size=50, marker_color='red')[source]

Args: name: Name to show in plot legend dates: pandas Series or numpy array of datetime64 values: pandas Series or numpy array of floats plot_type: ‘line’ or ‘scatter’ marker: If set, show a marker at each value in values. See matplotlib marker types

reindex(dates, fill)[source]

Reindex this series given a new array of dates, forward filling holes if fill is set to True

class pyqstrat.plot.TradeSet(name, trades, marker='P', marker_color=None, marker_size=50)[source]

Bases: object

Data for subplot that contains a set of trades along with marker properties for these trades

__init__(name, trades, marker='P', marker_color=None, marker_size=50)[source]
Parameters:
  • name – String to display in a subplot legend
  • trades – List of Trade objects to plot
reindex(all_dates, fill)[source]
class pyqstrat.plot.VerticalLine(x, name=None, line_type='dashed', color=None)[source]

Bases: object

Draws a vertical line on a subplot where x axis is not a date-time axis

class pyqstrat.plot.XYData(name, x, y, plot_type='line', line_type='solid', line_width=None, color=None, marker=None, marker_size=50, marker_color='red')[source]

Bases: object

Data in a subplot that has x and y values that are both arrays of floats

__init__(name, x, y, plot_type='line', line_type='solid', line_width=None, color=None, marker=None, marker_size=50, marker_color='red')[source]
Parameters:
  • x – pandas series or numpy array of floats
  • y – pandas series or numpy arry of floats
class pyqstrat.plot.XYZData(name, x, y, z, plot_type='surface', marker='X', marker_size=50, marker_color='red', interpolation='linear', cmap='viridis')[source]

Bases: object

Data in a subplot that has x, y and z values that are all floats

__init__(name, x, y, z, plot_type='surface', marker='X', marker_size=50, marker_color='red', interpolation='linear', cmap='viridis')[source]
Parameters:
  • x – pandas series or numpy array of floats
  • y – pandas series or numpy array of floats
  • z – pandas series or numpy array of floats
  • plot_type – surface or contour (default surface)
  • 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.
  • interpolation – Can be ‘linear’, ‘nearest’ or ‘cubic’ for plotting z points between the ones passed in. See scipy.interpolate.griddata for details
  • cmap – Colormap to use (default viridis). See matplotlib colormap for details
pyqstrat.plot.draw_3d_plot(ax, x, y, z, plot_type, marker='X', marker_size=50, marker_color='red', interpolation='linear', cmap='viridis')[source]

Draw a 3d plot. See XYZData class for explanation of arguments

>>> points = np.random.rand(1000, 2)
>>> x = np.random.rand(10)
>>> y = np.random.rand(10)
>>> z = x ** 2 + y ** 2
>>> if has_display():
...    fig, ax = plt.subplots()
...    draw_3d_plot(ax, x = x, y = y, z = z, plot_type = 'contour', interpolation = 'linear')
pyqstrat.plot.draw_boxplot(ax, names, values, proportional_widths=True, notched=False, show_outliers=True, show_means=True, show_all=True)[source]

Draw a boxplot. See BucketedValues class for explanation of arguments

pyqstrat.plot.draw_candlestick(ax, index, o, h, l, c, v, colorup='darkgreen', colordown='#F2583E')[source]

Draw candlesticks given parrallel numpy arrays of o, h, l, c, v values. v is optional. See OHLC class __init__ for argument descriptions.

pyqstrat.plot.draw_date_line(ax, plot_dates, date, linestyle, color)[source]

Draw vertical line on a subplot with datetime x axis

pyqstrat.plot.draw_horizontal_line(ax, y, linestyle, color)[source]

Draw horizontal line on a subplot

pyqstrat.plot.draw_poly(ax, left, bottom, top, right, facecolor, edgecolor, zorder)[source]

Draw a set of polygrams given parrallel numpy arrays of left, bottom, top, right points

pyqstrat.plot.draw_vertical_line(ax, x, linestyle, color)[source]

Draw vertical line on a subplot

pyqstrat.plot.get_date_formatter(plot_dates, date_format)[source]

Create an appropriate DateFormatter for x axis labels. If date_format is set to None, figures out an appropriate date format based on the range of dates passed in

pyqstrat.plot.test_plot()[source]
pyqstrat.plot.trade_sets_by_reason_code(trades, marker_props={'backtest end': {'symbol': '*', 'color': 'green', 'size': 50}, 'enter long': {'symbol': 'P', 'color': 'blue', 'size': 50}, 'enter short': {'symbol': 'P', 'color': 'red', 'size': 50}, 'exit long': {'symbol': 'X', 'color': 'blue', 'size': 50}, 'exit short': {'symbol': 'X', 'color': 'red', 'size': 50}, 'none': {'symbol': 'o', 'color': 'green', 'size': 50}, 'roll future': {'symbol': '>', 'color': 'green', 'size': 50}})[source]

Returns a list of TradeSet objects. Each TradeSet contains trades with a different reason code. The markers for each TradeSet are set by looking up marker properties for each reason code using the marker_props argument:

Parameters:
  • trades – List of Trade objects, each containing an order attribute which in turn contains a reason_code attribute
  • marker_props – Dictionary from reason code string -> dictionary of marker properties. See ReasonCode.MARKER_PROPERTIES for example. Default ReasonCode.MARKER_PROPERTIES

pyqstrat.pq_utils module

class pyqstrat.pq_utils.ReasonCode[source]

Bases: object

A class containing constants for predefined order reason codes. Prefer these predefined reason codes if they suit the reason you are creating your order. Otherwise, use your own string.

BACKTEST_END = 'backtest end'
ENTER_LONG = 'enter long'
ENTER_SHORT = 'enter short'
EXIT_LONG = 'exit long'
EXIT_SHORT = 'exit short'
MARKER_PROPERTIES = {'backtest end': {'symbol': '*', 'color': 'green', 'size': 50}, 'enter long': {'symbol': 'P', 'color': 'blue', 'size': 50}, 'enter short': {'symbol': 'P', 'color': 'red', 'size': 50}, 'exit long': {'symbol': 'X', 'color': 'blue', 'size': 50}, 'exit short': {'symbol': 'X', 'color': 'red', 'size': 50}, 'none': {'symbol': 'o', 'color': 'green', 'size': 50}, 'roll future': {'symbol': '>', 'color': 'green', 'size': 50}}
NONE = 'none'
ROLL_FUTURE = 'roll future'
pyqstrat.pq_utils.date_2_num(d)[source]

Adopted from matplotlib.mdates.date2num so we don’t have to add a dependency on matplotlib here

pyqstrat.pq_utils.has_display()[source]

If we are running in unit test mode or on a server, then don’t try to draw graphs, etc.

pyqstrat.pq_utils.infer_compression(input_filename)[source]

Infers compression for a file from its suffix. For example, given “/tmp/hello.gz”, this will return “gzip” >>> infer_compression(“/tmp/hello.gz”) ‘gzip’ >>> infer_compression(“/tmp/abc.txt”) is None True

pyqstrat.pq_utils.infer_frequency(dates)[source]

Returns most common frequency of date differences as a fraction of days :param dates: A numpy array of monotonically increasing datetime64

>>> dates = np.array(['2018-01-01 11:00:00', '2018-01-01 11:15:00', '2018-01-01 11:30:00', '2018-01-01 11:35:00'], dtype = 'M8[ns]')
>>> infer_frequency(dates)
0.01041667
pyqstrat.pq_utils.is_newer(filename, ref_filename)[source]

whether filename ctime (modfication time) is newer than ref_filename or either file does not exist >>> import time >>> touch(‘/tmp/x.txt’) >>> time.sleep(0.1) >>> touch(‘/tmp/y.txt’) >>> is_newer(‘/tmp/y.txt’, ‘/tmp/x.txt’) True >>> touch(‘/tmp/y.txt’) >>> time.sleep(0.1) >>> touch(‘/tmp/x.txt’) >>> is_newer(‘/tmp/y.txt’, ‘/tmp/x.txt’) False

pyqstrat.pq_utils.millis_since_epoch(dt)[source]

Given a python datetime, return number of milliseconds between the unix epoch and the datetime. Returns a float since it can contain fractions of milliseconds as well >>> millis_since_epoch(datetime.datetime(2018, 1, 1)) 1514764800000.0

pyqstrat.pq_utils.monotonically_increasing(array)[source]

Returns True if the array is monotonically_increasing, False otherwise

>>> monotonically_increasing(np.array(['2018-01-02', '2018-01-03'], dtype = 'M8[D]'))
True
>>> monotonically_increasing(np.array(['2018-01-02', '2018-01-02'], dtype = 'M8[D]'))
False
pyqstrat.pq_utils.nan_to_zero(array)[source]

Converts any nans in a numpy float array to 0

pyqstrat.pq_utils.np_get_index(array, value)[source]

Get index of a value in a numpy array. Returns -1 if the value does not exist.

pyqstrat.pq_utils.resample_ohlc(dates, o, h, l, c, v, sampling_frequency)[source]

Downsample OHLCV data using sampling frequency

Parameters:
  • o – open price, downsampling uses the first point in the bin
  • h – high price, downsampling uses the max
  • l – low price, downsampling uses the min
  • c – close price, downsampling uses the last point
  • v – volume, downsampling uses the sum
  • sampling_frequency – See pandas frequency strings
Returns:

A tuple of arrays, corresponding to each array passed in that was not None.

For example, if l and v were passed in as None, the tuple will not contain these.

>>> dates = np.array(['2018-01-08 15:00:00', '2018-01-09 15:00:00', '2018-01-09 15:00:00', '2018-01-11 15:00:00'], dtype = 'M8[ns]')
>>> 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])
>>> resample_ohlc(dates, o, h, l, c, None, sampling_frequency = 'D')
(array(['2018-01-08T00:00:00.000000000', '2018-01-09T00:00:00.000000000',
        '2018-01-10T00:00:00.000000000', '2018-01-11T00:00:00.000000000'], dtype='datetime64[ns]'),
        array([8.9, 9.1, nan, 8.6]), array([9. , 9.4, nan, 8.7]), array([8.8, 9. , nan, 8.4]), array([8.95, 9.35,  nan, 8.5 ]), None)
pyqstrat.pq_utils.resample_ts(dates, values, sampling_frequency)[source]

Downsample a pair of dates and values using sampling frequency, using the last value if it does not exist at bin edge. See pandas.Series.resample

Parameters:
  • dates – a numpy datetime64 array
  • values – a numpy array
  • sampling_frequency – See pandas frequency strings
pyqstrat.pq_utils.series_to_array(series)[source]

Convert a pandas series to a numpy array. If the object is not a pandas Series return it back unchanged

pyqstrat.pq_utils.set_defaults(df_float_sf=4, df_display_max_rows=200, df_display_max_columns=99, np_seterr='raise', plot_style='ggplot', mpl_figsize=(8, 6))[source]

Set some display defaults to make it easier to view dataframes and graphs.

Parameters:
  • df_float_sf – Number of significant figures to show in dataframes (default 4). Set to None to use pandas defaults
  • df_display_max_rows – Number of rows to display for pandas dataframes when you print them (default 200). Set to None to use pandas defaults
  • df_display_max_columns – Number of columns to display for pandas dataframes when you print them (default 99). Set to None to use pandas defaults
  • np_seterr – Error mode for numpy warnings. See numpy seterr function for details. Set to None to use numpy defaults
  • plot_style – Style for matplotlib plots. Set to None to use default plot style.
  • mpl_figsize – Default figure size to use when displaying matplotlib plots (default 8,6). Set to None to use defaults
pyqstrat.pq_utils.shift_np(array, n, fill_value=None)[source]

Similar to pandas.Series.shift but works on numpy arrays.

Parameters:
  • array – The numpy array to shift
  • n – Number of places to shift, can be positive or negative
  • fill_value – After shifting, there will be empty slots left in the array. If set, fill these with fill_value. If fill_value is set to None (default), we will fill these with False for boolean arrays, np.nan for floats
pyqstrat.pq_utils.str2date(s)[source]

Converts a string like “2008-01-15 15:00:00” to a numpy datetime64. If s is not a string, return s back

pyqstrat.pq_utils.strtup2date(tup)[source]

Converts a string tuple like (“2008-01-15”, “2009-01-16”) to a numpy datetime64 tuple. If the tuple does not contain strings, return it back unchanged

pyqstrat.pq_utils.to_csv(df, file_name, index=False, compress=False, *args, **kwargs)[source]

Creates a temporary file then renames to the permanent file so we don’t have half written files. Also optionally compresses using the xz algorithm

pyqstrat.pq_utils.touch(fname, mode=438, dir_fd=None, **kwargs)[source]

replicate unix touch command, i.e create file if it doesn’t exist, otherwise update timestamp

pyqstrat.pq_utils.zero_to_nan(array)[source]

Converts any zeros in a numpy array to nans

pyqstrat.strategy module

class pyqstrat.strategy.Account(contracts, starting_equity=1000000.0, calc_frequency='D')[source]

Bases: object

An Account calculates pnl for a set of contracts

__init__(contracts, starting_equity=1000000.0, calc_frequency='D')[source]
Parameters:
  • contracts – A list of Contract objects
  • starting_equity – Starting equity in account currency. Default 1.e6
  • calc_frequency – Account will calculate pnl at this frequency. Default ‘D’ for daily
add_contract(contract)[source]
calc(i)[source]

Computes P&L and stores it internally for all contracts.

Parameters:i – Index to compute P&L at. Account remembers the last index it computed P&L up to and will compute P&L between these two indices
df_pnl(symbol=None)[source]

Returns a dataframe with P&L columns. If symbol is set to None (default), sums up P&L across symbols

df_trades(symbol=None, start_date=None, end_date=None)[source]

Returns a dataframe with data from trades with the given symbol and with trade date between (and including) start date and end date if they are specified. If symbol is None, trades for all symbols are returned

equity(date)[source]

Returns equity in this account in Account currency. Will cause calculation if Account has not previously calculated up to this date

find_index_before(date)[source]

Returns the market data index before or at date

position(symbol, date)[source]

Returns position for a symbol at a given date in number of contracts or shares. Will cause calculation if Account has not previously calculated up to this date

symbols()[source]
trades(symbol=None, start_date=None, end_date=None)[source]

Returns a list of trades with the given symbol and with trade date between (and including) start date and end date if they are specified. If symbol is None trades for all symbols are returned

transfer_cash(date, amount)[source]

Move cash from one portfolio to another

class pyqstrat.strategy.Contract(symbol, marketdata, multiplier=1.0)[source]

Bases: object

A Contract can be a real or virtual instrument. For example, for futures you may wish to create a single continous contract instead of a contract for each future series

__init__(symbol, marketdata, multiplier=1.0)[source]
Parameters:
  • symbol – A unique string reprenting this contract. e.g IBM or WTI_FUTURE
  • multiplier – If you have to multiply price to get price per contract, set that multiplier there.
  • marketdata – A MarketData object containing prices for this contract.
class pyqstrat.strategy.ContractPNL(contract)[source]

Bases: object

Computes pnl for a single contract over time given trades and market data

add_trades(trades)[source]

Args: trades: A list of Trade objects

calc(prev_i, i)[source]

Compute pnl and store it internally

Parameters:
  • prev_i – Start index to compute pnl from
  • i – End index to compute pnl to
df()[source]

Returns a pandas dataframe with pnl data, indexed by date

trades(start_date=None, end_date=None)[source]

Get a list of trades

Parameters:
  • start_date – A string or numpy datetime64. Trades with trade dates >= start_date will be returned. Default None
  • end_date – A string or numpy datetime64. Trades with trade dates <= end_date will be returned. Default None
class pyqstrat.strategy.Portfolio(name='main')[source]

Bases: object

A portfolio contains one or more strategies that run concurrently so you can test running strategies that are uncorrelated together.

__init__(name='main')[source]

Args: name: String used for displaying this portfolio

add_strategy(name, strategy)[source]
Parameters:
  • name – Name of the strategy
  • strategy – Strategy object
df_returns(sampling_frequency='D', strategy_names=None)[source]

Return dataframe containing equity and returns with a date index. Equity and returns are combined from all strategies passed in.

Parameters:
  • sampling_frequency – Date frequency for rows. Default ‘D’ for daily so we will have one row per day
  • strategy_names – A list of strategy names. By default this is set to None and we use all strategies.
evaluate_returns(sampling_frequency='D', strategy_names=None, plot=True, float_precision=4)[source]

Returns a dictionary of common return metrics.

Parameters:
  • sampling_frequency – Date frequency. Default ‘D’ for daily so we downsample to daily returns before computing metrics
  • strategy_names – A list of strategy names. By default this is set to None and we use all strategies.
  • plot – If set to True, display plots of equity, drawdowns and returns. Default False
  • float_precision – Number of significant figures to show in returns. Default 4
plot(sampling_frequency='D', strategy_names=None)[source]

Display plots of equity, drawdowns and returns

Parameters:
  • sampling_frequency – Date frequency. Default ‘D’ for daily so we downsample to daily returns before computing metrics
  • strategy_names – A list of strategy names. By default this is set to None and we use all strategies.
run(strategy_names=None, start_date=None, end_date=None, run_first=False, run_last=True)[source]

Run indicators, signals and rules.

Parameters:
  • strategy_names – A list of strategy names. By default this is set to None and we use all strategies.
  • start_date – Run rules starting from this date. Sometimes we have a few strategies in a portfolio that need different lead times before they are ready to trade so you can set this so they are all ready by this date. Default None
  • end_date – Don’t run rules after this date. Default None
  • run_first – Force running rules on the first bar even if signals do not require this. Default False
  • run_last – Force running rules on penultimate bar even if signals do not require this.
run_indicators(strategy_names=None)[source]

Compute indicators for the strategies specified

Parameters:strategy_names – A list of strategy names. By default this is set to None and we use all strategies.
run_rules(strategy_names=None, start_date=None, end_date=None, run_first=False, run_last=True)[source]

Run rules for the strategies specified. Must be called after run_indicators and run_signals. See run function for argument descriptions

run_signals(strategy_names=None)[source]

Compute signals for the strategies specified. Must be called after run_indicators

Parameters:strategy_names – A list of strategy names. By default this is set to None and we use all strategies.
class pyqstrat.strategy.Strategy(contracts, starting_equity=1000000.0, calc_frequency='D')[source]

Bases: object

__init__(contracts, starting_equity=1000000.0, calc_frequency='D')[source]
Parameters:
  • contracts – A list of contract objects
  • starting_equity – Starting equity in Strategy currency. Default 1.e6
  • calc_frequency – How often P&L is calculated. Default is ‘D’ for daily
add_indicator(name, indicator_function)[source]
Parameters:
  • name – Name of the indicator
  • indicator_function – A function taking a MarketData object and returning a numpy array containing indicator values. The return array must have the same length as the MarketData object
add_market_sim(market_sim_function, symbols=None)[source]

Add a market simulator. A market simulator takes a list of Orders as input and returns a list of Trade objects.

Parameters:
  • market_sim_function – A function that takes a list of Orders and MarketData as input and returns a list of Trade objects
  • symbols – A list of the symbols that this market_sim_function applies to. If None (default) it will apply to all symbols
add_rule(name, rule_function, signal_name, sig_true_values)[source]

Add a trading rule

Parameters:
  • name – Name of the trading rule
  • rule_function – A trading rule function that returns a list of Orders
  • signal_name – The strategy will call the trading rule function when the signal with this name matches sig_true_values
  • sig_true_values – A numpy array of values. If the signal value at a bar is equal to one of these, the Strategy will call the trading rule function
add_signal(name, signal_function)[source]
Parameters:
  • name – Name of the signal
  • signal_function – A function taking a MarketData object and a dictionary of indicator value arrays as input and returning a numpy array containing signal values. The return array must have the same length as the MarketData object
df_data(symbols=None, add_pnl=True, start_date=None, end_date=None)[source]

Add indicators and signals to end of market data and return as a pandas dataframe.

Parameters:
  • symbols – list of symbols to include. All if set to None (default)
  • add_pnl – If True (default), include P&L columns in dataframe
  • start_date – string or numpy datetime64. Default None
  • end_date – string or numpy datetime64: Default None
df_orders(symbol=None, start_date=None, end_date=None)[source]

Returns a dataframe with data from orders with the given symbol and with order date between (and including) start date and end date if they are specified. If symbol is None, orders for all symbols are returned

df_pnl(symbol=None)[source]

Returns a dataframe with P&L columns. If symbol is set to None (default), sums up P&L across symbols

df_returns(symbol=None, sampling_frequency='D')[source]

Return a dataframe of returns and equity indexed by date.

Parameters:
  • symbol – The symbol to get returns for. If set to None (default), this returns the sum of PNL for all symbols
  • sampling_frequency – Downsampling frequency. Default is None. See pandas frequency strings for possible values
df_trades(symbol=None, start_date=None, end_date=None)[source]

Returns a dataframe with data from trades with the given symbol and with trade date between (and including) start date and end date if they are specified. If symbol is None, trades for all symbols are returned

evaluate_returns(symbol=None, plot=True, float_precision=4)[source]

Returns a dictionary of common return metrics.

Parameters:
  • sampling_frequency – Date frequency. Default ‘D’ for daily so we downsample to daily returns before computing metrics
  • strategy_names – A list of strategy names. By default this is set to None and we use all strategies.
  • plot – If set to True, display plots of equity, drawdowns and returns. Default False
  • float_precision – Number of significant figures to show in returns. Default 4
marketdata(symbol)[source]

Return MarketData object for this symbol

orders(symbol=None, start_date=None, end_date=None)[source]

Returns a list of orders with the given symbol and with order date between (and including) start date and end date if they are specified. If symbol is None orders for all symbols are returned

plot(symbols=None, md_columns='c', pnl_columns='equity', title=None, figsize=(20, 15), date_range=None, date_format=None, sampling_frequency=None, trade_marker_properties=None, hspace=0.15)[source]

Plot indicators, signals, trades, position, pnl

Parameters:
  • symbols – List of symbols or None (default) for all symbols
  • md_columns – List of columns of market data to plot. Default is ‘c’ for close price. You can set this to ‘ohlcv’ if you want to plot a candlestick of OHLCV data
  • pnl_columns – List of P&L columns to plot. Default is ‘equity’
  • title – Title of plot (None)
  • figsize – Figure size. Default is (20, 15)
  • date_range – Tuple of strings or datetime64, e.g. (“2018-01-01”, “2018-04-18 15:00”) to restrict the graph. Default None
  • date_format – Date format for tick labels on x axis. If set to None (default), will be selected based on date range. See matplotlib date format strings
  • sampling_frequency – Downsampling frequency. Default is None. The graph may get too busy if you have too many bars of data, in which case you may want to downsample before plotting. See pandas frequency strings for possible values
  • trade_marker_properties – A dictionary of order reason code -> marker shape, marker size, marker color for plotting trades with different reason codes. Default is None in which case the dictionary from the ReasonCode class is used
  • hspace – Height (vertical) space between subplots. Default is 0.15
plot_returns(symbol=None)[source]

Display plots of equity, drawdowns and returns for the given symbol or for all symbols if symbol is None (default)

run_indicators(indicator_names=None, symbols=None)[source]

Calculate values of the indicators specified and store them.

Parameters:
  • indicator_names – List of indicator names. If None (default) run all indicators
  • symbols – List of symbols to run these indicators for. If None (default) use all symbols
run_rules(rule_names=None, symbols=None, start_date=None, end_date=None, run_first=False, run_last=True)[source]

Run trading rules.

Parameters:
  • rule_names – List of rule names. If None (default) run all rules
  • symbols – List of symbols to run these signals for. If None (default) use all symbols
  • start_date – Run rules starting from this date. Default None
  • end_date – Don’t run rules after this date. Default None
  • run_first – Force running rules on the first bar even if signals do not require this. Default False
  • run_last – Force running rules on penultimate bar even if signals do not require this.
run_signals(signal_names=None, symbols=None)[source]

Calculate values of the signals specified and store them.

Parameters:
  • signal_names – List of signal names. If None (default) run all signals
  • symbols – List of symbols to run these signals for. If None (default) use all symbols
trades(symbol=None, start_date=None, end_date=None)[source]

Returns a list of trades with the given symbol and with trade date between (and including) start date and end date if they are specified. If symbol is None trades for all symbols are returned

class pyqstrat.strategy.Trade(symbol, date, qty, price, fee=0.0, commission=0.0, order=None)[source]

Bases: object

__init__(symbol, date, qty, price, fee=0.0, commission=0.0, order=None)[source]

Args: symbol: a string date: Trade execution datetime qty: Number of contracts or shares filled price: Trade price fee: Fees paid to brokers or others. Default 0 commision: Commission paid to brokers or others. Default 0 order: A reference to the order that created this trade. Default None

pyqstrat.strategy.test_strategy()[source]

pyqstrat.pyqstrat_cpp module

class pyqstrat.pyqstrat_cpp.AllOpenInterestAggregator

Bases: pybind11_builtins.pybind11_object

Writes out all open interest records

__call__()

Add an open interest record to be written to disk at some point

Parameters:
  • oi (OpenInterestRecord) –
  • line_number (int) – The line number of the source file that this trade came from. Used for debugging
__init__()
Parameters:
  • writer_creator – A function that takes an output_file_prefix, schema, create_batch_id and max_batch_size and returns an object implementing the Writer interface
  • output_file_prefix (str) – Path of the output file to create. The writer and aggregator may add suffixes to this to indicate the kind of data and format the file creates. E.g. “/tmp/output_file_1”
  • batch_size (int, optional) – If set, we will write a batch to disk every time we have this many records queued up. Defaults to 2.1 billion
  • timestamp_unit (Schema.Type, optional) – Whether timestamps are measured as milliseconds or microseconds since the unix epoch. Defaults to Schema.TIMESTAMP_MILLI
class pyqstrat.pyqstrat_cpp.AllOtherAggregator

Bases: pybind11_builtins.pybind11_object

Writes out any records that are not trades, quotes or open interest

__call__()

Add a record to be written to disk at some point

Parameters:
  • other (OtherRecord) –
  • line_number (int) – The line number of the source file that this trade came from. Used for debugging
__init__()
Parameters:
  • writer_creator – A function that takes an output_file_prefix, schema, create_batch_id and max_batch_size and returns an object implementing the Writer interface
  • output_file_prefix (str) – Path of the output file to create. The writer and aggregator may add suffixes to this to indicate the kind of data and format the file creates. E.g. “/tmp/output_file_1”
  • batch_size (int, optional) – If set, we will write a batch to disk every time we have this many records queued up. Defaults to 2.1 billion
  • timestamp_unit (Schema.Type, optional) – Whether timestamps are measured as milliseconds or microseconds since the unix epoch. Defaults to Schema.TIMESTAMP_MILLI
class pyqstrat.pyqstrat_cpp.AllQuoteAggregator

Bases: pybind11_builtins.pybind11_object

Writes out every quote we see

__call__()

Add a quote record to be written to disk at some point

Parameters:
  • quote (QuoteRecord) –
  • line_number (int) – The line number of the source file that this trade came from. Used for debugging
__init__()
Parameters:
  • writer_creator – A function that takes an output_file_prefix, schema, create_batch_id and max_batch_size and returns an object implementing the Writer interface
  • output_file_prefix (str) – Path of the output file to create. The writer and aggregator may add suffixes to this to indicate the kind of data and format the file creates. E.g. “/tmp/output_file_1”
  • batch_size – If set, we will write a batch to disk every time we have this many records queued up. Defaults to 2.1 billion
class pyqstrat.pyqstrat_cpp.AllTradeAggregator

Bases: pybind11_builtins.pybind11_object

Writes out every trade we see

__call__()

Add a trade record to be written to disk at some point

Parameters:
  • trade (TradeRecord) –
  • line_number (int) – The line number of the source file that this trade came from. Used for debugging
__init__()
Parameters:
  • writer_creator – A function that takes an output_file_prefix, schema, create_batch_id and max_batch_size and returns an object implementing the Writer interface
  • output_file_prefix (str) – Path of the output file to create. The writer and aggregator may add suffixes to this to indicate the kind of data and format the file creates. E.g. “/tmp/output_file_1”
  • batch_size (int, optional) – If set, we will write a batch to disk every time we have this many records queued up. Defaults to 2.1 billion
  • timestamp_unit (Schema.Type, optional) – Whether timestamps are measured as milliseconds or microseconds since the unix epoch. Defaults to Schema.TIMESTAMP_MILLI
class pyqstrat.pyqstrat_cpp.ArrowWriter

Bases: pyqstrat.pyqstrat_cpp.Writer

A subclass of Writer that batches of records to a disk file in the Apache arrow format. See Apache arrow for details

__init__()
Parameters:
  • output_file_prefix (str) – Path of the output file to create. The writer and aggregator may add suffixes to this to indicate the kind of data and format the file creates. E.g. “/tmp/output_file_1”
  • schema (Schema) – A schema object containing the names and datatypes of each field we want to save in a record
  • create_batch_id_file (bool, optional) – Whether to create a corresponding file that contains a map from batch id -> batch number so we can easily lookup a batch number and then retrieve it from disk. Defaults to False
  • max_batch_size (int, optional) – If set, when we get this many records, we write out a batch of records to disk. May be necessary when we are creating large output files, to avoid running out of memory when reading and writing. Defaults to -1
add_record()

Add a record that will be written to disk at some point.

Parameters:
  • line_number (int) – The line number of the source file that this trade came from. Used for debugging
  • tuple (tuple) – Must correspond to the schema defined in the constructor. For example, if the schema has a bool and a float, the tuple could be (False, 0.5)
close()

Close the writer and flush any remaining data to disk

Parameters:success (bool, optional) – If set to False, we had some kind of exception and are cleaning up. Tells the function to not indicate the file was written successfully, for example by renaming a temp file to the actual filename. Defaults to True
write_batch()

Write a batch of records to disk. The batch can have an optional string id so we can later retrieve just this batch of records without reading the whole file.

Parameters:batch_id (str, optional) – An identifier which can later be used to retrieve this batch from disk. Defaults to “”
class pyqstrat.pyqstrat_cpp.FormatTimestampParser

Bases: pybind11_builtins.pybind11_object

Helper class that parses timestamps according to the strftime format string passed in. strftime is slow so use fast_milli_time_parser
or fast_time_micro_parser if your timestamps are in “HH:MM:SS….” format
__call__()
Parameters:time (str) – The timestamp to parse
Returns:Number of millis or micros since epoch
Return type:int
__init__()
Parameters:
  • base_date (int) – Sometimes the timestamps in a file contain time only and the name of a file contains the date. In these cases, pass in the date as number of millis or micros from the epoch to the start of that date. If the timestamp has date also, pass in 0 here.
  • time_format (str, optional) – strftime format string for parsing the timestamp. Defaults to “%H:%M:%S”
  • micros (bool, optional) – If this is set, we will parse and store microseconds. Otherwise we will parse and store milliseconds. Defaults to True
class pyqstrat.pyqstrat_cpp.OpenInterestRecord

Bases: pyqstrat.pyqstrat_cpp.Record

Open interest for a future or option. Usually one record per instrument at the beginning of the day

id

str – Represents a symbol or instrument id, for example, for an option you may concantenate underlying symbol, expiration, strike, put or call to uniquely identify the instrument

timestamp

int – Trade time, in milliseconds or microseconds since 1/1/1970

qty

float – Trade quantity

metadata

str – A string representing any extra information you want to save, such as exchange, or special trade conditions

__init__()
id
metadata
qty
timestamp
class pyqstrat.pyqstrat_cpp.OtherRecord

Bases: pyqstrat.pyqstrat_cpp.Record

Any other data you want to store from market data besides trades, quotes and open interest. You can capture any important fields in the metadata attribute

id

str – Represents a symbol or instrument id, for example, for an option you may concantenate underlying symbol, expiration, strike, put or call to uniquely identify the instrument

timestamp

int – trade time, in milliseconds or microseconds since 1/1/1970

metadata

str – a string representing any extra information you want to save, such as exchange, or special trade conditions

__init__()
id
metadata
timestamp
class pyqstrat.pyqstrat_cpp.PrintBadLineHandler

Bases: pybind11_builtins.pybind11_object

A helper class that takes in lines we cannot parse and either prints them and continues or raises an Exception

__call__()
Parameters:
  • line_number (int) – Line number of the input file that corresponds to this line (for debugging)
  • line (str) – The actual line that failed to parse
  • exception (Exception) – The exception that caused us to fail to parse this line.
__init__()
Parameters:raise (bool, optional) – Whether to raise an exception every time this is called or just print debugging info. Defaults to False
class pyqstrat.pyqstrat_cpp.QuoteRecord

Bases: pyqstrat.pyqstrat_cpp.Record

A parsed quote record that we can save to disk

id

str – Represents a symbol or instrument id, for example, for an option you may concantenate underlying symbol, expiration, strike, put or call to uniquely identify the instrument

timestamp

int – Trade time, in milliseconds or microseconds since 1/1/1970

bid

bool – If True, this is a bid quote, otherwise it is an offer

qty

float – Trade quantity

price

float – Trade price

metadata

str – A string representing any extra information you want to save, such as exchange, or special trade conditions

__init__()
bid
id
metadata
price
qty
timestamp
class pyqstrat.pyqstrat_cpp.QuoteTOBAggregator

Bases: pybind11_builtins.pybind11_object

Aggregate top of book quotes to top of book records. If you specify a frequency such as “5m”, we will calculate a record every 5 minutes which has the top of book at the end of that bar. If no frequency is specified, we will create a top of book every time a quote comes in. We assume that the quotes are all top of book quotes and are written in pairs so we have a bid quote followed by a offer quote with the same timestamp or vice versa

__call__()

Add a quote record to be written to disk at some point

Parameters:
  • quote (QuoteRecord) –
  • line_number (int) – The line number of the source file that this trade came from. Used for debugging
__init__()
Parameters:
  • writer_creator – A function that takes an output_file_prefix, schema, create_batch_id and max_batch_size and returns an object implementing the Writer interface
  • output_file_prefix (str) – Path of the output file to create. The writer and aggregator may add suffixes to this to indicate the kind of data and format the file creates. E.g. “/tmp/output_file_1”
  • frequency (str, optional) – A string like “5m” indicating the bar size is 5 mins. Units can be s,m,h or d for second, minute, hour or day. Defaults to “5m”. If you set this to “”, each tick will be recorded.
  • batch_by_id (bool, optional) – If set, we will create one batch for each id. This will allow us to retrieve all records for a single
  • by reading a single batch. Defaults to True. (instrument) –
  • batch_size (int, optional) – If set, we will write a batch to disk every time we have this many records queued up. Defaults to 2.1 billion
  • timestamp_unit (Schema.Type, optional) – Whether timestamps are measured as milliseconds or microseconds since the unix epoch. Defaults to Schema.TIMESTAMP_MILLI
close()

Flush all unwritten records to the Writer, which writes them to disk when its close function is called

class pyqstrat.pyqstrat_cpp.Record

Bases: pybind11_builtins.pybind11_object

__init__

Initialize self. See help(type(self)) for accurate signature.

class pyqstrat.pyqstrat_cpp.RegExLineFilter

Bases: pybind11_builtins.pybind11_object

A helper class that filters lines from the input file based on a regular expression. Note that regular expressions are slow, so if you just need to match specific strings, use a string matching filter instead.

__call__()
Parameters:line (str) – The string that the regular expression should match.
Returns:Whether the regex matched
Return type:bool
__init__()
Parameters:pattern (str) – The regex pattern to match. This follows C++ std::regex pattern matching rules as opposed to python
class pyqstrat.pyqstrat_cpp.Schema

Bases: pybind11_builtins.pybind11_object

Describes a list of field names and data types for writing records to disk

types

A list of (str, type) tuples describing a record with the name of each field and its datatype

BOOL = Type.BOOL
FLOAT32 = Type.FLOAT32
FLOAT64 = Type.FLOAT64
INT32 = Type.INT32
INT64 = Type.INT64
STRING = Type.STRING
TIMESTAMP_MICRO = Type.TIMESTAMP_MICRO
TIMESTAMP_MILLI = Type.TIMESTAMP_MILLI
class Type

Bases: pybind11_builtins.pybind11_object

BOOL = Type.BOOL
FLOAT32 = Type.FLOAT32
FLOAT64 = Type.FLOAT64
INT32 = Type.INT32
INT64 = Type.INT64
STRING = Type.STRING
TIMESTAMP_MICRO = Type.TIMESTAMP_MICRO
TIMESTAMP_MILLI = Type.TIMESTAMP_MILLI
__init__()
__init__()
types
class pyqstrat.pyqstrat_cpp.SubStringLineFilter

Bases: pybind11_builtins.pybind11_object

A helper class that will check if a line matches any of a set of strings

__call__()
Parameters:line (str) – We check if any of the patterns are present in this string
Returns:Whether any of the patterns were present
Return type:bool
__init__()
Parameters:patterns (list of str) – The list of strings to match against
class pyqstrat.pyqstrat_cpp.TextFileProcessor

Bases: pybind11_builtins.pybind11_object

__call__()
Parameters:
  • input_filename (str) – The file to read
  • compression (str) – One of “” for uncompressed files, “gzip”, “bz2” or “lzip”
Returns:

Number of lines processed

Return type:

int

__init__()

A helper class that takes text based market data files and creates parsed and aggregated quote, trade, open interest, and other files from them.

Parameters:
  • record_generator – A function that takes a filename and its compression type, and returns a function that we can use to iterate over lines in that file
  • line_filter – A function that takes a line (str) as input and returns whether we should parse it or discard it
  • record_parser – A function that takes a line (str) as input and returns a Record object
  • bad_line_handler – A function that takes a line that failed to parse and returns a Record object or None
  • record_filter – A function that takes a parsed Record object and returns whether we should keep it or discard it
  • missing_data_handler – A function that takes a parsed Record object and deals with missing data, for example, by converting 0’s to NANs
  • quote_aggregator – A function that takes parsed quote objects and aggregates them
  • trade_aggregator – A function that takes parsed trade objects and aggregates them
  • open_interest_aggregator – A function that takes parsed open interest objects and aggregates them
  • other_aggregator – A function that takes parsed OtherRecord objects and aggregates them
  • skip_rows (int, optional) – Number of rows to skip in the file before starting to read it. Defaults to 1 to ignore a header line
class pyqstrat.pyqstrat_cpp.TextOpenInterestParser

Bases: pybind11_builtins.pybind11_object

Helper class that parses an open interest record from a list of fields (strings)

__call__()
Parameters:fields (list of str) – A list of fields representing the record
Returns:or None if this record is not an open interest record
Return type:OpenInterestRecord
__init__()
Parameters:
  • is_open_interest – A function that takes a list of strings as input and returns a bool if the fields represent an open interest record
  • base_date (int) – If the timestamp in the files does not have a date component, pass in the date as number of millis or micros since the epoch
  • timestamp_idx (int) – Index of the timestamp field within the record
  • qty_idx (int) – Index of the quote size field
  • id_field_indices (list of str) – Indices of the fields identifying an instrument. For example, for a future this could be symbol and expiry. These fields will be concatenated with a separator and placed in the id field in the record
  • meta_field_indices (list of str) – Indices of additional fields you want to store. For example, the exchange.
  • timestamp_parser – A function that takes a timestamp as a string and returns number of millis or micros since the epoch
  • strip_id (bool, optional) – If we want to strip any whitespace from the id fields before concatenating them. Defaults to True
  • strip_meta (bool, optional) – If we want to strip any whitespace from the meta fields before concatenating them. Defaults to True
class pyqstrat.pyqstrat_cpp.TextOtherParser

Bases: pybind11_builtins.pybind11_object

Helper class that parses a record that contains information other than a quote, trade or open interest record

__call__()
Parameters:fields (list of str) – a list of fields representing the record
Returns:
Return type:OtherRecord
__init__()
Parameters:
  • is_other – A function that takes a list of strings as input and returns a bool if we want to parse this record
  • base_date (int) – If the timestamp in the files does not have a date component, pass in the date as number of millis or micros since the epoch
  • timestamp_idx (int) – Index of the timestamp field within the record
  • id_field_indices (list of str) – Indices of the fields identifying an instrument. For example, for a future this could be symbol and expiry. These fields will be concatenated with a separator and placed in the id field in the record
  • meta_field_indices (list of str) – Indices of additional fields you want to store. For example, the exchange.
  • timestamp_parser – A function that takes a timestamp as a string and returns number of millis or micros since the epoch
  • strip_id (bool, optional) – If we want to strip any whitespace from the id fields before concatenating them. Defaults to True
  • strip_meta (bool, optional) – If we want to strip any whitespace from the meta fields before concatenating them. Defaults to True
class pyqstrat.pyqstrat_cpp.TextQuoteParser

Bases: pybind11_builtins.pybind11_object

Helper class that parses a quote from a list of fields (strings)

__call__()
Parameters:fields (list of str) – A list of fields representing the record
Returns:Or None if this field is not a quote
Return type:QuoteRecord
__init__()
Parameters:
  • is_quote – a function that takes a list of strings as input and returns a bool if the fields represent a quote
  • base_date (int) – if the timestamp in the files does not have a date component, pass in the date as number of millis or micros since the epoch
  • timestamp_idx (int) – index of the timestamp field within the record
  • bid_offer_idx (int) – index of the field that contains whether this is a bid or offer quote
  • price_idx (int) – index of the price field
  • qty_idx (int) – index of the quote size field
  • id_field_indices (list of str) – indices of the fields identifying an instrument. For example, for a future this could be symbol and expiry. These fields will be concatenated with a separator and placed in the id field in the record
  • meta_field_indices (list of str) – indices of additional fields you want to store. For example, the exchange.
  • timestamp_parser – a function that takes a timestamp as a string and returns number of millis or micros since the epoch
  • bid_str (str) – if the field indicated in bid_offer_idx matches this string, we consider this quote to be a bid
  • offer_str (str) – if the field indicated in bid_offer_idx matches this string, we consider this quote to be an offer
  • price_multiplier – (float, optional): sometimes the price in a file could be in hundredths of cents, and we divide by this to get dollars. Defaults to 1.0
  • strip_id (bool, optional) – if we want to strip any whitespace from the id fields before concatenating them. Defaults to True
  • strip_meta (bool, optional) – if we want to strip any whitespace from the meta fields before concatenating them. Defaults to True
class pyqstrat.pyqstrat_cpp.TextRecordParser

Bases: pybind11_builtins.pybind11_object

A helper class that takes in a text line, separates it into a list of fields based on a delimiter, and then uess the parsers passed in to try and parse the line as a quote, trade, open interest record or any other info

__call__()
Parameters:line (str) – The line we need to parse
__init__()
Parameters:
  • quote_parser – A function that takes a list of strings as input and returns either a QuoteRecord or None
  • trade_parser – A function that takes a list of strings as input and returns either a TradeRecord or None
  • open_interest_parser – A function that takes a list of strings as input and returns either an OpenInterest or None
  • other_parser – A function that takes a list of strings as input and returns an OtherRecord or None
  • separator (str, optional) – A single character string. This is the delimiter we use to separate fields from the text passed in
class pyqstrat.pyqstrat_cpp.TextTradeParser

Bases: pybind11_builtins.pybind11_object

Helper class that parses a trade from a list of fields (strings)

__call__()
Parameters:fields (list of str) – A list of fields representing the record
Returns:or None if this record is not a trade
Return type:TradeRecord
__init__()
Parameters:
  • is_trade – A function that takes a list of strings as input and returns a bool if the fields represent a trade
  • base_date (int) – If the timestamp in the files does not have a date component, pass in the date as number of millis or micros since the epoch
  • timestamp_idx (int) – Index of the timestamp field within the record
  • price_idx (int) – Index of the price field
  • qty_idx (int) – Index of the quote size field
  • id_field_indices (list of str) – Indices of the fields identifying an instrument. For example, for a future this could be symbol and expiry. These fields will be concatenated with a separator and placed in the id field in the record
  • meta_field_indices (list of str) – Indices of additional fields you want to store. For example, the exchange.
  • timestamp_parser – A function that takes a timestamp as a string and returns number of millis or micros since the epoch
  • price_multiplier – (float, optional): Sometimes the price in a file could be in hundredths of cents, and we divide by this to get dollars. Defaults to 1.0
  • strip_id (bool, optional) – If we want to strip any whitespace from the id fields before concatenating them. Defaults to True
  • strip_meta (bool, optional) – If we want to strip any whitespace from the meta fields before concatenating them. Defaults to True
class pyqstrat.pyqstrat_cpp.TradeBarAggregator

Bases: pybind11_builtins.pybind11_object

Aggregate trade records to create trade bars, given a frequency. Calculates open, high, low, close, volume, vwap as well as last_update_time
which is timestamp of the last trade that we processed before the bar ended.
__call__()

Add a trade record to be written to disk at some point

Parameters:
  • trade (TradeRecord) –
  • line_number (int) – The line number of the source file that this trade came from. Used for debugging
__init__()
Parameters:
  • writer_creator – A function that takes an output_file_prefix, schema, create_batch_id and max_batch_size and returns an object implementing the Writer interface
  • output_file_prefix (str) – Path of the output file to create. The writer and aggregator may add suffixes to this to indicate the kind of data and format the file creates. E.g. “/tmp/output_file_1”
  • frequency (str, optional) – A string like “5m” indicating the bar size is 5 mins. Units can be s,m,h or d for second, minute, hour or day. Defaults to “5m”
  • batch_by_id (bool, optional) – If set, we will create one batch for each id. This will allow us to retrieve all records for a single instrument by reading a single batch. Defaults to True.
  • batch_size (int, optional) – If set, we will write a batch to disk every time we have this many records queued up. Defaults to 2.1 billion
  • timestamp_unit (Schema.Type, optional) – Whether timestamps are measured as milliseconds or microseconds since the unix epoch. Defaults to Schema.TIMESTAMP_MILLI
close()

Flush all unwritten records to the Writer, which writes them to disk when its close function is called

class pyqstrat.pyqstrat_cpp.TradeRecord

Bases: pyqstrat.pyqstrat_cpp.Record

A parsed trade record that we can save to disk

id

str – A unique string representing a symbol or instrument id

timestamp

int – Trade time, in milliseconds or microseconds since 1/1/1970

qty

float – Trade quantity

price

float – Trade price

metadata

str – a string representing any extra information you want to save, such as exchange, or special trade conditions

__init__()
id
metadata
price
qty
timestamp
class pyqstrat.pyqstrat_cpp.Writer

Bases: pybind11_builtins.pybind11_object

An abstract class that you subclass to provide an object that can write to disk

__init__

Initialize self. See help(type(self)) for accurate signature.

close()

Close the writer and flush any remaining data to disk

Parameters:success (bool, optional) – If set to False, we had some kind of exception and are cleaning up. Tells the function to not indicate the file was written successfully, for example by renaming a temp file to the actual filename. Defaults to True
write_batch()

Write a batch of records to disk. The batch can have an optional string id so we can later retrieve just this batch of records without reading the whole file

Parameters:batch_id (str, optional) – An identifier which can later be used to retrieve this batch from disk. Defaults to “”
pyqstrat.pyqstrat_cpp.fast_time_micro_parser()

A helper function that takes a string formatted as HH:MM:SS.xxxxxx and parses it into number of microseconds since the beginning of the day

Parameters:time (str) – A string like “08:35:22.132876”
Returns:Microseconds since beginning of day
Return type:int
pyqstrat.pyqstrat_cpp.fast_time_milli_parser()

A helper function that takes a string formatted as HH:MM:SS.xxx and parses it into number of milliseconds since the beginning of the day

Parameters:time (str) – A string like “08:35:22.132”
Returns:Millis since beginning of day
Return type:int
pyqstrat.pyqstrat_cpp.is_field_in_list()

Simple utility function to check whether the value of fields[flag_idx] is in any of flag_values

Parameters:
  • fields – a vector of strings
  • flag_idx – the index of fields to check
  • flag_values – a vector of strings containing possible values for the field
Returns:

a boolean

pyqstrat.pyqstrat_cpp.price_qty_missing_data_handler()

A helper function that takes a Record as an input, checks whether its a trade or a quote or any open interest record, and if any of the prices or quantities are 0, sets them to NAN

Parameters:record – Any subclass of Record
pyqstrat.pyqstrat_cpp.text_file_decompressor()

A helper function that takes a filename and its compression type, and returns a function that we can use to iterate over lines in that file

Parameters:
  • filename (str) – The file to read
  • compression (str) – One of “” for uncompressed files, “gzip”, “bz2” or “lzip”
Returns:

A function that takes an empty string as input, and fills in that string. The function should return False EOF has been reached, True otherwise

Module contents