Code
stringlengths
103
85.9k
Summary
listlengths
0
94
Please provide a description of the function:def naive_grouped_rowwise_apply(data, group_labels, func, func_args=(), out=None): if out is None: out = np.empty_like(data) ...
[ "\n Simple implementation of grouped row-wise function application.\n\n Parameters\n ----------\n data : ndarray[ndim=2]\n Input array over which to apply a grouped function.\n group_labels : ndarray[ndim=2, dtype=int64]\n Labels to use to bucket inputs from array.\n Should be th...
Please provide a description of the function:def bulleted_list(items, indent=0, bullet_type='-'): format_string = ' ' * indent + bullet_type + ' {}' return "\n".join(map(format_string.format, items))
[ "Format a bulleted list of values.\n\n Parameters\n ----------\n items : sequence\n The items to make a list.\n indent : int, optional\n The number of spaces to add before each bullet.\n bullet_type : str, optional\n The bullet type to use.\n\n Returns\n -------\n format...
Please provide a description of the function:def make_rotating_equity_info(num_assets, first_start, frequency, periods_between_starts, asset_lifetime, exchange='TEST'): ...
[ "\n Create a DataFrame representing lifetimes of assets that are constantly\n rotating in and out of existence.\n\n Parameters\n ----------\n num_assets : int\n How many assets to create.\n first_start : pd.Timestamp\n The start date for the first asset.\n frequency : str or pd.ts...
Please provide a description of the function:def make_simple_equity_info(sids, start_date, end_date, symbols=None, names=None, exchange='TEST'): num_assets = len(sids) ...
[ "\n Create a DataFrame representing assets that exist for the full duration\n between `start_date` and `end_date`.\n\n Parameters\n ----------\n sids : array-like of int\n start_date : pd.Timestamp, optional\n end_date : pd.Timestamp, optional\n symbols : list, optional\n Symbols to u...
Please provide a description of the function:def make_simple_multi_country_equity_info(countries_to_sids, countries_to_exchanges, start_date, end_date): sids = [] symbols = [] e...
[ "Create a DataFrame representing assets that exist for the full duration\n between `start_date` and `end_date`, from multiple countries.\n " ]
Please provide a description of the function:def make_jagged_equity_info(num_assets, start_date, first_end, frequency, periods_between_ends, auto_close_delta): frame = pd....
[ "\n Create a DataFrame representing assets that all begin at the same start\n date, but have cascading end dates.\n\n Parameters\n ----------\n num_assets : int\n How many assets to create.\n start_date : pd.Timestamp\n The start date for all the assets.\n first_end : pd.Timestamp...
Please provide a description of the function:def make_future_info(first_sid, root_symbols, years, notice_date_func, expiration_date_func, start_date_func, month_codes=None, ...
[ "\n Create a DataFrame representing futures for `root_symbols` during `year`.\n\n Generates a contract per triple of (symbol, year, month) supplied to\n `root_symbols`, `years`, and `month_codes`.\n\n Parameters\n ----------\n first_sid : int\n The first sid to use for assigning sids to the...
Please provide a description of the function:def make_commodity_future_info(first_sid, root_symbols, years, month_codes=None, multiplier=500): nineteen_days = pd.Timedelta(days=19) on...
[ "\n Make futures testing data that simulates the notice/expiration date\n behavior of physical commodities like oil.\n\n Parameters\n ----------\n first_sid : int\n The first sid to use for assigning sids to the created contracts.\n root_symbols : list[str]\n A list of root symbols f...
Please provide a description of the function:def eq(self, other): # We treat this as an error because missing_values have NaN semantics, # which means this would return an array of all False, which is almost # certainly not what the user wants. if other == self.missing_value: ...
[ "\n Construct a Filter returning True for asset/date pairs where the output\n of ``self`` matches ``other``.\n " ]
Please provide a description of the function:def startswith(self, prefix): return ArrayPredicate( term=self, op=LabelArray.startswith, opargs=(prefix,), )
[ "\n Construct a Filter matching values starting with ``prefix``.\n\n Parameters\n ----------\n prefix : str\n String prefix against which to compare values produced by ``self``.\n\n Returns\n -------\n matches : Filter\n Filter returning True fo...
Please provide a description of the function:def endswith(self, suffix): return ArrayPredicate( term=self, op=LabelArray.endswith, opargs=(suffix,), )
[ "\n Construct a Filter matching values ending with ``suffix``.\n\n Parameters\n ----------\n suffix : str\n String suffix against which to compare values produced by ``self``.\n\n Returns\n -------\n matches : Filter\n Filter returning True for ...
Please provide a description of the function:def has_substring(self, substring): return ArrayPredicate( term=self, op=LabelArray.has_substring, opargs=(substring,), )
[ "\n Construct a Filter matching values containing ``substring``.\n\n Parameters\n ----------\n substring : str\n Sub-string against which to compare values produced by ``self``.\n\n Returns\n -------\n matches : Filter\n Filter returning True fo...
Please provide a description of the function:def matches(self, pattern): return ArrayPredicate( term=self, op=LabelArray.matches, opargs=(pattern,), )
[ "\n Construct a Filter that checks regex matches against ``pattern``.\n\n Parameters\n ----------\n pattern : str\n Regex pattern against which to compare values produced by ``self``.\n\n Returns\n -------\n matches : Filter\n Filter returning T...
Please provide a description of the function:def element_of(self, choices): try: choices = frozenset(choices) except Exception as e: raise TypeError( "Expected `choices` to be an iterable of hashable values," " but got {} instead.\n" ...
[ "\n Construct a Filter indicating whether values are in ``choices``.\n\n Parameters\n ----------\n choices : iterable[str or int]\n An iterable of choices.\n\n Returns\n -------\n matches : Filter\n Filter returning True for all sid/date pairs f...
Please provide a description of the function:def to_workspace_value(self, result, assets): if self.dtype == int64_dtype: return super(Classifier, self).to_workspace_value(result, assets) assert isinstance(result.values, pd.Categorical), ( 'Expected a Categorical, got %r...
[ "\n Called with the result of a pipeline. This needs to return an object\n which can be put into the workspace to continue doing computations.\n\n This is the inverse of :func:`~zipline.pipeline.term.Term.postprocess`.\n " ]
Please provide a description of the function:def _to_integral(self, output_array): if self.dtype == int64_dtype: group_labels = output_array null_label = self.missing_value elif self.dtype == categorical_dtype: # Coerce LabelArray into an isomorphic array of ...
[ "\n Convert an array produced by this classifier into an array of integer\n labels and a missing value label.\n " ]
Please provide a description of the function:def _allocate_output(self, windows, shape): if self.dtype == int64_dtype: return super(CustomClassifier, self)._allocate_output( windows, shape, ) # This is a little bit of a hack. We might no...
[ "\n Override the default array allocation to produce a LabelArray when we\n have a string-like dtype.\n " ]
Please provide a description of the function:def verify_indices_all_unique(obj): axis_names = [ ('index',), # Series ('index', 'columns'), # DataFrame ('items', 'major_axis', 'minor_axis') # Panel ][obj.ndim - 1] # ndim = 1 should go to ...
[ "\n Check that all axes of a pandas object are unique.\n\n Parameters\n ----------\n obj : pd.Series / pd.DataFrame / pd.Panel\n The object to validate.\n\n Returns\n -------\n obj : pd.Series / pd.DataFrame / pd.Panel\n The validated object, unchanged.\n\n Raises\n ------\n...
Please provide a description of the function:def optionally(preprocessor): @wraps(preprocessor) def wrapper(func, argname, arg): return arg if arg is None else preprocessor(func, argname, arg) return wrapper
[ "Modify a preprocessor to explicitly allow `None`.\n\n Parameters\n ----------\n preprocessor : callable[callable, str, any -> any]\n A preprocessor to delegate to when `arg is not None`.\n\n Returns\n -------\n optional_preprocessor : callable[callable, str, any -> any]\n A preproce...
Please provide a description of the function:def ensure_dtype(func, argname, arg): try: return dtype(arg) except TypeError: raise TypeError( "{func}() couldn't convert argument " "{argname}={arg!r} to a numpy dtype.".format( func=_qualified_name(func)...
[ "\n Argument preprocessor that converts the input into a numpy dtype.\n\n Examples\n --------\n >>> import numpy as np\n >>> from zipline.utils.preprocess import preprocess\n >>> @preprocess(dtype=ensure_dtype)\n ... def foo(dtype):\n ... return dtype\n ...\n >>> foo(float)\n dt...
Please provide a description of the function:def ensure_timezone(func, argname, arg): if isinstance(arg, tzinfo): return arg if isinstance(arg, string_types): return timezone(arg) raise TypeError( "{func}() couldn't convert argument " "{argname}={arg!r} to a timezone."....
[ "Argument preprocessor that converts the input into a tzinfo object.\n\n Examples\n --------\n >>> from zipline.utils.preprocess import preprocess\n >>> @preprocess(tz=ensure_timezone)\n ... def foo(tz):\n ... return tz\n >>> foo('utc')\n <UTC>\n " ]
Please provide a description of the function:def ensure_timestamp(func, argname, arg): try: return pd.Timestamp(arg) except ValueError as e: raise TypeError( "{func}() couldn't convert argument " "{argname}={arg!r} to a pandas Timestamp.\n" "Original erro...
[ "Argument preprocessor that converts the input into a pandas Timestamp\n object.\n\n Examples\n --------\n >>> from zipline.utils.preprocess import preprocess\n >>> @preprocess(ts=ensure_timestamp)\n ... def foo(ts):\n ... return ts\n >>> foo('2014-01-01')\n Timestamp('2014-01-01 00:0...
Please provide a description of the function:def expect_dtypes(__funcname=_qualified_name, **named): for name, type_ in iteritems(named): if not isinstance(type_, (dtype, tuple)): raise TypeError( "expect_dtypes() expected a numpy dtype or tuple of dtypes" " ...
[ "\n Preprocessing decorator that verifies inputs have expected numpy dtypes.\n\n Examples\n --------\n >>> from numpy import dtype, arange, int8, float64\n >>> @expect_dtypes(x=dtype(int8))\n ... def foo(x, y):\n ... return x, y\n ...\n >>> foo(arange(3, dtype=int8), 'foo')\n (array...
Please provide a description of the function:def expect_kinds(**named): for name, kind in iteritems(named): if not isinstance(kind, (str, tuple)): raise TypeError( "expect_dtype_kinds() expected a string or tuple of strings" " for argument {name!r}, but got {...
[ "\n Preprocessing decorator that verifies inputs have expected dtype kinds.\n\n Examples\n --------\n >>> from numpy import int64, int32, float32\n >>> @expect_kinds(x='i')\n ... def foo(x):\n ... return x\n ...\n >>> foo(int64(2))\n 2\n >>> foo(int32(2))\n 2\n >>> foo(floa...
Please provide a description of the function:def expect_types(__funcname=_qualified_name, **named): for name, type_ in iteritems(named): if not isinstance(type_, (type, tuple)): raise TypeError( "expect_types() expected a type or tuple of types for " "argumen...
[ "\n Preprocessing decorator that verifies inputs have expected types.\n\n Examples\n --------\n >>> @expect_types(x=int, y=str)\n ... def foo(x, y):\n ... return x, y\n ...\n >>> foo(2, '3')\n (2, '3')\n >>> foo(2.0, '3') # doctest: +NORMALIZE_WHITESPACE +ELLIPSIS\n Traceback (m...
Please provide a description of the function:def make_check(exc_type, template, pred, actual, funcname): if isinstance(funcname, str): def get_funcname(_): return funcname else: get_funcname = funcname def _check(func, argname, argvalue): if pred(argvalue): ...
[ "\n Factory for making preprocessing functions that check a predicate on the\n input value.\n\n Parameters\n ----------\n exc_type : Exception\n The exception type to raise if the predicate fails.\n template : str\n A template string to use to create error messages.\n Should h...
Please provide a description of the function:def expect_element(__funcname=_qualified_name, **named): def _expect_element(collection): if isinstance(collection, (set, frozenset)): # Special case the error message for set and frozen set to make it # less verbose. coll...
[ "\n Preprocessing decorator that verifies inputs are elements of some\n expected collection.\n\n Examples\n --------\n >>> @expect_element(x=('a', 'b'))\n ... def foo(x):\n ... return x.upper()\n ...\n >>> foo('a')\n 'A'\n >>> foo('b')\n 'B'\n >>> foo('c') # doctest: +NORM...
Please provide a description of the function:def expect_bounded(__funcname=_qualified_name, **named): def _make_bounded_check(bounds): (lower, upper) = bounds if lower is None: def should_fail(value): return value > upper predicate_descr = "less than or e...
[ "\n Preprocessing decorator verifying that inputs fall INCLUSIVELY between\n bounds.\n\n Bounds should be passed as a pair of ``(min_value, max_value)``.\n\n ``None`` may be passed as ``min_value`` or ``max_value`` to signify that\n the input is only bounded above or below.\n\n Examples\n -----...
Please provide a description of the function:def expect_dimensions(__funcname=_qualified_name, **dimensions): if isinstance(__funcname, str): def get_funcname(_): return __funcname else: get_funcname = __funcname def _expect_dimension(expected_ndim): def _check(func...
[ "\n Preprocessing decorator that verifies inputs are numpy arrays with a\n specific dimensionality.\n\n Examples\n --------\n >>> from numpy import array\n >>> @expect_dimensions(x=1, y=2)\n ... def foo(x, y):\n ... return x[0] + y[0, 0]\n ...\n >>> foo(array([1, 1]), array([[1, 1],...
Please provide a description of the function:def coerce(from_, to, **to_kwargs): def preprocessor(func, argname, arg): if isinstance(arg, from_): return to(arg, **to_kwargs) return arg return preprocessor
[ "\n A preprocessing decorator that coerces inputs of a given type by passing\n them to a callable.\n\n Parameters\n ----------\n from : type or tuple or types\n Inputs types on which to call ``to``.\n to : function\n Coercion function to call on inputs.\n **to_kwargs\n Addi...
Please provide a description of the function:def coerce_types(**kwargs): def _coerce(types): return coerce(*types) return preprocess(**valmap(_coerce, kwargs))
[ "\n Preprocessing decorator that applies type coercions.\n\n Parameters\n ----------\n **kwargs : dict[str -> (type, callable)]\n Keyword arguments mapping function parameter names to pairs of\n (from_type, to_type).\n\n Examples\n --------\n >>> @coerce_types(x=(float, int), y=...
Please provide a description of the function:def validate_keys(dict_, expected, funcname): expected = set(expected) received = set(dict_) missing = expected - received if missing: raise ValueError( "Missing keys in {}:\n" "Expected Keys: {}\n" "Received ...
[ "Validate that a dictionary has an expected set of keys.\n " ]
Please provide a description of the function:def enum(option, *options): options = (option,) + options rangeob = range(len(options)) try: inttype = _inttypes[int(np.log2(len(options) - 1)) // 8] except IndexError: raise OverflowError( 'Cannot store enums with more than ...
[ "\n Construct a new enum object.\n\n Parameters\n ----------\n *options : iterable of str\n The names of the fields for the enum.\n\n Returns\n -------\n enum\n A new enum collection.\n\n Examples\n --------\n >>> e = enum('a', 'b', 'c')\n >>> e\n <enum: ('a', 'b', ...
Please provide a description of the function:def oldest_frame(self, raw=False): if raw: return self.buffer.values[:, self._start_index, :] return self.buffer.iloc[:, self._start_index, :]
[ "\n Get the oldest frame in the panel.\n " ]
Please provide a description of the function:def extend_back(self, missing_dts): delta = len(missing_dts) if not delta: raise ValueError( 'missing_dts must be a non-empty index', ) self._window += delta self._pos += delta self....
[ "\n Resizes the buffer to hold a new window with a new cap_multiple.\n If cap_multiple is None, then the old cap_multiple is used.\n " ]
Please provide a description of the function:def get_current(self, item=None, raw=False, start=None, end=None): item_indexer = slice(None) if item: item_indexer = self.items.get_loc(item) start_index = self._start_index end_index = self._pos # get inital da...
[ "\n Get a Panel that is the current data in view. It is not safe to persist\n these objects because internal data might change\n " ]
Please provide a description of the function:def set_current(self, panel): where = slice(self._start_index, self._pos) self.buffer.values[:, where, :] = panel.values
[ "\n Set the values stored in our current in-view data to be values of the\n passed panel. The passed panel must have the same indices as the panel\n that would be returned by self.get_current.\n " ]
Please provide a description of the function:def _roll_data(self): self.buffer.values[:, :self._window, :] = \ self.buffer.values[:, -self._window:, :] self.date_buf[:self._window] = self.date_buf[-self._window:] self._pos = self._window
[ "\n Roll window worth of data up to position zero.\n Save the effort of having to expensively roll at each iteration\n " ]
Please provide a description of the function:def oldest_frame(self, raw=False): if raw: return self.buffer.values[:, self._oldest_frame_idx(), :] return self.buffer.iloc[:, self._oldest_frame_idx(), :]
[ "\n Get the oldest frame in the panel.\n " ]
Please provide a description of the function:def get_current(self): where = slice(self._oldest_frame_idx(), self._pos) major_axis = pd.DatetimeIndex(deepcopy(self.date_buf[where]), tz='utc') return pd.Panel(self.buffer.values[:, where, :], self.items, major_axis...
[ "\n Get a Panel that is the current data in view. It is not safe to persist\n these objects because internal data might change\n " ]
Please provide a description of the function:def check_triggers(self, price, dt): stop_reached, limit_reached, sl_stop_reached = \ self.check_order_triggers(price) if (stop_reached, limit_reached) \ != (self.stop_reached, self.limit_reached): self.dt = dt...
[ "\n Update internal state based on price triggers and the\n trade event's price.\n " ]
Please provide a description of the function:def check_order_triggers(self, current_price): if self.triggered: return (self.stop_reached, self.limit_reached, False) stop_reached = False limit_reached = False sl_stop_reached = False order_type = 0 i...
[ "\n Given an order and a trade event, return a tuple of\n (stop_reached, limit_reached).\n For market orders, will return (False, False).\n For stop orders, limit_reached will always be False.\n For limit orders, stop_reached will always be False.\n For stop limit orders a ...
Please provide a description of the function:def triggered(self): if self.stop is not None and not self.stop_reached: return False if self.limit is not None and not self.limit_reached: return False return True
[ "\n For a market order, True.\n For a stop order, True IFF stop_reached.\n For a limit order, True IFF limit_reached.\n " ]
Please provide a description of the function:def setup(self, np=np, numpy_version=numpy_version, StrictVersion=StrictVersion, new_pandas=new_pandas): if numpy_version >= StrictVersion('1.14'): self.old_opts = np.get_printoptions() np.set_printoptions(leg...
[ "Lives in zipline.__init__ for doctests." ]
Please provide a description of the function:def teardown(self, np=np): if self.old_err is not None: np.seterr(**self.old_err) if self.old_opts is not None: np.set_printoptions(**self.old_opts)
[ "Lives in zipline.__init__ for doctests." ]
Please provide a description of the function:def hash_args(*args, **kwargs): arg_string = '_'.join([str(arg) for arg in args]) kwarg_string = '_'.join([str(key) + '=' + str(value) for key, value in iteritems(kwargs)]) combined = ':'.join([arg_string, kwarg_string]) has...
[ "Define a unique string for any set of representable args." ]
Please provide a description of the function:def assert_datasource_protocol(event): assert event.type in DATASOURCE_TYPE # Done packets have no dt. if not event.type == DATASOURCE_TYPE.DONE: assert isinstance(event.dt, datetime) assert event.dt.tzinfo == pytz.utc
[ "Assert that an event meets the protocol for datasource outputs." ]
Please provide a description of the function:def assert_trade_protocol(event): assert_datasource_protocol(event) assert event.type == DATASOURCE_TYPE.TRADE assert isinstance(event.price, numbers.Real) assert isinstance(event.volume, numbers.Integral) assert isinstance(event.dt, datetime)
[ "Assert that an event meets the protocol for datasource TRADE outputs." ]
Please provide a description of the function:def date_sorted_sources(*sources): sorted_stream = heapq.merge(*(_decorate_source(s) for s in sources)) # Strip out key decoration for _, message in sorted_stream: yield message
[ "\n Takes an iterable of sources, generating namestrings and\n piping their output into date_sort.\n " ]
Please provide a description of the function:def create_daily_trade_source(sids, sim_params, asset_finder, trading_calendar): return create_trade_source( sids, timedelta(days=1), sim_params, ...
[ "\n creates trade_count trades for each sid in sids list.\n first trade will be on sim_params.start_session, and daily\n thereafter for each sid. Thus, two sids should result in two trades per\n day.\n " ]
Please provide a description of the function:def load_data_table(file, index_col, show_progress=False): with ZipFile(file) as zip_file: file_names = zip_file.namelist() assert len(file_names) == 1, "Expected a single file from Quandl." wiki_prices...
[ " Load data table from zip file provided by Quandl.\n " ]
Please provide a description of the function:def fetch_data_table(api_key, show_progress, retries): for _ in range(retries): try: if show_progress: log.info('Downloading WIKI metadata.') metadata = pd.read_csv( ...
[ " Fetch WIKI Prices data table from Quandl\n " ]
Please provide a description of the function:def quandl_bundle(environ, asset_db_writer, minute_bar_writer, daily_bar_writer, adjustment_writer, calendar, start_session, end_session, ...
[ "\n quandl_bundle builds a daily dataset using Quandl's WIKI Prices dataset.\n\n For more information on Quandl's API and how to obtain an API key,\n please visit https://docs.quandl.com/docs#section-authentication\n " ]
Please provide a description of the function:def download_with_progress(url, chunk_size, **progress_kwargs): resp = requests.get(url, stream=True) resp.raise_for_status() total_size = int(resp.headers['content-length']) data = BytesIO() with progressbar(length=total_size, **progress_kwargs) as...
[ "\n Download streaming data from a URL, printing progress information to the\n terminal.\n\n Parameters\n ----------\n url : str\n A URL that can be understood by ``requests.get``.\n chunk_size : int\n Number of bytes to read at a time from requests.\n **progress_kwargs\n F...
Please provide a description of the function:def download_without_progress(url): resp = requests.get(url) resp.raise_for_status() return BytesIO(resp.content)
[ "\n Download data from a URL, returning a BytesIO containing the loaded data.\n\n Parameters\n ----------\n url : str\n A URL that can be understood by ``requests.get``.\n\n Returns\n -------\n data : BytesIO\n A BytesIO containing the downloaded data.\n " ]
Please provide a description of the function:def minute_frame_to_session_frame(minute_frame, calendar): how = OrderedDict((c, _MINUTE_TO_SESSION_OHCLV_HOW[c]) for c in minute_frame.columns) labels = calendar.minute_index_to_session_labels(minute_frame.index) return minute_frame.g...
[ "\n Resample a DataFrame with minute data into the frame expected by a\n BcolzDailyBarWriter.\n\n Parameters\n ----------\n minute_frame : pd.DataFrame\n A DataFrame with the columns `open`, `high`, `low`, `close`, `volume`,\n and `dt` (minute dts)\n calendar : trading_calendars.trad...
Please provide a description of the function:def minute_to_session(column, close_locs, data, out): if column == 'open': _minute_to_session_open(close_locs, data, out) elif column == 'high': _minute_to_session_high(close_locs, data, out) elif column == 'low': _minute_to_session_l...
[ "\n Resample an array with minute data into an array with session data.\n\n This function assumes that the minute data is the exact length of all\n minutes in the sessions in the output.\n\n Parameters\n ----------\n column : str\n The `open`, `high`, `low`, `close`, or `volume` column.\n ...
Please provide a description of the function:def opens(self, assets, dt): market_open, prev_dt, dt_value, entries = self._prelude(dt, 'open') opens = [] session_label = self._trading_calendar.minute_to_session_label(dt) for asset in assets: if not asset.is_alive_fo...
[ "\n The open field's aggregation returns the first value that occurs\n for the day, if there has been no data on or before the `dt` the open\n is `nan`.\n\n Once the first non-nan open is seen, that value remains constant per\n asset for the remainder of the day.\n\n Return...
Please provide a description of the function:def highs(self, assets, dt): market_open, prev_dt, dt_value, entries = self._prelude(dt, 'high') highs = [] session_label = self._trading_calendar.minute_to_session_label(dt) for asset in assets: if not asset.is_alive_fo...
[ "\n The high field's aggregation returns the largest high seen between\n the market open and the current dt.\n If there has been no data on or before the `dt` the high is `nan`.\n\n Returns\n -------\n np.array with dtype=float64, in order of assets parameter.\n " ]
Please provide a description of the function:def lows(self, assets, dt): market_open, prev_dt, dt_value, entries = self._prelude(dt, 'low') lows = [] session_label = self._trading_calendar.minute_to_session_label(dt) for asset in assets: if not asset.is_alive_for_s...
[ "\n The low field's aggregation returns the smallest low seen between\n the market open and the current dt.\n If there has been no data on or before the `dt` the low is `nan`.\n\n Returns\n -------\n np.array with dtype=float64, in order of assets parameter.\n " ]
Please provide a description of the function:def closes(self, assets, dt): market_open, prev_dt, dt_value, entries = self._prelude(dt, 'close') closes = [] session_label = self._trading_calendar.minute_to_session_label(dt) def _get_filled_close(asset): ...
[ "\n The close field's aggregation returns the latest close at the given\n dt.\n If the close for the given dt is `nan`, the most recent non-nan\n `close` is used.\n If there has been no data on or before the `dt` the close is `nan`.\n\n Returns\n -------\n np....
Please provide a description of the function:def volumes(self, assets, dt): market_open, prev_dt, dt_value, entries = self._prelude(dt, 'volume') volumes = [] session_label = self._trading_calendar.minute_to_session_label(dt) for asset in assets: if not asset.is_al...
[ "\n The volume field's aggregation returns the sum of all volumes\n between the market open and the `dt`\n If there has been no data on or before the `dt` the volume is 0.\n\n Returns\n -------\n np.array with dtype=int64, in order of assets parameter.\n " ]
Please provide a description of the function:def infer_domain(terms): domains = {t.domain for t in terms} num_domains = len(domains) if num_domains == 0: return GENERIC elif num_domains == 1: return domains.pop() elif num_domains == 2 and GENERIC in domains: domains.rem...
[ "\n Infer the domain from a collection of terms.\n\n The algorithm for inferring domains is as follows:\n\n - If all input terms have a domain of GENERIC, the result is GENERIC.\n\n - If there is exactly one non-generic domain in the input terms, the result\n is that domain.\n\n - Otherwise, an ...
Please provide a description of the function:def roll_forward(self, dt): dt = pd.Timestamp(dt, tz='UTC') trading_days = self.all_sessions() try: return trading_days[trading_days.searchsorted(dt)] except IndexError: raise ValueError( "Date...
[ "\n Given a date, align it to the calendar of the pipeline's domain.\n\n Parameters\n ----------\n dt : pd.Timestamp\n\n Returns\n -------\n pd.Timestamp\n " ]
Please provide a description of the function:def days_and_sids_for_frames(frames): if not frames: days = np.array([], dtype='datetime64[ns]') sids = np.array([], dtype='int64') return days, sids # Ensure the indices and columns all match. check_indexes_all_same( [frame....
[ "\n Returns the date index and sid columns shared by a list of dataframes,\n ensuring they all match.\n\n Parameters\n ----------\n frames : list[pd.DataFrame]\n A list of dataframes indexed by day, with a column per sid.\n\n Returns\n -------\n days : np.array[datetime64[ns]]\n ...
Please provide a description of the function:def compute_asset_lifetimes(frames): # Build a 2D array (dates x sids), where an entry is True if all # fields are nan for the given day and sid. is_null_matrix = np.logical_and.reduce( [frames[field].isnull().values for field in FIELDS], ) i...
[ "\n Parameters\n ----------\n frames : dict[str, pd.DataFrame]\n A dict mapping each OHLCV field to a dataframe with a row for\n each date and a column for each sid, as passed to write().\n\n Returns\n -------\n start_date_ixs : np.array[int64]\n The index of the first date wi...
Please provide a description of the function:def write(self, country_code, frames, scaling_factors=None): if scaling_factors is None: scaling_factors = DEFAULT_SCALING_FACTORS with self.h5_file(mode='a') as h5_file: # ensure that the file version has been written ...
[ "Write the OHLCV data for one country to the HDF5 file.\n\n Parameters\n ----------\n country_code : str\n The ISO 3166 alpha-2 country code for this country.\n frames : dict[str, pd.DataFrame]\n A dict mapping each OHLCV field to a dataframe with a row\n ...
Please provide a description of the function:def write_from_sid_df_pairs(self, country_code, data, scaling_factors=None): data = list(data) if not data: empty_frame = pd.DataFrame( ...
[ "\n Parameters\n ----------\n country_code : str\n The ISO 3166 alpha-2 country code for this country.\n data : iterable[tuple[int, pandas.DataFrame]]\n The data chunks to write. Each chunk should be a tuple of\n sid and the data for that asset.\n ...
Please provide a description of the function:def from_file(cls, h5_file, country_code): if h5_file.attrs['version'] != VERSION: raise ValueError( 'mismatched version: file is of version %s, expected %s' % ( h5_file.attrs['version'], VE...
[ "\n Construct from an h5py.File and a country code.\n\n Parameters\n ----------\n h5_file : h5py.File\n An HDF5 daily pricing file.\n country_code : str\n The ISO 3166 alpha-2 country code for the country to read.\n " ]
Please provide a description of the function:def from_path(cls, path, country_code): return cls.from_file(h5py.File(path), country_code)
[ "\n Construct from a file path and a country code.\n\n Parameters\n ----------\n path : str\n The path to an HDF5 daily pricing file.\n country_code : str\n The ISO 3166 alpha-2 country code for the country to read.\n " ]
Please provide a description of the function:def load_raw_arrays(self, columns, start_date, end_date, assets): self._validate_timestamp(start_date) self._validate_timestamp(end_date) start =...
[ "\n Parameters\n ----------\n columns : list of str\n 'open', 'high', 'low', 'close', or 'volume'\n start_date: Timestamp\n Beginning of the window range.\n end_date: Timestamp\n End of the window range.\n assets : list of int\n The a...
Please provide a description of the function:def _make_sid_selector(self, assets): assets = np.array(assets) sid_selector = self.sids.searchsorted(assets) unknown = np.in1d(assets, self.sids, invert=True) sid_selector[unknown] = -1 return sid_selector
[ "\n Build an indexer mapping ``self.sids`` to ``assets``.\n\n Parameters\n ----------\n assets : list[int]\n List of assets requested by a caller of ``load_raw_arrays``.\n\n Returns\n -------\n index : np.array[int64]\n Index array containing th...
Please provide a description of the function:def _validate_assets(self, assets): missing_sids = np.setdiff1d(assets, self.sids) if len(missing_sids): raise NoDataForSid( 'Assets not contained in daily pricing file: {}'.format( missing_sids ...
[ "Validate that asset identifiers are contained in the daily bars.\n\n Parameters\n ----------\n assets : array-like[int]\n The asset identifiers to validate.\n\n Raises\n ------\n NoDataForSid\n If one or more of the provided asset identifiers are not\n...
Please provide a description of the function:def get_value(self, sid, dt, field): self._validate_assets([sid]) self._validate_timestamp(dt) sid_ix = self.sids.searchsorted(sid) dt_ix = self.dates.searchsorted(dt.asm8) value = self._postprocessors[field]( se...
[ "\n Retrieve the value at the given coordinates.\n\n Parameters\n ----------\n sid : int\n The asset identifier.\n dt : pd.Timestamp\n The timestamp for the desired data point.\n field : string\n The OHLVC name for the desired data point.\n\...
Please provide a description of the function:def get_last_traded_dt(self, asset, dt): sid_ix = self.sids.searchsorted(asset.sid) # Used to get a slice of all dates up to and including ``dt``. dt_limit_ix = self.dates.searchsorted(dt.asm8, side='right') # Get the indices of all ...
[ "\n Get the latest day on or before ``dt`` in which ``asset`` traded.\n\n If there are no trades on or before ``dt``, returns ``pd.NaT``.\n\n Parameters\n ----------\n asset : zipline.asset.Asset\n The asset for which to get the last traded day.\n dt : pd.Timesta...
Please provide a description of the function:def from_file(cls, h5_file): return cls({ country: HDF5DailyBarReader.from_file(h5_file, country) for country in h5_file.keys() })
[ "\n Construct from an h5py.File.\n\n Parameters\n ----------\n h5_file : h5py.File\n An HDF5 daily pricing file.\n " ]
Please provide a description of the function:def load_raw_arrays(self, columns, start_date, end_date, assets): country_code = self._country_code_for_assets(assets) return self._readers[country_code]...
[ "\n Parameters\n ----------\n columns : list of str\n 'open', 'high', 'low', 'close', or 'volume'\n start_date: Timestamp\n Beginning of the window range.\n end_date: Timestamp\n End of the window range.\n assets : list of int\n The a...
Please provide a description of the function:def sessions(self): return pd.to_datetime( reduce( np.union1d, (reader.dates for reader in self._readers.values()), ), utc=True, )
[ "\n Returns\n -------\n sessions : DatetimeIndex\n All session labels (unioning the range for all assets) which the\n reader can provide.\n " ]
Please provide a description of the function:def get_value(self, sid, dt, field): try: country_code = self._country_code_for_assets([sid]) except ValueError as exc: raise_from( NoDataForSid( 'Asset not contained in daily pricing file: ...
[ "\n Retrieve the value at the given coordinates.\n\n Parameters\n ----------\n sid : int\n The asset identifier.\n dt : pd.Timestamp\n The timestamp for the desired data point.\n field : string\n The OHLVC name for the desired data point.\n\...
Please provide a description of the function:def get_last_traded_dt(self, asset, dt): country_code = self._country_code_for_assets([asset.sid]) return self._readers[country_code].get_last_traded_dt(asset, dt)
[ "\n Get the latest day on or before ``dt`` in which ``asset`` traded.\n\n If there are no trades on or before ``dt``, returns ``pd.NaT``.\n\n Parameters\n ----------\n asset : zipline.asset.Asset\n The asset for which to get the last traded day.\n dt : pd.Timesta...
Please provide a description of the function:def _normalize_index_columns_in_place(equities, equity_supplementary_mappings, futures, exchanges, root_symbols): ...
[ "\n Update dataframes in place to set indentifier columns as indices.\n\n For each input frame, if the frame has a column with the same name as its\n associated index column, set that column as the index.\n\n Otherwise, assume the index already contains identifiers.\n\n If frames are passed as None, ...
Please provide a description of the function:def split_delimited_symbol(symbol): # return blank strings for any bad fuzzy symbols, like NaN or None if symbol in _delimited_symbol_default_triggers: return '', '' symbol = symbol.upper() split_list = re.split( pattern=_delimited_symb...
[ "\n Takes in a symbol that may be delimited and splits it in to a company\n symbol and share class symbol. Also returns the fuzzy symbol, which is the\n symbol without any fuzzy characters at all.\n\n Parameters\n ----------\n symbol : str\n The possibly-delimited symbol to be split\n\n ...
Please provide a description of the function:def _generate_output_dataframe(data_subset, defaults): # The columns provided. cols = set(data_subset.columns) desired_cols = set(defaults) # Drop columns with unrecognised headers. data_subset.drop(cols - desired_cols, axis=1, ...
[ "\n Generates an output dataframe from the given subset of user-provided\n data, the given column names, and the given default values.\n\n Parameters\n ----------\n data_subset : DataFrame\n A DataFrame, usually from an AssetData object,\n that contains the user's input metadata for the...
Please provide a description of the function:def _check_symbol_mappings(df, exchanges, asset_exchange): mappings = df.set_index('sid')[list(mapping_columns)].copy() mappings['country_code'] = exchanges['country_code'][ asset_exchange.loc[df['sid']] ].values ambigious = {} def check_int...
[ "Check that there are no cases where multiple symbols resolve to the same\n asset at the same time in the same country.\n\n Parameters\n ----------\n df : pd.DataFrame\n The equity symbol mappings table.\n exchanges : pd.DataFrame\n The exchanges table.\n asset_exchange : pd.Series\n...
Please provide a description of the function:def _split_symbol_mappings(df, exchanges): mappings = df[list(mapping_columns)] with pd.option_context('mode.chained_assignment', None): mappings['sid'] = mappings.index mappings.reset_index(drop=True, inplace=True) # take the most recent sid->e...
[ "Split out the symbol: sid mappings from the raw data.\n\n Parameters\n ----------\n df : pd.DataFrame\n The dataframe with multiple rows for each symbol: sid pair.\n exchanges : pd.DataFrame\n The exchanges table.\n\n Returns\n -------\n asset_info : pd.DataFrame\n The ass...
Please provide a description of the function:def _dt_to_epoch_ns(dt_series): index = pd.to_datetime(dt_series.values) if index.tzinfo is None: index = index.tz_localize('UTC') else: index = index.tz_convert('UTC') return index.view(np.int64)
[ "Convert a timeseries into an Int64Index of nanoseconds since the epoch.\n\n Parameters\n ----------\n dt_series : pd.Series\n The timeseries to convert.\n\n Returns\n -------\n idx : pd.Int64Index\n The index converted to nanoseconds since the epoch.\n " ]
Please provide a description of the function:def check_version_info(conn, version_table, expected_version): # Read the version out of the table version_from_table = conn.execute( sa.select((version_table.c.version,)), ).scalar() # A db without a version is considered v0 if version_fro...
[ "\n Checks for a version value in the version table.\n\n Parameters\n ----------\n conn : sa.Connection\n The connection to use to perform the check.\n version_table : sa.Table\n The version table of the asset database\n expected_version : int\n The expected version of the ass...
Please provide a description of the function:def write_version_info(conn, version_table, version_value): conn.execute(sa.insert(version_table, values={'version': version_value}))
[ "\n Inserts the version value in to the version table.\n\n Parameters\n ----------\n conn : sa.Connection\n The connection to use to execute the insert.\n version_table : sa.Table\n The version table of the asset database\n version_value : int\n The version to write in to the ...
Please provide a description of the function:def write_direct(self, equities=None, equity_symbol_mappings=None, equity_supplementary_mappings=None, futures=None, exchanges=None, root_symbols=Non...
[ "Write asset metadata to a sqlite database in the format that it is\n stored in the assets db.\n\n Parameters\n ----------\n equities : pd.DataFrame, optional\n The equity metadata. The columns for this dataframe are:\n\n symbol : str\n The ticker...
Please provide a description of the function:def write(self, equities=None, futures=None, exchanges=None, root_symbols=None, equity_supplementary_mappings=None, chunk_size=DEFAULT_CHUNK_SIZE): if exchanges is None: ...
[ "Write asset metadata to a sqlite database.\n\n Parameters\n ----------\n equities : pd.DataFrame, optional\n The equity metadata. The columns for this dataframe are:\n\n symbol : str\n The ticker symbol for this equity.\n asset_name : str\n...
Please provide a description of the function:def _all_tables_present(self, txn): conn = txn.connect() for table_name in asset_db_table_names: if txn.dialect.has_table(conn, table_name): return True return False
[ "\n Checks if any tables are present in the current assets database.\n\n Parameters\n ----------\n txn : Transaction\n The open transaction to check in.\n\n Returns\n -------\n has_tables : bool\n True if any tables are present, otherwise False....
Please provide a description of the function:def init_db(self, txn=None): with ExitStack() as stack: if txn is None: txn = stack.enter_context(self.engine.begin()) tables_already_exist = self._all_tables_present(txn) # Create the SQL tables if they ...
[ "Connect to database and create tables.\n\n Parameters\n ----------\n txn : sa.engine.Connection, optional\n The transaction to execute in. If this is not provided, a new\n transaction will be started with the engine provided.\n\n Returns\n -------\n m...
Please provide a description of the function:def _load_data(self, equities, futures, exchanges, root_symbols, equity_supplementary_mappings): # Set named identifier columns as indices, if provided. _n...
[ "\n Returns a standard set of pandas.DataFrames:\n equities, futures, exchanges, root_symbols\n " ]
Please provide a description of the function:def load_raw_data(assets, data_query_cutoff_times, expr, odo_kwargs, checkpoints=None): lower_dt, upper_dt = data_query_cutoff_times[[0, -1]] raw = ffill_query_in_range( expr, ...
[ "\n Given an expression representing data to load, perform normalization and\n forward-filling and return the data, materialized. Only accepts data with a\n `sid` field.\n\n Parameters\n ----------\n assets : pd.int64index\n the assets to load data for.\n data_query_cutoff_times : pd.Dat...
Please provide a description of the function:def from_tuple(tup): if len(tup) not in (2, 3): raise ValueError( 'tuple must contain 2 or 3 elements, not: %d (%r' % ( len(tup), tup, ), ) return range(*tup)
[ "Convert a tuple into a range with error handling.\n\n Parameters\n ----------\n tup : tuple (len 2 or 3)\n The tuple to turn into a range.\n\n Returns\n -------\n range : range\n The range from the tuple.\n\n Raises\n ------\n ValueError\n Raised when the tuple lengt...
Please provide a description of the function:def maybe_from_tuple(tup_or_range): if isinstance(tup_or_range, tuple): return from_tuple(tup_or_range) elif isinstance(tup_or_range, range): return tup_or_range raise ValueError( 'maybe_from_tuple expects a tuple or range, got %r: %...
[ "Convert a tuple into a range but pass ranges through silently.\n\n This is useful to ensure that input is a range so that attributes may\n be accessed with `.start`, `.stop` or so that containment checks are\n constant time.\n\n Parameters\n ----------\n tup_or_range : tuple or range\n A t...
Please provide a description of the function:def _check_steps(a, b): if a.step != 1: raise ValueError('a.step must be equal to 1, got: %s' % a.step) if b.step != 1: raise ValueError('b.step must be equal to 1, got: %s' % b.step)
[ "Check that the steps of ``a`` and ``b`` are both 1.\n\n Parameters\n ----------\n a : range\n The first range to check.\n b : range\n The second range to check.\n\n Raises\n ------\n ValueError\n Raised when either step is not 1.\n " ]
Please provide a description of the function:def overlap(a, b): _check_steps(a, b) return a.stop >= b.start and b.stop >= a.start
[ "Check if two ranges overlap.\n\n Parameters\n ----------\n a : range\n The first range.\n b : range\n The second range.\n\n Returns\n -------\n overlaps : bool\n Do these ranges overlap.\n\n Notes\n -----\n This function does not support ranges with step != 1.\n ...
Please provide a description of the function:def merge(a, b): _check_steps(a, b) return range(min(a.start, b.start), max(a.stop, b.stop))
[ "Merge two ranges with step == 1.\n\n Parameters\n ----------\n a : range\n The first range.\n b : range\n The second range.\n " ]
Please provide a description of the function:def _combine(n, rs): try: r, rs = peek(rs) except StopIteration: yield n return if overlap(n, r): yield merge(n, r) next(rs) for r in rs: yield r else: yield n for r in rs: ...
[ "helper for ``_group_ranges``\n " ]