INSTRUCTION
stringlengths
1
8.43k
RESPONSE
stringlengths
75
104k
Restride an array of shape
def rolling_window(array, length): """ Restride an array of shape (X_0, ... X_N) into an array of shape (length, X_0 - length + 1, ... X_N) where each slice at index i along the first axis is equivalent to result[i] = array[length * i:length * (i + 1)] Parameters --...
Check if a value is np. NaT.
def isnat(obj): """ Check if a value is np.NaT. """ if obj.dtype.kind not in ('m', 'M'): raise ValueError("%s is not a numpy datetime or timedelta") return obj.view(int64_dtype) == iNaT
Generic is_missing function that handles NaN and NaT.
def is_missing(data, missing_value): """ Generic is_missing function that handles NaN and NaT. """ 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)
Simple of numpy. busday_count that returns float arrays rather than int arrays and handles NaT s by returning NaN s where the inputs were NaT.
def busday_count_mask_NaT(begindates, enddates, out=None): """ Simple of numpy.busday_count that returns `float` arrays rather than int arrays, and handles `NaT`s by returning `NaN`s where the inputs were `NaT`. Doesn't support custom weekdays or calendars, but probably should in the future. S...
Compute indices of values in a that differ from the previous value.
def changed_locations(a, include_first): """ Compute indices of values in ``a`` that differ from the previous value. Parameters ---------- a : np.ndarray The array on which to indices of change. include_first : bool Whether or not to consider the first index of the array as "cha...
Compute the start and end dates to run a pipeline for.
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 a pipeline.
def run_pipeline(self, pipeline, start_date, end_date): """ Compute a pipeline. Parameters ---------- pipeline : zipline.pipeline.Pipeline The pipeline to run. start_date : pd.Timestamp Start date of the computed matrix. end_date : pd.Time...
Compute a lifetimes matrix from our AssetFinder then drop columns that didn t exist at all during the query dates.
def _compute_root_mask(self, domain, start_date, end_date, extra_rows): """ Compute a lifetimes matrix from our AssetFinder, then drop columns that didn't exist at all during the query dates. Parameters ---------- domain : zipline.pipeline.domain.Domain Domai...
Compute the Pipeline terms in the graph for the requested start and end dates.
def compute_chunk(self, graph, dates, sids, initial_workspace): """ Compute the Pipeline terms in the graph for the requested start and end dates. This is where we do the actual work of running a pipeline. Parameters ---------- graph : zipline.pipeline.graph.Exe...
Convert raw computed pipeline results into a DataFrame for public APIs.
def _to_narrow(self, terms, data, mask, dates, assets): """ Convert raw computed pipeline results into a DataFrame for public APIs. Parameters ---------- terms : dict[str -> Term] Dict mapping column names to terms. data : dict[str -> ndarray[ndim=2]] ...
Verify that the values passed to compute_chunk are well - formed.
def _validate_compute_chunk_params(self, graph, dates, sids, initial_workspace): """ Verify that the values passed to compute_chunk are well-formed....
Resolve a concrete domain for pipeline.
def resolve_domain(self, pipeline): """Resolve a concrete domain for ``pipeline``. """ domain = pipeline.domain(default=self._default_domain) if domain is GENERIC: raise ValueError( "Unable to determine domain for Pipeline.\n" "Pass domain=<des...
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.
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 cannot be called from within TradingAlgorithm. before_trading_start. exception will be raised if the method is called inside before_trading_start.
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(...
Simple implementation of grouped row - wise function application.
def naive_grouped_rowwise_apply(data, group_labels, func, func_args=(), out=None): """ Simple implementation of grouped row-wise function application. Parameters ---------- ...
Format a bulleted list of values.
def bulleted_list(items, indent=0, bullet_type='-'): """Format a bulleted list of values. Parameters ---------- items : sequence The items to make a list. indent : int, optional The number of spaces to add before each bullet. bullet_type : str, optional The bullet type t...
Create a DataFrame representing lifetimes of assets that are constantly rotating in and out of existence.
def make_rotating_equity_info(num_assets, first_start, frequency, periods_between_starts, asset_lifetime, exchange='TEST'): """ Create a DataFrame representing li...
Create a DataFrame representing assets that exist for the full duration between start_date and end_date.
def make_simple_equity_info(sids, start_date, end_date, symbols=None, names=None, exchange='TEST'): """ Create a DataFrame representing assets that exist for the full durat...
Create a DataFrame representing assets that exist for the full duration between start_date and end_date from multiple countries.
def make_simple_multi_country_equity_info(countries_to_sids, countries_to_exchanges, start_date, end_date): """Create a DataFrame representing assets that exist for the full duration bet...
Create a DataFrame representing assets that all begin at the same start date but have cascading end dates.
def make_jagged_equity_info(num_assets, start_date, first_end, frequency, periods_between_ends, auto_close_delta): """ Create a DataFrame representing assets that all begin...
Create a DataFrame representing futures for root_symbols during year.
def make_future_info(first_sid, root_symbols, years, notice_date_func, expiration_date_func, start_date_func, month_codes=None, multiplier=500): """ Create a DataFra...
Make futures testing data that simulates the notice/ expiration date behavior of physical commodities like oil.
def make_commodity_future_info(first_sid, root_symbols, years, month_codes=None, multiplier=500): """ Make futures testing data that simulates the notice/expiration date behavior of ph...
Construct a Filter returning True for asset/ date pairs where the output of self matches other.
def eq(self, other): """ Construct a Filter returning True for asset/date pairs where the output of ``self`` matches ``other``. """ # We treat this as an error because missing_values have NaN semantics, # which means this would return an array of all False, which is almos...
Construct a Filter matching values starting with prefix.
def startswith(self, prefix): """ Construct a Filter matching values starting with ``prefix``. Parameters ---------- prefix : str String prefix against which to compare values produced by ``self``. Returns ------- matches : Filter ...
Construct a Filter matching values ending with suffix.
def endswith(self, suffix): """ Construct a Filter matching values ending with ``suffix``. Parameters ---------- suffix : str String suffix against which to compare values produced by ``self``. Returns ------- matches : Filter Fil...
Construct a Filter matching values containing substring.
def has_substring(self, substring): """ Construct a Filter matching values containing ``substring``. Parameters ---------- substring : str Sub-string against which to compare values produced by ``self``. Returns ------- matches : Filter ...
Construct a Filter that checks regex matches against pattern.
def matches(self, pattern): """ Construct a Filter that checks regex matches against ``pattern``. Parameters ---------- pattern : str Regex pattern against which to compare values produced by ``self``. Returns ------- matches : Filter ...
Construct a Filter indicating whether values are in choices.
def element_of(self, choices): """ Construct a Filter indicating whether values are in ``choices``. Parameters ---------- choices : iterable[str or int] An iterable of choices. Returns ------- matches : Filter Filter returning Tru...
Called with the result of a pipeline. This needs to return an object which can be put into the workspace to continue doing computations.
def to_workspace_value(self, result, assets): """ Called with the result of a pipeline. This needs to return an object which can be put into the workspace to continue doing computations. This is the inverse of :func:`~zipline.pipeline.term.Term.postprocess`. """ if self....
Convert an array produced by this classifier into an array of integer labels and a missing value label.
def _to_integral(self, output_array): """ Convert an array produced by this classifier into an array of integer labels and a missing value label. """ if self.dtype == int64_dtype: group_labels = output_array null_label = self.missing_value elif sel...
Override the default array allocation to produce a LabelArray when we have a string - like dtype.
def _allocate_output(self, windows, shape): """ Override the default array allocation to produce a LabelArray when we have a string-like dtype. """ if self.dtype == int64_dtype: return super(CustomClassifier, self)._allocate_output( windows, ...
Check that all axes of a pandas object are unique.
def verify_indices_all_unique(obj): """ Check that all axes of a pandas object are unique. Parameters ---------- obj : pd.Series / pd.DataFrame / pd.Panel The object to validate. Returns ------- obj : pd.Series / pd.DataFrame / pd.Panel The validated object, unchanged. ...
Modify a preprocessor to explicitly allow None.
def optionally(preprocessor): """Modify a preprocessor to explicitly allow `None`. Parameters ---------- preprocessor : callable[callable, str, any -> any] A preprocessor to delegate to when `arg is not None`. Returns ------- optional_preprocessor : callable[callable, str, any -> a...
Argument preprocessor that converts the input into a numpy dtype.
def ensure_dtype(func, argname, arg): """ Argument preprocessor that converts the input into a numpy dtype. Examples -------- >>> import numpy as np >>> from zipline.utils.preprocess import preprocess >>> @preprocess(dtype=ensure_dtype) ... def foo(dtype): ... return dtype ....
Argument preprocessor that converts the input into a tzinfo object.
def ensure_timezone(func, argname, arg): """Argument preprocessor that converts the input into a tzinfo object. Examples -------- >>> from zipline.utils.preprocess import preprocess >>> @preprocess(tz=ensure_timezone) ... def foo(tz): ... return tz >>> foo('utc') <UTC> """ ...
Argument preprocessor that converts the input into a pandas Timestamp object.
def ensure_timestamp(func, argname, arg): """Argument preprocessor that converts the input into a pandas Timestamp object. Examples -------- >>> from zipline.utils.preprocess import preprocess >>> @preprocess(ts=ensure_timestamp) ... def foo(ts): ... return ts >>> foo('2014-01-0...
Preprocessing decorator that verifies inputs have expected numpy dtypes.
def expect_dtypes(__funcname=_qualified_name, **named): """ Preprocessing decorator that verifies inputs have expected numpy dtypes. Examples -------- >>> from numpy import dtype, arange, int8, float64 >>> @expect_dtypes(x=dtype(int8)) ... def foo(x, y): ... return x, y ... >...
Preprocessing decorator that verifies inputs have expected dtype kinds.
def expect_kinds(**named): """ Preprocessing decorator that verifies inputs have expected dtype kinds. Examples -------- >>> from numpy import int64, int32, float32 >>> @expect_kinds(x='i') ... def foo(x): ... return x ... >>> foo(int64(2)) 2 >>> foo(int32(2)) 2 ...
Preprocessing decorator that verifies inputs have expected types.
def expect_types(__funcname=_qualified_name, **named): """ Preprocessing decorator that verifies inputs have expected types. Examples -------- >>> @expect_types(x=int, y=str) ... def foo(x, y): ... return x, y ... >>> foo(2, '3') (2, '3') >>> foo(2.0, '3') # doctest: +NO...
Factory for making preprocessing functions that check a predicate on the input value.
def make_check(exc_type, template, pred, actual, funcname): """ Factory for making preprocessing functions that check a predicate on the input value. Parameters ---------- exc_type : Exception The exception type to raise if the predicate fails. template : str A template stri...
Preprocessing decorator that verifies inputs are elements of some expected collection.
def expect_element(__funcname=_qualified_name, **named): """ Preprocessing decorator that verifies inputs are elements of some expected collection. Examples -------- >>> @expect_element(x=('a', 'b')) ... def foo(x): ... return x.upper() ... >>> foo('a') 'A' >>> foo('b...
Preprocessing decorator verifying that inputs fall INCLUSIVELY between bounds.
def expect_bounded(__funcname=_qualified_name, **named): """ Preprocessing decorator verifying that inputs fall INCLUSIVELY between bounds. Bounds should be passed as a pair of ``(min_value, max_value)``. ``None`` may be passed as ``min_value`` or ``max_value`` to signify that the input is onl...
Preprocessing decorator that verifies inputs are numpy arrays with a specific dimensionality.
def expect_dimensions(__funcname=_qualified_name, **dimensions): """ Preprocessing decorator that verifies inputs are numpy arrays with a specific dimensionality. Examples -------- >>> from numpy import array >>> @expect_dimensions(x=1, y=2) ... def foo(x, y): ... return x[0] + y...
A preprocessing decorator that coerces inputs of a given type by passing them to a callable.
def coerce(from_, to, **to_kwargs): """ A preprocessing decorator that coerces inputs of a given type by passing them to a callable. Parameters ---------- from : type or tuple or types Inputs types on which to call ``to``. to : function Coercion function to call on inputs. ...
Preprocessing decorator that applies type coercions.
def coerce_types(**kwargs): """ Preprocessing decorator that applies type coercions. Parameters ---------- **kwargs : dict[str -> (type, callable)] Keyword arguments mapping function parameter names to pairs of (from_type, to_type). Examples -------- >>> @coerce_types...
Validate that a dictionary has an expected set of keys.
def validate_keys(dict_, expected, funcname): """Validate that a dictionary has an expected set of keys. """ expected = set(expected) received = set(dict_) missing = expected - received if missing: raise ValueError( "Missing keys in {}:\n" "Expected Keys: {}\n" ...
Construct a new enum object.
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...
Get the oldest frame in the panel.
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, :]
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.
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...
Get a Panel that is the current data in view. It is not safe to persist these objects because internal data might change
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...
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.
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) ...
Roll window worth of data up to position zero. Save the effort of having to expensively roll at each iteration
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...
Get the oldest frame in the panel.
def oldest_frame(self, raw=False): """ Get the oldest frame in the panel. """ if raw: return self.buffer.values[:, self._oldest_frame_idx(), :] return self.buffer.iloc[:, self._oldest_frame_idx(), :]
Get a Panel that is the current data in view. It is not safe to persist these objects because internal data might change
def get_current(self): """ Get a Panel that is the current data in view. It is not safe to persist these objects because internal data might change """ where = slice(self._oldest_frame_idx(), self._pos) major_axis = pd.DatetimeIndex(deepcopy(self.date_buf[where]), tz='ut...
Update internal state based on price triggers and the trade event s price.
def check_triggers(self, price, dt): """ Update internal state based on price triggers and the trade event's price. """ stop_reached, limit_reached, sl_stop_reached = \ self.check_order_triggers(price) if (stop_reached, limit_reached) \ != (sel...
Given an order and a trade event return a tuple of ( stop_reached limit_reached ). For market orders will return ( False False ). For stop orders limit_reached will always be False. For limit orders stop_reached will always be False. For stop limit orders a Boolean is returned to flag that the stop has been reached.
def check_order_triggers(self, current_price): """ Given an order and a trade event, return a tuple of (stop_reached, limit_reached). For market orders, will return (False, False). For stop orders, limit_reached will always be False. For limit orders, stop_reached will al...
For a market order True. For a stop order True IFF stop_reached. For a limit order True IFF limit_reached.
def triggered(self): """ For a market order, True. For a stop order, True IFF stop_reached. For a limit order, True IFF limit_reached. """ if self.stop is not None and not self.stop_reached: return False if self.limit is not None and not self.limit_re...
Lives in zipline. __init__ for doctests.
def setup(self, np=np, numpy_version=numpy_version, StrictVersion=StrictVersion, new_pandas=new_pandas): """Lives in zipline.__init__ for doctests.""" if numpy_version >= StrictVersion('1.14'): self.old_opts = np.get_printoptions() np.set_printoptions(leg...
Lives in zipline. __init__ for doctests.
def teardown(self, np=np): """Lives in zipline.__init__ for doctests.""" if self.old_err is not None: np.seterr(**self.old_err) if self.old_opts is not None: np.set_printoptions(**self.old_opts)
Define a unique string for any set of representable args.
def hash_args(*args, **kwargs): """Define a unique string for any set of representable args.""" arg_string = '_'.join([str(arg) for arg in args]) kwarg_string = '_'.join([str(key) + '=' + str(value) for key, value in iteritems(kwargs)]) combined = ':'.join([arg_string, kwarg...
Assert that an event meets the protocol for datasource outputs.
def assert_datasource_protocol(event): """Assert that an event meets the protocol for datasource outputs.""" assert event.type in DATASOURCE_TYPE # Done packets have no dt. if not event.type == DATASOURCE_TYPE.DONE: assert isinstance(event.dt, datetime) assert event.dt.tzinfo == pytz.u...
Assert that an event meets the protocol for datasource TRADE outputs.
def assert_trade_protocol(event): """Assert that an event meets the protocol for datasource TRADE outputs.""" assert_datasource_protocol(event) assert event.type == DATASOURCE_TYPE.TRADE assert isinstance(event.price, numbers.Real) assert isinstance(event.volume, numbers.Integral) assert isinst...
Takes an iterable of sources generating namestrings and piping their output into date_sort.
def date_sorted_sources(*sources): """ Takes an iterable of sources, generating namestrings and piping their output into date_sort. """ sorted_stream = heapq.merge(*(_decorate_source(s) for s in sources)) # Strip out key decoration for _, message in sorted_stream: yield message
creates trade_count trades for each sid in sids list. first trade will be on sim_params. start_session and daily thereafter for each sid. Thus two sids should result in two trades per day.
def create_daily_trade_source(sids, sim_params, asset_finder, trading_calendar): """ creates trade_count trades for each sid in sids list. first trade will be on sim_params.start_session, and daily thereafter for e...
Load data table from zip file provided by Quandl.
def load_data_table(file, index_col, show_progress=False): """ Load data table from zip file provided by Quandl. """ with ZipFile(file) as zip_file: file_names = zip_file.namelist() assert len(file_names) == 1, "Expected a single file from Quandl." ...
Fetch WIKI Prices data table from Quandl
def fetch_data_table(api_key, show_progress, retries): """ Fetch WIKI Prices data table from Quandl """ for _ in range(retries): try: if show_progress: log.info('Downloading WIKI metadata.') metadata = pd.read_csv( ...
quandl_bundle builds a daily dataset using Quandl s WIKI Prices dataset.
def quandl_bundle(environ, asset_db_writer, minute_bar_writer, daily_bar_writer, adjustment_writer, calendar, start_session, end_session, cache, show_progress...
Download streaming data from a URL printing progress information to the terminal.
def download_with_progress(url, chunk_size, **progress_kwargs): """ Download streaming data from a URL, printing progress information to the terminal. Parameters ---------- url : str A URL that can be understood by ``requests.get``. chunk_size : int Number of bytes to read a...
Download data from a URL returning a BytesIO containing the loaded data.
def download_without_progress(url): """ Download data from a URL, returning a BytesIO containing the loaded data. Parameters ---------- url : str A URL that can be understood by ``requests.get``. Returns ------- data : BytesIO A BytesIO containing the downloaded data. ...
Resample a DataFrame with minute data into the frame expected by a BcolzDailyBarWriter.
def minute_frame_to_session_frame(minute_frame, calendar): """ Resample a DataFrame with minute data into the frame expected by a BcolzDailyBarWriter. Parameters ---------- minute_frame : pd.DataFrame A DataFrame with the columns `open`, `high`, `low`, `close`, `volume`, and `d...
Resample an array with minute data into an array with session data.
def minute_to_session(column, close_locs, data, out): """ Resample an array with minute data into an array with session data. This function assumes that the minute data is the exact length of all minutes in the sessions in the output. Parameters ---------- column : str The `open`, ...
The open field s aggregation returns the first value that occurs for the day if there has been no data on or before the dt the open is nan.
def opens(self, assets, dt): """ The open field's aggregation returns the first value that occurs for the day, if there has been no data on or before the `dt` the open is `nan`. Once the first non-nan open is seen, that value remains constant per asset for the remainder ...
The high field s aggregation returns the largest high seen between the market open and the current dt. If there has been no data on or before the dt the high is nan.
def highs(self, assets, dt): """ The high field's aggregation returns the largest high seen between the market open and the current dt. If there has been no data on or before the `dt` the high is `nan`. Returns ------- np.array with dtype=float64, in order of ass...
The low field s aggregation returns the smallest low seen between the market open and the current dt. If there has been no data on or before the dt the low is nan.
def lows(self, assets, dt): """ The low field's aggregation returns the smallest low seen between the market open and the current dt. If there has been no data on or before the `dt` the low is `nan`. Returns ------- np.array with dtype=float64, in order of assets...
The close field s aggregation returns the latest close at the given dt. If the close for the given dt is nan the most recent non - nan close is used. If there has been no data on or before the dt the close is nan.
def closes(self, assets, dt): """ The close field's aggregation returns the latest close at the given dt. If the close for the given dt is `nan`, the most recent non-nan `close` is used. If there has been no data on or before the `dt` the close is `nan`. Returns ...
The volume field s aggregation returns the sum of all volumes between the market open and the dt If there has been no data on or before the dt the volume is 0.
def volumes(self, assets, dt): """ The volume field's aggregation returns the sum of all volumes between the market open and the `dt` If there has been no data on or before the `dt` the volume is 0. Returns ------- np.array with dtype=int64, in order of assets pa...
Infer the domain from a collection of terms.
def infer_domain(terms): """ Infer the domain from a collection of terms. The algorithm for inferring domains is as follows: - If all input terms have a domain of GENERIC, the result is GENERIC. - If there is exactly one non-generic domain in the input terms, the result is that domain. ...
Given a date align it to the calendar of the pipeline s domain.
def roll_forward(self, dt): """ Given a date, align it to the calendar of the pipeline's domain. Parameters ---------- dt : pd.Timestamp Returns ------- pd.Timestamp """ dt = pd.Timestamp(dt, tz='UTC') trading_days = self.all_ses...
Returns the date index and sid columns shared by a list of dataframes ensuring they all match.
def days_and_sids_for_frames(frames): """ Returns the date index and sid columns shared by a list of dataframes, ensuring they all match. Parameters ---------- frames : list[pd.DataFrame] A list of dataframes indexed by day, with a column per sid. Returns ------- days : np....
Parameters ---------- frames: dict [ str pd. DataFrame ] A dict mapping each OHLCV field to a dataframe with a row for each date and a column for each sid as passed to write ().
def compute_asset_lifetimes(frames): """ Parameters ---------- frames : dict[str, pd.DataFrame] A dict mapping each OHLCV field to a dataframe with a row for each date and a column for each sid, as passed to write(). Returns ------- start_date_ixs : np.array[int64] T...
Write the OHLCV data for one country to the HDF5 file.
def write(self, country_code, frames, scaling_factors=None): """Write the OHLCV data for one country to the HDF5 file. Parameters ---------- country_code : str The ISO 3166 alpha-2 country code for this country. frames : dict[str, pd.DataFrame] A dict map...
Parameters ---------- country_code: str The ISO 3166 alpha - 2 country code for this country. data: iterable [ tuple [ int pandas. DataFrame ]] The data chunks to write. Each chunk should be a tuple of sid and the data for that asset. scaling_factors: dict [ str float ] optional A dict mapping each OHLCV field to a sca...
def write_from_sid_df_pairs(self, country_code, data, scaling_factors=None): """ Parameters ---------- country_code : str The ISO 3166 alpha-2 country code for this country. ...
Construct from an h5py. File and a country code.
def from_file(cls, h5_file, country_code): """ Construct from an h5py.File and a country code. Parameters ---------- h5_file : h5py.File An HDF5 daily pricing file. country_code : str The ISO 3166 alpha-2 country code for the country to read. ...
Construct from a file path and a country code.
def from_path(cls, path, country_code): """ Construct from a file path and a country code. Parameters ---------- path : str The path to an HDF5 daily pricing file. country_code : str The ISO 3166 alpha-2 country code for the country to read. ...
Parameters ---------- columns: list of str open high low close or volume start_date: Timestamp Beginning of the window range. end_date: Timestamp End of the window range. assets: list of int The asset identifiers in the window.
def load_raw_arrays(self, columns, start_date, end_date, assets): """ Parameters ---------- columns : list of str 'open', 'high', 'low', 'close', or 'volume' start_date: Tim...
Build an indexer mapping self. sids to assets.
def _make_sid_selector(self, assets): """ Build an indexer mapping ``self.sids`` to ``assets``. Parameters ---------- assets : list[int] List of assets requested by a caller of ``load_raw_arrays``. Returns ------- index : np.array[int64] ...
Validate that asset identifiers are contained in the daily bars.
def _validate_assets(self, assets): """Validate that asset identifiers are contained in the daily bars. Parameters ---------- assets : array-like[int] The asset identifiers to validate. Raises ------ NoDataForSid If one or more of the prov...
Retrieve the value at the given coordinates.
def get_value(self, sid, dt, field): """ Retrieve the value at the given coordinates. Parameters ---------- sid : int The asset identifier. dt : pd.Timestamp The timestamp for the desired data point. field : string The OHLVC na...
Get the latest day on or before dt in which asset traded.
def get_last_traded_dt(self, asset, dt): """ Get the latest day on or before ``dt`` in which ``asset`` traded. If there are no trades on or before ``dt``, returns ``pd.NaT``. Parameters ---------- asset : zipline.asset.Asset The asset for which to get the la...
Construct from an h5py. File.
def from_file(cls, h5_file): """ Construct from an h5py.File. Parameters ---------- h5_file : h5py.File An HDF5 daily pricing file. """ return cls({ country: HDF5DailyBarReader.from_file(h5_file, country) for country in h5_file...
Parameters ---------- columns: list of str open high low close or volume start_date: Timestamp Beginning of the window range. end_date: Timestamp End of the window range. assets: list of int The asset identifiers in the window.
def load_raw_arrays(self, columns, start_date, end_date, assets): """ Parameters ---------- columns : list of str 'open', 'high', 'low', 'close', or 'volume' start_date: Tim...
Returns ------- sessions: DatetimeIndex All session labels ( unioning the range for all assets ) which the reader can provide.
def sessions(self): """ Returns ------- sessions : DatetimeIndex All session labels (unioning the range for all assets) which the reader can provide. """ return pd.to_datetime( reduce( np.union1d, (reader.d...
Retrieve the value at the given coordinates.
def get_value(self, sid, dt, field): """ Retrieve the value at the given coordinates. Parameters ---------- sid : int The asset identifier. dt : pd.Timestamp The timestamp for the desired data point. field : string The OHLVC na...
Get the latest day on or before dt in which asset traded.
def get_last_traded_dt(self, asset, dt): """ Get the latest day on or before ``dt`` in which ``asset`` traded. If there are no trades on or before ``dt``, returns ``pd.NaT``. Parameters ---------- asset : zipline.asset.Asset The asset for which to get the la...
Update dataframes in place to set indentifier columns as indices.
def _normalize_index_columns_in_place(equities, equity_supplementary_mappings, futures, exchanges, root_symbols): """ Update dataframes in place to set indentif...
Takes in a symbol that may be delimited and splits it in to a company symbol and share class symbol. Also returns the fuzzy symbol which is the symbol without any fuzzy characters at all.
def split_delimited_symbol(symbol): """ Takes in a symbol that may be delimited and splits it in to a company symbol and share class symbol. Also returns the fuzzy symbol, which is the symbol without any fuzzy characters at all. Parameters ---------- symbol : str The possibly-delimi...
Generates an output dataframe from the given subset of user - provided data the given column names and the given default values.
def _generate_output_dataframe(data_subset, defaults): """ Generates an output dataframe from the given subset of user-provided data, the given column names, and the given default values. Parameters ---------- data_subset : DataFrame A DataFrame, usually from an AssetData object, ...
Check that there are no cases where multiple symbols resolve to the same asset at the same time in the same country.
def _check_symbol_mappings(df, exchanges, asset_exchange): """Check that there are no cases where multiple symbols resolve to the same asset at the same time in the same country. Parameters ---------- df : pd.DataFrame The equity symbol mappings table. exchanges : pd.DataFrame T...
Split out the symbol: sid mappings from the raw data.
def _split_symbol_mappings(df, exchanges): """Split out the symbol: sid mappings from the raw data. Parameters ---------- df : pd.DataFrame The dataframe with multiple rows for each symbol: sid pair. exchanges : pd.DataFrame The exchanges table. Returns ------- asset_in...
Convert a timeseries into an Int64Index of nanoseconds since the epoch.
def _dt_to_epoch_ns(dt_series): """Convert a timeseries into an Int64Index of nanoseconds since the epoch. Parameters ---------- dt_series : pd.Series The timeseries to convert. Returns ------- idx : pd.Int64Index The index converted to nanoseconds since the epoch. """ ...