code
stringlengths
66
870k
docstring
stringlengths
19
26.7k
func_name
stringlengths
1
138
language
stringclasses
1 value
repo
stringlengths
7
68
path
stringlengths
5
324
url
stringlengths
46
389
license
stringclasses
7 values
def previous_event_indexer(data_query_cutoff_times, all_sids, event_dates, event_timestamps, event_sids): """ Construct an index array that, when applied to an array of values, produces a 2D array con...
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 ...
previous_event_indexer
python
quantopian/zipline
zipline/pipeline/loaders/utils.py
https://github.com/quantopian/zipline/blob/master/zipline/pipeline/loaders/utils.py
Apache-2.0
def last_in_date_group(df, data_query_cutoff_times, assets, reindex=True, have_sids=True, extra_groupers=None): """ Determine the last piece of information known on each date in the date index...
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 th...
last_in_date_group
python
quantopian/zipline
zipline/pipeline/loaders/utils.py
https://github.com/quantopian/zipline/blob/master/zipline/pipeline/loaders/utils.py
Apache-2.0
def ffill_across_cols(df, columns, name_map): """ 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 : lis...
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 corres...
ffill_across_cols
python
quantopian/zipline
zipline/pipeline/loaders/utils.py
https://github.com/quantopian/zipline/blob/master/zipline/pipeline/loaders/utils.py
Apache-2.0
def shift_dates(dates, start_date, end_date, shift): """ Shift dates of a pipeline query back by ``shift`` days. Parameters ---------- dates : DatetimeIndex All known dates. start_date : pd.Timestamp Start date of the pipeline query. end_date : pd.Timestamp End date ...
Shift dates of a pipeline query back by ``shift`` days. Parameters ---------- dates : DatetimeIndex All known dates. start_date : pd.Timestamp Start date of the pipeline query. end_date : pd.Timestamp End date of the pipeline query. shift : int The number of...
shift_dates
python
quantopian/zipline
zipline/pipeline/loaders/utils.py
https://github.com/quantopian/zipline/blob/master/zipline/pipeline/loaders/utils.py
Apache-2.0
def datashape_type_to_numpy(type_): """ Given a datashape type, return the associated numpy type. Maps datashape's DateTime type to numpy's `datetime64[ns]` dtype, since the numpy datetime returned by datashape isn't supported by pipeline. Parameters ---------- type_: datashape.coretypes.Ty...
Given a datashape type, return the associated numpy type. Maps datashape's DateTime type to numpy's `datetime64[ns]` dtype, since the numpy datetime returned by datashape isn't supported by pipeline. Parameters ---------- type_: datashape.coretypes.Type The datashape type. Returns...
datashape_type_to_numpy
python
quantopian/zipline
zipline/pipeline/loaders/blaze/core.py
https://github.com/quantopian/zipline/blob/master/zipline/pipeline/loaders/blaze/core.py
Apache-2.0
def new_dataset(expr, missing_values, domain): """ Creates or returns a dataset from a blaze expression. Parameters ---------- expr : Expr The blaze expression representing the values. missing_values : frozenset((name, value) pairs Association pairs column name and missing_value...
Creates or returns a dataset from a blaze expression. Parameters ---------- expr : Expr The blaze expression representing the values. missing_values : frozenset((name, value) pairs Association pairs column name and missing_value for that column. This needs to be a frozense...
new_dataset
python
quantopian/zipline
zipline/pipeline/loaders/blaze/core.py
https://github.com/quantopian/zipline/blob/master/zipline/pipeline/loaders/blaze/core.py
Apache-2.0
def _check_resources(name, expr, resources): """Validate that the expression and resources passed match up. Parameters ---------- name : str The name of the argument we are checking. expr : Expr The potentially bound expr. resources The explicitly passed resources to com...
Validate that the expression and resources passed match up. Parameters ---------- name : str The name of the argument we are checking. expr : Expr The potentially bound expr. resources The explicitly passed resources to compute expr. Raises ------ ValueError ...
_check_resources
python
quantopian/zipline
zipline/pipeline/loaders/blaze/core.py
https://github.com/quantopian/zipline/blob/master/zipline/pipeline/loaders/blaze/core.py
Apache-2.0
def _check_datetime_field(name, measure): """Check that a field is a datetime inside some measure. Parameters ---------- name : str The name of the field to check. measure : Record The record to check the field of. Raises ------ TypeError If the field is not a d...
Check that a field is a datetime inside some measure. Parameters ---------- name : str The name of the field to check. measure : Record The record to check the field of. Raises ------ TypeError If the field is not a datetime inside ``measure``.
_check_datetime_field
python
quantopian/zipline
zipline/pipeline/loaders/blaze/core.py
https://github.com/quantopian/zipline/blob/master/zipline/pipeline/loaders/blaze/core.py
Apache-2.0
def _get_metadata(field, expr, metadata_expr, no_metadata_rule): """Find the correct metadata expression for the expression. Parameters ---------- field : {'deltas', 'checkpoints'} The kind of metadata expr to lookup. expr : Expr The baseline expression. metadata_expr : Expr, 'a...
Find the correct metadata expression for the expression. Parameters ---------- field : {'deltas', 'checkpoints'} The kind of metadata expr to lookup. expr : Expr The baseline expression. metadata_expr : Expr, 'auto', or None The metadata argument. If this is 'auto', then the...
_get_metadata
python
quantopian/zipline
zipline/pipeline/loaders/blaze/core.py
https://github.com/quantopian/zipline/blob/master/zipline/pipeline/loaders/blaze/core.py
Apache-2.0
def _ad_as_ts(expr): """Duplicate the asof_date column as the timestamp column. Parameters ---------- expr : Expr or None The expression to change the columns of. Returns ------- transformed : Expr or None The transformed expression or None if ``expr`` is None. """ ...
Duplicate the asof_date column as the timestamp column. Parameters ---------- expr : Expr or None The expression to change the columns of. Returns ------- transformed : Expr or None The transformed expression or None if ``expr`` is None.
_ad_as_ts
python
quantopian/zipline
zipline/pipeline/loaders/blaze/core.py
https://github.com/quantopian/zipline/blob/master/zipline/pipeline/loaders/blaze/core.py
Apache-2.0
def _ensure_timestamp_field(dataset_expr, deltas, checkpoints): """Verify that the baseline and deltas expressions have a timestamp field. If there is not a ``TS_FIELD_NAME`` on either of the expressions, it will be copied from the ``AD_FIELD_NAME``. If one is provided, then we will verify that it is t...
Verify that the baseline and deltas expressions have a timestamp field. If there is not a ``TS_FIELD_NAME`` on either of the expressions, it will be copied from the ``AD_FIELD_NAME``. If one is provided, then we will verify that it is the correct dshape. Parameters ---------- dataset_expr : Ex...
_ensure_timestamp_field
python
quantopian/zipline
zipline/pipeline/loaders/blaze/core.py
https://github.com/quantopian/zipline/blob/master/zipline/pipeline/loaders/blaze/core.py
Apache-2.0
def from_blaze(expr, deltas='auto', checkpoints='auto', loader=None, resources=None, odo_kwargs=None, missing_values=None, domain=GENERIC, no_deltas_rule='warn', no_checkpoints_rule='wa...
Create a Pipeline API object from a blaze expression. Parameters ---------- expr : Expr The blaze expression to use. deltas : Expr, 'auto' or None, optional The expression to use for the point in time adjustments. If the string 'auto' is passed, a deltas expr will be looked up ...
from_blaze
python
quantopian/zipline
zipline/pipeline/loaders/blaze/core.py
https://github.com/quantopian/zipline/blob/master/zipline/pipeline/loaders/blaze/core.py
Apache-2.0
def register_dataset(self, dataset, expr, deltas=None, checkpoints=None, odo_kwargs=None): """Explicitly map a datset to a collection of blaze expressions. Parameters ---...
Explicitly map a datset to a collection of blaze expressions. Parameters ---------- dataset : DataSet The pipeline dataset to map to the given expressions. expr : Expr The baseline values. deltas : Expr, optional The deltas for the data. ...
register_dataset
python
quantopian/zipline
zipline/pipeline/loaders/blaze/core.py
https://github.com/quantopian/zipline/blob/master/zipline/pipeline/loaders/blaze/core.py
Apache-2.0
def register_column(self, column, expr, deltas=None, checkpoints=None, odo_kwargs=None): """Explicitly map a single bound column to a collection of blaze expressions. The expressions n...
Explicitly map a single bound column to a collection of blaze expressions. The expressions need to have ``timestamp`` and ``as_of`` columns. Parameters ---------- column : BoundColumn The pipeline dataset to map to the given expressions. expr : Expr ...
register_column
python
quantopian/zipline
zipline/pipeline/loaders/blaze/core.py
https://github.com/quantopian/zipline/blob/master/zipline/pipeline/loaders/blaze/core.py
Apache-2.0
def collect_expr(e, lower): """Materialize the expression as a dataframe. Parameters ---------- e : Expr The baseline or deltas expression. lower : datetime The lower time bound to query. Returns ------...
Materialize the expression as a dataframe. Parameters ---------- e : Expr The baseline or deltas expression. lower : datetime The lower time bound to query. Returns ------- result : pd.DataFrame ...
collect_expr
python
quantopian/zipline
zipline/pipeline/loaders/blaze/core.py
https://github.com/quantopian/zipline/blob/master/zipline/pipeline/loaders/blaze/core.py
Apache-2.0
def bind_expression_to_resources(expr, resources): """ Bind a Blaze expression to resources. Parameters ---------- expr : bz.Expr The expression to which we want to bind resources. resources : dict[bz.Symbol -> any] Mapping from the loadable terms of ``expr`` to actual data reso...
Bind a Blaze expression to resources. Parameters ---------- expr : bz.Expr The expression to which we want to bind resources. resources : dict[bz.Symbol -> any] Mapping from the loadable terms of ``expr`` to actual data resources. Returns ------- bound_expr : bz.Expr ...
bind_expression_to_resources
python
quantopian/zipline
zipline/pipeline/loaders/blaze/core.py
https://github.com/quantopian/zipline/blob/master/zipline/pipeline/loaders/blaze/core.py
Apache-2.0
def get_materialized_checkpoints(checkpoints, colnames, lower_dt, odo_kwargs): """ Computes a lower bound and a DataFrame checkpoints. Parameters ---------- checkpoints : Expr Bound blaze expression for a checkpoints table from which to get a computed lower bound. colnames : ite...
Computes a lower bound and a DataFrame checkpoints. Parameters ---------- checkpoints : Expr Bound blaze expression for a checkpoints table from which to get a computed lower bound. colnames : iterable of str The names of the columns for which checkpoints should be computed...
get_materialized_checkpoints
python
quantopian/zipline
zipline/pipeline/loaders/blaze/core.py
https://github.com/quantopian/zipline/blob/master/zipline/pipeline/loaders/blaze/core.py
Apache-2.0
def ffill_query_in_range(expr, lower, upper, checkpoints=None, odo_kwargs=None, ts_field=TS_FIELD_NAME): """Query a blaze expression in a given time range properly forward filling from va...
Query a blaze expression in a given time range properly forward filling from values that fall before the lower date. Parameters ---------- expr : Expr Bound blaze expression. lower : datetime The lower date to query for. upper : datetime The upper date to query for. ...
ffill_query_in_range
python
quantopian/zipline
zipline/pipeline/loaders/blaze/core.py
https://github.com/quantopian/zipline/blob/master/zipline/pipeline/loaders/blaze/core.py
Apache-2.0
def load_raw_data(assets, data_query_cutoff_times, expr, odo_kwargs, checkpoints=None): """ Given an expression representing data to load, perform normalization and forward-filling and return the data, materialized. Only accepts data wi...
Given an expression representing data to load, perform normalization and forward-filling and return the data, materialized. Only accepts data with a `sid` field. Parameters ---------- assets : pd.int64index the assets to load data for. data_query_cutoff_times : pd.DatetimeIndex ...
load_raw_data
python
quantopian/zipline
zipline/pipeline/loaders/blaze/utils.py
https://github.com/quantopian/zipline/blob/master/zipline/pipeline/loaders/blaze/utils.py
Apache-2.0
def daily_returns(self, start, end=None): """Returns the daily returns for the given period. Parameters ---------- start : datetime The inclusive starting session label. end : datetime, optional The inclusive ending session label. If not provided, treat ...
Returns the daily returns for the given period. Parameters ---------- start : datetime The inclusive starting session label. end : datetime, optional The inclusive ending session label. If not provided, treat ``start`` as a scalar key. Return...
daily_returns
python
quantopian/zipline
zipline/sources/benchmark_source.py
https://github.com/quantopian/zipline/blob/master/zipline/sources/benchmark_source.py
Apache-2.0
def _initialize_precalculated_series(self, asset, trading_calendar, trading_days, data_portal): """ Internal method that pre-calculates the ...
Internal method that pre-calculates the benchmark return series for use in the simulation. Parameters ---------- asset: Asset to use trading_calendar: TradingCalendar trading_days: pd.DateTimeIndex data_portal: DataPortal Notes -----...
_initialize_precalculated_series
python
quantopian/zipline
zipline/sources/benchmark_source.py
https://github.com/quantopian/zipline/blob/master/zipline/sources/benchmark_source.py
Apache-2.0
def parse_date_str_series(format_str, tz, date_str_series, data_frequency, trading_day): """ Efficient parsing for a 1d Pandas/numpy object containing string representations of dates. Note: pd.to_datetime is significantly faster when no format string is ...
Efficient parsing for a 1d Pandas/numpy object containing string representations of dates. Note: pd.to_datetime is significantly faster when no format string is passed, and in pandas 0.12.0 the %p strptime directive is not correctly handled if a format string is explicitly pass...
parse_date_str_series
python
quantopian/zipline
zipline/sources/requests_csv.py
https://github.com/quantopian/zipline/blob/master/zipline/sources/requests_csv.py
Apache-2.0
def _lookup_unconflicted_symbol(self, symbol): """ Attempt to find a unique asset whose symbol is the given string. If multiple assets have held the given symbol, return a 0. If no asset has held the given symbol, return a NaN. """ try: uppered = symbol.upp...
Attempt to find a unique asset whose symbol is the given string. If multiple assets have held the given symbol, return a 0. If no asset has held the given symbol, return a NaN.
_lookup_unconflicted_symbol
python
quantopian/zipline
zipline/sources/requests_csv.py
https://github.com/quantopian/zipline/blob/master/zipline/sources/requests_csv.py
Apache-2.0
def date_gen(start, end, trading_calendar, delta=timedelta(minutes=1), repeats=None): """ Utility to generate a stream of dates. """ daily_delta = not (delta.total_seconds() % timedelta(days=1).total_seconds()) cur = start ...
Utility to generate a stream of dates.
date_gen
python
quantopian/zipline
zipline/sources/test_source.py
https://github.com/quantopian/zipline/blob/master/zipline/sources/test_source.py
Apache-2.0
def advance_current(cur): """ Advances the current dt skipping non market days and minutes. """ cur = cur + delta currently_executing = \ (daily_delta and (cur in trading_calendar.all_sessions)) or \ (trading_calendar.is_open_on_minute(cur)) if c...
Advances the current dt skipping non market days and minutes.
advance_current
python
quantopian/zipline
zipline/sources/test_source.py
https://github.com/quantopian/zipline/blob/master/zipline/sources/test_source.py
Apache-2.0
def product_upper_triangle(values, include_diagonal=False): """ Return an iterator over pairs, (v0, v1), drawn from values. If `include_diagonal` is True, returns all pairs such that v0 <= v1. If `include_diagonal` is False, returns all pairs such that v0 < v1. """ return all_pairs_matching_pre...
Return an iterator over pairs, (v0, v1), drawn from values. If `include_diagonal` is True, returns all pairs such that v0 <= v1. If `include_diagonal` is False, returns all pairs such that v0 < v1.
product_upper_triangle
python
quantopian/zipline
zipline/testing/core.py
https://github.com/quantopian/zipline/blob/master/zipline/testing/core.py
Apache-2.0
def all_subindices(index): """ Return all valid sub-indices of a pandas Index. """ return ( index[start:stop] for start, stop in product_upper_triangle(range(len(index) + 1)) )
Return all valid sub-indices of a pandas Index.
all_subindices
python
quantopian/zipline
zipline/testing/core.py
https://github.com/quantopian/zipline/blob/master/zipline/testing/core.py
Apache-2.0
def make_trade_data_for_asset_info(dates, asset_info, price_start, price_step_by_date, price_step_by_sid, volume_start, ...
Convert the asset info dataframe into a dataframe of trade data for each sid, and write to the writer if provided. Write NaNs for locations where assets did not exist. Return a dict of the dataframes, keyed by sid.
make_trade_data_for_asset_info
python
quantopian/zipline
zipline/testing/core.py
https://github.com/quantopian/zipline/blob/master/zipline/testing/core.py
Apache-2.0
def check_allclose(actual, desired, rtol=1e-07, atol=0, err_msg='', verbose=True): """ Wrapper around np.testing.assert_allclose that also verifies that inputs are ndarrays. See Also -------- np.asser...
Wrapper around np.testing.assert_allclose that also verifies that inputs are ndarrays. See Also -------- np.assert_allclose
check_allclose
python
quantopian/zipline
zipline/testing/core.py
https://github.com/quantopian/zipline/blob/master/zipline/testing/core.py
Apache-2.0
def check_arrays(x, y, err_msg='', verbose=True, check_dtypes=True): """ Wrapper around np.testing.assert_array_equal that also verifies that inputs are ndarrays. See Also -------- np.assert_array_equal """ assert type(x) == type(y), "{x} != {y}".format(x=type(x), y=type(y)) assert ...
Wrapper around np.testing.assert_array_equal that also verifies that inputs are ndarrays. See Also -------- np.assert_array_equal
check_arrays
python
quantopian/zipline
zipline/testing/core.py
https://github.com/quantopian/zipline/blob/master/zipline/testing/core.py
Apache-2.0
def subtest(iterator, *_names): """ Construct a subtest in a unittest. Consider using ``zipline.testing.parameter_space`` when subtests are constructed over a single input or over the cross-product of multiple inputs. ``subtest`` works by decorating a function as a subtest. The decorated f...
Construct a subtest in a unittest. Consider using ``zipline.testing.parameter_space`` when subtests are constructed over a single input or over the cross-product of multiple inputs. ``subtest`` works by decorating a function as a subtest. The decorated function will be run by iterating over t...
subtest
python
quantopian/zipline
zipline/testing/core.py
https://github.com/quantopian/zipline/blob/master/zipline/testing/core.py
Apache-2.0
def assert_timestamp_equal(left, right, compare_nat_equal=True, msg=""): """ Assert that two pandas Timestamp objects are the same. Parameters ---------- left, right : pd.Timestamp The values to compare. compare_nat_equal : bool, optional Whether to consider `NaT` values equal. ...
Assert that two pandas Timestamp objects are the same. Parameters ---------- left, right : pd.Timestamp The values to compare. compare_nat_equal : bool, optional Whether to consider `NaT` values equal. Defaults to True. msg : str, optional A message to forward to `pd.u...
assert_timestamp_equal
python
quantopian/zipline
zipline/testing/core.py
https://github.com/quantopian/zipline/blob/master/zipline/testing/core.py
Apache-2.0
def to_series(knowledge_dates, earning_dates): """ Helper for converting a dict of strings to a Series of datetimes. This is just for making the test cases more readable. """ return pd.Series( index=pd.to_datetime(knowledge_dates), data=pd.to_datetime(earning_dates), )
Helper for converting a dict of strings to a Series of datetimes. This is just for making the test cases more readable.
to_series
python
quantopian/zipline
zipline/testing/core.py
https://github.com/quantopian/zipline/blob/master/zipline/testing/core.py
Apache-2.0
def gen_calendars(start, stop, critical_dates): """ Generate calendars to use as inputs. """ all_dates = pd.date_range(start, stop, tz='utc') for to_drop in map(list, powerset(critical_dates)): # Have to yield tuples. yield (all_dates.drop(to_drop),) # Also test with the trading...
Generate calendars to use as inputs.
gen_calendars
python
quantopian/zipline
zipline/testing/core.py
https://github.com/quantopian/zipline/blob/master/zipline/testing/core.py
Apache-2.0
def temp_pipeline_engine(calendar, sids, random_seed, symbols=None): """ A contextManager that yields a SimplePipelineEngine holding a reference to an AssetFinder generated via tmp_asset_finder. Parameters ---------- calendar : pd.DatetimeIndex Calendar to pass to the constructed Pipeli...
A contextManager that yields a SimplePipelineEngine holding a reference to an AssetFinder generated via tmp_asset_finder. Parameters ---------- calendar : pd.DatetimeIndex Calendar to pass to the constructed PipelineEngine. sids : iterable[int] Sids to use for the temp asset fi...
temp_pipeline_engine
python
quantopian/zipline
zipline/testing/core.py
https://github.com/quantopian/zipline/blob/master/zipline/testing/core.py
Apache-2.0
def bool_from_envvar(name, default=False, env=None): """ Get a boolean value from the environment, making a reasonable attempt to convert "truthy" values to True and "falsey" values to False. Strings are coerced to bools using ``json.loads(s.lower())``. Parameters ---------- name : str ...
Get a boolean value from the environment, making a reasonable attempt to convert "truthy" values to True and "falsey" values to False. Strings are coerced to bools using ``json.loads(s.lower())``. Parameters ---------- name : str Name of the environment variable. default : bool, o...
bool_from_envvar
python
quantopian/zipline
zipline/testing/core.py
https://github.com/quantopian/zipline/blob/master/zipline/testing/core.py
Apache-2.0
def parameter_space(__fail_fast=_FAIL_FAST_DEFAULT, **params): """ Wrapper around subtest that allows passing keywords mapping names to iterables of values. The decorated test function will be called with the cross-product of all possible inputs Examples -------- >>> from unittest impo...
Wrapper around subtest that allows passing keywords mapping names to iterables of values. The decorated test function will be called with the cross-product of all possible inputs Examples -------- >>> from unittest import TestCase >>> class SomeTestCase(TestCase): ... @paramet...
parameter_space
python
quantopian/zipline
zipline/testing/core.py
https://github.com/quantopian/zipline/blob/master/zipline/testing/core.py
Apache-2.0
def make_alternating_boolean_array(shape, first_value=True): """ Create a 2D numpy array with the given shape containing alternating values of False, True, False, True,... along each row and each column. Examples -------- >>> make_alternating_boolean_array((4,4)) array([[ True, False, True...
Create a 2D numpy array with the given shape containing alternating values of False, True, False, True,... along each row and each column. Examples -------- >>> make_alternating_boolean_array((4,4)) array([[ True, False, True, False], [False, True, False, True], [ True...
make_alternating_boolean_array
python
quantopian/zipline
zipline/testing/core.py
https://github.com/quantopian/zipline/blob/master/zipline/testing/core.py
Apache-2.0
def make_cascading_boolean_array(shape, first_value=True): """ Create a numpy array with the given shape containing cascading boolean values, with `first_value` being the top-left value. Examples -------- >>> make_cascading_boolean_array((4,4)) array([[ True, True, True, False], ...
Create a numpy array with the given shape containing cascading boolean values, with `first_value` being the top-left value. Examples -------- >>> make_cascading_boolean_array((4,4)) array([[ True, True, True, False], [ True, True, False, False], [ True, False, False, F...
make_cascading_boolean_array
python
quantopian/zipline
zipline/testing/core.py
https://github.com/quantopian/zipline/blob/master/zipline/testing/core.py
Apache-2.0
def permute_rows(seed, array): """ Shuffle each row in ``array`` based on permutations generated by ``seed``. Parameters ---------- seed : int Seed for numpy.RandomState array : np.ndarray[ndim=2] Array over which to apply permutations. """ rand = np.random.RandomState(s...
Shuffle each row in ``array`` based on permutations generated by ``seed``. Parameters ---------- seed : int Seed for numpy.RandomState array : np.ndarray[ndim=2] Array over which to apply permutations.
permute_rows
python
quantopian/zipline
zipline/testing/core.py
https://github.com/quantopian/zipline/blob/master/zipline/testing/core.py
Apache-2.0
def make_test_handler(testcase, *args, **kwargs): """ Returns a TestHandler which will be used by the given testcase. This handler can be used to test log messages. Parameters ---------- testcase: unittest.TestCase The test class in which the log handler will be used. *args, **kwarg...
Returns a TestHandler which will be used by the given testcase. This handler can be used to test log messages. Parameters ---------- testcase: unittest.TestCase The test class in which the log handler will be used. *args, **kwargs Forwarded to the new TestHandler object. R...
make_test_handler
python
quantopian/zipline
zipline/testing/core.py
https://github.com/quantopian/zipline/blob/master/zipline/testing/core.py
Apache-2.0
def patch_os_environment(remove=None, **values): """ Context manager for patching the operating system environment. """ old_values = {} remove = remove or [] for key in remove: old_values[key] = os.environ.pop(key) for key, value in values.iteritems(): old_values[key] = os.ge...
Context manager for patching the operating system environment.
patch_os_environment
python
quantopian/zipline
zipline/testing/core.py
https://github.com/quantopian/zipline/blob/master/zipline/testing/core.py
Apache-2.0
def patch_read_csv(url_map, module=pd, strict=False): """Patch pandas.read_csv to map lookups from url to another. Parameters ---------- url_map : mapping[str or file-like object -> str or file-like object] The mapping to use to redirect read_csv calls. module : module, optional The...
Patch pandas.read_csv to map lookups from url to another. Parameters ---------- url_map : mapping[str or file-like object -> str or file-like object] The mapping to use to redirect read_csv calls. module : module, optional The module to patch ``read_csv`` on. By default this is ``pandas...
patch_read_csv
python
quantopian/zipline
zipline/testing/core.py
https://github.com/quantopian/zipline/blob/master/zipline/testing/core.py
Apache-2.0
def ensure_doctest(f, name=None): """Ensure that an object gets doctested. This is useful for instances of objects like curry or partial which are not discovered by default. Parameters ---------- f : any The thing to doctest. name : str, optional The name to use in the doctest f...
Ensure that an object gets doctested. This is useful for instances of objects like curry or partial which are not discovered by default. Parameters ---------- f : any The thing to doctest. name : str, optional The name to use in the doctest function mapping. If this is None, ...
ensure_doctest
python
quantopian/zipline
zipline/testing/core.py
https://github.com/quantopian/zipline/blob/master/zipline/testing/core.py
Apache-2.0
def prices_generating_returns(returns, starting_price): """Construct the time series of prices that produce the given returns. Parameters ---------- returns : np.ndarray[float] The returns that these prices generate. starting_price : float The value of the asset. Returns --...
Construct the time series of prices that produce the given returns. Parameters ---------- returns : np.ndarray[float] The returns that these prices generate. starting_price : float The value of the asset. Returns ------- prices : np.ndaray[float] The prices that gen...
prices_generating_returns
python
quantopian/zipline
zipline/testing/core.py
https://github.com/quantopian/zipline/blob/master/zipline/testing/core.py
Apache-2.0
def random_tick_prices(starting_price, count, tick_size=0.01, tick_range=(-5, 7), seed=42): """ Construct a time series of prices that ticks by a random multiple of ``tick_size`` every period. Parameters ---...
Construct a time series of prices that ticks by a random multiple of ``tick_size`` every period. Parameters ---------- starting_price : float The first price of the series. count : int Number of price observations to return. tick_size : float Unit of price movement ...
random_tick_prices
python
quantopian/zipline
zipline/testing/core.py
https://github.com/quantopian/zipline/blob/master/zipline/testing/core.py
Apache-2.0
def simulate_minutes_for_day(open_, high, low, close, volume, trading_minutes=390, random_state=None): """Generate a random walk of minute ret...
Generate a random walk of minute returns which meets the given OHLCV profile for an asset. The volume will be evenly distributed through the day. Parameters ---------- open_ : float The day's open. high : float The day's high. low : float The day's low. close : f...
simulate_minutes_for_day
python
quantopian/zipline
zipline/testing/core.py
https://github.com/quantopian/zipline/blob/master/zipline/testing/core.py
Apache-2.0
def write_hdf5_daily_bars(writer, asset_finder, country_codes, generate_data, generate_currency_codes): """Write an HDF5 file of pricing data using an HDF5DailyBarWriter. """ asset_finder = asset_finder ...
Write an HDF5 file of pricing data using an HDF5DailyBarWriter.
write_hdf5_daily_bars
python
quantopian/zipline
zipline/testing/core.py
https://github.com/quantopian/zipline/blob/master/zipline/testing/core.py
Apache-2.0
def exchange_info_for_domains(domains): """ Build an exchange_info suitable for passing to an AssetFinder from a list of EquityCalendarDomain. """ return pd.DataFrame.from_records([ {'exchange': domain.calendar.name, 'country_code': domain.country_code} for domain in domains ])
Build an exchange_info suitable for passing to an AssetFinder from a list of EquityCalendarDomain.
exchange_info_for_domains
python
quantopian/zipline
zipline/testing/core.py
https://github.com/quantopian/zipline/blob/master/zipline/testing/core.py
Apache-2.0
def init_class_fixtures(cls): """ Override and implement this classmethod to register resources that should be created and/or torn down on a per-class basis. Subclass implementations of this should always invoke this with super() to ensure that fixture mixins work properly. ...
Override and implement this classmethod to register resources that should be created and/or torn down on a per-class basis. Subclass implementations of this should always invoke this with super() to ensure that fixture mixins work properly.
init_class_fixtures
python
quantopian/zipline
zipline/testing/fixtures.py
https://github.com/quantopian/zipline/blob/master/zipline/testing/fixtures.py
Apache-2.0
def enter_class_context(cls, context_manager): """ Enter a context manager to be exited during the tearDownClass """ if cls._in_setup: raise ValueError( 'Attempted to enter a class context in init_instance_fixtures.' '\nDid you mean to call ent...
Enter a context manager to be exited during the tearDownClass
enter_class_context
python
quantopian/zipline
zipline/testing/fixtures.py
https://github.com/quantopian/zipline/blob/master/zipline/testing/fixtures.py
Apache-2.0
def add_class_callback(cls, callback, *args, **kwargs): """ Register a callback to be executed during tearDownClass. Parameters ---------- callback : callable The callback to invoke at the end of the test suite. """ if cls._in_setup: raise...
Register a callback to be executed during tearDownClass. Parameters ---------- callback : callable The callback to invoke at the end of the test suite.
add_class_callback
python
quantopian/zipline
zipline/testing/fixtures.py
https://github.com/quantopian/zipline/blob/master/zipline/testing/fixtures.py
Apache-2.0
def make_asset_finder(cls): """Returns a new AssetFinder Returns ------- asset_finder : zipline.assets.AssetFinder """ equities = cls.make_equity_info() futures = cls.make_futures_info() root_symbols = cls.make_root_symbols_info() exchanges = cls...
Returns a new AssetFinder Returns ------- asset_finder : zipline.assets.AssetFinder
make_asset_finder
python
quantopian/zipline
zipline/testing/fixtures.py
https://github.com/quantopian/zipline/blob/master/zipline/testing/fixtures.py
Apache-2.0
def exchange_names(cls): """A list of canonical exchange names for all exchanges in this suite. """ infos = itervalues(cls.asset_finder.exchange_info) return sorted(i.canonical_name for i in infos)
A list of canonical exchange names for all exchanges in this suite.
exchange_names
python
quantopian/zipline
zipline/testing/fixtures.py
https://github.com/quantopian/zipline/blob/master/zipline/testing/fixtures.py
Apache-2.0
def make_equity_daily_bar_data(cls, country_code, sids): """ Create daily pricing data. Parameters ---------- country_code : str An ISO 3166 alpha-2 country code. Data should be created for this country. sids : tuple[int] The sids to i...
Create daily pricing data. Parameters ---------- country_code : str An ISO 3166 alpha-2 country code. Data should be created for this country. sids : tuple[int] The sids to include in the data. Yields ------ (int, pd....
make_equity_daily_bar_data
python
quantopian/zipline
zipline/testing/fixtures.py
https://github.com/quantopian/zipline/blob/master/zipline/testing/fixtures.py
Apache-2.0
def write_hdf5_daily_bars(cls, path, country_codes): """ Write HDF5 pricing data using an HDF5DailyBarWriter. Parameters ---------- path : str Location (relative to cls.tmpdir) at which to write data. country_codes : list[str] List of country code...
Write HDF5 pricing data using an HDF5DailyBarWriter. Parameters ---------- path : str Location (relative to cls.tmpdir) at which to write data. country_codes : list[str] List of country codes to write. Returns ------- written : h...
write_hdf5_daily_bars
python
quantopian/zipline
zipline/testing/fixtures.py
https://github.com/quantopian/zipline/blob/master/zipline/testing/fixtures.py
Apache-2.0
def raw_expected_values(self, column, start_date, end_date): """ Get an array containing the raw values we expect to be produced for the given dates between start_date and end_date, inclusive. """ all_values = self.seeded_random_loader.values( column.dtype, ...
Get an array containing the raw values we expect to be produced for the given dates between start_date and end_date, inclusive.
raw_expected_values
python
quantopian/zipline
zipline/testing/fixtures.py
https://github.com/quantopian/zipline/blob/master/zipline/testing/fixtures.py
Apache-2.0
def merge_with_inherited_algo_kwargs(self, overriding_type, suite_overrides, method_overrides): """ Helper for subclasses overriding ``make_algo_kwargs``. A common pattern ...
Helper for subclasses overriding ``make_algo_kwargs``. A common pattern for tests using `WithMakeAlgoKwargs` is that a particular test suite has a set of default keywords it wants to use everywhere, but also accepts test-specific overrides. Test suites that fit that pattern ca...
merge_with_inherited_algo_kwargs
python
quantopian/zipline
zipline/testing/fixtures.py
https://github.com/quantopian/zipline/blob/master/zipline/testing/fixtures.py
Apache-2.0
def make_fx_rates_from_reference(cls, reference): """ Helper method for implementing make_fx_rates. Takes a (dates x currencies) DataFrame of "reference" values, which are assumed to be the "true" value of each currency in some unknown external currency. Computes fx rates from A...
Helper method for implementing make_fx_rates. Takes a (dates x currencies) DataFrame of "reference" values, which are assumed to be the "true" value of each currency in some unknown external currency. Computes fx rates from A -> B as by dividing the reference value for A by the...
make_fx_rates_from_reference
python
quantopian/zipline
zipline/testing/fixtures.py
https://github.com/quantopian/zipline/blob/master/zipline/testing/fixtures.py
Apache-2.0
def write_h5_fx_rates(cls, path): """Write cls.fx_rates to disk with an HDF5FXRateWriter. Returns an HDF5FXRateReader that reader from written data. """ sessions = cls.fx_rates_sessions # Write in-memory data to h5 file. with h5py.File(path, 'w') as h5_file: ...
Write cls.fx_rates to disk with an HDF5FXRateWriter. Returns an HDF5FXRateReader that reader from written data.
write_h5_fx_rates
python
quantopian/zipline
zipline/testing/fixtures.py
https://github.com/quantopian/zipline/blob/master/zipline/testing/fixtures.py
Apache-2.0
def get_expected_fx_rate_scalar(cls, rate, quote, base, dt): """Get the expected FX rate for the given scalar coordinates. """ if base is None: return np.nan if rate == DEFAULT_FX_RATE: rate = cls.FX_RATES_DEFAULT_RATE col = cls.fx_rates[rate][quote][bas...
Get the expected FX rate for the given scalar coordinates.
get_expected_fx_rate_scalar
python
quantopian/zipline
zipline/testing/fixtures.py
https://github.com/quantopian/zipline/blob/master/zipline/testing/fixtures.py
Apache-2.0
def get_expected_fx_rates(cls, rate, quote, bases, dts): """Get an array of expected FX rates for the given indices. """ out = np.empty((len(dts), len(bases)), dtype='float64') for i, dt in enumerate(dts): for j, base in enumerate(bases): out[i, j] = cls.get_...
Get an array of expected FX rates for the given indices.
get_expected_fx_rates
python
quantopian/zipline
zipline/testing/fixtures.py
https://github.com/quantopian/zipline/blob/master/zipline/testing/fixtures.py
Apache-2.0
def fast_get_loc_ffilled(dts, dt): """ Equivalent to dts.get_loc(dt, method='ffill'), but with reasonable microperformance. """ ix = dts.searchsorted(dt, side='right') - 1 if ix < 0: raise KeyError(dt) return ix
Equivalent to dts.get_loc(dt, method='ffill'), but with reasonable microperformance.
fast_get_loc_ffilled
python
quantopian/zipline
zipline/testing/fixtures.py
https://github.com/quantopian/zipline/blob/master/zipline/testing/fixtures.py
Apache-2.0
def keywords(func): """Get the argument names of a function >>> def f(x, y=2): ... pass >>> keywords(f) ['x', 'y'] Notes ----- Taken from odo.utils """ if isinstance(func, type): return keywords(func.__init__) elif isinstance(func, partial): return keyw...
Get the argument names of a function >>> def f(x, y=2): ... pass >>> keywords(f) ['x', 'y'] Notes ----- Taken from odo.utils
keywords
python
quantopian/zipline
zipline/testing/predicates.py
https://github.com/quantopian/zipline/blob/master/zipline/testing/predicates.py
Apache-2.0
def _fmt_path(path): """Format the path for final display. Parameters ---------- path : iterable of str The path to the values that are not equal. Returns ------- fmtd : str The formatted path to put into the error message. """ if not path: return '' ret...
Format the path for final display. Parameters ---------- path : iterable of str The path to the values that are not equal. Returns ------- fmtd : str The formatted path to put into the error message.
_fmt_path
python
quantopian/zipline
zipline/testing/predicates.py
https://github.com/quantopian/zipline/blob/master/zipline/testing/predicates.py
Apache-2.0
def _fmt_msg(msg): """Format the message for final display. Parameters ---------- msg : str The message to show to the user to provide additional context. returns ------- fmtd : str The formatted message to put into the error message. """ if not msg: return ...
Format the message for final display. Parameters ---------- msg : str The message to show to the user to provide additional context. returns ------- fmtd : str The formatted message to put into the error message.
_fmt_msg
python
quantopian/zipline
zipline/testing/predicates.py
https://github.com/quantopian/zipline/blob/master/zipline/testing/predicates.py
Apache-2.0
def assert_is_subclass(subcls, cls, msg=''): """Assert that ``subcls`` is a subclass of ``cls``. Parameters ---------- subcls : type The type to check. cls : type The type to check ``subcls`` against. msg : str, optional An extra assertion message to print if this fails....
Assert that ``subcls`` is a subclass of ``cls``. Parameters ---------- subcls : type The type to check. cls : type The type to check ``subcls`` against. msg : str, optional An extra assertion message to print if this fails.
assert_is_subclass
python
quantopian/zipline
zipline/testing/predicates.py
https://github.com/quantopian/zipline/blob/master/zipline/testing/predicates.py
Apache-2.0
def assert_is_not_subclass(not_subcls, cls, msg=''): """Assert that ``not_subcls`` is not a subclass of ``cls``. Parameters ---------- not_subcls : type The type to check. cls : type The type to check ``not_subcls`` against. msg : str, optional An extra assertion message...
Assert that ``not_subcls`` is not a subclass of ``cls``. Parameters ---------- not_subcls : type The type to check. cls : type The type to check ``not_subcls`` against. msg : str, optional An extra assertion message to print if this fails.
assert_is_not_subclass
python
quantopian/zipline
zipline/testing/predicates.py
https://github.com/quantopian/zipline/blob/master/zipline/testing/predicates.py
Apache-2.0
def assert_regex(result, expected, msg=''): """Assert that ``expected`` matches the result. Parameters ---------- result : str The string to search. expected : str or compiled regex The pattern to search for in ``result``. msg : str, optional An extra assertion message t...
Assert that ``expected`` matches the result. Parameters ---------- result : str The string to search. expected : str or compiled regex The pattern to search for in ``result``. msg : str, optional An extra assertion message to print if this fails.
assert_regex
python
quantopian/zipline
zipline/testing/predicates.py
https://github.com/quantopian/zipline/blob/master/zipline/testing/predicates.py
Apache-2.0
def assert_raises_regex(exc, pattern, msg=''): """Assert that some exception is raised in a context and that the message matches some pattern. Parameters ---------- exc : type or tuple[type] The exception type or types to expect. pattern : str or compiled regex The pattern to se...
Assert that some exception is raised in a context and that the message matches some pattern. Parameters ---------- exc : type or tuple[type] The exception type or types to expect. pattern : str or compiled regex The pattern to search for in the str of the raised exception. msg :...
assert_raises_regex
python
quantopian/zipline
zipline/testing/predicates.py
https://github.com/quantopian/zipline/blob/master/zipline/testing/predicates.py
Apache-2.0
def assert_raises_str(exc, expected_str, msg=''): """Assert that some exception is raised in a context and that the message exactly matches some string. Parameters ---------- exc : type or tuple[type] The exception type or types to expect. expected_str : str The expected result ...
Assert that some exception is raised in a context and that the message exactly matches some string. Parameters ---------- exc : type or tuple[type] The exception type or types to expect. expected_str : str The expected result of ``str(exception)``. msg : str, optional An...
assert_raises_str
python
quantopian/zipline
zipline/testing/predicates.py
https://github.com/quantopian/zipline/blob/master/zipline/testing/predicates.py
Apache-2.0
def make_assert_equal_assertion_error(assertion_message, path, msg): """Create an assertion error formatted for use in ``assert_equal``. Parameters ---------- assertion_message : str The concrete reason for the failure. path : tuple[str] The path leading up to the failure. msg :...
Create an assertion error formatted for use in ``assert_equal``. Parameters ---------- assertion_message : str The concrete reason for the failure. path : tuple[str] The path leading up to the failure. msg : str The user supplied message. Returns ------- excepti...
make_assert_equal_assertion_error
python
quantopian/zipline
zipline/testing/predicates.py
https://github.com/quantopian/zipline/blob/master/zipline/testing/predicates.py
Apache-2.0
def assert_equal(result, expected, path=(), msg='', **kwargs): """Assert that two objects are equal using the ``==`` operator. Parameters ---------- result : object The result that came from the function under test. expected : object The expected result. Raises ------ A...
Assert that two objects are equal using the ``==`` operator. Parameters ---------- result : object The result that came from the function under test. expected : object The expected result. Raises ------ AssertionError Raised when ``result`` is not equal to ``expecte...
assert_equal
python
quantopian/zipline
zipline/testing/predicates.py
https://github.com/quantopian/zipline/blob/master/zipline/testing/predicates.py
Apache-2.0
def _check_sets(result, expected, msg, path, type_): """Compare two sets. This is used to check dictionary keys and sets. Parameters ---------- result : set expected : set msg : str path : tuple type : str The type of an element. For dict we use ``'key'`` and for set we use ...
Compare two sets. This is used to check dictionary keys and sets. Parameters ---------- result : set expected : set msg : str path : tuple type : str The type of an element. For dict we use ``'key'`` and for set we use ``'element'``.
_check_sets
python
quantopian/zipline
zipline/testing/predicates.py
https://github.com/quantopian/zipline/blob/master/zipline/testing/predicates.py
Apache-2.0
def _register_assert_equal_wrapper(type_, assert_eq): """Register a new check for an ndframe object. Parameters ---------- type_ : type The class to register an ``assert_equal`` dispatch for. assert_eq : callable[type_, type_] The function which checks that if the two ndframes are e...
Register a new check for an ndframe object. Parameters ---------- type_ : type The class to register an ``assert_equal`` dispatch for. assert_eq : callable[type_, type_] The function which checks that if the two ndframes are equal. Returns ------- assert_ndframe_equal : cal...
_register_assert_equal_wrapper
python
quantopian/zipline
zipline/testing/predicates.py
https://github.com/quantopian/zipline/blob/master/zipline/testing/predicates.py
Apache-2.0
def assert_timestamp_and_datetime_equal(result, expected, path=(), msg='', allow_datetime_coercions=False, compare_nat_e...
Branch for comparing python datetime (which includes pandas Timestamp) and np.datetime64 as equal. Returns raises unless ``allow_datetime_coercions`` is passed as True.
assert_timestamp_and_datetime_equal
python
quantopian/zipline
zipline/testing/predicates.py
https://github.com/quantopian/zipline/blob/master/zipline/testing/predicates.py
Apache-2.0
def assert_messages_equal(result, expected, msg=''): """Assertion helper for comparing very long strings (e.g. error messages). """ # The arg here is "keepends" which keeps trailing newlines (which # matters for checking trailing whitespace). You can't pass keepends by # name :(. left_lines = re...
Assertion helper for comparing very long strings (e.g. error messages).
assert_messages_equal
python
quantopian/zipline
zipline/testing/predicates.py
https://github.com/quantopian/zipline/blob/master/zipline/testing/predicates.py
Apache-2.0
def index_of_first_difference(left, right): """Get the index of the first difference between two strings.""" difflocs = (i for (i, (lc, rc)) in enumerate(zip_longest(left, right)) if lc != rc) try: return next(difflocs) except StopIteration: raise ValueError("Left was equ...
Get the index of the first difference between two strings.
index_of_first_difference
python
quantopian/zipline
zipline/testing/predicates.py
https://github.com/quantopian/zipline/blob/master/zipline/testing/predicates.py
Apache-2.0
def require_not_initialized(exception): """ Decorator for API methods that should only be called during or before TradingAlgorithm.initialize. `exception` will be raised if the method is called after initialize. Examples -------- @require_not_initialized(SomeException("Don't do that!")) ...
Decorator for API methods that should only be called during or before TradingAlgorithm.initialize. `exception` will be raised if the method is called after initialize. Examples -------- @require_not_initialized(SomeException("Don't do that!")) def method(self): # Do stuff that sho...
require_not_initialized
python
quantopian/zipline
zipline/utils/api_support.py
https://github.com/quantopian/zipline/blob/master/zipline/utils/api_support.py
Apache-2.0
def require_initialized(exception): """ Decorator for API methods that should only be called after TradingAlgorithm.initialize. `exception` will be raised if the method is called before initialize has completed. Examples -------- @require_initialized(SomeException("Don't do that!")) de...
Decorator for API methods that should only be called after TradingAlgorithm.initialize. `exception` will be raised if the method is called before initialize has completed. Examples -------- @require_initialized(SomeException("Don't do that!")) def method(self): # Do stuff that sho...
require_initialized
python
quantopian/zipline
zipline/utils/api_support.py
https://github.com/quantopian/zipline/blob/master/zipline/utils/api_support.py
Apache-2.0
def disallowed_in_before_trading_start(exception): """ Decorator for API methods that cannot be called from within TradingAlgorithm.before_trading_start. `exception` will be raised if the method is called inside `before_trading_start`. Examples -------- @disallowed_in_before_trading_start(...
Decorator for API methods that cannot be called from within TradingAlgorithm.before_trading_start. `exception` will be raised if the method is called inside `before_trading_start`. Examples -------- @disallowed_in_before_trading_start(SomeException("Don't do that!")) def method(self): ...
disallowed_in_before_trading_start
python
quantopian/zipline
zipline/utils/api_support.py
https://github.com/quantopian/zipline/blob/master/zipline/utils/api_support.py
Apache-2.0
def parse_argspec(callable_): """ Takes a callable and returns a tuple with the list of Argument objects, the name of *args, and the name of **kwargs. If *args or **kwargs is not present, it will be None. This returns a namedtuple called Argspec that has three fields named: ...
Takes a callable and returns a tuple with the list of Argument objects, the name of *args, and the name of **kwargs. If *args or **kwargs is not present, it will be None. This returns a namedtuple called Argspec that has three fields named: args, starargs, and kwargs.
parse_argspec
python
quantopian/zipline
zipline/utils/argcheck.py
https://github.com/quantopian/zipline/blob/master/zipline/utils/argcheck.py
Apache-2.0
def _expect_extra(expected, present, exc_unexpected, exc_missing, exc_args): """ Checks for the presence of an extra to the argument list. Raises expections if this is unexpected or if it is missing and expected. """ if present: if not expected: raise exc_unexpected(*exc_args) ...
Checks for the presence of an extra to the argument list. Raises expections if this is unexpected or if it is missing and expected.
_expect_extra
python
quantopian/zipline
zipline/utils/argcheck.py
https://github.com/quantopian/zipline/blob/master/zipline/utils/argcheck.py
Apache-2.0
def verify_callable_argspec(callable_, expected_args=Argument.ignore, expect_starargs=Argument.ignore, expect_kwargs=Argument.ignore): """ Checks the callable_ to make sure that it satisfies the given expectations. expec...
Checks the callable_ to make sure that it satisfies the given expectations. expected_args should be an iterable of Arguments in the order you expect to receive them. expect_starargs means that the function should or should not take a *args param. expect_kwargs says the callable should or should...
verify_callable_argspec
python
quantopian/zipline
zipline/utils/argcheck.py
https://github.com/quantopian/zipline/blob/master/zipline/utils/argcheck.py
Apache-2.0
def unwrap(self, dt): """ Get the cached value. Returns ------- value : object The cached value. Raises ------ Expired Raised when `dt` is greater than self.expires. """ expires = self._expires if expires i...
Get the cached value. Returns ------- value : object The cached value. Raises ------ Expired Raised when `dt` is greater than self.expires.
unwrap
python
quantopian/zipline
zipline/utils/cache.py
https://github.com/quantopian/zipline/blob/master/zipline/utils/cache.py
Apache-2.0
def get(self, key, dt): """Get the value of a cached object. Parameters ---------- key : any The key to lookup. dt : datetime The time of the lookup. Returns ------- result : any The value for ``key``. Raises ...
Get the value of a cached object. Parameters ---------- key : any The key to lookup. dt : datetime The time of the lookup. Returns ------- result : any The value for ``key``. Raises ------ KeyError ...
get
python
quantopian/zipline
zipline/utils/cache.py
https://github.com/quantopian/zipline/blob/master/zipline/utils/cache.py
Apache-2.0
def ensure_dir(self, *path_parts): """Ensures a subdirectory of the working directory. Parameters ---------- path_parts : iterable[str] The parts of the path after the working directory. """ path = self.getpath(*path_parts) ensure_directory(path) ...
Ensures a subdirectory of the working directory. Parameters ---------- path_parts : iterable[str] The parts of the path after the working directory.
ensure_dir
python
quantopian/zipline
zipline/utils/cache.py
https://github.com/quantopian/zipline/blob/master/zipline/utils/cache.py
Apache-2.0
def maybe_show_progress(it, show_progress, **kwargs): """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. ...
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 ...
maybe_show_progress
python
quantopian/zipline
zipline/utils/cli.py
https://github.com/quantopian/zipline/blob/master/zipline/utils/cli.py
Apache-2.0
def wraps(wrapped, assigned=functools.WRAPPER_ASSIGNMENTS, updated=functools.WRAPPER_UPDATES): """Decorator factory to apply update_wrapper() to a wrapper function Returns a decorator that invokes update_wrapper() with the decorated function as the wrapper argu...
Decorator factory to apply update_wrapper() to a wrapper function Returns a decorator that invokes update_wrapper() with the decorated function as the wrapper argument and the arguments to wraps() as the remaining arguments. Default arguments are as for update_wrapper(). Thi...
wraps
python
quantopian/zipline
zipline/utils/compat.py
https://github.com/quantopian/zipline/blob/master/zipline/utils/compat.py
Apache-2.0
def oldest_frame(self, raw=False): """ Get the oldest frame in the panel. """ if raw: return self.buffer.values[:, self._start_index, :] return self.buffer.iloc[:, self._start_index, :]
Get the oldest frame in the panel.
oldest_frame
python
quantopian/zipline
zipline/utils/data.py
https://github.com/quantopian/zipline/blob/master/zipline/utils/data.py
Apache-2.0
def extend_back(self, missing_dts): """ Resizes the buffer to hold a new window with a new cap_multiple. If cap_multiple is None, then the old cap_multiple is used. """ delta = len(missing_dts) if not delta: raise ValueError( 'missing_dts must...
Resizes the buffer to hold a new window with a new cap_multiple. If cap_multiple is None, then the old cap_multiple is used.
extend_back
python
quantopian/zipline
zipline/utils/data.py
https://github.com/quantopian/zipline/blob/master/zipline/utils/data.py
Apache-2.0
def get_current(self, item=None, raw=False, start=None, end=None): """ Get a Panel that is the current data in view. It is not safe to persist these objects because internal data might change """ item_indexer = slice(None) if item: item_indexer = self.items.ge...
Get a Panel that is the current data in view. It is not safe to persist these objects because internal data might change
get_current
python
quantopian/zipline
zipline/utils/data.py
https://github.com/quantopian/zipline/blob/master/zipline/utils/data.py
Apache-2.0
def set_current(self, panel): """ Set the values stored in our current in-view data to be values of the passed panel. The passed panel must have the same indices as the panel that would be returned by self.get_current. """ where = slice(self._start_index, self._pos) ...
Set the values stored in our current in-view data to be values of the passed panel. The passed panel must have the same indices as the panel that would be returned by self.get_current.
set_current
python
quantopian/zipline
zipline/utils/data.py
https://github.com/quantopian/zipline/blob/master/zipline/utils/data.py
Apache-2.0
def _roll_data(self): """ Roll window worth of data up to position zero. Save the effort of having to expensively roll at each iteration """ self.buffer.values[:, :self._window, :] = \ self.buffer.values[:, -self._window:, :] self.date_buf[:self._window] = se...
Roll window worth of data up to position zero. Save the effort of having to expensively roll at each iteration
_roll_data
python
quantopian/zipline
zipline/utils/data.py
https://github.com/quantopian/zipline/blob/master/zipline/utils/data.py
Apache-2.0
def compute_date_range_chunks(sessions, start_date, end_date, chunksize): """Compute the start and end dates to run a pipeline for. Parameters ---------- sessions : DatetimeIndex The available dates. start_date : pd.Timestamp The first date in the pipeline. end_date : pd.Timesta...
Compute the start and end dates to run a pipeline for. Parameters ---------- sessions : DatetimeIndex The available dates. start_date : pd.Timestamp The first date in the pipeline. end_date : pd.Timestamp The last date in the pipeline. chunksize : int or None The...
compute_date_range_chunks
python
quantopian/zipline
zipline/utils/date_utils.py
https://github.com/quantopian/zipline/blob/master/zipline/utils/date_utils.py
Apache-2.0
def deprecated(msg=None, stacklevel=2): """ Used to mark a function as deprecated. Parameters ---------- msg : str The message to display in the deprecation warning. stacklevel : int How far up the stack the warning needs to go, before showing the relevant calling lines....
Used to mark a function as deprecated. Parameters ---------- msg : str The message to display in the deprecation warning. stacklevel : int How far up the stack the warning needs to go, before showing the relevant calling lines. Examples -------- @deprecated(msg...
deprecated
python
quantopian/zipline
zipline/utils/deprecate.py
https://github.com/quantopian/zipline/blob/master/zipline/utils/deprecate.py
Apache-2.0
def enum(option, *options): """ Construct a new enum object. Parameters ---------- *options : iterable of str The names of the fields for the enum. Returns ------- enum A new enum collection. Examples -------- >>> e = enum('a', 'b', 'c') >>> e <enum...
Construct a new enum object. Parameters ---------- *options : iterable of str The names of the fields for the enum. Returns ------- enum A new enum collection. Examples -------- >>> e = enum('a', 'b', 'c') >>> e <enum: ('a', 'b', 'c')> >>> e.a ...
enum
python
quantopian/zipline
zipline/utils/enum.py
https://github.com/quantopian/zipline/blob/master/zipline/utils/enum.py
Apache-2.0
def naive_to_utc(ts): """ Converts a UTC tz-naive timestamp to a tz-aware timestamp. """ # Drop the nanoseconds field. warn=False suppresses the warning # that we are losing the nanoseconds; however, this is intended. return pd.Timestamp(ts.to_pydatetime(warn=False), tz='UTC')
Converts a UTC tz-naive timestamp to a tz-aware timestamp.
naive_to_utc
python
quantopian/zipline
zipline/utils/events.py
https://github.com/quantopian/zipline/blob/master/zipline/utils/events.py
Apache-2.0
def ensure_utc(time, tz='UTC'): """ Normalize a time. If the time is tz-naive, assume it is UTC. """ if not time.tzinfo: time = time.replace(tzinfo=pytz.timezone(tz)) return time.replace(tzinfo=pytz.utc)
Normalize a time. If the time is tz-naive, assume it is UTC.
ensure_utc
python
quantopian/zipline
zipline/utils/events.py
https://github.com/quantopian/zipline/blob/master/zipline/utils/events.py
Apache-2.0
def _build_offset(offset, kwargs, default): """ Builds the offset argument for event rules. """ # Filter down to just kwargs that were actually passed. kwargs = {k: v for k, v in six.iteritems(kwargs) if v is not None} if offset is None: if not kwargs: return default # use t...
Builds the offset argument for event rules.
_build_offset
python
quantopian/zipline
zipline/utils/events.py
https://github.com/quantopian/zipline/blob/master/zipline/utils/events.py
Apache-2.0