Code stringlengths 103 85.9k | Summary listlengths 0 94 |
|---|---|
Please provide a description of the function:def data_len_for_day(self, day):
day_ix = self._session_labels.get_loc(day)
# Add one to the 0-indexed day_ix to get the number of days.
num_days = day_ix + 1
return num_days * self._minutes_per_day | [
"\n Return the number of data points up to and including the\n provided day.\n "
] |
Please provide a description of the function:def truncate(self, date):
truncate_slice_end = self.data_len_for_day(date)
glob_path = os.path.join(self._rootdir, "*", "*", "*.bcolz")
sid_paths = sorted(glob(glob_path))
for sid_path in sid_paths:
file_name = os.path.b... | [
"Truncate data beyond this date in all ctables."
] |
Please provide a description of the function:def _minutes_to_exclude(self):
market_opens = self._market_opens.values.astype('datetime64[m]')
market_closes = self._market_closes.values.astype('datetime64[m]')
minutes_per_day = (market_closes - market_opens).astype(np.int64)
early... | [
"\n Calculate the minutes which should be excluded when a window\n occurs on days which had an early close, i.e. days where the close\n based on the regular period of minutes per day and the market close\n do not match.\n\n Returns\n -------\n List of DatetimeIndex r... |
Please provide a description of the function:def _minute_exclusion_tree(self):
itree = IntervalTree()
for market_open, early_close in self._minutes_to_exclude():
start_pos = self._find_position_of_minute(early_close) + 1
end_pos = (
self._find_position_of... | [
"\n Build an interval tree keyed by the start and end of each range\n of positions should be dropped from windows. (These are the minutes\n between an early close and the minute which would be the close based\n on the regular period if there were no early close.)\n The value of ea... |
Please provide a description of the function:def _exclusion_indices_for_range(self, start_idx, end_idx):
itree = self._minute_exclusion_tree
if itree.overlaps(start_idx, end_idx):
ranges = []
intervals = itree[start_idx:end_idx]
for interval in intervals:
... | [
"\n Returns\n -------\n List of tuples of (start, stop) which represent the ranges of minutes\n which should be excluded when a market minute window is requested.\n "
] |
Please provide a description of the function:def get_value(self, sid, dt, field):
if self._last_get_value_dt_value == dt.value:
minute_pos = self._last_get_value_dt_position
else:
try:
minute_pos = self._find_position_of_minute(dt)
except Valu... | [
"\n Retrieve the pricing info for the given sid, dt, and field.\n\n Parameters\n ----------\n sid : int\n Asset identifier.\n dt : datetime-like\n The datetime at which the trade occurred.\n field : string\n The type of pricing data to retri... |
Please provide a description of the function:def _find_position_of_minute(self, minute_dt):
return find_position_of_minute(
self._market_open_values,
self._market_close_values,
minute_dt.value / NANOS_IN_MINUTE,
self._minutes_per_day,
False,
... | [
"\n Internal method that returns the position of the given minute in the\n list of every trading minute since market open of the first trading\n day. Adjusts non market minutes to the last close.\n\n ex. this method would return 1 for 2002-01-02 9:32 AM Eastern, if\n 2002-01-02 is... |
Please provide a description of the function:def load_raw_arrays(self, fields, start_dt, end_dt, sids):
start_idx = self._find_position_of_minute(start_dt)
end_idx = self._find_position_of_minute(end_dt)
num_minutes = (end_idx - start_idx + 1)
results = []
indices_to_... | [
"\n Parameters\n ----------\n fields : list of str\n 'open', 'high', 'low', 'close', or 'volume'\n start_dt: Timestamp\n Beginning of the window range.\n end_dt: Timestamp\n End of the window range.\n sids : list of int\n The asset id... |
Please provide a description of the function:def write(self, frames):
with HDFStore(self._path, 'w',
complevel=self._complevel, complib=self._complib) \
as store:
panel = pd.Panel.from_dict(dict(frames))
panel.to_hdf(store, 'updates')
... | [
"\n Write the frames to the target HDF5 file, using the format used by\n ``pd.Panel.to_hdf``\n\n Parameters\n ----------\n frames : iter[(int, DataFrame)] or dict[int -> DataFrame]\n An iterable or other mapping of sid to the corresponding OHLCV\n pricing dat... |
Please provide a description of the function:def next_event_indexer(all_dates,
data_query_cutoff,
all_sids,
event_dates,
event_timestamps,
event_sids):
validate_event_metadata(event_dates, event_t... | [
"\n Construct an index array that, when applied to an array of values, produces\n a 2D array containing the values associated with the next event for each\n sid at each moment in time.\n\n Locations where no next event was known will be filled with -1.\n\n Parameters\n ----------\n all_dates : ... |
Please provide a description of the function:def previous_event_indexer(data_query_cutoff_times,
all_sids,
event_dates,
event_timestamps,
event_sids):
validate_event_metadata(event_dates, event_timestamp... | [
"\n Construct an index array that, when applied to an array of values, produces\n a 2D array containing the values associated with the previous event for\n each sid at each moment in time.\n\n Locations where no previous event was known will be filled with -1.\n\n Parameters\n ----------\n data... |
Please provide a description of the function:def last_in_date_group(df,
data_query_cutoff_times,
assets,
reindex=True,
have_sids=True,
extra_groupers=None):
idx = [data_query_cutoff_times[data_que... | [
"\n Determine the last piece of information known on each date in the date\n\n index for each group. Input df MUST be sorted such that the correct last\n item is chosen from each group.\n\n Parameters\n ----------\n df : pd.DataFrame\n The DataFrame containing the data to be grouped. Must b... |
Please provide a description of the function:def ffill_across_cols(df, columns, name_map):
df.ffill(inplace=True)
# Fill in missing values specified by each column. This is made
# significantly more complex by the fact that we need to work around
# two pandas issues:
# 1) When we have sids, i... | [
"\n Forward fill values in a DataFrame with special logic to handle cases\n that pd.DataFrame.ffill cannot and cast columns to appropriate types.\n\n Parameters\n ----------\n df : pd.DataFrame\n The DataFrame to do forward-filling on.\n columns : list of BoundColumn\n The BoundColum... |
Please provide a description of the function:def shift_dates(dates, start_date, end_date, shift):
try:
start = dates.get_loc(start_date)
except KeyError:
if start_date < dates[0]:
raise NoFurtherDataError(
msg=(
"Pipeline Query requested data ... | [
"\n Shift dates of a pipeline query back by `shift` days.\n\n load_adjusted_array is called with dates on which the user's algo\n will be shown data, which means we need to return the data that would\n be known at the start of each date. This is often labeled with a\n previous date in the underlying... |
Please provide a description of the function:def format_docstring(owner_name, docstring, formatters):
# Build a dict of parameters to a vanilla format() call by searching for
# each entry in **formatters and applying any leading whitespace to each
# line in the desired substitution.
format_params =... | [
"\n Template ``formatters`` into ``docstring``.\n\n Parameters\n ----------\n owner_name : str\n The name of the function or class whose docstring is being templated.\n Only used for error messages.\n docstring : str\n The docstring to template.\n formatters : dict[str -> str]... |
Please provide a description of the function:def templated_docstring(**docs):
def decorator(f):
f.__doc__ = format_docstring(f.__name__, f.__doc__, docs)
return f
return decorator | [
"\n Decorator allowing the use of templated docstrings.\n\n Examples\n --------\n >>> @templated_docstring(foo='bar')\n ... def my_func(self, foo):\n ... '''{foo}'''\n ...\n >>> my_func.__doc__\n 'bar'\n "
] |
Please provide a description of the function:def add(self, term, name, overwrite=False):
self.validate_column(name, term)
columns = self.columns
if name in columns:
if overwrite:
self.remove(name)
else:
raise KeyError("Column '{}'... | [
"\n Add a column.\n\n The results of computing `term` will show up as a column in the\n DataFrame produced by running this pipeline.\n\n Parameters\n ----------\n column : zipline.pipeline.Term\n A Filter, Factor, or Classifier to add to the pipeline.\n na... |
Please provide a description of the function:def set_screen(self, screen, overwrite=False):
if self._screen is not None and not overwrite:
raise ValueError(
"set_screen() called with overwrite=False and screen already "
"set.\n"
"If you want t... | [
"\n Set a screen on this Pipeline.\n\n Parameters\n ----------\n filter : zipline.pipeline.Filter\n The filter to apply as a screen.\n overwrite : bool\n Whether to overwrite any existing screen. If overwrite is False\n and self.screen is not None... |
Please provide a description of the function:def to_execution_plan(self,
domain,
default_screen,
start_date,
end_date):
if self._domain is not GENERIC and self._domain is not domain:
rais... | [
"\n Compile into an ExecutionPlan.\n\n Parameters\n ----------\n domain : zipline.pipeline.domain.Domain\n Domain on which the pipeline will be executed.\n default_screen : zipline.pipeline.term.Term\n Term to use as a screen if self.screen is None.\n ... |
Please provide a description of the function:def _prepare_graph_terms(self, default_screen):
columns = self.columns.copy()
screen = self.screen
if screen is None:
screen = default_screen
columns[SCREEN_NAME] = screen
return columns | [
"Helper for to_graph and to_execution_plan."
] |
Please provide a description of the function:def show_graph(self, format='svg'):
g = self.to_simple_graph(AssetExists())
if format == 'svg':
return g.svg
elif format == 'png':
return g.png
elif format == 'jpeg':
return g.jpeg
else:
... | [
"\n Render this Pipeline as a DAG.\n\n Parameters\n ----------\n format : {'svg', 'png', 'jpeg'}\n Image format to render with. Default is 'svg'.\n "
] |
Please provide a description of the function:def _output_terms(self):
terms = list(six.itervalues(self._columns))
screen = self.screen
if screen is not None:
terms.append(screen)
return terms | [
"\n A list of terms that are outputs of this pipeline.\n\n Includes all terms registered as data outputs of the pipeline, plus the\n screen, if present.\n "
] |
Please provide a description of the function:def domain(self, default):
# Always compute our inferred domain to ensure that it's compatible
# with our explicit domain.
inferred = infer_domain(self._output_terms)
if inferred is GENERIC and self._domain is GENERIC:
# ... | [
"\n Get the domain for this pipeline.\n\n - If an explicit domain was provided at construction time, use it.\n - Otherwise, infer a domain from the registered columns.\n - If no domain can be inferred, return ``default``.\n\n Parameters\n ----------\n default : zipli... |
Please provide a description of the function:def _ensure_element(tup, elem):
try:
return tup, tup.index(elem)
except ValueError:
return tuple(chain(tup, (elem,))), len(tup) | [
"\n Create a tuple containing all elements of tup, plus elem.\n\n Returns the new tuple and the index of elem in the new tuple.\n "
] |
Please provide a description of the function:def _validate(self):
variable_names, _unused = getExprNames(self._expr, {})
expr_indices = []
for name in variable_names:
if name == 'inf':
continue
match = _VARIABLE_NAME_RE.match(name)
if ... | [
"\n Ensure that our expression string has variables of the form x_0, x_1,\n ... x_(N - 1), where N is the length of our inputs.\n "
] |
Please provide a description of the function:def _compute(self, arrays, dates, assets, mask):
out = full(mask.shape, self.missing_value, dtype=self.dtype)
# This writes directly into our output buffer.
numexpr.evaluate(
self._expr,
local_dict={
"x... | [
"\n Compute our stored expression string with numexpr.\n "
] |
Please provide a description of the function:def _rebind_variables(self, new_inputs):
expr = self._expr
# If we have 11+ variables, some of our variable names may be
# substrings of other variable names. For example, we might have x_1,
# x_10, and x_100. By enumerating in rever... | [
"\n Return self._expr with all variables rebound to the indices implied by\n new_inputs.\n "
] |
Please provide a description of the function:def _merge_expressions(self, other):
new_inputs = tuple(set(self.inputs).union(other.inputs))
new_self_expr = self._rebind_variables(new_inputs)
new_other_expr = other._rebind_variables(new_inputs)
return new_self_expr, new_other_expr... | [
"\n Merge the inputs of two NumericalExpressions into a single input tuple,\n rewriting their respective string expressions to make input names\n resolve correctly.\n\n Returns a tuple of (new_self_expr, new_other_expr, new_inputs)\n "
] |
Please provide a description of the function:def build_binary_op(self, op, other):
if isinstance(other, NumericalExpression):
self_expr, other_expr, new_inputs = self._merge_expressions(other)
elif isinstance(other, Term):
self_expr = self._expr
new_inputs, o... | [
"\n Compute new expression strings and a new inputs tuple for combining\n self and other with a binary operator.\n "
] |
Please provide a description of the function:def graph_repr(self):
# Replace any floating point numbers in the expression
# with their scientific notation
final = re.sub(r"[-+]?\d*\.\d+",
lambda x: format(float(x.group(0)), '.2E'),
self._ex... | [
"Short repr to use when rendering Pipeline graphs."
] |
Please provide a description of the function:def last_modified_time(path):
return pd.Timestamp(os.path.getmtime(path), unit='s', tz='UTC') | [
"\n Get the last modified time of path as a Timestamp.\n "
] |
Please provide a description of the function:def zipline_root(environ=None):
if environ is None:
environ = os.environ
root = environ.get('ZIPLINE_ROOT', None)
if root is None:
root = expanduser('~/.zipline')
return root | [
"\n Get the root directory for all zipline-managed files.\n\n For testing purposes, this accepts a dictionary to interpret as the os\n environment.\n\n Parameters\n ----------\n environ : dict, optional\n A dict to interpret as the os environment.\n\n Returns\n -------\n root : str... |
Please provide a description of the function:def format_adjustments(self, dates, assets):
make_adjustment = partial(make_adjustment_from_labels, dates, assets)
min_date, max_date = dates[[0, -1]]
# TODO: Consider porting this to Cython.
if len(self.adjustments) == 0:
... | [
"\n Build a dict of Adjustment objects in the format expected by\n AdjustedArray.\n\n Returns a dict of the form:\n {\n # Integer index into `dates` for the date on which we should\n # apply the list of adjustments.\n 1 : [\n Float64Multipl... |
Please provide a description of the function:def load_adjusted_array(self, domain, columns, dates, sids, mask):
if len(columns) != 1:
raise ValueError(
"Can't load multiple columns with DataFrameLoader"
)
column = columns[0]
self._validate_input_... | [
"\n Load data from our stored baseline.\n "
] |
Please provide a description of the function:def _validate_input_column(self, column):
if column != self.column and column.unspecialize() != self.column:
raise ValueError("Can't load unknown column %s" % column) | [
"Make sure a passed column is our column.\n "
] |
Please provide a description of the function:def load_from_directory(list_name):
data = {}
dir_path = os.path.join(SECURITY_LISTS_DIR, list_name)
for kd_name in listdir(dir_path):
kd = datetime.strptime(kd_name, DATE_FORMAT).replace(
tzinfo=pytz.utc)
data[kd] = {}
kd... | [
"\n To resolve the symbol in the LEVERAGED_ETF list,\n the date on which the symbol was in effect is needed.\n\n Furthermore, to maintain a point in time record of our own maintenance\n of the restricted list, we need a knowledge date. Thus, restricted lists\n are dictionaries of datetime->symbol lis... |
Please provide a description of the function:def _weak_lru_cache(maxsize=100):
def decorating_function(
user_function, tuple=tuple, sorted=sorted, len=len,
KeyError=KeyError):
hits, misses = [0], [0]
kwd_mark = (object(),) # separates positional and keyword args
... | [
"\n Users should only access the lru_cache through its public API:\n cache_info, cache_clear\n The internals of the lru_cache are encapsulated for thread safety and\n to allow the implementation to change.\n ",
"Report cache statistics",
"Clear the cache and cache statistics"
] |
Please provide a description of the function:def weak_lru_cache(maxsize=100):
class desc(lazyval):
def __get__(self, instance, owner):
if instance is None:
return self
try:
return self._cache[instance]
except KeyError:
... | [
"Weak least-recently-used cache decorator.\n\n If *maxsize* is set to None, the LRU features are disabled and the cache\n can grow without bound.\n\n Arguments to the cached function must be hashable. Any that are weak-\n referenceable will be stored by weak reference. Once any of the args have\n be... |
Please provide a description of the function:def is_final(name, mro):
return any(isinstance(getattr(c, '__dict__', {}).get(name), final)
for c in bases_mro(mro)) | [
"\n Checks if `name` is a `final` object in the given `mro`.\n We need to check the mro because we need to directly go into the __dict__\n of the classes. Because `final` objects are descriptor, we need to grab\n them _BEFORE_ the `__call__` is invoked.\n "
] |
Please provide a description of the function:def bind(self, name):
return _BoundColumnDescr(
dtype=self.dtype,
missing_value=self.missing_value,
name=name,
doc=self.doc,
metadata=self.metadata,
) | [
"\n Bind a `Column` object to its name.\n "
] |
Please provide a description of the function:def specialize(self, domain):
if domain == self.domain:
return self
return type(self)(
dtype=self.dtype,
missing_value=self.missing_value,
dataset=self._dataset.specialize(domain),
name=sel... | [
"Specialize ``self`` to a concrete domain.\n "
] |
Please provide a description of the function:def get_column(cls, name):
clsdict = vars(cls)
try:
maybe_column = clsdict[name]
if not isinstance(maybe_column, _BoundColumnDescr):
raise KeyError(name)
except KeyError:
raise AttributeErro... | [
"Look up a column by name.\n\n Parameters\n ----------\n name : str\n Name of the column to look up.\n\n Returns\n -------\n column : zipline.pipeline.data.BoundColumn\n Column with the given name.\n\n Raises\n ------\n AttributeEr... |
Please provide a description of the function:def _make_dataset(cls, coords):
class Slice(cls._SliceType):
extra_coords = coords
Slice.__name__ = '%s.slice(%s)' % (
cls.__name__,
', '.join('%s=%r' % item for item in coords.items()),
)
return S... | [
"Construct a new dataset given the coordinates.\n "
] |
Please provide a description of the function:def slice(cls, *args, **kwargs):
coords, hash_key = cls._canonical_key(args, kwargs)
try:
return cls._slice_cache[hash_key]
except KeyError:
pass
Slice = cls._make_dataset(coords)
cls._slice_cache[hash... | [
"Take a slice of a DataSetFamily to produce a dataset\n indexed by asset and date.\n\n Parameters\n ----------\n *args\n **kwargs\n The coordinates to fix along each extra dimension.\n\n Returns\n -------\n dataset : DataSet\n A regular p... |
Please provide a description of the function:def expected_bar_value(asset_id, date, colname):
from_asset = asset_id * 100000
from_colname = OHLCV.index(colname) * 1000
from_date = (date - PSEUDO_EPOCH).days
return from_asset + from_colname + from_date | [
"\n Check that the raw value for an asset/date/column triple is as\n expected.\n\n Used by tests to verify data written by a writer.\n "
] |
Please provide a description of the function:def expected_bar_values_2d(dates,
assets,
asset_info,
colname,
holes=None):
if colname == 'volume':
dtype = uint32
missing = 0
else:
... | [
"\n Return an 2D array containing cls.expected_value(asset_id, date,\n colname) for each date/asset pair in the inputs.\n\n Missing locs are filled with 0 for volume and NaN for price columns:\n\n - Values before/after an asset's lifetime.\n - Values for asset_ids not contained in asset_info.... |
Please provide a description of the function:def load_adjusted_array(self, domain, columns, dates, sids, mask):
out = {}
for col in columns:
try:
loader = self._loaders.get(col)
if loader is None:
loader = self._loaders[col.unspeci... | [
"\n Load by delegating to sub-loaders.\n "
] |
Please provide a description of the function:def values(self, dtype, dates, sids):
shape = (len(dates), len(sids))
return {
datetime64ns_dtype: self._datetime_values,
float64_dtype: self._float_values,
int64_dtype: self._int_values,
bool_dtype: se... | [
"\n Make a random array of shape (len(dates), len(sids)) with ``dtype``.\n "
] |
Please provide a description of the function:def _float_values(self, shape):
return self.state.uniform(low=0.0, high=100.0, size=shape) | [
"\n Return uniformly-distributed floats between -0.0 and 100.0.\n "
] |
Please provide a description of the function:def _int_values(self, shape):
return (self.state.randint(low=0, high=100, size=shape)
.astype('int64')) | [
"\n Return uniformly-distributed integers between 0 and 100.\n "
] |
Please provide a description of the function:def _datetime_values(self, shape):
start = Timestamp('2014', tz='UTC').asm8
offsets = self.state.randint(
low=0,
high=364,
size=shape,
).astype('timedelta64[D]')
return start + offsets | [
"\n Return uniformly-distributed dates in 2014.\n "
] |
Please provide a description of the function:def quantiles(data, nbins_or_partition_bounds):
return apply_along_axis(
qcut,
1,
data,
q=nbins_or_partition_bounds, labels=False,
) | [
"\n Compute rowwise array quantiles on an input.\n "
] |
Please provide a description of the function:def handle_minute_close(self, dt, data_portal):
self.sync_last_sale_prices(dt, data_portal)
packet = {
'period_start': self._first_session,
'period_end': self._last_session,
'capital_base': self._capital_base,
... | [
"\n Handles the close of the given minute in minute emission.\n\n Parameters\n ----------\n dt : Timestamp\n The minute that is ending\n\n Returns\n -------\n A minute perf packet.\n "
] |
Please provide a description of the function:def handle_market_open(self, session_label, data_portal):
ledger = self._ledger
ledger.start_of_session(session_label)
adjustment_reader = data_portal.adjustment_reader
if adjustment_reader is not None:
# this is None whe... | [
"Handles the start of each session.\n\n Parameters\n ----------\n session_label : Timestamp\n The label of the session that is about to begin.\n data_portal : DataPortal\n The current data portal.\n "
] |
Please provide a description of the function:def handle_market_close(self, dt, data_portal):
completed_session = self._current_session
if self.emission_rate == 'daily':
# this method is called for both minutely and daily emissions, but
# this chunk of code here only app... | [
"Handles the close of the given day.\n\n Parameters\n ----------\n dt : Timestamp\n The most recently completed simulation datetime.\n data_portal : DataPortal\n The current data portal.\n\n Returns\n -------\n A daily perf packet.\n "
] |
Please provide a description of the function:def handle_simulation_end(self, data_portal):
log.info(
'Simulated {} trading days\n'
'first open: {}\n'
'last close: {}',
self._session_count,
self._trading_calendar.session_open(self._first_sessio... | [
"\n When the simulation is complete, run the full period risk report\n and send it out on the results socket.\n "
] |
Please provide a description of the function:def create_args(args, root):
extension_args = {}
for arg in args:
parse_extension_arg(arg, extension_args)
for name in sorted(extension_args, key=len):
path = name.split('.')
update_namespace(root, path, extension_args[name]) | [
"\n Encapsulates a set of custom command line arguments in key=value\n or key.namespace=value form into a chain of Namespace objects,\n where each next level is an attribute of the Namespace object on the\n current level\n\n Parameters\n ----------\n args : list\n A list of strings repre... |
Please provide a description of the function:def parse_extension_arg(arg, arg_dict):
match = re.match(r'^(([^\d\W]\w*)(\.[^\d\W]\w*)*)=(.*)$', arg)
if match is None:
raise ValueError(
"invalid extension argument '%s', must be in key=value form" % arg
)
name = match.group(1... | [
"\n Converts argument strings in key=value or key.namespace=value form\n to dictionary entries\n\n Parameters\n ----------\n arg : str\n The argument string to parse, which must be in key=value or\n key.namespace=value form.\n arg_dict : dict\n The dictionary into which the ke... |
Please provide a description of the function:def update_namespace(namespace, path, name):
if len(path) == 1:
setattr(namespace, path[0], name)
else:
if hasattr(namespace, path[0]):
if isinstance(getattr(namespace, path[0]), six.string_types):
raise ValueError("C... | [
"\n A recursive function that takes a root element, list of namespaces,\n and the value being stored, and assigns namespaces to the root object\n via a chain of Namespace objects, connected through attributes\n\n Parameters\n ----------\n namespace : Namespace\n The object onto which an att... |
Please provide a description of the function:def create_registry(interface):
if interface in custom_types:
raise ValueError('there is already a Registry instance '
'for the specified type')
custom_types[interface] = Registry(interface)
return interface | [
"\n Create a new registry for an extensible interface.\n\n Parameters\n ----------\n interface : type\n The abstract data type for which to create a registry,\n which will manage registration of factories for this type.\n\n Returns\n -------\n interface : type\n The data ty... |
Please provide a description of the function:def load(self, name):
try:
return self._factories[name]()
except KeyError:
raise ValueError(
"no %s factory registered under name %r, options are: %r" %
(self.interface.__name__, name, sorted(se... | [
"Construct an object from a registered factory.\n\n Parameters\n ----------\n name : str\n Name with which the factory was registered.\n "
] |
Please provide a description of the function:def calculate_per_unit_commission(order,
transaction,
cost_per_unit,
initial_commission,
min_trade_cost):
additional_commission = ... | [
"\n If there is a minimum commission:\n If the order hasn't had a commission paid yet, pay the minimum\n commission.\n\n If the order has paid a commission, start paying additional\n commission once the minimum commission has been reached.\n\n If there is no minimum commission:\n ... |
Please provide a description of the function:def calculate(self, order, transaction):
cost_per_share = transaction.price * self.cost_per_dollar
return abs(transaction.amount) * cost_per_share | [
"\n Pay commission based on dollar value of shares.\n "
] |
Please provide a description of the function:def risk_metric_period(cls,
start_session,
end_session,
algorithm_returns,
benchmark_returns,
algorithm_leverages):
algori... | [
"\n Creates a dictionary representing the state of the risk report.\n\n Parameters\n ----------\n start_session : pd.Timestamp\n Start of period (inclusive) to produce metrics on\n end_session : pd.Timestamp\n End of period (inclusive) to produce metrics on\n... |
Please provide a description of the function:def _get_active_contract_at_offset(self, root_symbol, dt, offset):
oc = self.asset_finder.get_ordered_contracts(root_symbol)
session = self.trading_calendar.minute_to_session_label(dt)
front = oc.contract_before_auto_close(session.value)
... | [
"\n For the given root symbol, find the contract that is considered active\n on a specific date at a specific offset.\n "
] |
Please provide a description of the function:def get_contract_center(self, root_symbol, dt, offset):
return self._get_active_contract_at_offset(root_symbol, dt, offset) | [
"\n Parameters\n ----------\n root_symbol : str\n The root symbol for the contract chain.\n dt : Timestamp\n The datetime for which to retrieve the current contract.\n offset : int\n The offset from the primary contract.\n 0 is the prima... |
Please provide a description of the function:def get_rolls(self, root_symbol, start, end, offset):
oc = self.asset_finder.get_ordered_contracts(root_symbol)
front = self._get_active_contract_at_offset(root_symbol, end, 0)
back = oc.contract_at_offset(front, 1, end.value)
if back... | [
"\n Get the rolls, i.e. the session at which to hop from contract to\n contract in the chain.\n\n Parameters\n ----------\n root_symbol : str\n The root symbol for which to calculate rolls.\n start : Timestamp\n Start of the date range.\n end : ... |
Please provide a description of the function:def _active_contract(self, oc, front, back, dt):
r
front_contract = oc.sid_to_contract[front].contract
back_contract = oc.sid_to_contract[back].contract
tc = self.trading_calendar
trading_day = tc.day
prev = dt - trading_day
... | [
"\n Return the active contract based on the previous trading day's volume.\n\n In the rare case that a double volume switch occurs we treat the first\n switch as the roll. Take the following case for example:\n\n | +++++ _____\n | + __ / <--- 'G'\n ... |
Please provide a description of the function:def get_contract_center(self, root_symbol, dt, offset):
# When determining the center contract on a specific day using volume
# rolls, simply picking the contract with the highest volume could
# cause flip-flopping between active contracts ea... | [
"\n Parameters\n ----------\n root_symbol : str\n The root symbol for the contract chain.\n dt : Timestamp\n The datetime for which to retrieve the current contract.\n offset : int\n The offset from the primary contract.\n 0 is the prima... |
Please provide a description of the function:def _normalize_array(data, missing_value):
if isinstance(data, LabelArray):
return data, {}
data_dtype = data.dtype
if data_dtype in BOOL_DTYPES:
return data.astype(uint8), {'dtype': dtype(bool_)}
elif data_dtype in FLOAT_DTYPES:
... | [
"\n Coerce buffer data for an AdjustedArray into a standard scalar\n representation, returning the coerced array and a dict of argument to pass\n to np.view to use when providing a user-facing view of the underlying data.\n\n - float* data is coerced to float64 with viewtype float64.\n - int32, int64... |
Please provide a description of the function:def _merge_simple(adjustment_lists, front_idx, back_idx):
if len(adjustment_lists) == 1:
return list(adjustment_lists[0])
else:
return adjustment_lists[front_idx] + adjustment_lists[back_idx] | [
"\n Merge lists of new and existing adjustments for a given index by appending\n or prepending new adjustments to existing adjustments.\n\n Notes\n -----\n This method is meant to be used with ``toolz.merge_with`` to merge\n adjustment mappings. In case of a collision ``adjustment_lists`` contains... |
Please provide a description of the function:def ensure_ndarray(ndarray_or_adjusted_array):
if isinstance(ndarray_or_adjusted_array, ndarray):
return ndarray_or_adjusted_array
elif isinstance(ndarray_or_adjusted_array, AdjustedArray):
return ndarray_or_adjusted_array.data
else:
... | [
"\n Return the input as a numpy ndarray.\n\n This is a no-op if the input is already an ndarray. If the input is an\n adjusted_array, this extracts a read-only view of its internal data buffer.\n\n Parameters\n ----------\n ndarray_or_adjusted_array : numpy.ndarray | zipline.data.adjusted_array\n... |
Please provide a description of the function:def _check_window_params(data, window_length):
if window_length < 1:
raise WindowLengthNotPositive(window_length=window_length)
if window_length > data.shape[0]:
raise WindowLengthTooLong(
nrows=data.shape[0],
window_leng... | [
"\n Check that a window of length `window_length` is well-defined on `data`.\n\n Parameters\n ----------\n data : np.ndarray[ndim=2]\n The array of data to check.\n window_length : int\n Length of the desired window.\n\n Returns\n -------\n None\n\n Raises\n ------\n W... |
Please provide a description of the function:def update_adjustments(self, adjustments, method):
try:
merge_func = _merge_methods[method]
except KeyError:
raise ValueError(
"Invalid merge method %s\n"
"Valid methods are: %s" % (method, ', '... | [
"\n Merge ``adjustments`` with existing adjustments, handling index\n collisions according to ``method``.\n\n Parameters\n ----------\n adjustments : dict[int -> list[Adjustment]]\n The mapping of row indices to lists of adjustments that should be\n appended ... |
Please provide a description of the function:def _iterator_type(self):
if isinstance(self._data, LabelArray):
return LabelWindow
return CONCRETE_WINDOW_TYPES[self._data.dtype] | [
"\n The iterator produced when `traverse` is called on this Array.\n "
] |
Please provide a description of the function:def traverse(self,
window_length,
offset=0,
perspective_offset=0):
data = self._data.copy()
_check_window_params(data, window_length)
return self._iterator_type(
data,
... | [
"\n Produce an iterator rolling windows rows over our data.\n Each emitted window will have `window_length` rows.\n\n Parameters\n ----------\n window_length : int\n The number of rows in each emitted window.\n offset : int, optional\n Number of rows t... |
Please provide a description of the function:def inspect(self):
return dedent(
).format(
dtype=self.dtype.name,
data=self.data,
adjustments=self.adjustments,
) | [
"\n Return a string representation of the data stored in this array.\n ",
"\\\n Adjusted Array ({dtype}):\n\n Data:\n {data!r}\n\n Adjustments:\n {adjustments}\n "
] |
Please provide a description of the function:def update_labels(self, func):
if not isinstance(self.data, LabelArray):
raise TypeError(
'update_labels only supported if data is of type LabelArray.'
)
# Map the baseline values.
self._data = self._d... | [
"\n Map a function over baseline and adjustment values in place.\n\n Note that the baseline data values must be a LabelArray.\n "
] |
Please provide a description of the function:def handle_violation(self, asset, amount, datetime, metadata=None):
constraint = self._constraint_msg(metadata)
if self.on_error == 'fail':
raise TradingControlViolation(
asset=asset,
amount=amount,
... | [
"\n Handle a TradingControlViolation, either by raising or logging and\n error with information about the failure.\n\n If dynamic information should be displayed as well, pass it in via\n `metadata`.\n "
] |
Please provide a description of the function:def validate(self,
asset,
amount,
portfolio,
algo_datetime,
algo_current_data):
algo_date = algo_datetime.date()
# Reset order count if it's a new day.
if s... | [
"\n Fail if we've already placed self.max_count orders today.\n "
] |
Please provide a description of the function:def validate(self,
asset,
amount,
portfolio,
algo_datetime,
algo_current_data):
if self.restrictions.is_restricted(asset, algo_datetime):
self.handle_violation(a... | [
"\n Fail if the asset is in the restricted_list.\n "
] |
Please provide a description of the function:def validate(self,
asset,
amount,
portfolio,
algo_datetime,
algo_current_data):
if self.asset is not None and self.asset != asset:
return
if self.max_s... | [
"\n Fail if the magnitude of the given order exceeds either self.max_shares\n or self.max_notional.\n "
] |
Please provide a description of the function:def validate(self,
asset,
amount,
portfolio,
algo_datetime,
algo_current_data):
if self.asset is not None and self.asset != asset:
return
current_share... | [
"\n Fail if the given order would cause the magnitude of our position to be\n greater in shares than self.max_shares or greater in dollar value than\n self.max_notional.\n "
] |
Please provide a description of the function:def validate(self,
asset,
amount,
portfolio,
algo_datetime,
algo_current_data):
if portfolio.positions[asset].amount + amount < 0:
self.handle_violation(asset, a... | [
"\n Fail if we would hold negative shares of asset after completing this\n order.\n "
] |
Please provide a description of the function:def validate(self,
asset,
amount,
portfolio,
algo_datetime,
algo_current_data):
# If the order is for 0 shares, then silently pass through.
if amount == 0:
... | [
"\n Fail if the algo has passed this Asset's end_date, or before the\n Asset's start date.\n "
] |
Please provide a description of the function:def validate(self,
_portfolio,
_account,
_algo_datetime,
_algo_current_data):
if _account.leverage > self.max_leverage:
self.fail() | [
"\n Fail if the leverage is greater than the allowed leverage.\n "
] |
Please provide a description of the function:def validate(self,
_portfolio,
account,
algo_datetime,
_algo_current_data):
if (algo_datetime > self.deadline and
account.leverage < self.min_leverage):
self.fail... | [
"\n Make validation checks if we are after the deadline.\n Fail if the leverage is less than the min leverage.\n "
] |
Please provide a description of the function:def alter_columns(op, name, *columns, **kwargs):
selection_string = kwargs.pop('selection_string', None)
if kwargs:
raise TypeError(
'alter_columns received extra arguments: %r' % sorted(kwargs),
)
if selection_string is None:
... | [
"Alter columns from a table.\n\n Parameters\n ----------\n name : str\n The name of the table.\n *columns\n The new columns to have.\n selection_string : str, optional\n The string to use in the selection. If not provided, it will select all\n of the new columns from the o... |
Please provide a description of the function:def downgrade(engine, desired_version):
# Check the version of the db at the engine
with engine.begin() as conn:
metadata = sa.MetaData(conn)
metadata.reflect()
version_info_table = metadata.tables['version_info']
starting_versio... | [
"Downgrades the assets db at the given engine to the desired version.\n\n Parameters\n ----------\n engine : Engine\n An SQLAlchemy engine to the assets database.\n desired_version : int\n The desired resulting version for the assets database.\n "
] |
Please provide a description of the function:def downgrades(src):
def _(f):
destination = src - 1
@do(operator.setitem(_downgrade_methods, destination))
@wraps(f)
def wrapper(op, conn, version_info_table):
conn.execute(version_info_table.delete()) # clear the versi... | [
"Decorator for marking that a method is a downgrade to a version to the\n previous version.\n\n Parameters\n ----------\n src : int\n The version this downgrades from.\n\n Returns\n -------\n decorator : callable[(callable) -> callable]\n The decorator to apply.\n "
] |
Please provide a description of the function:def _downgrade_v1(op):
# Drop indices before batch
# This is to prevent index collision when creating the temp table
op.drop_index('ix_futures_contracts_root_symbol')
op.drop_index('ix_futures_contracts_symbol')
# Execute batch op to allow column mo... | [
"\n Downgrade assets db by removing the 'tick_size' column and renaming the\n 'multiplier' column.\n "
] |
Please provide a description of the function:def _downgrade_v2(op):
# Drop indices before batch
# This is to prevent index collision when creating the temp table
op.drop_index('ix_equities_fuzzy_symbol')
op.drop_index('ix_equities_company_symbol')
# Execute batch op to allow column modificatio... | [
"\n Downgrade assets db by removing the 'auto_close_date' column.\n "
] |
Please provide a description of the function:def _downgrade_v3(op):
op.create_table(
'_new_equities',
sa.Column(
'sid',
sa.Integer,
unique=True,
nullable=False,
primary_key=True,
),
sa.Column('symbol', sa.Text),
... | [
"\n Downgrade assets db by adding a not null constraint on\n ``equities.first_traded``\n ",
"\n insert into _new_equities\n select * from equities\n where equities.first_traded is not null\n "
] |
Please provide a description of the function:def _downgrade_v4(op):
op.drop_index('ix_equities_fuzzy_symbol')
op.drop_index('ix_equities_company_symbol')
op.execute("UPDATE equities SET exchange = exchange_full")
with op.batch_alter_table('equities') as batch_op:
batch_op.drop_column('exc... | [
"\n Downgrades assets db by copying the `exchange_full` column to `exchange`,\n then dropping the `exchange_full` column.\n "
] |
Please provide a description of the function:def _make_metrics_set_core():
_metrics_sets = {}
# Expose _metrics_sets through a proxy so that users cannot mutate this
# accidentally. Users may go through `register` to update this which will
# warn when trampling another metrics set.
metrics_sets... | [
"Create a family of metrics sets functions that read from the same\n metrics set mapping.\n\n Returns\n -------\n metrics_sets : mappingproxy\n The mapping of metrics sets to load functions.\n register : callable\n The function which registers new metrics sets in the ``metrics_sets``\n ... |
Please provide a description of the function:def validate_column_specs(events, columns):
required = required_estimates_fields(columns)
received = set(events.columns)
missing = required - received
if missing:
raise ValueError(
"EarningsEstimatesLoader missing required columns {mi... | [
"\n Verify that the columns of ``events`` can be used by a\n EarningsEstimatesLoader to serve the BoundColumns described by\n `columns`.\n "
] |
Please provide a description of the function:def get_requested_quarter_data(self,
zero_qtr_data,
zeroth_quarter_idx,
stacked_last_per_qtr,
num_announcements,
... | [
"\n Selects the requested data for each date.\n\n Parameters\n ----------\n zero_qtr_data : pd.DataFrame\n The 'time zero' data for each calendar date per sid.\n zeroth_quarter_idx : pd.Index\n An index of calendar dates, sid, and normalized quarters, for onl... |
Please provide a description of the function:def get_split_adjusted_asof_idx(self, dates):
split_adjusted_asof_idx = dates.searchsorted(
self._split_adjusted_asof
)
# The split-asof date is after the date index.
if split_adjusted_asof_idx == len(dates):
s... | [
"\n Compute the index in `dates` where the split-adjusted-asof-date\n falls. This is the date up to which, and including which, we will\n need to unapply all adjustments for and then re-apply them as they\n come in. After this date, adjustments are applied as normal.\n\n Parameter... |
Please provide a description of the function:def collect_overwrites_for_sid(self,
group,
dates,
requested_qtr_data,
last_per_qtr,
sid_idx,
... | [
"\n Given a sid, collect all overwrites that should be applied for this\n sid at each quarter boundary.\n\n Parameters\n ----------\n group : pd.DataFrame\n The data for `sid`.\n dates : pd.DatetimeIndex\n The calendar dates for which estimates data is... |
Please provide a description of the function:def merge_into_adjustments_for_all_sids(self,
all_adjustments_for_sid,
col_to_all_adjustments):
for col_name in all_adjustments_for_sid:
if col_name not in c... | [
"\n Merge adjustments for a particular sid into a dictionary containing\n adjustments for all sids.\n\n Parameters\n ----------\n all_adjustments_for_sid : dict[int -> AdjustedArray]\n All adjustments for a particular sid.\n col_to_all_adjustments : dict[int -> A... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.