text
stringlengths
81
112k
Get a Series of benchmark returns from IEX associated with `symbol`. Default is `SPY`. Parameters ---------- symbol : str Benchmark symbol for which we're getting the returns. The data is provided by IEX (https://iextrading.com/), and we can get up to 5 years worth of data. def get_be...
Surround `content` with the first and last characters of `delimiters`. >>> delimit('[]', "foo") # doctest: +SKIP '[foo]' >>> delimit('""', "foo") # doctest: +SKIP '"foo"' def delimit(delimiters, content): """ Surround `content` with the first and last characters of `delimiters`. >>> del...
Get nodes from graph G with indegree 0 def roots(g): "Get nodes from graph G with indegree 0" return set(n for n, d in iteritems(g.in_degree()) if d == 0)
Draw `g` as a graph to `out`, in format `format`. Parameters ---------- g : zipline.pipeline.graph.TermGraph Graph to render. out : file-like object format_ : str {'png', 'svg'} Output format. include_asset_exists : bool Whether to filter out `AssetExists()` nodes. def ...
Display a TermGraph interactively from within IPython. def display_graph(g, format='svg', include_asset_exists=False): """ Display a TermGraph interactively from within IPython. """ try: import IPython.display as display except ImportError: raise NoIPython("IPython is not installed....
Format key, value pairs from attrs into graphviz attrs format Examples -------- >>> format_attrs({'key1': 'value1', 'key2': 'value2'}) # doctest: +SKIP '[key1=value1, key2=value2]' def format_attrs(attrs): """ Format key, value pairs from attrs into graphviz attrs format Examples ---...
Apply a function but emulate the API of an asynchronous call. Parameters ---------- f : callable The function to call. args : tuple, optional The positional arguments. kwargs : dict, optional The keyword arguments. Returns ---...
Optionally show a progress bar for the given iterator. Parameters ---------- it : iterable The underlying iterator. show_progress : bool Should progress be shown. **kwargs Forwarded to the click progress bar. Returns ------- itercontext : context manager ...
Top level zipline entry point. def main(extension, strict_extensions, default_extension, x): """Top level zipline entry point. """ # install a logbook handler before performing any other operations logbook.StderrHandler().push_application() create_args(x, zipline.extension_args) load_extension...
Mark that an option should only be exposed in IPython. Parameters ---------- option : decorator A click.option decorator. Returns ------- ipython_only_dec : decorator A decorator that correctly applies the argument even when not using IPython mode. def ipython_only(opt...
Run a backtest for the given algorithm. def run(ctx, algofile, algotext, define, data_frequency, capital_base, bundle, bundle_timestamp, start, end, output, trading_calendar, print_algo, metrics_set, local_n...
The zipline IPython cell magic. def zipline_magic(line, cell=None): """The zipline IPython cell magic. """ load_extensions( default=True, extensions=[], strict=True, environ=os.environ, ) try: return run.main( # put our overrides at the start of t...
Ingest the data for the given bundle. def ingest(bundle, assets_version, show_progress): """Ingest the data for the given bundle. """ bundles_module.ingest( bundle, os.environ, pd.Timestamp.utcnow(), assets_version, show_progress, )
Clean up data downloaded with the ingest command. def clean(bundle, before, after, keep_last): """Clean up data downloaded with the ingest command. """ bundles_module.clean( bundle, before, after, keep_last, )
List all of the available data bundles. def bundles(): """List all of the available data bundles. """ for bundle in sorted(bundles_module.bundles.keys()): if bundle.startswith('.'): # hide the test data continue try: ingestions = list( map...
Factory function for making binary operator methods on a Filter subclass. Returns a function "binary_operator" suitable for implementing functions like __and__ or __or__. def binary_operator(op): """ Factory function for making binary operator methods on a Filter subclass. Returns a function "bin...
Factory function for making unary operator methods for Filters. def unary_operator(op): """ Factory function for making unary operator methods for Filters. """ valid_ops = {'~'} if op not in valid_ops: raise ValueError("Invalid unary operator %s." % op) def unary_operator(self): ...
Helper for creating new NumExprFactors. This is just a wrapper around NumericalExpression.__new__ that always forwards `bool` as the dtype, since Filters can only be of boolean dtype. def create(cls, expr, binds): """ Helper for creating new NumExprFactors. This is jus...
Compute our result with numexpr, then re-apply `mask`. def _compute(self, arrays, dates, assets, mask): """ Compute our result with numexpr, then re-apply `mask`. """ return super(NumExprFilter, self)._compute( arrays, dates, assets, mask,...
Ensure that our percentile bounds are well-formed. def _validate(self): """ Ensure that our percentile bounds are well-formed. """ if not 0.0 <= self._min_percentile < self._max_percentile <= 100.0: raise BadPercentileBounds( min_percentile=self._min_percenti...
For each row in the input, compute a mask of all values falling between the given percentiles. def _compute(self, arrays, dates, assets, mask): """ For each row in the input, compute a mask of all values falling between the given percentiles. """ # TODO: Review whether t...
Parse a treasury CSV column into a more human-readable format. Columns start with 'RIFLGFC', followed by Y or M (year or month), followed by a two-digit number signifying number of years/months, followed by _N.B. We only care about the middle two entries, which we turn into a string like 3month or 30ye...
Download daily 10 year treasury rates from the Federal Reserve and return a pandas.Series. def get_daily_10yr_treasury_data(): """Download daily 10 year treasury rates from the Federal Reserve and return a pandas.Series.""" url = "https://www.federalreserve.gov/datadownload/Output.aspx?rel=H15" \ ...
Format subdir path to limit the number directories in any given subdirectory to 100. The number in each directory is designed to support at least 100000 equities. Parameters ---------- sid : int Asset identifier. Returns ------- out : string A path for the bcolz ro...
Adapt OHLCV columns into uint32 columns. Parameters ---------- cols : dict A dict mapping each column name (open, high, low, close, volume) to a float column to convert to uint32. scale_factor : int Factor to use to scale float values before converting to uint32. sid : int ...
Write the metadata to a JSON file in the rootdir. Values contained in the metadata are: version : int The value of FORMAT_VERSION of this class. ohlc_ratio : int The default ratio by which to multiply the pricing data to convert the floats from floats to an ...
Open an existing ``rootdir`` for writing. Parameters ---------- end_session : Timestamp (optional) When appending, the intended new ``end_session``. def open(cls, rootdir, end_session=None): """ Open an existing ``rootdir`` for writing. Parameters -...
Parameters ---------- sid : int Asset identifier. Returns ------- out : string Full path to the bcolz rootdir for the given sid. def sidpath(self, sid): """ Parameters ---------- sid : int Asset identifier. ...
Parameters ---------- sid : int Asset identifier. Returns ------- out : pd.Timestamp The midnight of the last date written in to the output for the given sid. def last_date_in_output_for_sid(self, sid): """ Parameters ...
Create empty ctable for given path. Parameters ---------- path : string The path to rootdir of the new ctable. def _init_ctable(self, path): """ Create empty ctable for given path. Parameters ---------- path : string The path to ...
Ensure that a ctable exists for ``sid``, then return it. def _ensure_ctable(self, sid): """Ensure that a ctable exists for ``sid``, then return it.""" sidpath = self.sidpath(sid) if not os.path.exists(sidpath): return self._init_ctable(sidpath) return bcolz.ctable(rootdir=si...
Fill sid container with empty data through the specified date. If the last recorded trade is not at the close, then that day will be padded with zeros until its close. Any day after that (up to and including the specified date) will be padded with `minute_per_day` worth of zeros ...
Write all the supplied kwargs as attributes of the sid's file. def set_sid_attrs(self, sid, **kwargs): """Write all the supplied kwargs as attributes of the sid's file. """ table = self._ensure_ctable(sid) for k, v in kwargs.items(): table.attrs[k] = v
Write a stream of minute data. Parameters ---------- data : iterable[(int, pd.DataFrame)] The data to write. Each element should be a tuple of sid, data where data has the following format: columns : ('open', 'high', 'low', 'close', 'volume') ...
Write the OHLCV data for the given sid. If there is no bcolz ctable yet created for the sid, create it. If the length of the bcolz ctable is not exactly to the date before the first day provided, fill the ctable with 0s up to that date. Parameters ---------- sid : int ...
Write the OHLCV data for the given sid. If there is no bcolz ctable yet created for the sid, create it. If the length of the bcolz ctable is not exactly to the date before the first day provided, fill the ctable with 0s up to that date. Parameters ---------- sid : int ...
Internal method for `write_cols` and `write`. Parameters ---------- sid : int The asset identifier for the data being written. dts : datetime64 array The dts corresponding to values in cols. cols : dict of str -> np.array dict of market data w...
Return the number of data points up to and including the provided day. def data_len_for_day(self, day): """ Return the number of data points up to and including the provided day. """ day_ix = self._session_labels.get_loc(day) # Add one to the 0-indexed day_ix to ...
Truncate data beyond this date in all ctables. def truncate(self, date): """Truncate data beyond this date in all ctables.""" truncate_slice_end = self.data_len_for_day(date) glob_path = os.path.join(self._rootdir, "*", "*", "*.bcolz") sid_paths = sorted(glob(glob_path)) for s...
Calculate the minutes which should be excluded when a window occurs on days which had an early close, i.e. days where the close based on the regular period of minutes per day and the market close do not match. Returns ------- List of DatetimeIndex representing the minute...
Build an interval tree keyed by the start and end of each range of positions should be dropped from windows. (These are the minutes between an early close and the minute which would be the close based on the regular period if there were no early close.) The value of each node is the same...
Returns ------- List of tuples of (start, stop) which represent the ranges of minutes which should be excluded when a market minute window is requested. def _exclusion_indices_for_range(self, start_idx, end_idx): """ Returns ------- List of tuples of (start, stop...
Retrieve the pricing info for the given sid, dt, and field. Parameters ---------- sid : int Asset identifier. dt : datetime-like The datetime at which the trade occurred. field : string The type of pricing data to retrieve. ('open'...
Internal method that returns the position of the given minute in the list of every trading minute since market open of the first trading day. Adjusts non market minutes to the last close. ex. this method would return 1 for 2002-01-02 9:32 AM Eastern, if 2002-01-02 is the first trading d...
Parameters ---------- fields : list of str 'open', 'high', 'low', 'close', or 'volume' start_dt: Timestamp Beginning of the window range. end_dt: Timestamp End of the window range. sids : list of int The asset identifiers in the window....
Write the frames to the target HDF5 file, using the format used by ``pd.Panel.to_hdf`` Parameters ---------- frames : iter[(int, DataFrame)] or dict[int -> DataFrame] An iterable or other mapping of sid to the corresponding OHLCV pricing data. def write(self, fr...
Construct an index array that, when applied to an array of values, produces a 2D array containing the values associated with the next event for each sid at each moment in time. Locations where no next event was known will be filled with -1. Parameters ---------- all_dates : ndarray[datetime64[...
Construct an index array that, when applied to an array of values, produces a 2D array containing the values associated with the previous event for each sid at each moment in time. Locations where no previous event was known will be filled with -1. Parameters ---------- data_query_cutoff : pd....
Determine the last piece of information known on each date in the date index for each group. Input df MUST be sorted such that the correct last item is chosen from each group. Parameters ---------- df : pd.DataFrame The DataFrame containing the data to be grouped. Must be sorted so that ...
Forward fill values in a DataFrame with special logic to handle cases that pd.DataFrame.ffill cannot and cast columns to appropriate types. Parameters ---------- df : pd.DataFrame The DataFrame to do forward-filling on. columns : list of BoundColumn The BoundColumns that correspond ...
Shift dates of a pipeline query back by `shift` days. load_adjusted_array is called with dates on which the user's algo will be shown data, which means we need to return the data that would be known at the start of each date. This is often labeled with a previous date in the underlying data (e.g. at t...
Template ``formatters`` into ``docstring``. Parameters ---------- owner_name : str The name of the function or class whose docstring is being templated. Only used for error messages. docstring : str The docstring to template. formatters : dict[str -> str] Parameters ...
Decorator allowing the use of templated docstrings. Examples -------- >>> @templated_docstring(foo='bar') ... def my_func(self, foo): ... '''{foo}''' ... >>> my_func.__doc__ 'bar' def templated_docstring(**docs): """ Decorator allowing the use of templated docstrings. ...
Add a column. The results of computing `term` will show up as a column in the DataFrame produced by running this pipeline. Parameters ---------- column : zipline.pipeline.Term A Filter, Factor, or Classifier to add to the pipeline. name : str Nam...
Set a screen on this Pipeline. Parameters ---------- filter : zipline.pipeline.Filter The filter to apply as a screen. overwrite : bool Whether to overwrite any existing screen. If overwrite is False and self.screen is not None, we raise an error. d...
Compile into an ExecutionPlan. Parameters ---------- domain : zipline.pipeline.domain.Domain Domain on which the pipeline will be executed. default_screen : zipline.pipeline.term.Term Term to use as a screen if self.screen is None. all_dates : pd.Datetime...
Helper for to_graph and to_execution_plan. def _prepare_graph_terms(self, default_screen): """Helper for to_graph and to_execution_plan.""" columns = self.columns.copy() screen = self.screen if screen is None: screen = default_screen columns[SCREEN_NAME] = screen ...
Render this Pipeline as a DAG. Parameters ---------- format : {'svg', 'png', 'jpeg'} Image format to render with. Default is 'svg'. def show_graph(self, format='svg'): """ Render this Pipeline as a DAG. Parameters ---------- format : {'svg'...
A list of terms that are outputs of this pipeline. Includes all terms registered as data outputs of the pipeline, plus the screen, if present. def _output_terms(self): """ A list of terms that are outputs of this pipeline. Includes all terms registered as data outputs of the p...
Get the domain for this pipeline. - If an explicit domain was provided at construction time, use it. - Otherwise, infer a domain from the registered columns. - If no domain can be inferred, return ``default``. Parameters ---------- default : zipline.pipeline.Domain ...
Create a tuple containing all elements of tup, plus elem. Returns the new tuple and the index of elem in the new tuple. def _ensure_element(tup, elem): """ Create a tuple containing all elements of tup, plus elem. Returns the new tuple and the index of elem in the new tuple. """ try: ...
Ensure that our expression string has variables of the form x_0, x_1, ... x_(N - 1), where N is the length of our inputs. def _validate(self): """ Ensure that our expression string has variables of the form x_0, x_1, ... x_(N - 1), where N is the length of our inputs. """ ...
Compute our stored expression string with numexpr. def _compute(self, arrays, dates, assets, mask): """ Compute our stored expression string with numexpr. """ out = full(mask.shape, self.missing_value, dtype=self.dtype) # This writes directly into our output buffer. nume...
Return self._expr with all variables rebound to the indices implied by new_inputs. def _rebind_variables(self, new_inputs): """ Return self._expr with all variables rebound to the indices implied by new_inputs. """ expr = self._expr # If we have 11+ variables, s...
Merge the inputs of two NumericalExpressions into a single input tuple, rewriting their respective string expressions to make input names resolve correctly. Returns a tuple of (new_self_expr, new_other_expr, new_inputs) def _merge_expressions(self, other): """ Merge the inputs ...
Compute new expression strings and a new inputs tuple for combining self and other with a binary operator. def build_binary_op(self, op, other): """ Compute new expression strings and a new inputs tuple for combining self and other with a binary operator. """ if isinstan...
Short repr to use when rendering Pipeline graphs. def graph_repr(self): """Short repr to use when rendering Pipeline graphs.""" # Replace any floating point numbers in the expression # with their scientific notation final = re.sub(r"[-+]?\d*\.\d+", lambda x: form...
Get the last modified time of path as a Timestamp. def last_modified_time(path): """ Get the last modified time of path as a Timestamp. """ return pd.Timestamp(os.path.getmtime(path), unit='s', tz='UTC')
Get the root directory for all zipline-managed files. For testing purposes, this accepts a dictionary to interpret as the os environment. Parameters ---------- environ : dict, optional A dict to interpret as the os environment. Returns ------- root : string Path to the...
Build a dict of Adjustment objects in the format expected by AdjustedArray. Returns a dict of the form: { # Integer index into `dates` for the date on which we should # apply the list of adjustments. 1 : [ Float64Multiply(first_row=2, last_row...
Load data from our stored baseline. def load_adjusted_array(self, domain, columns, dates, sids, mask): """ Load data from our stored baseline. """ if len(columns) != 1: raise ValueError( "Can't load multiple columns with DataFrameLoader" ) ...
Make sure a passed column is our column. def _validate_input_column(self, column): """Make sure a passed column is our column. """ if column != self.column and column.unspecialize() != self.column: raise ValueError("Can't load unknown column %s" % column)
To resolve the symbol in the LEVERAGED_ETF list, the date on which the symbol was in effect is needed. Furthermore, to maintain a point in time record of our own maintenance of the restricted list, we need a knowledge date. Thus, restricted lists are dictionaries of datetime->symbol lists. new symb...
Users should only access the lru_cache through its public API: cache_info, cache_clear The internals of the lru_cache are encapsulated for thread safety and to allow the implementation to change. def _weak_lru_cache(maxsize=100): """ Users should only access the lru_cache through its public API: ...
Weak least-recently-used cache decorator. If *maxsize* is set to None, the LRU features are disabled and the cache can grow without bound. Arguments to the cached function must be hashable. Any that are weak- referenceable will be stored by weak reference. Once any of the args have been garbage c...
Checks if `name` is a `final` object in the given `mro`. We need to check the mro because we need to directly go into the __dict__ of the classes. Because `final` objects are descriptor, we need to grab them _BEFORE_ the `__call__` is invoked. def is_final(name, mro): """ Checks if `name` is a `fin...
Bind a `Column` object to its name. def bind(self, name): """ Bind a `Column` object to its name. """ return _BoundColumnDescr( dtype=self.dtype, missing_value=self.missing_value, name=name, doc=self.doc, metadata=self.metadata...
Specialize ``self`` to a concrete domain. def specialize(self, domain): """Specialize ``self`` to a concrete domain. """ if domain == self.domain: return self return type(self)( dtype=self.dtype, missing_value=self.missing_value, dataset=...
Look up a column by name. Parameters ---------- name : str Name of the column to look up. Returns ------- column : zipline.pipeline.data.BoundColumn Column with the given name. Raises ------ AttributeError If ...
Construct a new dataset given the coordinates. def _make_dataset(cls, coords): """Construct a new dataset given the coordinates. """ class Slice(cls._SliceType): extra_coords = coords Slice.__name__ = '%s.slice(%s)' % ( cls.__name__, ', '.join('%s=%r...
Take a slice of a DataSetFamily to produce a dataset indexed by asset and date. Parameters ---------- *args **kwargs The coordinates to fix along each extra dimension. Returns ------- dataset : DataSet A regular pipeline dataset i...
Check that the raw value for an asset/date/column triple is as expected. Used by tests to verify data written by a writer. def expected_bar_value(asset_id, date, colname): """ Check that the raw value for an asset/date/column triple is as expected. Used by tests to verify data written by a wr...
Return an 2D array containing cls.expected_value(asset_id, date, colname) for each date/asset pair in the inputs. Missing locs are filled with 0 for volume and NaN for price columns: - Values before/after an asset's lifetime. - Values for asset_ids not contained in asset_info. - Locs d...
Load by delegating to sub-loaders. def load_adjusted_array(self, domain, columns, dates, sids, mask): """ Load by delegating to sub-loaders. """ out = {} for col in columns: try: loader = self._loaders.get(col) if loader is None: ...
Make a random array of shape (len(dates), len(sids)) with ``dtype``. def values(self, dtype, dates, sids): """ Make a random array of shape (len(dates), len(sids)) with ``dtype``. """ shape = (len(dates), len(sids)) return { datetime64ns_dtype: self._datetime_values,...
Return uniformly-distributed floats between -0.0 and 100.0. def _float_values(self, shape): """ Return uniformly-distributed floats between -0.0 and 100.0. """ return self.state.uniform(low=0.0, high=100.0, size=shape)
Return uniformly-distributed integers between 0 and 100. def _int_values(self, shape): """ Return uniformly-distributed integers between 0 and 100. """ return (self.state.randint(low=0, high=100, size=shape) .astype('int64'))
Return uniformly-distributed dates in 2014. def _datetime_values(self, shape): """ Return uniformly-distributed dates in 2014. """ start = Timestamp('2014', tz='UTC').asm8 offsets = self.state.randint( low=0, high=364, size=shape, ).as...
Compute rowwise array quantiles on an input. def quantiles(data, nbins_or_partition_bounds): """ Compute rowwise array quantiles on an input. """ return apply_along_axis( qcut, 1, data, q=nbins_or_partition_bounds, labels=False, )
Handles the close of the given minute in minute emission. Parameters ---------- dt : Timestamp The minute that is ending Returns ------- A minute perf packet. def handle_minute_close(self, dt, data_portal): """ Handles the close of the given...
Handles the start of each session. Parameters ---------- session_label : Timestamp The label of the session that is about to begin. data_portal : DataPortal The current data portal. def handle_market_open(self, session_label, data_portal): """Handles the...
Handles the close of the given day. Parameters ---------- dt : Timestamp The most recently completed simulation datetime. data_portal : DataPortal The current data portal. Returns ------- A daily perf packet. def handle_market_close(self...
When the simulation is complete, run the full period risk report and send it out on the results socket. def handle_simulation_end(self, data_portal): """ When the simulation is complete, run the full period risk report and send it out on the results socket. """ log.info(...
Encapsulates a set of custom command line arguments in key=value or key.namespace=value form into a chain of Namespace objects, where each next level is an attribute of the Namespace object on the current level Parameters ---------- args : list A list of strings representing arguments i...
Converts argument strings in key=value or key.namespace=value form to dictionary entries Parameters ---------- arg : str The argument string to parse, which must be in key=value or key.namespace=value form. arg_dict : dict The dictionary into which the key/value pair will be...
A recursive function that takes a root element, list of namespaces, and the value being stored, and assigns namespaces to the root object via a chain of Namespace objects, connected through attributes Parameters ---------- namespace : Namespace The object onto which an attribute will be add...
Create a new registry for an extensible interface. Parameters ---------- interface : type The abstract data type for which to create a registry, which will manage registration of factories for this type. Returns ------- interface : type The data type specified/decorated...
Construct an object from a registered factory. Parameters ---------- name : str Name with which the factory was registered. def load(self, name): """Construct an object from a registered factory. Parameters ---------- name : str Name wit...
If there is a minimum commission: If the order hasn't had a commission paid yet, pay the minimum commission. If the order has paid a commission, start paying additional commission once the minimum commission has been reached. If there is no minimum commission: Pay commissio...
Pay commission based on dollar value of shares. def calculate(self, order, transaction): """ Pay commission based on dollar value of shares. """ cost_per_share = transaction.price * self.cost_per_dollar return abs(transaction.amount) * cost_per_share