Code stringlengths 103 85.9k | Summary listlengths 0 94 |
|---|---|
Please provide a description of the function:def get(self, key, dt):
try:
return self._cache[key].unwrap(dt)
except Expired:
self.cleanup(self._cache[key]._unsafe_get_value())
del self._cache[key]
raise KeyError(key) | [
"Get the value of a cached object.\n\n Parameters\n ----------\n key : any\n The key to lookup.\n dt : datetime\n The time of the lookup.\n\n Returns\n -------\n result : any\n The value for ``key``.\n\n Raises\n ------\... |
Please provide a description of the function:def set(self, key, value, expiration_dt):
self._cache[key] = CachedObject(value, expiration_dt) | [
"Adds a new key value pair to the cache.\n\n Parameters\n ----------\n key : any\n The key to use for the pair.\n value : any\n The value to store under the name ``key``.\n expiration_dt : datetime\n When should this mapping expire? The cache is co... |
Please provide a description of the function:def ensure_dir(self, *path_parts):
path = self.getpath(*path_parts)
ensure_directory(path)
return path | [
"Ensures a subdirectory of the working directory.\n\n Parameters\n ----------\n path_parts : iterable[str]\n The parts of the path after the working directory.\n "
] |
Please provide a description of the function:def verify_frames_aligned(frames, calendar):
indexes = [f.index for f in frames]
check_indexes_all_same(indexes, message="DataFrame indexes don't match:")
columns = [f.columns for f in frames]
check_indexes_all_same(columns, message="DataFrame columns d... | [
"\n Verify that DataFrames in ``frames`` have the same indexing scheme and are\n aligned to ``calendar``.\n\n Parameters\n ----------\n frames : list[pd.DataFrame]\n calendar : trading_calendars.TradingCalendar\n\n Raises\n ------\n ValueError\n If frames have different indexes/col... |
Please provide a description of the function:def get_value(self, sid, dt, field):
return self.frames[field].loc[dt, sid] | [
"\n Parameters\n ----------\n sid : int\n The asset identifier.\n day : datetime64-like\n Midnight of the day for which data is requested.\n field : string\n The price field. e.g. ('open', 'high', 'low', 'close', 'volume')\n\n Returns\n ... |
Please provide a description of the function:def get_last_traded_dt(self, asset, dt):
try:
return self.frames['close'].loc[:, asset.sid].last_valid_index()
except IndexError:
return NaT | [
"\n Parameters\n ----------\n asset : zipline.asset.Asset\n The asset identifier.\n dt : datetime64-like\n Midnight of the day for which data is requested.\n\n Returns\n -------\n pd.Timestamp : The last know dt for the asset and dt;\n ... |
Please provide a description of the function:def same(*values):
if not values:
return True
first, rest = values[0], values[1:]
return all(value == first for value in rest) | [
"\n Check if all values in a sequence are equal.\n\n Returns True on empty sequences.\n\n Examples\n --------\n >>> same(1, 1, 1, 1)\n True\n >>> same(1, 2, 1)\n False\n >>> same()\n True\n "
] |
Please provide a description of the function:def dzip_exact(*dicts):
if not same(*map(viewkeys, dicts)):
raise ValueError(
"dict keys not all equal:\n\n%s" % _format_unequal_keys(dicts)
)
return {k: tuple(d[k] for d in dicts) for k in dicts[0]} | [
"\n Parameters\n ----------\n *dicts : iterable[dict]\n A sequence of dicts all sharing the same keys.\n\n Returns\n -------\n zipped : dict\n A dict whose keys are the union of all keys in *dicts, and whose values\n are tuples of length len(dicts) containing the result of loo... |
Please provide a description of the function:def _gen_unzip(it, elem_len):
elem = next(it)
first_elem_len = len(elem)
if elem_len is not None and elem_len != first_elem_len:
raise ValueError(
'element at index 0 was length %d, expected %d' % (
first_elem_len,
... | [
"Helper for unzip which checks the lengths of each element in it.\n Parameters\n ----------\n it : iterable[tuple]\n An iterable of tuples. ``unzip`` should map ensure that these are\n already tuples.\n elem_len : int or None\n The expected element length. If this is None it is infe... |
Please provide a description of the function:def unzip(seq, elem_len=None):
ret = tuple(zip(*_gen_unzip(map(tuple, seq), elem_len)))
if ret:
return ret
if elem_len is None:
raise ValueError("cannot unzip empty sequence without 'elem_len'")
return ((),) * elem_len | [
"Unzip a length n sequence of length m sequences into m seperate length\n n sequences.\n Parameters\n ----------\n seq : iterable[iterable]\n The sequence to unzip.\n elem_len : int, optional\n The expected length of each element of ``seq``. If not provided this\n will be infered... |
Please provide a description of the function:def getattrs(value, attrs, default=_no_default):
try:
for attr in attrs:
value = getattr(value, attr)
except AttributeError:
if default is _no_default:
raise
value = default
return value | [
"\n Perform a chained application of ``getattr`` on ``value`` with the values\n in ``attrs``.\n\n If ``default`` is supplied, return it if any of the attribute lookups fail.\n\n Parameters\n ----------\n value : object\n Root of the lookup chain.\n attrs : iterable[str]\n Sequence... |
Please provide a description of the function:def set_attribute(name, value):
def decorator(f):
setattr(f, name, value)
return f
return decorator | [
"\n Decorator factory for setting attributes on a function.\n\n Doesn't change the behavior of the wrapped function.\n\n Examples\n --------\n >>> @set_attribute('__name__', 'foo')\n ... def bar():\n ... return 3\n ...\n >>> bar()\n 3\n >>> bar.__name__\n 'foo'\n "
] |
Please provide a description of the function:def foldr(f, seq, default=_no_default):
return reduce(
flip(f),
reversed(seq),
*(default,) if default is not _no_default else ()
) | [
"Fold a function over a sequence with right associativity.\n\n Parameters\n ----------\n f : callable[any, any]\n The function to reduce the sequence with.\n The first argument will be the element of the sequence; the second\n argument will be the accumulator.\n seq : iterable[any]\... |
Please provide a description of the function:def invert(d):
out = {}
for k, v in iteritems(d):
try:
out[v].add(k)
except KeyError:
out[v] = {k}
return out | [
"\n Invert a dictionary into a dictionary of sets.\n\n >>> invert({'a': 1, 'b': 2, 'c': 1}) # doctest: +SKIP\n {1: {'a', 'c'}, 2: {'b'}}\n "
] |
Please provide a description of the function:def simplex_projection(v, b=1):
r
v = np.asarray(v)
p = len(v)
# Sort v into u in descending order
v = (v > 0) * v
u = np.sort(v)[::-1]
sv = np.cumsum(u)
rho = np.where(u > (sv - b) / np.arange(1, p + 1))[0][-1]
theta = np.max([0, (sv[r... | [
"Projection vectors to the simplex domain\n\n Implemented according to the paper: Efficient projections onto the\n l1-ball for learning in high dimensions, John Duchi, et al. ICML 2008.\n Implementation Time: 2011 June 17 by Bin@libin AT pmail.ntu.edu.sg\n Optimization Problem: min_{w}\\| w - v \\|_{2}^... |
Please provide a description of the function:def run_example(example_name, environ):
mod = EXAMPLE_MODULES[example_name]
register_calendar("YAHOO", get_calendar("NYSE"), force=True)
return run_algorithm(
initialize=getattr(mod, 'initialize', None),
handle_data=getattr(mod, 'handle_dat... | [
"\n Run an example module from zipline.examples.\n "
] |
Please provide a description of the function:def vectorized_beta(dependents, independent, allowed_missing, out=None):
# Cache these as locals since we're going to call them multiple times.
nan = np.nan
isnan = np.isnan
N, M = dependents.shape
if out is None:
out = np.full(M, nan)
... | [
"\n Compute slopes of linear regressions between columns of ``dependents`` and\n ``independent``.\n\n Parameters\n ----------\n dependents : np.array[N, M]\n Array with columns of data to be regressed against ``independent``.\n independent : np.array[N, 1]\n Independent variable of t... |
Please provide a description of the function:def _format_url(instrument_type,
instrument_ids,
start_date,
end_date,
earliest_allowed_date):
return (
"http://www.bankofcanada.ca/stats/results/csv"
"?lP=lookup_{instrument_type}_yield... | [
"\n Format a URL for loading data from Bank of Canada.\n "
] |
Please provide a description of the function:def load_frame(url, skiprows):
return pd.read_csv(
url,
skiprows=skiprows,
skipinitialspace=True,
na_values=["Bank holiday", "Not available"],
parse_dates=["Date"],
index_col="Date",
).dropna(how='all') \
.tz_... | [
"\n Load a DataFrame of data from a Bank of Canada site.\n "
] |
Please provide a description of the function:def check_known_inconsistencies(bill_data, bond_data):
inconsistent_dates = bill_data.index.sym_diff(bond_data.index)
known_inconsistencies = [
# bill_data has an entry for 2010-02-15, which bond_data doesn't.
# bond_data has an entry for 2006-09... | [
"\n There are a couple quirks in the data provided by Bank of Canada.\n Check that no new quirks have been introduced in the latest download.\n "
] |
Please provide a description of the function:def earliest_possible_date():
today = pd.Timestamp('now', tz='UTC').normalize()
# Bank of Canada only has the last 10 years of data at any given time.
return today.replace(year=today.year - 10) | [
"\n The earliest date for which we can load data from this module.\n "
] |
Please provide a description of the function:def fill_price_worse_than_limit_price(fill_price, order):
if order.limit:
# this is tricky! if an order with a limit price has reached
# the limit price, we will try to fill the order. do not fill
# these shares if the impacted price is worse... | [
"\n Checks whether the fill price is worse than the order's limit price.\n\n Parameters\n ----------\n fill_price: float\n The price to check.\n\n order: zipline.finance.order.Order\n The order whose limit price to check.\n\n Returns\n -------\n bool: Whether the fill price is ... |
Please provide a description of the function:def _get_window_data(self, data, asset, window_length):
try:
values = self._window_data_cache.get(asset, data.current_session)
except KeyError:
try:
# Add a day because we want 'window_length' complete days,
... | [
"\n Internal utility method to return the trailing mean volume over the\n past 'window_length' days, and volatility of close prices for a\n specific asset.\n\n Parameters\n ----------\n data : The BarData from which to fetch the daily windows.\n asset : The Asset who... |
Please provide a description of the function:def validate_dtype(termname, dtype, missing_value):
if dtype is NotSpecified:
raise DTypeNotSpecified(termname=termname)
try:
dtype = dtype_class(dtype)
except TypeError:
raise NotDType(dtype=dtype, termname=termname)
if not can... | [
"\n Validate a `dtype` and `missing_value` passed to Term.__new__.\n\n Ensures that we know how to represent ``dtype``, and that missing_value\n is specified for types without default missing values.\n\n Returns\n -------\n validated_dtype, validated_missing_value : np.dtype, any\n The dtyp... |
Please provide a description of the function:def _assert_valid_categorical_missing_value(value):
label_types = LabelArray.SUPPORTED_SCALAR_TYPES
if not isinstance(value, label_types):
raise TypeError(
"Categorical terms must have missing values of type "
"{types}.".format(
... | [
"\n Check that value is a valid categorical missing_value.\n\n Raises a TypeError if the value is cannot be used as the missing_value for\n a categorical_dtype Term.\n "
] |
Please provide a description of the function:def _pop_params(cls, kwargs):
params = cls.params
if not isinstance(params, Mapping):
params = {k: NotSpecified for k in params}
param_values = []
for key, default_value in params.items():
try:
... | [
"\n Pop entries from the `kwargs` passed to cls.__new__ based on the values\n in `cls.params`.\n\n Parameters\n ----------\n kwargs : dict\n The kwargs passed to cls.__new__.\n\n Returns\n -------\n params : list[(str, object)]\n A list o... |
Please provide a description of the function:def _static_identity(cls,
domain,
dtype,
missing_value,
window_safe,
ndim,
params):
return (cls, domain, dty... | [
"\n Return the identity of the Term that would be constructed from the\n given arguments.\n\n Identities that compare equal will cause us to return a cached instance\n rather than constructing a new one. We do this primarily because it\n makes dependency resolution easier.\n\n ... |
Please provide a description of the function:def _init(self, domain, dtype, missing_value, window_safe, ndim, params):
self.domain = domain
self.dtype = dtype
self.missing_value = missing_value
self.window_safe = window_safe
self.ndim = ndim
for name, value in p... | [
"\n Parameters\n ----------\n domain : zipline.pipeline.domain.Domain\n The domain of this term.\n dtype : np.dtype\n Dtype of this term's output.\n missing_value : object\n Missing value for this term.\n ndim : 1 or 2\n The dimen... |
Please provide a description of the function:def dependencies(self):
extra_input_rows = max(0, self.window_length - 1)
out = {}
for term in self.inputs:
out[term] = extra_input_rows
out[self.mask] = 0
return out | [
"\n The number of extra rows needed for each of our inputs to compute this\n term.\n "
] |
Please provide a description of the function:def to_workspace_value(self, result, assets):
return result.unstack().fillna(self.missing_value).reindex(
columns=assets,
fill_value=self.missing_value,
).values | [
"\n Called with a column of the result of a pipeline. This needs to put\n the data into a format that can be used in a workspace to continue\n doing computations.\n\n Parameters\n ----------\n result : pd.Series\n A multiindexed series with (dates, assets) whose ... |
Please provide a description of the function:def earn_stock_dividend(self, stock_dividend):
return {
'payment_asset': stock_dividend.payment_asset,
'share_count': np.floor(
self.amount * float(stock_dividend.ratio)
)
} | [
"\n Register the number of shares we held at this dividend's ex date so\n that we can pay out the correct amount on the dividend's pay date.\n "
] |
Please provide a description of the function:def handle_split(self, asset, ratio):
if self.asset != asset:
raise Exception("updating split with the wrong asset!")
# adjust the # of shares by the ratio
# (if we had 100 shares, and the ratio is 3,
# we now have 33 sh... | [
"\n Update the position by the split ratio, and return the resulting\n fractional share that will be converted into cash.\n\n Returns the unused cash.\n "
] |
Please provide a description of the function:def adjust_commission_cost_basis(self, asset, cost):
if asset != self.asset:
raise Exception('Updating a commission for a different asset?')
if cost == 0.0:
return
# If we no longer hold this position, there is no co... | [
"\n A note about cost-basis in zipline: all positions are considered\n to share a cost basis, even if they were executed in different\n transactions with different commission costs, different prices, etc.\n\n Due to limitations about how zipline handles positions, zipline will\n c... |
Please provide a description of the function:def to_dict(self):
return {
'sid': self.asset,
'amount': self.amount,
'cost_basis': self.cost_basis,
'last_sale_price': self.last_sale_price
} | [
"\n Creates a dictionary representing the state of this position.\n Returns a dict object of the form:\n "
] |
Please provide a description of the function:def _make_bundle_core():
_bundles = {} # the registered bundles
# Expose _bundles through a proxy so that users cannot mutate this
# accidentally. Users may go through `register` to update this which will
# warn when trampling another bundle.
bundle... | [
"Create a family of data bundle functions that read from the same\n bundle mapping.\n\n Returns\n -------\n bundles : mappingproxy\n The mapping of bundles to bundle payloads.\n register : callable\n The function which registers new bundles in the ``bundles`` mapping.\n unregister : ... |
Please provide a description of the function:def deprecated(msg=None, stacklevel=2):
def deprecated_dec(fn):
@wraps(fn)
def wrapper(*args, **kwargs):
warnings.warn(
msg or "Function %s is deprecated." % fn.__name__,
category=DeprecationWarning,
... | [
"\n Used to mark a function as deprecated.\n\n Parameters\n ----------\n msg : str\n The message to display in the deprecation warning.\n stacklevel : int\n How far up the stack the warning needs to go, before\n showing the relevant calling lines.\n\n Examples\n --------\n ... |
Please provide a description of the function:def load_pricing_adjustments(self, columns, dts, assets):
out = [None] * len(columns)
for i, column in enumerate(columns):
adjs = {}
for asset in assets:
adjs.update(self._get_adjustments_in_range(
... | [
"\n Returns\n -------\n adjustments : list[dict[int -> Adjustment]]\n A list, where each element corresponds to the `columns`, of\n mappings from index to adjustment objects to apply at that index.\n "
] |
Please provide a description of the function:def _get_adjustments_in_range(self, asset, dts, field):
sid = int(asset)
start = normalize_date(dts[0])
end = normalize_date(dts[-1])
adjs = {}
if field != 'volume':
mergers = self._adjustments_reader.get_adjustmen... | [
"\n Get the Float64Multiply objects to pass to an AdjustedArrayWindow.\n\n For the use of AdjustedArrayWindow in the loader, which looks back\n from current simulation time back to a window of data the dictionary is\n structured with:\n - the key into the dictionary for adjustment... |
Please provide a description of the function:def get(self, end_ix):
if self.most_recent_ix == end_ix:
return self.current
target = end_ix - self.cal_start - self.offset + 1
self.current = self.window.seek(target)
self.most_recent_ix = end_ix
return self.cur... | [
"\n Returns\n -------\n out : A np.ndarray of the equity pricing up to end_ix after adjustments\n and rounding have been applied.\n "
] |
Please provide a description of the function:def _ensure_sliding_windows(self, assets, dts, field,
is_perspective_after):
end = dts[-1]
size = len(dts)
asset_windows = {}
needed_assets = []
cal = self._calendar
assets = self._asse... | [
"\n Ensure that there is a Float64Multiply window for each asset that can\n provide data for the given parameters.\n If the corresponding window for the (assets, len(dts), field) does not\n exist, then create a new one.\n If a corresponding window does exist for (assets, len(dts),... |
Please provide a description of the function:def history(self, assets, dts, field, is_perspective_after):
block = self._ensure_sliding_windows(assets,
dts,
field,
is_pe... | [
"\n A window of pricing data with adjustments applied assuming that the\n end of the window is the day before the current simulation time.\n\n Parameters\n ----------\n assets : iterable of Assets\n The assets in the window.\n dts : iterable of datetime64-like\n ... |
Please provide a description of the function:def parse_date_str_series(format_str, tz, date_str_series, data_frequency,
trading_day):
# Explicitly ignoring this parameter. See note above.
if format_str is not None:
logger.warn(
"The 'f... | [
"\n Efficient parsing for a 1d Pandas/numpy object containing string\n representations of dates.\n\n Note: pd.to_datetime is significantly faster when no format string is\n passed, and in pandas 0.12.0 the %p strptime directive is not correctly\n handled if a format string is expl... |
Please provide a description of the function:def _lookup_unconflicted_symbol(self, symbol):
try:
uppered = symbol.upper()
except AttributeError:
# The mapping fails because symbol was a non-string
return numpy.nan
try:
return self.finder.... | [
"\n Attempt to find a unique asset whose symbol is the given string.\n\n If multiple assets have held the given symbol, return a 0.\n\n If no asset has held the given symbol, return a NaN.\n "
] |
Please provide a description of the function:def transform(self):
algo = self.algo
metrics_tracker = algo.metrics_tracker
emission_rate = metrics_tracker.emission_rate
def every_bar(dt_to_use, current_data=self.current_data,
handle_data=algo.event_manager.... | [
"\n Main generator work loop.\n "
] |
Please provide a description of the function:def _cleanup_expired_assets(self, dt, position_assets):
algo = self.algo
def past_auto_close_date(asset):
acd = asset.auto_close_date
return acd is not None and acd <= dt
# Remove positions in any sids that have reac... | [
"\n Clear out any assets that have expired before starting a new sim day.\n\n Performs two functions:\n\n 1. Finds all assets for which we have open orders and clears any\n orders whose assets are on or after their auto_close_date.\n\n 2. Finds all assets for which we have posi... |
Please provide a description of the function:def _get_daily_message(self, dt, algo, metrics_tracker):
perf_message = metrics_tracker.handle_market_close(
dt,
self.data_portal,
)
perf_message['daily_perf']['recorded_vars'] = algo.recorded_vars
return perf_... | [
"\n Get a perf message for the given datetime.\n "
] |
Please provide a description of the function:def _get_minute_message(self, dt, algo, metrics_tracker):
rvars = algo.recorded_vars
minute_message = metrics_tracker.handle_minute_close(
dt,
self.data_portal,
)
minute_message['minute_perf']['recorded_vars'... | [
"\n Get a perf message for the given datetime.\n "
] |
Please provide a description of the function:def load_adjustments(self,
dates,
assets,
should_include_splits,
should_include_mergers,
should_include_dividends,
adjustment... | [
"\n Load collection of Adjustment objects from underlying adjustments db.\n\n Parameters\n ----------\n dates : pd.DatetimeIndex\n Dates for which adjustments are needed.\n assets : pd.Int64Index\n Assets for which adjustments are needed.\n should_incl... |
Please provide a description of the function:def unpack_db_to_component_dfs(self, convert_dates=False):
return {
t_name: self.get_df_from_table(t_name, convert_dates)
for t_name in self._datetime_int_cols
} | [
"Returns the set of known tables in the adjustments file in DataFrame\n form.\n\n Parameters\n ----------\n convert_dates : bool, optional\n By default, dates are returned in seconds since EPOCH. If\n convert_dates is True, all ints in date columns will be converted... |
Please provide a description of the function:def _df_dtypes(self, table_name, convert_dates):
out = self._raw_table_dtypes[table_name]
if convert_dates:
out = out.copy()
for date_column in self._datetime_int_cols[table_name]:
out[date_column] = datetime64... | [
"Get dtypes to use when unpacking sqlite tables as dataframes.\n "
] |
Please provide a description of the function:def calc_dividend_ratios(self, dividends):
if dividends is None or dividends.empty:
return pd.DataFrame(np.array(
[],
dtype=[
('sid', uint64_dtype),
('effective_date', uint32... | [
"\n Calculate the ratios to apply to equities when looking back at pricing\n history so that the price is smoothed over the ex_date, when the market\n adjusts to the change in equity value due to upcoming dividend.\n\n Returns\n -------\n DataFrame\n A frame in t... |
Please provide a description of the function:def write_dividend_data(self, dividends, stock_dividends=None):
# First write the dividend payouts.
self._write_dividends(dividends)
self._write_stock_dividends(stock_dividends)
# Second from the dividend payouts, calculate ratios.
... | [
"\n Write both dividend payouts and the derived price adjustment ratios.\n "
] |
Please provide a description of the function:def write(self,
splits=None,
mergers=None,
dividends=None,
stock_dividends=None):
self.write_frame('splits', splits)
self.write_frame('mergers', mergers)
self.write_dividend_data(dividen... | [
"\n Writes data to a SQLite file to be read by SQLiteAdjustmentReader.\n\n Parameters\n ----------\n splits : pandas.DataFrame, optional\n Dataframe containing split data. The format of this dataframe is:\n effective_date : int\n The date, represe... |
Please provide a description of the function:def compute(self, today, assets, out, *arrays):
raise NotImplementedError(
"{name} must define a compute method".format(
name=type(self).__name__
)
) | [
"\n Override this method with a function that writes a value into `out`.\n "
] |
Please provide a description of the function:def _allocate_output(self, windows, shape):
missing_value = self.missing_value
outputs = self.outputs
if outputs is not NotSpecified:
out = recarray(
shape,
formats=[self.dtype.str] * len(outputs),
... | [
"\n Allocate an output array whose rows should be passed to `self.compute`.\n\n The resulting array must have a shape of ``shape``.\n\n If we have standard outputs (i.e. self.outputs is NotSpecified), the\n default is an empty ndarray whose dtype is ``self.dtype``.\n\n If we have ... |
Please provide a description of the function:def _compute(self, windows, dates, assets, mask):
format_inputs = self._format_inputs
compute = self.compute
params = self.params
ndim = self.ndim
shape = (len(mask), 1) if ndim == 1 else mask.shape
out = self._alloca... | [
"\n Call the user's `compute` function on each window with a pre-built\n output array.\n "
] |
Please provide a description of the function:def make_aliased_type(cls, other_base):
docstring = dedent(
).format(t=other_base.__name__)
doc = format_docstring(
owner_name=other_base.__name__,
docstring=docstring,
formatters={'name': PIP... | [
"\n Factory for making Aliased{Filter,Factor,Classifier}.\n ",
"\n A {t} that names another {t}.\n\n Parameters\n ----------\n term : {t}\n {{name}}\n "
] |
Please provide a description of the function:def compute_extra_rows(self,
all_dates,
start_date,
end_date,
min_extra_rows):
try:
current_start_pos = all_dates.get_loc(start_date) - mi... | [
"\n Ensure that min_extra_rows pushes us back to a computation date.\n\n Parameters\n ----------\n all_dates : pd.DatetimeIndex\n The trading sessions against which ``self`` will be computed.\n start_date : pd.Timestamp\n The first date for which final output... |
Please provide a description of the function:def _compute(self, inputs, dates, assets, mask):
to_sample = dates[select_sampling_indices(dates, self._frequency)]
assert to_sample[0] == dates[0], \
"Misaligned sampling dates in %s." % type(self).__name__
real_compute = self._... | [
"\n Compute by delegating to self._wrapped_term._compute on sample dates.\n\n On non-sample dates, forward-fill from previously-computed samples.\n "
] |
Please provide a description of the function:def make_downsampled_type(cls, other_base):
docstring = dedent(
).format(t=other_base.__name__)
doc = format_docstring(
owner_name=other_base.__name__,
docstring=docstring,
formatters={'freque... | [
"\n Factory for making Downsampled{Filter,Factor,Classifier}.\n ",
"\n A {t} that defers to another {t} at lower-than-daily frequency.\n\n Parameters\n ----------\n term : {t}\n {{frequency}}\n "
] |
Please provide a description of the function:def preprocess(*_unused, **processors):
if _unused:
raise TypeError("preprocess() doesn't accept positional arguments")
def _decorator(f):
args, varargs, varkw, defaults = argspec = getargspec(f)
if defaults is None:
defaults... | [
"\n Decorator that applies pre-processors to the arguments of a function before\n calling the function.\n\n Parameters\n ----------\n **processors : dict\n Map from argument name -> processor function.\n\n A processor function takes three arguments: (func, argname, argvalue).\n\n ... |
Please provide a description of the function:def call(f):
@wraps(f)
def processor(func, argname, arg):
return f(arg)
return processor | [
"\n Wrap a function in a processor that calls `f` on the argument before\n passing it along.\n\n Useful for creating simple arguments to the `@preprocess` decorator.\n\n Parameters\n ----------\n f : function\n Function accepting a single argument and returning a replacement.\n\n Example... |
Please provide a description of the function:def _build_preprocessed_function(func,
processors,
args_defaults,
varargs,
varkw):
format_kwargs = {'func_name': func.__name__}
d... | [
"\n Build a preprocessed function with the same signature as `func`.\n\n Uses `exec` internally to build a function that actually has the same\n signature as `func.\n ",
"\\\n @wraps({wrapped_funcname})\n def {func_name}({signature}):\n {assignments}\n return {wrapp... |
Please provide a description of the function:def get_benchmark_returns(symbol):
r = requests.get(
'https://api.iextrading.com/1.0/stock/{}/chart/5y'.format(symbol)
)
data = r.json()
df = pd.DataFrame(data)
df.index = pd.DatetimeIndex(df['date'])
df = df['close']
return df.sor... | [
"\n Get a Series of benchmark returns from IEX associated with `symbol`.\n Default is `SPY`.\n\n Parameters\n ----------\n symbol : str\n Benchmark symbol for which we're getting the returns.\n\n The data is provided by IEX (https://iextrading.com/), and we can\n get up to 5 years worth ... |
Please provide a description of the function:def delimit(delimiters, content):
if len(delimiters) != 2:
raise ValueError(
"`delimiters` must be of length 2. Got %r" % delimiters
)
return ''.join([delimiters[0], content, delimiters[1]]) | [
"\n Surround `content` with the first and last characters of `delimiters`.\n\n >>> delimit('[]', \"foo\") # doctest: +SKIP\n '[foo]'\n >>> delimit('\"\"', \"foo\") # doctest: +SKIP\n '\"foo\"'\n "
] |
Please provide a description of the function:def roots(g):
"Get nodes from graph G with indegree 0"
return set(n for n, d in iteritems(g.in_degree()) if d == 0) | [] |
Please provide a description of the function:def _render(g, out, format_, include_asset_exists=False):
graph_attrs = {'rankdir': 'TB', 'splines': 'ortho'}
cluster_attrs = {'style': 'filled', 'color': 'lightgoldenrod1'}
in_nodes = g.loadable_terms
out_nodes = list(g.outputs.values())
f = Bytes... | [
"\n Draw `g` as a graph to `out`, in format `format`.\n\n Parameters\n ----------\n g : zipline.pipeline.graph.TermGraph\n Graph to render.\n out : file-like object\n format_ : str {'png', 'svg'}\n Output format.\n include_asset_exists : bool\n Whether to filter out `AssetE... |
Please provide a description of the function:def display_graph(g, format='svg', include_asset_exists=False):
try:
import IPython.display as display
except ImportError:
raise NoIPython("IPython is not installed. Can't display graph.")
if format == 'svg':
display_cls = display.S... | [
"\n Display a TermGraph interactively from within IPython.\n "
] |
Please provide a description of the function:def format_attrs(attrs):
if not attrs:
return ''
entries = ['='.join((key, value)) for key, value in iteritems(attrs)]
return '[' + ', '.join(entries) + ']' | [
"\n Format key, value pairs from attrs into graphviz attrs format\n\n Examples\n --------\n >>> format_attrs({'key1': 'value1', 'key2': 'value2'}) # doctest: +SKIP\n '[key1=value1, key2=value2]'\n "
] |
Please provide a description of the function:def apply_async(f, args=(), kwargs=None, callback=None):
try:
value = (identity if callback is None else callback)(
f(*args, **kwargs or {}),
)
successful = True
except Exception as e:
v... | [
"Apply a function but emulate the API of an asynchronous call.\n\n Parameters\n ----------\n f : callable\n The function to call.\n args : tuple, optional\n The positional arguments.\n kwargs : dict, optional\n The keyword arguments.\n\n Ret... |
Please provide a description of the function:def maybe_show_progress(it, show_progress, **kwargs):
if show_progress:
return click.progressbar(it, **kwargs)
# context manager that just return `it` when we enter it
return CallbackManager(lambda it=it: it) | [
"Optionally show a progress bar for the given iterator.\n\n Parameters\n ----------\n it : iterable\n The underlying iterator.\n show_progress : bool\n Should progress be shown.\n **kwargs\n Forwarded to the click progress bar.\n\n Returns\n -------\n itercontext : conte... |
Please provide a description of the function:def main(extension, strict_extensions, default_extension, x):
# install a logbook handler before performing any other operations
logbook.StderrHandler().push_application()
create_args(x, zipline.extension_args)
load_extensions(
default_extension... | [
"Top level zipline entry point.\n "
] |
Please provide a description of the function:def ipython_only(option):
if __IPYTHON__:
return option
argname = extract_option_object(option).name
def d(f):
@wraps(f)
def _(*args, **kwargs):
kwargs[argname] = None
return f(*args, **kwargs)
return... | [
"Mark that an option should only be exposed in IPython.\n\n Parameters\n ----------\n option : decorator\n A click.option decorator.\n\n Returns\n -------\n ipython_only_dec : decorator\n A decorator that correctly applies the argument even when not\n using IPython mode.\n ... |
Please provide a description of the function:def run(ctx,
algofile,
algotext,
define,
data_frequency,
capital_base,
bundle,
bundle_timestamp,
start,
end,
output,
trading_calendar,
print_algo,
metrics_set,
loc... | [
"Run a backtest for the given algorithm.\n "
] |
Please provide a description of the function:def zipline_magic(line, cell=None):
load_extensions(
default=True,
extensions=[],
strict=True,
environ=os.environ,
)
try:
return run.main(
# put our overrides at the start of the parameter list so that
... | [
"The zipline IPython cell magic.\n "
] |
Please provide a description of the function:def ingest(bundle, assets_version, show_progress):
bundles_module.ingest(
bundle,
os.environ,
pd.Timestamp.utcnow(),
assets_version,
show_progress,
) | [
"Ingest the data for the given bundle.\n "
] |
Please provide a description of the function:def clean(bundle, before, after, keep_last):
bundles_module.clean(
bundle,
before,
after,
keep_last,
) | [
"Clean up data downloaded with the ingest command.\n "
] |
Please provide a description of the function:def bundles():
for bundle in sorted(bundles_module.bundles.keys()):
if bundle.startswith('.'):
# hide the test data
continue
try:
ingestions = list(
map(text_type, bundles_module.ingestions_for_bund... | [
"List all of the available data bundles.\n "
] |
Please provide a description of the function:def binary_operator(op):
# When combining a Filter with a NumericalExpression, we use this
# attrgetter instance to defer to the commuted interpretation of the
# NumericalExpression operator.
commuted_method_getter = attrgetter(method_name_for_op(op, com... | [
"\n Factory function for making binary operator methods on a Filter subclass.\n\n Returns a function \"binary_operator\" suitable for implementing functions\n like __and__ or __or__.\n "
] |
Please provide a description of the function:def unary_operator(op):
valid_ops = {'~'}
if op not in valid_ops:
raise ValueError("Invalid unary operator %s." % op)
def unary_operator(self):
# This can't be hoisted up a scope because the types returned by
# unary_op_return_type a... | [
"\n Factory function for making unary operator methods for Filters.\n "
] |
Please provide a description of the function:def create(cls, expr, binds):
return cls(expr=expr, binds=binds, dtype=bool_dtype) | [
"\n Helper for creating new NumExprFactors.\n\n This is just a wrapper around NumericalExpression.__new__ that always\n forwards `bool` as the dtype, since Filters can only be of boolean\n dtype.\n "
] |
Please provide a description of the function:def _compute(self, arrays, dates, assets, mask):
return super(NumExprFilter, self)._compute(
arrays,
dates,
assets,
mask,
) & mask | [
"\n Compute our result with numexpr, then re-apply `mask`.\n "
] |
Please provide a description of the function:def _validate(self):
if not 0.0 <= self._min_percentile < self._max_percentile <= 100.0:
raise BadPercentileBounds(
min_percentile=self._min_percentile,
max_percentile=self._max_percentile,
upper_bo... | [
"\n Ensure that our percentile bounds are well-formed.\n "
] |
Please provide a description of the function:def _compute(self, arrays, dates, assets, mask):
# TODO: Review whether there's a better way of handling small numbers
# of columns.
data = arrays[0].copy().astype(float64)
data[~mask] = nan
# FIXME: np.nanpercentile **should... | [
"\n For each row in the input, compute a mask of all values falling between\n the given percentiles.\n "
] |
Please provide a description of the function:def parse_treasury_csv_column(column):
column_re = re.compile(
r"^(?P<prefix>RIFLGFC)"
"(?P<unit>[YM])"
"(?P<periods>[0-9]{2})"
"(?P<suffix>_N.B)$"
)
match = column_re.match(column)
if match is None:
raise ValueEr... | [
"\n Parse a treasury CSV column into a more human-readable format.\n\n Columns start with 'RIFLGFC', followed by Y or M (year or month), followed\n by a two-digit number signifying number of years/months, followed by _N.B.\n We only care about the middle two entries, which we turn into a string like\n ... |
Please provide a description of the function:def get_daily_10yr_treasury_data():
url = "https://www.federalreserve.gov/datadownload/Output.aspx?rel=H15" \
"&series=bcb44e57fb57efbe90002369321bfb3f&lastObs=&from=&to=" \
"&filetype=csv&label=include&layout=seriescolumn"
return pd.read_csv... | [
"Download daily 10 year treasury rates from the Federal Reserve and\n return a pandas.Series."
] |
Please provide a description of the function:def _sid_subdir_path(sid):
padded_sid = format(sid, '06')
return os.path.join(
# subdir 1 00/XX
padded_sid[0:2],
# subdir 2 XX/00
padded_sid[2:4],
"{0}.bcolz".format(str(padded_sid))
) | [
"\n Format subdir path to limit the number directories in any given\n subdirectory to 100.\n\n The number in each directory is designed to support at least 100000\n equities.\n\n Parameters\n ----------\n sid : int\n Asset identifier.\n\n Returns\n -------\n out : string\n ... |
Please provide a description of the function:def convert_cols(cols, scale_factor, sid, invalid_data_behavior):
scaled_opens = (np.nan_to_num(cols['open']) * scale_factor).round()
scaled_highs = (np.nan_to_num(cols['high']) * scale_factor).round()
scaled_lows = (np.nan_to_num(cols['low']) * scale_factor... | [
"Adapt OHLCV columns into uint32 columns.\n\n Parameters\n ----------\n cols : dict\n A dict mapping each column name (open, high, low, close, volume)\n to a float column to convert to uint32.\n scale_factor : int\n Factor to use to scale float values before converting to uint32.\n ... |
Please provide a description of the function:def write(self, rootdir):
calendar = self.calendar
slicer = calendar.schedule.index.slice_indexer(
self.start_session,
self.end_session,
)
schedule = calendar.schedule[slicer]
market_opens = schedule.m... | [
"\n Write the metadata to a JSON file in the rootdir.\n\n Values contained in the metadata are:\n\n version : int\n The value of FORMAT_VERSION of this class.\n ohlc_ratio : int\n The default ratio by which to multiply the pricing data to\n convert the fl... |
Please provide a description of the function:def open(cls, rootdir, end_session=None):
metadata = BcolzMinuteBarMetadata.read(rootdir)
return BcolzMinuteBarWriter(
rootdir,
metadata.calendar,
metadata.start_session,
end_session if end_session is n... | [
"\n Open an existing ``rootdir`` for writing.\n\n Parameters\n ----------\n end_session : Timestamp (optional)\n When appending, the intended new ``end_session``.\n "
] |
Please provide a description of the function:def sidpath(self, sid):
sid_subdir = _sid_subdir_path(sid)
return join(self._rootdir, sid_subdir) | [
"\n Parameters\n ----------\n sid : int\n Asset identifier.\n\n Returns\n -------\n out : string\n Full path to the bcolz rootdir for the given sid.\n "
] |
Please provide a description of the function:def last_date_in_output_for_sid(self, sid):
sizes_path = "{0}/close/meta/sizes".format(self.sidpath(sid))
if not os.path.exists(sizes_path):
return pd.NaT
with open(sizes_path, mode='r') as f:
sizes = f.read()
... | [
"\n Parameters\n ----------\n sid : int\n Asset identifier.\n\n Returns\n -------\n out : pd.Timestamp\n The midnight of the last date written in to the output for the\n given sid.\n "
] |
Please provide a description of the function:def _init_ctable(self, path):
# Only create the containing subdir on creation.
# This is not to be confused with the `.bcolz` directory, but is the
# directory up one level from the `.bcolz` directories.
sid_containing_dirname = os.pa... | [
"\n Create empty ctable for given path.\n\n Parameters\n ----------\n path : string\n The path to rootdir of the new ctable.\n "
] |
Please provide a description of the function:def _ensure_ctable(self, sid):
sidpath = self.sidpath(sid)
if not os.path.exists(sidpath):
return self._init_ctable(sidpath)
return bcolz.ctable(rootdir=sidpath, mode='a') | [
"Ensure that a ctable exists for ``sid``, then return it."
] |
Please provide a description of the function:def pad(self, sid, date):
table = self._ensure_ctable(sid)
last_date = self.last_date_in_output_for_sid(sid)
tds = self._session_labels
if date <= last_date or date < tds[0]:
# No need to pad.
return
... | [
"\n Fill sid container with empty data through the specified date.\n\n If the last recorded trade is not at the close, then that day will be\n padded with zeros until its close. Any day after that (up to and\n including the specified date) will be padded with `minute_per_day`\n wo... |
Please provide a description of the function:def set_sid_attrs(self, sid, **kwargs):
table = self._ensure_ctable(sid)
for k, v in kwargs.items():
table.attrs[k] = v | [
"Write all the supplied kwargs as attributes of the sid's file.\n "
] |
Please provide a description of the function:def write(self, data, show_progress=False, invalid_data_behavior='warn'):
ctx = maybe_show_progress(
data,
show_progress=show_progress,
item_show_func=lambda e: e if e is None else str(e[0]),
label="Merging min... | [
"Write a stream of minute data.\n\n Parameters\n ----------\n data : iterable[(int, pd.DataFrame)]\n The data to write. Each element should be a tuple of sid, data\n where data has the following format:\n columns : ('open', 'high', 'low', 'close', 'volume')\n ... |
Please provide a description of the function:def write_sid(self, sid, df, invalid_data_behavior='warn'):
cols = {
'open': df.open.values,
'high': df.high.values,
'low': df.low.values,
'close': df.close.values,
'volume': df.volume.values,
... | [
"\n Write the OHLCV data for the given sid.\n If there is no bcolz ctable yet created for the sid, create it.\n If the length of the bcolz ctable is not exactly to the date before\n the first day provided, fill the ctable with 0s up to that date.\n\n Parameters\n ----------... |
Please provide a description of the function:def write_cols(self, sid, dts, cols, invalid_data_behavior='warn'):
if not all(len(dts) == len(cols[name]) for name in self.COL_NAMES):
raise BcolzMinuteWriterColumnMismatch(
"Length of dts={0} should match cols: {1}".format(
... | [
"\n Write the OHLCV data for the given sid.\n If there is no bcolz ctable yet created for the sid, create it.\n If the length of the bcolz ctable is not exactly to the date before\n the first day provided, fill the ctable with 0s up to that date.\n\n Parameters\n ----------... |
Please provide a description of the function:def _write_cols(self, sid, dts, cols, invalid_data_behavior):
table = self._ensure_ctable(sid)
tds = self._session_labels
input_first_day = self._calendar.minute_to_session_label(
pd.Timestamp(dts[0]), direction='previous')
... | [
"\n Internal method for `write_cols` and `write`.\n\n Parameters\n ----------\n sid : int\n The asset identifier for the data being written.\n dts : datetime64 array\n The dts corresponding to values in cols.\n cols : dict of str -> np.array\n ... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.