Code
stringlengths
103
85.9k
Summary
listlengths
0
94
Please provide a description of the function:def get_adjustments(self, zero_qtr_data, requested_qtr_data, last_per_qtr, dates, assets, columns, **kwargs...
[ "\n Creates an AdjustedArray from the given estimates data for the given\n dates.\n\n Parameters\n ----------\n zero_qtr_data : pd.DataFrame\n The 'time zero' data for each calendar date per sid.\n requested_qtr_data : pd.DataFrame\n The requested quar...
Please provide a description of the function:def create_overwrites_for_quarter(self, col_to_overwrites, next_qtr_start_idx, last_per_qtr, quarters_with_estimates_for_si...
[ "\n Add entries to the dictionary of columns to adjustments for the given\n sid and the given quarter.\n\n Parameters\n ----------\n col_to_overwrites : dict [column_name -> list of ArrayAdjustment]\n A dictionary mapping column names to all overwrites for those\n ...
Please provide a description of the function:def get_last_data_per_qtr(self, assets_with_data, columns, dates, data_query_cutoff_times): # Get a DataFrame indexed by date with a Multi...
[ "\n Determine the last piece of information we know for each column on each\n date in the index for each sid and quarter.\n\n Parameters\n ----------\n assets_with_data : pd.Index\n Index of all assets that appear in the raw data given to the\n loader.\n ...
Please provide a description of the function:def get_zeroth_quarter_idx(self, stacked_last_per_qtr): previous_releases_per_date = stacked_last_per_qtr.loc[ stacked_last_per_qtr[EVENT_DATE_FIELD_NAME] <= stacked_last_per_qtr.index.get_level_values(SIMULATION_DATES) ].grou...
[ "\n Filters for releases that are on or after each simulation date and\n determines the previous quarter by picking out the most recent\n release relative to each date in the index.\n\n Parameters\n ----------\n stacked_last_per_qtr : pd.DataFrame\n A DataFrame w...
Please provide a description of the function:def get_adjustments_for_sid(self, group, dates, requested_qtr_data, last_per_qtr, sid_to_idx, ...
[ "\n Collects both overwrites and adjustments for a particular sid.\n\n Parameters\n ----------\n split_adjusted_asof_idx : int\n The integer index of the date on which the data was split-adjusted.\n split_adjusted_cols_for_group : list of str\n The names of r...
Please provide a description of the function:def get_adjustments(self, zero_qtr_data, requested_qtr_data, last_per_qtr, dates, assets, columns, **kwargs...
[ "\n Calculates both split adjustments and overwrites for all sids.\n " ]
Please provide a description of the function:def determine_end_idx_for_adjustment(self, adjustment_ts, dates, upper_bound, requested_quarter, ...
[ "\n Determines the date until which the adjustment at the given date\n index should be applied for the given quarter.\n\n Parameters\n ----------\n adjustment_ts : pd.Timestamp\n The timestamp at which the adjustment occurs.\n dates : pd.DatetimeIndex\n ...
Please provide a description of the function:def collect_pre_split_asof_date_adjustments( self, split_adjusted_asof_date_idx, sid_idx, pre_adjustments, requested_split_adjusted_columns ): col_to_split_adjustments = {} if len(pre_ad...
[ "\n Collect split adjustments that occur before the\n split-adjusted-asof-date. All those adjustments must first be\n UN-applied at the first date index and then re-applied on the\n appropriate dates in order to match point in time share pricing data.\n\n Parameters\n -----...
Please provide a description of the function:def collect_post_asof_split_adjustments(self, post_adjustments, requested_qtr_data, sid, sid_idx, ...
[ "\n Collect split adjustments that occur after the\n split-adjusted-asof-date. Each adjustment needs to be applied to all\n dates on which knowledge for the requested quarter was older than the\n date of the adjustment.\n\n Parameters\n ----------\n post_adjustments ...
Please provide a description of the function:def retrieve_split_adjustment_data_for_sid(self, dates, sid, split_adjusted_asof_idx): adjustments = self._split_adju...
[ "\n dates : pd.DatetimeIndex\n The calendar dates.\n sid : int\n The sid for which we want to retrieve adjustments.\n split_adjusted_asof_idx : int\n The index in `dates` as-of which the data is split adjusted.\n\n Returns\n -------\n pre_ad...
Please provide a description of the function:def merge_split_adjustments_with_overwrites( self, pre, post, overwrites, requested_split_adjusted_columns ): for column_name in requested_split_adjusted_columns: # We can do a merge here because the ti...
[ "\n Merge split adjustments with the dict containing overwrites.\n\n Parameters\n ----------\n pre : dict[str -> dict[int -> list]]\n The adjustments that occur before the split-adjusted-asof-date.\n post : dict[str -> dict[int -> list]]\n The adjustments tha...
Please provide a description of the function:def collect_split_adjustments(self, adjustments_for_sid, requested_qtr_data, dates, sid, sid_idx, ...
[ "\n Collect split adjustments for previous quarters and apply them to the\n given dictionary of splits for the given sid. Since overwrites just\n replace all estimates before the new quarter with NaN, we don't need to\n worry about re-applying split adjustments.\n\n Parameters\n ...
Please provide a description of the function:def collect_split_adjustments(self, adjustments_for_sid, requested_qtr_data, dates, sid, sid_idx, ...
[ "\n Collect split adjustments for future quarters. Re-apply adjustments\n that would be overwritten by overwrites. Merge split adjustments with\n overwrites into the given dictionary of splits for the given sid.\n\n Parameters\n ----------\n adjustments_for_sid : dict[str -...
Please provide a description of the function:def from_span(cls, inputs, window_length, span, **kwargs): if span <= 1: raise ValueError( "`span` must be a positive number. %s was passed." % span ) decay_rate = (1.0 - (2.0 / (1.0 + span))) assert 0...
[ "\n Convenience constructor for passing `decay_rate` in terms of `span`.\n\n Forwards `decay_rate` as `1 - (2.0 / (1 + span))`. This provides the\n behavior equivalent to passing `span` to pandas.ewma.\n\n Examples\n --------\n .. code-block:: python\n\n # Equiv...
Please provide a description of the function:def from_halflife(cls, inputs, window_length, halflife, **kwargs): if halflife <= 0: raise ValueError( "`span` must be a positive number. %s was passed." % halflife ) decay_rate = exp(log(.5) / halflife) ...
[ "\n Convenience constructor for passing ``decay_rate`` in terms of half\n life.\n\n Forwards ``decay_rate`` as ``exp(log(.5) / halflife)``. This provides\n the behavior equivalent to passing `halflife` to pandas.ewma.\n\n Examples\n --------\n .. code-block:: python...
Please provide a description of the function:def from_center_of_mass(cls, inputs, window_length, center_of_mass, **kwargs): return cls( inputs=inputs, window_length=wi...
[ "\n Convenience constructor for passing `decay_rate` in terms of center of\n mass.\n\n Forwards `decay_rate` as `1 - (1 / 1 + center_of_mass)`. This provides\n behavior equivalent to passing `center_of_mass` to pandas.ewma.\n\n Examples\n --------\n .. code-block:: ...
Please provide a description of the function:def tolerant_equals(a, b, atol=10e-7, rtol=10e-7, equal_nan=False): if equal_nan and isnan(a) and isnan(b): return True return math.fabs(a - b) <= (atol + rtol * math.fabs(b))
[ "Check if a and b are equal with some tolerance.\n\n Parameters\n ----------\n a, b : float\n The floats to check for equality.\n atol : float, optional\n The absolute tolerance.\n rtol : float, optional\n The relative tolerance.\n equal_nan : bool, optional\n Should Na...
Please provide a description of the function:def round_if_near_integer(a, epsilon=1e-4): if abs(a - round(a)) <= epsilon: return round(a) else: return a
[ "\n Round a to the nearest integer if that integer is within an epsilon\n of a.\n " ]
Please provide a description of the function:def coerce_numbers_to_my_dtype(f): @wraps(f) def method(self, other): if isinstance(other, Number): other = coerce_to_dtype(self.dtype, other) return f(self, other) return method
[ "\n A decorator for methods whose signature is f(self, other) that coerces\n ``other`` to ``self.dtype``.\n\n This is used to make comparison operations between numbers and `Factor`\n instances work independently of whether the user supplies a float or\n integer literal.\n\n For example, if I writ...
Please provide a description of the function:def binop_return_dtype(op, left, right): if is_comparison(op): if left != right: raise TypeError( "Don't know how to compute {left} {op} {right}.\n" "Comparisons are only supported between Factors of equal " ...
[ "\n Compute the expected return dtype for the given binary operator.\n\n Parameters\n ----------\n op : str\n Operator symbol, (e.g. '+', '-', ...).\n left : numpy.dtype\n Dtype of left hand side.\n right : numpy.dtype\n Dtype of right hand side.\n\n Returns\n -------\n ...
Please provide a description of the function:def binary_operator(op): # When combining a Factor with a NumericalExpression, we use this # attrgetter instance to defer to the commuted implementation of the # NumericalExpression operator. commuted_method_getter = attrgetter(method_name_for_op(op, com...
[ "\n Factory function for making binary operator methods on a Factor subclass.\n\n Returns a function, \"binary_operator\" suitable for implementing functions\n like __add__.\n " ]
Please provide a description of the function:def reflected_binary_operator(op): assert not is_comparison(op) @with_name(method_name_for_op(op, commute=True)) @coerce_numbers_to_my_dtype def reflected_binary_operator(self, other): if isinstance(self, NumericalExpression): self_...
[ "\n Factory function for making binary operator methods on a Factor.\n\n Returns a function, \"reflected_binary_operator\" suitable for implementing\n functions like __radd__.\n " ]
Please provide a description of the function:def unary_operator(op): # Only negate is currently supported. valid_ops = {'-'} if op not in valid_ops: raise ValueError("Invalid unary operator %s." % op) @with_doc("Unary Operator: '%s'" % op) @with_name(unary_op_name(op)) def unary_op...
[ "\n Factory function for making unary operator methods for Factors.\n " ]
Please provide a description of the function:def function_application(func): if func not in NUMEXPR_MATH_FUNCS: raise ValueError("Unsupported mathematical function '%s'" % func) @with_doc(func) @with_name(func) def mathfunc(self): if isinstance(self, NumericalExpression): ...
[ "\n Factory function for producing function application methods for Factor\n subclasses.\n " ]
Please provide a description of the function:def winsorize(row, min_percentile, max_percentile): a = row.copy() nan_count = isnan(row).sum() nonnan_count = a.size - nan_count # NOTE: argsort() sorts nans to the end of the array. idx = a.argsort() # Set values at indices below the min perc...
[ "\n This implementation is based on scipy.stats.mstats.winsorize\n " ]
Please provide a description of the function:def demean(self, mask=NotSpecified, groupby=NotSpecified): return GroupedRowTransform( transform=demean, transform_args=(), factor=self, groupby=groupby, dtype=self.dtype, missing_value=...
[ "\n Construct a Factor that computes ``self`` and subtracts the mean from\n row of the result.\n\n If ``mask`` is supplied, ignore values where ``mask`` returns False\n when computing row means, and output NaN anywhere the mask is False.\n\n If ``groupby`` is supplied, compute by ...
Please provide a description of the function:def zscore(self, mask=NotSpecified, groupby=NotSpecified): return GroupedRowTransform( transform=zscore, transform_args=(), factor=self, groupby=groupby, dtype=self.dtype, missing_value=...
[ "\n Construct a Factor that Z-Scores each day's results.\n\n The Z-Score of a row is defined as::\n\n (row - row.mean()) / row.stddev()\n\n If ``mask`` is supplied, ignore values where ``mask`` returns False\n when computing row means and standard deviations, and output NaN\n ...
Please provide a description of the function:def rank(self, method='ordinal', ascending=True, mask=NotSpecified, groupby=NotSpecified): if groupby is NotSpecified: return Rank(self, method=method, ascending=ascending, mask=mask) ...
[ "\n Construct a new Factor representing the sorted rank of each column\n within each row.\n\n Parameters\n ----------\n method : str, {'ordinal', 'min', 'max', 'dense', 'average'}\n The method used to assign ranks to tied elements. See\n `scipy.stats.rankdata...
Please provide a description of the function:def pearsonr(self, target, correlation_length, mask=NotSpecified): from .statistical import RollingPearson return RollingPearson( base_factor=self, target=target, correlation_length=correlation_length, ...
[ "\n Construct a new Factor that computes rolling pearson correlation\n coefficients between `target` and the columns of `self`.\n\n This method can only be called on factors which are deemed safe for use\n as inputs to other factors. This includes `Returns` and any factors\n creat...
Please provide a description of the function:def spearmanr(self, target, correlation_length, mask=NotSpecified): from .statistical import RollingSpearman return RollingSpearman( base_factor=self, target=target, correlation_length=correlation_length, ...
[ "\n Construct a new Factor that computes rolling spearman rank correlation\n coefficients between `target` and the columns of `self`.\n\n This method can only be called on factors which are deemed safe for use\n as inputs to other factors. This includes `Returns` and any factors\n ...
Please provide a description of the function:def linear_regression(self, target, regression_length, mask=NotSpecified): from .statistical import RollingLinearRegression return RollingLinearRegression( dependent=self, independent=target, regression_length=regr...
[ "\n Construct a new Factor that performs an ordinary least-squares\n regression predicting the columns of `self` from `target`.\n\n This method can only be called on factors which are deemed safe for use\n as inputs to other factors. This includes `Returns` and any factors\n creat...
Please provide a description of the function:def winsorize(self, min_percentile, max_percentile, mask=NotSpecified, groupby=NotSpecified): if not 0.0 <= min_percentile < max_percentile <= 1.0: raise BadPercentileBounds(...
[ "\n Construct a new factor that winsorizes the result of this factor.\n\n Winsorizing changes values ranked less than the minimum percentile to\n the value at the minimum percentile. Similarly, values ranking above\n the maximum percentile are changed to the value at the maximum\n ...
Please provide a description of the function:def quantiles(self, bins, mask=NotSpecified): if mask is NotSpecified: mask = self.mask return Quantiles(inputs=(self,), bins=bins, mask=mask)
[ "\n Construct a Classifier computing quantiles of the output of ``self``.\n\n Every non-NaN data point the output is labelled with an integer value\n from 0 to (bins - 1). NaNs are labelled with -1.\n\n If ``mask`` is supplied, ignore data points in locations for which\n ``mask``...
Please provide a description of the function:def top(self, N, mask=NotSpecified, groupby=NotSpecified): if N == 1: # Special case: if N == 1, we can avoid doing a full sort on every # group, which is a big win. return self._maximum(mask=mask, groupby=groupby) ...
[ "\n Construct a Filter matching the top N asset values of self each day.\n\n If ``groupby`` is supplied, returns a Filter matching the top N asset\n values for each group.\n\n Parameters\n ----------\n N : int\n Number of assets passing the returned filter each d...
Please provide a description of the function:def bottom(self, N, mask=NotSpecified, groupby=NotSpecified): return self.rank(ascending=True, mask=mask, groupby=groupby) <= N
[ "\n Construct a Filter matching the bottom N asset values of self each day.\n\n If ``groupby`` is supplied, returns a Filter matching the bottom N\n asset values for each group.\n\n Parameters\n ----------\n N : int\n Number of assets passing the returned filter ...
Please provide a description of the function:def percentile_between(self, min_percentile, max_percentile, mask=NotSpecified): return PercentileFilter( self, min_percentile=min_percentile, ...
[ "\n Construct a new Filter representing entries from the output of this\n Factor that fall within the percentile range defined by min_percentile\n and max_percentile.\n\n Parameters\n ----------\n min_percentile : float [0.0, 100.0]\n Return True for assets falli...
Please provide a description of the function:def _validate(self): if self._method not in _RANK_METHODS: raise UnknownRankMethod( method=self._method, choices=set(_RANK_METHODS), ) return super(Rank, self)._validate()
[ "\n Verify that the stored rank method is valid.\n " ]
Please provide a description of the function:def _compute(self, arrays, dates, assets, mask): return masked_rankdata_2d( arrays[0], mask, self.inputs[0].missing_value, self._method, self._ascending, )
[ "\n For each row in the input, compute a like-shaped array of per-row\n ranks.\n " ]
Please provide a description of the function:def _time_to_micros(time): seconds = time.hour * 60 * 60 + time.minute * 60 + time.second return 1000000 * seconds + time.microsecond
[ "Convert a time into microseconds since midnight.\n Parameters\n ----------\n time : datetime.time\n The time to convert.\n Returns\n -------\n us : int\n The number of microseconds since midnight.\n Notes\n -----\n This does not account for leap seconds or daylight savings....
Please provide a description of the function:def mask_between_time(dts, start, end, include_start=True, include_end=True): # This function is adapted from # `pandas.Datetime.Index.indexer_between_time` which was originally # written by Wes McKinney, Chang She, and Grant Roch. time_micros = dts._get...
[ "Return a mask of all of the datetimes in ``dts`` that are between\n ``start`` and ``end``.\n Parameters\n ----------\n dts : pd.DatetimeIndex\n The index to mask.\n start : time\n Mask away times less than the start.\n end : time\n Mask away times greater than the end.\n i...
Please provide a description of the function:def find_in_sorted_index(dts, dt): ix = dts.searchsorted(dt) if ix == len(dts) or dts[ix] != dt: raise LookupError("{dt} is not in {dts}".format(dt=dt, dts=dts)) return ix
[ "\n Find the index of ``dt`` in ``dts``.\n\n This function should be used instead of `dts.get_loc(dt)` if the index is\n large enough that we don't want to initialize a hash table in ``dts``. In\n particular, this should always be used on minutely trading calendars.\n\n Parameters\n ----------\n ...
Please provide a description of the function:def nearest_unequal_elements(dts, dt): if not dts.is_unique: raise ValueError("dts must be unique") if not dts.is_monotonic_increasing: raise ValueError("dts must be sorted in increasing order") if not len(dts): return None, None ...
[ "\n Find values in ``dts`` closest but not equal to ``dt``.\n\n Returns a pair of (last_before, first_after).\n\n When ``dt`` is less than any element in ``dts``, ``last_before`` is None.\n When ``dt`` is greater any element in ``dts``, ``first_after`` is None.\n\n ``dts`` must be unique and sorted i...
Please provide a description of the function:def categorical_df_concat(df_list, inplace=False): if not inplace: df_list = deepcopy(df_list) # Assert each dataframe has the same columns/dtypes df = df_list[0] if not all([(df.dtypes.equals(df_i.dtypes)) for df_i in df_list[1:]]): ra...
[ "\n Prepare list of pandas DataFrames to be used as input to pd.concat.\n Ensure any columns of type 'category' have the same categories across each\n dataframe.\n\n Parameters\n ----------\n df_list : list\n List of dataframes with same columns.\n inplace : bool\n True if input l...
Please provide a description of the function:def check_indexes_all_same(indexes, message="Indexes are not equal."): iterator = iter(indexes) first = next(iterator) for other in iterator: same = (first == other) if not same.all(): bad_loc = np.flatnonzero(~same)[0] ...
[ "Check that a list of Index objects are all equal.\n\n Parameters\n ----------\n indexes : iterable[pd.Index]\n Iterable of indexes to check.\n\n Raises\n ------\n ValueError\n If the indexes are not all the same.\n " ]
Please provide a description of the function:def required_event_fields(next_value_columns, previous_value_columns): # These metadata columns are used to align event indexers. return { TS_FIELD_NAME, SID_FIELD_NAME, EVENT_DATE_FIELD_NAME, }.union( # We also expect any of ...
[ "\n Compute the set of resource columns required to serve\n ``next_value_columns`` and ``previous_value_columns``.\n " ]
Please provide a description of the function:def validate_column_specs(events, next_value_columns, previous_value_columns): required = required_event_fields(next_value_columns, previous_value_columns) received = set(events.columns) missing = required - received ...
[ "\n Verify that the columns of ``events`` can be used by an EventsLoader to\n serve the BoundColumns described by ``next_value_columns`` and\n ``previous_value_columns``.\n " ]
Please provide a description of the function:def split_next_and_previous_event_columns(self, requested_columns): def next_or_previous(c): if c in self.next_value_columns: return 'next' elif c in self.previous_value_columns: return 'previous' ...
[ "\n Split requested columns into columns that should load the next known\n value and columns that should load the previous known value.\n\n Parameters\n ----------\n requested_columns : iterable[BoundColumn]\n\n Returns\n -------\n next_cols, previous_cols : i...
Please provide a description of the function:def compare_arrays(left, right): "Eq check with a short-circuit for identical objects." return ( left is right or ((left.shape == right.shape) and (left == right).all()) )
[]
Please provide a description of the function:def from_codes_and_metadata(cls, codes, categories, reverse_categories, missing_value): ret = codes.view(type=cls, dtype=np.void) ...
[ "\n Rehydrate a LabelArray from the codes and metadata.\n\n Parameters\n ----------\n codes : np.ndarray[integral]\n The codes for the label array.\n categories : np.ndarray[object]\n The unique string categories.\n reverse_categories : dict[str, int]\...
Please provide a description of the function:def as_int_array(self): return self.view( type=ndarray, dtype=unsigned_int_dtype_with_size_in_bytes(self.itemsize), )
[ "\n Convert self into a regular ndarray of ints.\n\n This is an O(1) operation. It does not copy the underlying data.\n " ]
Please provide a description of the function:def as_categorical(self): if len(self.shape) > 1: raise ValueError("Can't convert a 2D array to a categorical.") with ignore_pandas_nan_categorical_warning(): return pd.Categorical.from_codes( self.as_int_arra...
[ "\n Coerce self into a pandas categorical.\n\n This is only defined on 1D arrays, since that's all pandas supports.\n " ]
Please provide a description of the function:def as_categorical_frame(self, index, columns, name=None): if len(self.shape) != 2: raise ValueError( "Can't convert a non-2D LabelArray into a DataFrame." ) expected_shape = (len(index), len(columns)) ...
[ "\n Coerce self into a pandas DataFrame of Categoricals.\n " ]
Please provide a description of the function:def set_scalar(self, indexer, value): try: value_code = self.reverse_categories[value] except KeyError: raise ValueError("%r is not in LabelArray categories." % value) self.as_int_array()[indexer] = value_code
[ "\n Set scalar value into the array.\n\n Parameters\n ----------\n indexer : any\n The indexer to set the value at.\n value : str\n The value to assign at the given locations.\n\n Raises\n ------\n ValueError\n Raised when ``va...
Please provide a description of the function:def _equality_check(op): def method(self, other): if isinstance(other, LabelArray): self_mv = self.missing_value other_mv = other.missing_value if self_mv != other_mv: raise Mis...
[ "\n Shared code for __eq__ and __ne__, parameterized on the actual\n comparison operator to use.\n " ]
Please provide a description of the function:def empty_like(self, shape): return type(self).from_codes_and_metadata( codes=np.full( shape, self.reverse_categories[self.missing_value], dtype=unsigned_int_dtype_with_size_in_bytes(self.itemsize),...
[ "\n Make an empty LabelArray with the same categories as ``self``, filled\n with ``self.missing_value``.\n " ]
Please provide a description of the function:def map_predicate(self, f): # Functions passed to this are of type str -> bool. Don't ever call # them on None, which is the only non-str value we ever store in # categories. if self.missing_value is None: def f_to_use(x)...
[ "\n Map a function from str -> bool element-wise over ``self``.\n\n ``f`` will be applied exactly once to each non-missing unique value in\n ``self``. Missing values will always return False.\n " ]
Please provide a description of the function:def map(self, f): # f() should only return None if None is our missing value. if self.missing_value is None: allowed_outtypes = self.SUPPORTED_SCALAR_TYPES else: allowed_outtypes = self.SUPPORTED_NON_NONE_SCALAR_TYPES ...
[ "\n Map a function from str -> str element-wise over ``self``.\n\n ``f`` will be applied exactly once to each non-missing unique value in\n ``self``. Missing values will always map to ``self.missing_value``.\n " ]
Please provide a description of the function:def asymmetric_round_price(price, prefer_round_down, tick_size, diff=0.95): precision = zp_math.number_of_decimal_places(tick_size) multiplier = int(tick_size * (10 ** precision)) diff -= 0.5 # shift the difference down diff *= (10 ** -precision) # adj...
[ "\n Asymmetric rounding function for adjusting prices to the specified number\n of places in a way that \"improves\" the price. For limit prices, this means\n preferring to round down on buys and preferring to round up on sells.\n For stop prices, it means the reverse.\n\n If prefer_round_down == Tru...
Please provide a description of the function:def check_stoplimit_prices(price, label): try: if not isfinite(price): raise BadOrderParameters( msg="Attempted to place an order with a {} price " "of {}.".format(label, price) ) # This catches...
[ "\n Check to make sure the stop/limit prices are reasonable and raise\n a BadOrderParameters exception if not.\n " ]
Please provide a description of the function:def csvdir_bundle(environ, asset_db_writer, minute_bar_writer, daily_bar_writer, adjustment_writer, calendar, start_session, end_session, ...
[ "\n Build a zipline data bundle from the directory with csv files.\n " ]
Please provide a description of the function:def restrict_to_dtype(dtype, message_template): def processor(term_method, _, term_instance): term_dtype = term_instance.dtype if term_dtype != dtype: raise TypeError( message_template.format( method_na...
[ "\n A factory for decorators that restrict Term methods to only be callable on\n Terms with a specific dtype.\n\n This is conceptually similar to\n zipline.utils.input_validation.expect_dtypes, but provides more flexibility\n for providing error messages that are specifically targeting Term methods.\...
Please provide a description of the function:def daily_returns(self, start, end=None): if end is None: return self._daily_returns[start] return self._daily_returns[start:end]
[ "Returns the daily returns for the given period.\n\n Parameters\n ----------\n start : datetime\n The inclusive starting session label.\n end : datetime, optional\n The inclusive ending session label. If not provided, treat\n ``start`` as a scalar key.\n\...
Please provide a description of the function:def _initialize_precalculated_series(self, asset, trading_calendar, trading_days, data_portal): ...
[ "\n Internal method that pre-calculates the benchmark return series for\n use in the simulation.\n\n Parameters\n ----------\n asset: Asset to use\n\n trading_calendar: TradingCalendar\n\n trading_days: pd.DateTimeIndex\n\n data_portal: DataPortal\n\n ...
Please provide a description of the function:def _run(handle_data, initialize, before_trading_start, analyze, algofile, algotext, defines, data_frequency, capital_base, bundle, bundle_timestamp, start, end, ...
[ "Run a backtest for the given algorithm.\n\n This is shared between the cli and :func:`zipline.run_algo`.\n " ]
Please provide a description of the function:def load_extensions(default, extensions, strict, environ, reload=False): if default: default_extension_path = pth.default_extension(environ=environ) pth.ensure_file(default_extension_path) # put the default extension first so other extensions...
[ "Load all of the given extensions. This should be called by run_algo\n or the cli.\n\n Parameters\n ----------\n default : bool\n Load the default exension (~/.zipline/extension.py)?\n extension : iterable[str]\n The paths to the extensions to load. If the path ends in ``.py`` it is\n ...
Please provide a description of the function:def run_algorithm(start, end, initialize, capital_base, handle_data=None, before_trading_start=None, analyze=None, data_frequency='daily', ...
[ "\n Run a trading algorithm.\n\n Parameters\n ----------\n start : datetime\n The start date of the backtest.\n end : datetime\n The end date of the backtest..\n initialize : callable[context -> None]\n The initialize function to use for the algorithm. This is called once\n ...
Please provide a description of the function:def handle_extra_source(self, source_df, sim_params): if source_df is None: return # Normalize all the dates in the df source_df.index = source_df.index.normalize() # source_df's sid column can either consist of assets w...
[ "\n Extra sources always have a sid column.\n\n We expand the given data (by forward filling) to the full range of\n the simulation dates, so that lookup is fast during simulation.\n " ]
Please provide a description of the function:def get_last_traded_dt(self, asset, dt, data_frequency): return self._get_pricing_reader(data_frequency).get_last_traded_dt( asset, dt)
[ "\n Given an asset and dt, returns the last traded dt from the viewpoint\n of the given dt.\n\n If there is a trade on the dt, the answer is dt provided.\n " ]
Please provide a description of the function:def _is_extra_source(asset, field, map): # If we have an extra source with a column called "price", only look # at it if it's on something like palladium and not AAPL (since our # own price data always wins when dealing with assets). ...
[ "\n Internal method that determines if this asset/field combination\n represents a fetcher value or a regular OHLCVP lookup.\n " ]
Please provide a description of the function:def get_spot_value(self, assets, field, dt, data_frequency): assets_is_scalar = False if isinstance(assets, (AssetConvertible, PricingDataAssociable)): assets_is_scalar = True else: # If 'assets' was not one of the exp...
[ "\n Public API method that returns a scalar value representing the value\n of the desired asset's field at either the given dt.\n\n Parameters\n ----------\n assets : Asset, ContinuousFuture, or iterable of same.\n The asset or assets whose data is desired.\n fie...
Please provide a description of the function:def get_scalar_asset_spot_value(self, asset, field, dt, data_frequency): return self._get_single_asset_value( self.trading_calendar.minute_to_session_label(dt), asset, field, dt, data_frequency, ...
[ "\n Public API method that returns a scalar value representing the value\n of the desired asset's field at either the given dt.\n\n Parameters\n ----------\n assets : Asset\n The asset or assets whose data is desired. This cannot be\n an arbitrary AssetConver...
Please provide a description of the function:def get_adjustments(self, assets, field, dt, perspective_dt): if isinstance(assets, Asset): assets = [assets] adjustment_ratios_per_asset = [] def split_adj_factor(x): return x if field != 'volume' else 1.0 / x ...
[ "\n Returns a list of adjustments between the dt and perspective_dt for the\n given field and list of assets\n\n Parameters\n ----------\n assets : list of type Asset, or Asset\n The asset, or assets whose adjustments are desired.\n field : {'open', 'high', 'low'...
Please provide a description of the function:def get_adjusted_value(self, asset, field, dt, perspective_dt, data_frequency, spot_value=None): if spot_value is None: # if this a fetcher field, we want to use per...
[ "\n Returns a scalar value representing the value\n of the desired asset's field at the given dt with adjustments applied.\n\n Parameters\n ----------\n asset : Asset\n The asset whose data is desired.\n field : {'open', 'high', 'low', 'close', 'volume', \\\n ...
Please provide a description of the function:def _get_history_daily_window(self, assets, end_dt, bar_count, field_to_use, data_frequency): ...
[ "\n Internal method that returns a dataframe containing history bars\n of daily frequency for the given sids.\n " ]
Please provide a description of the function:def _get_history_minute_window(self, assets, end_dt, bar_count, field_to_use): # get all the minutes for this window try: minutes_for_window = self.trading_calendar.minutes_window( end_dt...
[ "\n Internal method that returns a dataframe containing history bars\n of minute frequency for the given sids.\n " ]
Please provide a description of the function:def get_history_window(self, assets, end_dt, bar_count, frequency, field, data_frequency, ...
[ "\n Public API method that returns a dataframe containing the requested\n history window. Data is fully adjusted.\n\n Parameters\n ----------\n assets : list of zipline.data.Asset objects\n The assets whose data is desired.\n\n bar_count: int\n The nu...
Please provide a description of the function:def _get_minute_window_data(self, assets, field, minutes_for_window): return self._minute_history_loader.history(assets, minutes_for_window, field, ...
[ "\n Internal method that gets a window of adjusted minute data for an asset\n and specified date range. Used to support the history API method for\n minute bars.\n\n Missing bars are filled with NaN.\n\n Parameters\n ----------\n assets : iterable[Asset]\n ...
Please provide a description of the function:def _get_daily_window_data(self, assets, field, days_in_window, extra_slot=True): bar_count = len(days_in_window) # create an ...
[ "\n Internal method that gets a window of adjusted daily data for a sid\n and specified date range. Used to support the history API method for\n daily bars.\n\n Parameters\n ----------\n asset : Asset\n The asset whose data is desired.\n\n start_dt: panda...
Please provide a description of the function:def _get_adjustment_list(self, asset, adjustments_dict, table_name): if self._adjustment_reader is None: return [] sid = int(asset) try: adjustments = adjustments_dict[sid] except KeyError: adjust...
[ "\n Internal method that returns a list of adjustments for the given sid.\n\n Parameters\n ----------\n asset : Asset\n The asset for which to return adjustments.\n\n adjustments_dict: dict\n A dictionary of sid -> list that is used as a cache.\n\n tab...
Please provide a description of the function:def get_splits(self, assets, dt): if self._adjustment_reader is None or not assets: return [] # convert dt to # of seconds since epoch, because that's what we use # in the adjustments db seconds = int(dt.value / 1e9) ...
[ "\n Returns any splits for the given sids and the given dt.\n\n Parameters\n ----------\n assets : container\n Assets for which we want splits.\n dt : pd.Timestamp\n The date for which we are checking for splits. Note: this is\n expected to be midn...
Please provide a description of the function:def get_stock_dividends(self, sid, trading_days): if self._adjustment_reader is None: return [] if len(trading_days) == 0: return [] start_dt = trading_days[0].value / 1e9 end_dt = trading_days[-1].value / 1...
[ "\n Returns all the stock dividends for a specific sid that occur\n in the given trading range.\n\n Parameters\n ----------\n sid: int\n The asset whose stock dividends should be returned.\n\n trading_days: pd.DatetimeIndex\n The trading range.\n\n ...
Please provide a description of the function:def get_fetcher_assets(self, dt): # return a list of assets for the current date, as defined by the # fetcher source if self._extra_source_df is None: return [] day = normalize_date(dt) if day in self._extra_sour...
[ "\n Returns a list of assets for the current date, as defined by the\n fetcher data.\n\n Returns\n -------\n list: a list of Asset objects.\n " ]
Please provide a description of the function:def get_current_future_chain(self, continuous_future, dt): rf = self._roll_finders[continuous_future.roll_style] session = self.trading_calendar.minute_to_session_label(dt) contract_center = rf.get_contract_center( continuous_futu...
[ "\n Retrieves the future chain for the contract at the given `dt` according\n the `continuous_future` specification.\n\n Returns\n -------\n\n future_chain : list[Future]\n A list of active futures, where the first index is the current\n contract specified by...
Please provide a description of the function:def make_kind_check(python_types, numpy_kind): def check(value): if hasattr(value, 'dtype'): return value.dtype.kind == numpy_kind return isinstance(value, python_types) return check
[ "\n Make a function that checks whether a scalar or array is of a given kind\n (e.g. float, int, datetime, timedelta).\n " ]
Please provide a description of the function:def coerce_to_dtype(dtype, value): name = dtype.name if name.startswith('datetime64'): if name == 'datetime64[D]': return make_datetime64D(value) elif name == 'datetime64[ns]': return make_datetime64ns(value) else:...
[ "\n Make a value with the specified numpy dtype.\n\n Only datetime64[ns] and datetime64[D] are supported for datetime dtypes.\n " ]
Please provide a description of the function:def repeat_first_axis(array, count): return as_strided(array, (count,) + array.shape, (0,) + array.strides)
[ "\n Restride `array` to repeat `count` times along the first axis.\n\n Parameters\n ----------\n array : np.array\n The array to restride.\n count : int\n Number of times to repeat `array`.\n\n Returns\n -------\n result : array\n Array of shape (count,) + array.shape, c...
Please provide a description of the function:def repeat_last_axis(array, count): return as_strided(array, array.shape + (count,), array.strides + (0,))
[ "\n Restride `array` to repeat `count` times along the last axis.\n\n Parameters\n ----------\n array : np.array\n The array to restride.\n count : int\n Number of times to repeat `array`.\n\n Returns\n -------\n result : array\n Array of shape array.shape + (count,) com...
Please provide a description of the function:def isnat(obj): if obj.dtype.kind not in ('m', 'M'): raise ValueError("%s is not a numpy datetime or timedelta") return obj.view(int64_dtype) == iNaT
[ "\n Check if a value is np.NaT.\n " ]
Please provide a description of the function:def is_missing(data, missing_value): if is_float(data) and isnan(missing_value): return isnan(data) elif is_datetime(data) and isnat(missing_value): return isnat(data) return (data == missing_value)
[ "\n Generic is_missing function that handles NaN and NaT.\n " ]
Please provide a description of the function:def busday_count_mask_NaT(begindates, enddates, out=None): if out is None: out = empty(broadcast(begindates, enddates).shape, dtype=float) beginmask = isnat(begindates) endmask = isnat(enddates) out = busday_count( # Temporarily fill in...
[ "\n Simple of numpy.busday_count that returns `float` arrays rather than int\n arrays, and handles `NaT`s by returning `NaN`s where the inputs were `NaT`.\n\n Doesn't support custom weekdays or calendars, but probably should in the\n future.\n\n See Also\n --------\n np.busday_count\n " ]
Please provide a description of the function:def changed_locations(a, include_first): if a.ndim > 1: raise ValueError("indices_of_changed_values only supports 1D arrays.") indices = flatnonzero(diff(a)) + 1 if not include_first: return indices return hstack([[0], indices])
[ "\n Compute indices of values in ``a`` that differ from the previous value.\n\n Parameters\n ----------\n a : np.ndarray\n The array on which to indices of change.\n include_first : bool\n Whether or not to consider the first index of the array as \"changed\".\n\n Example\n ------...
Please provide a description of the function:def compute_date_range_chunks(sessions, start_date, end_date, chunksize): if start_date not in sessions: raise KeyError("Start date %s is not found in calendar." % (start_date.strftime("%Y-%m-%d"),)) if end_date not in sessions: ...
[ "Compute the start and end dates to run a pipeline for.\n\n Parameters\n ----------\n sessions : DatetimeIndex\n The available dates.\n start_date : pd.Timestamp\n The first date in the pipeline.\n end_date : pd.Timestamp\n The last date in the pipeline.\n chunksize : int or N...
Please provide a description of the function:def run_pipeline(self, pipeline, start_date, end_date): # See notes at the top of this module for a description of the # algorithm implemented here. if end_date < start_date: raise ValueError( "start_date must be b...
[ "\n Compute a pipeline.\n\n Parameters\n ----------\n pipeline : zipline.pipeline.Pipeline\n The pipeline to run.\n start_date : pd.Timestamp\n Start date of the computed matrix.\n end_date : pd.Timestamp\n End date of the computed matrix.\n...
Please provide a description of the function:def _compute_root_mask(self, domain, start_date, end_date, extra_rows): sessions = domain.all_sessions() if start_date not in sessions: raise ValueError( "Pipeline start date ({}) is not a trading session for " ...
[ "\n Compute a lifetimes matrix from our AssetFinder, then drop columns that\n didn't exist at all during the query dates.\n\n Parameters\n ----------\n domain : zipline.pipeline.domain.Domain\n Domain for which we're computing a pipeline.\n start_date : pd.Timest...
Please provide a description of the function:def compute_chunk(self, graph, dates, sids, initial_workspace): self._validate_compute_chunk_params( graph, dates, sids, initial_workspace, ) get_loader = self._get_loader # Copy the supplied initial workspace so we don't...
[ "\n Compute the Pipeline terms in the graph for the requested start and end\n dates.\n\n This is where we do the actual work of running a pipeline.\n\n Parameters\n ----------\n graph : zipline.pipeline.graph.ExecutionPlan\n Dependency graph of the terms to be ex...
Please provide a description of the function:def _to_narrow(self, terms, data, mask, dates, assets): if not mask.any(): # Manually handle the empty DataFrame case. This is a workaround # to pandas failing to tz_localize an empty dataframe with a # MultiIndex. It also...
[ "\n Convert raw computed pipeline results into a DataFrame for public APIs.\n\n Parameters\n ----------\n terms : dict[str -> Term]\n Dict mapping column names to terms.\n data : dict[str -> ndarray[ndim=2]]\n Dict mapping column names to computed results for...
Please provide a description of the function:def _validate_compute_chunk_params(self, graph, dates, sids, initial_workspace): root = self._root_mas...
[ "\n Verify that the values passed to compute_chunk are well-formed.\n " ]
Please provide a description of the function:def resolve_domain(self, pipeline): domain = pipeline.domain(default=self._default_domain) if domain is GENERIC: raise ValueError( "Unable to determine domain for Pipeline.\n" "Pass domain=<desired domain> ...
[ "Resolve a concrete domain for ``pipeline``.\n " ]
Please provide a description of the function:def require_initialized(exception): def decorator(method): @wraps(method) def wrapped_method(self, *args, **kwargs): if not self.initialized: raise exception return method(self, *args, **kwargs) return ...
[ "\n Decorator for API methods that should only be called after\n TradingAlgorithm.initialize. `exception` will be raised if the method is\n called before initialize has completed.\n\n Examples\n --------\n @require_initialized(SomeException(\"Don't do that!\"))\n def method(self):\n # D...
Please provide a description of the function:def disallowed_in_before_trading_start(exception): def decorator(method): @wraps(method) def wrapped_method(self, *args, **kwargs): if self._in_before_trading_start: raise exception return method(self, *args, *...
[ "\n Decorator for API methods that cannot be called from within\n TradingAlgorithm.before_trading_start. `exception` will be raised if the\n method is called inside `before_trading_start`.\n\n Examples\n --------\n @disallowed_in_before_trading_start(SomeException(\"Don't do that!\"))\n def me...