text
stringlengths
81
112k
Pops the topmost level for assignment tracking and updates the context variables if necessary. def pop_assign_tracking(self, frame): """Pops the topmost level for assignment tracking and updates the context variables if necessary. """ vars = self._assign_stack.pop() if n...
Call a block and register it for the template. def visit_Block(self, node, frame): """Call a block and register it for the template.""" level = 0 if frame.toplevel: # if we know that we are a child template, there is no need to # check if we are one if self.h...
Calls the extender. def visit_Extends(self, node, frame): """Calls the extender.""" if not frame.toplevel: self.fail('cannot use extend from a non top-level scope', node.lineno) # if the number of extends statements in general is zero so # far, we don'...
Handles includes. def visit_Include(self, node, frame): """Handles includes.""" if node.ignore_missing: self.writeline('try:') self.indent() func_name = 'get_or_select_template' if isinstance(node.template, nodes.Const): if isinstance(node.template.v...
Visit regular imports. def visit_Import(self, node, frame): """Visit regular imports.""" self.writeline('%s = ' % frame.symbols.ref(node.target), node) if frame.toplevel: self.write('context.vars[%r] = ' % node.target) if self.environment.is_async: self.write('aw...
Visit named imports. def visit_FromImport(self, node, frame): """Visit named imports.""" self.newline(node) self.write('included_template = %senvironment.get_template(' % (self.environment.is_async and 'await ' or '')) self.visit(node.template, frame) self.wri...
If alive then mark as dead and return (obj, func, args, kwargs); otherwise return None def detach(self): """If alive then mark as dead and return (obj, func, args, kwargs); otherwise return None""" info = self._registry.get(self) obj = info and info.weakref() if obj is n...
If alive then return (obj, func, args, kwargs); otherwise return None def peek(self): """If alive then return (obj, func, args, kwargs); otherwise return None""" info = self._registry.get(self) obj = info and info.weakref() if obj is not None: return (obj, in...
Whether finalizer should be called at exit def atexit(self): """Whether finalizer should be called at exit""" info = self._registry.get(self) return bool(info) and info.atexit
Serialize an element and its child nodes to a string def tostring(element): """Serialize an element and its child nodes to a string""" rv = [] def serializeElement(element): if not hasattr(element, "tag"): if element.docinfo.internalDTD: if element.docinfo.doctype: ...
Return the visitor function for this node or `None` if no visitor exists for this node. In that case the generic visit function is used instead. def get_visitor(self, node): """Return the visitor function for this node or `None` if no visitor exists for this node. In that case the gen...
Visit a node. def visit(self, node, *args, **kwargs): """Visit a node.""" f = self.get_visitor(node) if f is not None: return f(node, *args, **kwargs) return self.generic_visit(node, *args, **kwargs)
Called if no explicit visitor function exists for a node. def generic_visit(self, node, *args, **kwargs): """Called if no explicit visitor function exists for a node.""" for node in node.iter_child_nodes(): self.visit(node, *args, **kwargs)
As transformers may return lists in some places this method can be used to enforce a list as return value. def visit_list(self, node, *args, **kwargs): """As transformers may return lists in some places this method can be used to enforce a list as return value. """ rv = self.vis...
The default method of calling the wrapper subprocess. def default_subprocess_runner(cmd, cwd=None, extra_environ=None): """The default method of calling the wrapper subprocess.""" env = os.environ.copy() if extra_environ: env.update(extra_environ) check_call(cmd, cwd=cwd, env=env)
Build a wheel from this project. Returns the name of the newly created file. In general, this will call the 'build_wheel' hook in the backend. However, if that was previously called by 'prepare_metadata_for_build_wheel', and the same metadata_directory is used, the previously b...
r"""BNInception model architecture from <https://arxiv.org/pdf/1502.03167.pdf>`_ paper. def bninception(num_classes=1000, pretrained='imagenet'): r"""BNInception model architecture from <https://arxiv.org/pdf/1502.03167.pdf>`_ paper. """ model = BNInception(num_classes=num_classes) if pretrained is not...
3x3 convolution with padding def conv3x3(in_planes, out_planes, stride=1): "3x3 convolution with padding" return nn.Conv2d(in_planes, out_planes, kernel_size=3, stride=stride, padding=1, bias=True)
Constructs a ResNet-18 model. Args: pretrained (bool): If True, returns a model pre-trained on ImageNet def resnet18(pretrained=False, **kwargs): """Constructs a ResNet-18 model. Args: pretrained (bool): If True, returns a model pre-trained on ImageNet """ model = ResNet(BasicBloc...
Constructs a ResNet-50 model. Args: pretrained (bool): If True, returns a model pre-trained on ImageNet def resnet50(pretrained=False, **kwargs): """Constructs a ResNet-50 model. Args: pretrained (bool): If True, returns a model pre-trained on ImageNet """ model = ResNet(Bottlenec...
r"""NASNetALarge model architecture from the `"NASNet" <https://arxiv.org/abs/1707.07012>`_ paper. def nasnetamobile(num_classes=1000, pretrained='imagenet'): r"""NASNetALarge model architecture from the `"NASNet" <https://arxiv.org/abs/1707.07012>`_ paper. """ if pretrained: settings = pre...
Constructs a ResNet-101 model. Args: pretrained (bool): If True, returns a model pre-trained on ImageNet def cafferesnet101(num_classes=1000, pretrained='imagenet'): """Constructs a ResNet-101 model. Args: pretrained (bool): If True, returns a model pre-trained on ImageNet """ model = ResNe...
Constructs a ResNet-152 model. Args: pretrained (bool): If True, returns a model pre-trained on ImageNet def fbresnet152(num_classes=1000, pretrained='imagenet'): """Constructs a ResNet-152 model. Args: pretrained (bool): If True, returns a model pre-trained on ImageNet """ model ...
r"""AlexNet model architecture from the `"One weird trick..." <https://arxiv.org/abs/1404.5997>`_ paper. def alexnet(num_classes=1000, pretrained='imagenet'): r"""AlexNet model architecture from the `"One weird trick..." <https://arxiv.org/abs/1404.5997>`_ paper. """ # https://github.com/pytorch/vi...
r"""Densenet-121 model from `"Densely Connected Convolutional Networks" <https://arxiv.org/pdf/1608.06993.pdf>` def densenet121(num_classes=1000, pretrained='imagenet'): r"""Densenet-121 model from `"Densely Connected Convolutional Networks" <https://arxiv.org/pdf/1608.06993.pdf>` """ model = model...
r"""Inception v3 model architecture from `"Rethinking the Inception Architecture for Computer Vision" <http://arxiv.org/abs/1512.00567>`_. def inceptionv3(num_classes=1000, pretrained='imagenet'): r"""Inception v3 model architecture from `"Rethinking the Inception Architecture for Computer Vision" <http://...
Constructs a ResNet-50 model. def resnet50(num_classes=1000, pretrained='imagenet'): """Constructs a ResNet-50 model. """ model = models.resnet50(pretrained=False) if pretrained is not None: settings = pretrained_settings['resnet50'][pretrained] model = load_pretrained(model, num_classe...
r"""SqueezeNet model architecture from the `"SqueezeNet: AlexNet-level accuracy with 50x fewer parameters and <0.5MB model size" <https://arxiv.org/abs/1602.07360>`_ paper. def squeezenet1_0(num_classes=1000, pretrained='imagenet'): r"""SqueezeNet model architecture from the `"SqueezeNet: AlexNet-level ...
VGG 11-layer model (configuration "A") def vgg11(num_classes=1000, pretrained='imagenet'): """VGG 11-layer model (configuration "A") """ model = models.vgg11(pretrained=False) if pretrained is not None: settings = pretrained_settings['vgg11'][pretrained] model = load_pretrained(model, n...
Sets the learning rate to the initial LR decayed by 10 every 30 epochs def adjust_learning_rate(optimizer, epoch): """Sets the learning rate to the initial LR decayed by 10 every 30 epochs""" lr = args.lr * (0.1 ** (epoch // 30)) for param_group in optimizer.param_groups: param_group['lr'] = lr
r"""NASNetALarge model architecture from the `"NASNet" <https://arxiv.org/abs/1707.07012>`_ paper. def nasnetalarge(num_classes=1001, pretrained='imagenet'): r"""NASNetALarge model architecture from the `"NASNet" <https://arxiv.org/abs/1707.07012>`_ paper. """ if pretrained: settings = pret...
Selectable global pooling function with dynamic input kernel size def adaptive_avgmax_pool2d(x, pool_type='avg', padding=0, count_include_pad=False): """Selectable global pooling function with dynamic input kernel size """ if pool_type == 'avgmaxc': x = torch.cat([ F.avg_pool2d( ...
Download a URL to a local file. Parameters ---------- url : str The URL to download. destination : str, None The destination of the file. If None is given the file is saved to a temporary directory. progress_bar : bool Whether to show a command-line progress bar while downlo...
Args: output (Tensor): NxK tensor that for each of the N examples indicates the probability of the example belonging to each of the K classes, according to the model. The probabilities should sum to one over all classes target (Tensor): binary NxK ...
Returns the model's average precision for each class Return: ap (FloatTensor): 1xK tensor, with avg precision for each class k def value(self): """Returns the model's average precision for each class Return: ap (FloatTensor): 1xK tensor, with avg precision for each class...
PolyNet architecture from the paper 'PolyNet: A Pursuit of Structural Diversity in Very Deep Networks' https://arxiv.org/abs/1611.05725 def polynet(num_classes=1000, pretrained='imagenet'): """PolyNet architecture from the paper 'PolyNet: A Pursuit of Structural Diversity in Very Deep Networks' htt...
Get the cached value. Returns ------- value : object The cached value. Raises ------ Expired Raised when `dt` is greater than self.expires. def unwrap(self, dt): """ Get the cached value. Returns ------- ...
Get the value of a cached object. Parameters ---------- key : any The key to lookup. dt : datetime The time of the lookup. Returns ------- result : any The value for ``key``. Raises ------ KeyError ...
Adds a new key value pair to the cache. Parameters ---------- key : any The key to use for the pair. value : any The value to store under the name ``key``. expiration_dt : datetime When should this mapping expire? The cache is considered inval...
Ensures a subdirectory of the working directory. Parameters ---------- path_parts : iterable[str] The parts of the path after the working directory. def ensure_dir(self, *path_parts): """Ensures a subdirectory of the working directory. Parameters ----------...
Verify that DataFrames in ``frames`` have the same indexing scheme and are aligned to ``calendar``. Parameters ---------- frames : list[pd.DataFrame] calendar : trading_calendars.TradingCalendar Raises ------ ValueError If frames have different indexes/columns, or if frame inde...
Parameters ---------- sid : int The asset identifier. day : datetime64-like Midnight of the day for which data is requested. field : string The price field. e.g. ('open', 'high', 'low', 'close', 'volume') Returns ------- float ...
Parameters ---------- asset : zipline.asset.Asset The asset identifier. dt : datetime64-like Midnight of the day for which data is requested. Returns ------- pd.Timestamp : The last know dt for the asset and dt; NaT if no tr...
Check if all values in a sequence are equal. Returns True on empty sequences. Examples -------- >>> same(1, 1, 1, 1) True >>> same(1, 2, 1) False >>> same() True def same(*values): """ Check if all values in a sequence are equal. Returns True on empty sequences. ...
Parameters ---------- *dicts : iterable[dict] A sequence of dicts all sharing the same keys. Returns ------- zipped : dict A dict whose keys are the union of all keys in *dicts, and whose values are tuples of length len(dicts) containing the result of looking up each...
Helper for unzip which checks the lengths of each element in it. Parameters ---------- it : iterable[tuple] An iterable of tuples. ``unzip`` should map ensure that these are already tuples. elem_len : int or None The expected element length. If this is None it is infered from the...
Unzip a length n sequence of length m sequences into m seperate length n sequences. Parameters ---------- seq : iterable[iterable] The sequence to unzip. elem_len : int, optional The expected length of each element of ``seq``. If not provided this will be infered from the len...
Perform a chained application of ``getattr`` on ``value`` with the values in ``attrs``. If ``default`` is supplied, return it if any of the attribute lookups fail. Parameters ---------- value : object Root of the lookup chain. attrs : iterable[str] Sequence of attributes to loo...
Decorator factory for setting attributes on a function. Doesn't change the behavior of the wrapped function. Examples -------- >>> @set_attribute('__name__', 'foo') ... def bar(): ... return 3 ... >>> bar() 3 >>> bar.__name__ 'foo' def set_attribute(name, value): "...
Fold a function over a sequence with right associativity. Parameters ---------- f : callable[any, any] The function to reduce the sequence with. The first argument will be the element of the sequence; the second argument will be the accumulator. seq : iterable[any] The s...
Invert a dictionary into a dictionary of sets. >>> invert({'a': 1, 'b': 2, 'c': 1}) # doctest: +SKIP {1: {'a', 'c'}, 2: {'b'}} def invert(d): """ Invert a dictionary into a dictionary of sets. >>> invert({'a': 1, 'b': 2, 'c': 1}) # doctest: +SKIP {1: {'a', 'c'}, 2: {'b'}} """ out = ...
r"""Projection vectors to the simplex domain Implemented according to the paper: Efficient projections onto the l1-ball for learning in high dimensions, John Duchi, et al. ICML 2008. Implementation Time: 2011 June 17 by Bin@libin AT pmail.ntu.edu.sg Optimization Problem: min_{w}\| w - v \|_{2}^{2} ...
Run an example module from zipline.examples. def run_example(example_name, environ): """ Run an example module from zipline.examples. """ mod = EXAMPLE_MODULES[example_name] register_calendar("YAHOO", get_calendar("NYSE"), force=True) return run_algorithm( initialize=getattr(mod, 'ini...
Compute slopes of linear regressions between columns of ``dependents`` and ``independent``. Parameters ---------- dependents : np.array[N, M] Array with columns of data to be regressed against ``independent``. independent : np.array[N, 1] Independent variable of the regression a...
Format a URL for loading data from Bank of Canada. def _format_url(instrument_type, instrument_ids, start_date, end_date, earliest_allowed_date): """ Format a URL for loading data from Bank of Canada. """ return ( "http://www.banko...
Load a DataFrame of data from a Bank of Canada site. def load_frame(url, skiprows): """ Load a DataFrame of data from a Bank of Canada site. """ return pd.read_csv( url, skiprows=skiprows, skipinitialspace=True, na_values=["Bank holiday", "Not available"], parse_...
There are a couple quirks in the data provided by Bank of Canada. Check that no new quirks have been introduced in the latest download. def check_known_inconsistencies(bill_data, bond_data): """ There are a couple quirks in the data provided by Bank of Canada. Check that no new quirks have been introdu...
The earliest date for which we can load data from this module. def earliest_possible_date(): """ The earliest date for which we can load data from this module. """ today = pd.Timestamp('now', tz='UTC').normalize() # Bank of Canada only has the last 10 years of data at any given time. return tod...
Checks whether the fill price is worse than the order's limit price. Parameters ---------- fill_price: float The price to check. order: zipline.finance.order.Order The order whose limit price to check. Returns ------- bool: Whether the fill price is above the limit price (...
Internal utility method to return the trailing mean volume over the past 'window_length' days, and volatility of close prices for a specific asset. Parameters ---------- data : The BarData from which to fetch the daily windows. asset : The Asset whose data we are fetchin...
Validate a `dtype` and `missing_value` passed to Term.__new__. Ensures that we know how to represent ``dtype``, and that missing_value is specified for types without default missing values. Returns ------- validated_dtype, validated_missing_value : np.dtype, any The dtype and missing_value...
Check that value is a valid categorical missing_value. Raises a TypeError if the value is cannot be used as the missing_value for a categorical_dtype Term. def _assert_valid_categorical_missing_value(value): """ Check that value is a valid categorical missing_value. Raises a TypeError if the valu...
Pop entries from the `kwargs` passed to cls.__new__ based on the values in `cls.params`. Parameters ---------- kwargs : dict The kwargs passed to cls.__new__. Returns ------- params : list[(str, object)] A list of string, value pairs cont...
Return the identity of the Term that would be constructed from the given arguments. Identities that compare equal will cause us to return a cached instance rather than constructing a new one. We do this primarily because it makes dependency resolution easier. This is a classme...
Parameters ---------- domain : zipline.pipeline.domain.Domain The domain of this term. dtype : np.dtype Dtype of this term's output. missing_value : object Missing value for this term. ndim : 1 or 2 The dimensionality of this term. ...
The number of extra rows needed for each of our inputs to compute this term. def dependencies(self): """ The number of extra rows needed for each of our inputs to compute this term. """ extra_input_rows = max(0, self.window_length - 1) out = {} for term i...
Called with a column of the result of a pipeline. This needs to put the data into a format that can be used in a workspace to continue doing computations. Parameters ---------- result : pd.Series A multiindexed series with (dates, assets) whose values are the ...
Register the number of shares we held at this dividend's ex date so that we can pay out the correct amount on the dividend's pay date. def earn_stock_dividend(self, stock_dividend): """ Register the number of shares we held at this dividend's ex date so that we can pay out the correct a...
Update the position by the split ratio, and return the resulting fractional share that will be converted into cash. Returns the unused cash. def handle_split(self, asset, ratio): """ Update the position by the split ratio, and return the resulting fractional share that will be ...
A note about cost-basis in zipline: all positions are considered to share a cost basis, even if they were executed in different transactions with different commission costs, different prices, etc. Due to limitations about how zipline handles positions, zipline will currently spread an e...
Creates a dictionary representing the state of this position. Returns a dict object of the form: def to_dict(self): """ Creates a dictionary representing the state of this position. Returns a dict object of the form: """ return { 'sid': self.asset, ...
Create a family of data bundle functions that read from the same bundle mapping. Returns ------- bundles : mappingproxy The mapping of bundles to bundle payloads. register : callable The function which registers new bundles in the ``bundles`` mapping. unregister : callable ...
Used to mark a function as deprecated. Parameters ---------- msg : str The message to display in the deprecation warning. stacklevel : int How far up the stack the warning needs to go, before showing the relevant calling lines. Examples -------- @deprecated(msg='fun...
Returns ------- adjustments : list[dict[int -> Adjustment]] A list, where each element corresponds to the `columns`, of mappings from index to adjustment objects to apply at that index. def load_pricing_adjustments(self, columns, dts, assets): """ Returns ...
Get the Float64Multiply objects to pass to an AdjustedArrayWindow. For the use of AdjustedArrayWindow in the loader, which looks back from current simulation time back to a window of data the dictionary is structured with: - the key into the dictionary for adjustments is the location of...
Returns ------- out : A np.ndarray of the equity pricing up to end_ix after adjustments and rounding have been applied. def get(self, end_ix): """ Returns ------- out : A np.ndarray of the equity pricing up to end_ix after adjustments and roun...
Ensure that there is a Float64Multiply window for each asset that can provide data for the given parameters. If the corresponding window for the (assets, len(dts), field) does not exist, then create a new one. If a corresponding window does exist for (assets, len(dts), field), but ...
A window of pricing data with adjustments applied assuming that the end of the window is the day before the current simulation time. Parameters ---------- assets : iterable of Assets The assets in the window. dts : iterable of datetime64-like The datetime...
Efficient parsing for a 1d Pandas/numpy object containing string representations of dates. Note: pd.to_datetime is significantly faster when no format string is passed, and in pandas 0.12.0 the %p strptime directive is not correctly handled if a format string is explicitly passed, but A...
Attempt to find a unique asset whose symbol is the given string. If multiple assets have held the given symbol, return a 0. If no asset has held the given symbol, return a NaN. def _lookup_unconflicted_symbol(self, symbol): """ Attempt to find a unique asset whose symbol is the given...
Main generator work loop. def transform(self): """ Main generator work loop. """ 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, ...
Clear out any assets that have expired before starting a new sim day. Performs two functions: 1. Finds all assets for which we have open orders and clears any orders whose assets are on or after their auto_close_date. 2. Finds all assets for which we have positions and generates ...
Get a perf message for the given datetime. def _get_daily_message(self, dt, algo, metrics_tracker): """ Get a perf message for the given datetime. """ perf_message = metrics_tracker.handle_market_close( dt, self.data_portal, ) perf_message['daily_...
Get a perf message for the given datetime. def _get_minute_message(self, dt, algo, metrics_tracker): """ Get a perf message for the given datetime. """ rvars = algo.recorded_vars minute_message = metrics_tracker.handle_minute_close( dt, self.data_portal,...
Load collection of Adjustment objects from underlying adjustments db. Parameters ---------- dates : pd.DatetimeIndex Dates for which adjustments are needed. assets : pd.Int64Index Assets for which adjustments are needed. should_include_splits : bool ...
Returns the set of known tables in the adjustments file in DataFrame form. Parameters ---------- convert_dates : bool, optional By default, dates are returned in seconds since EPOCH. If convert_dates is True, all ints in date columns will be converted ...
Get dtypes to use when unpacking sqlite tables as dataframes. def _df_dtypes(self, table_name, convert_dates): """Get dtypes to use when unpacking sqlite tables as dataframes. """ out = self._raw_table_dtypes[table_name] if convert_dates: out = out.copy() for dat...
Calculate the ratios to apply to equities when looking back at pricing history so that the price is smoothed over the ex_date, when the market adjusts to the change in equity value due to upcoming dividend. Returns ------- DataFrame A frame in the same format as spli...
Write both dividend payouts and the derived price adjustment ratios. def write_dividend_data(self, dividends, stock_dividends=None): """ Write both dividend payouts and the derived price adjustment ratios. """ # First write the dividend payouts. self._write_dividends(dividends)...
Writes data to a SQLite file to be read by SQLiteAdjustmentReader. Parameters ---------- splits : pandas.DataFrame, optional Dataframe containing split data. The format of this dataframe is: effective_date : int The date, represented as seconds since ...
Override this method with a function that writes a value into `out`. def compute(self, today, assets, out, *arrays): """ Override this method with a function that writes a value into `out`. """ raise NotImplementedError( "{name} must define a compute method".format( ...
Allocate an output array whose rows should be passed to `self.compute`. The resulting array must have a shape of ``shape``. If we have standard outputs (i.e. self.outputs is NotSpecified), the default is an empty ndarray whose dtype is ``self.dtype``. If we have an outputs tuple, the ...
Call the user's `compute` function on each window with a pre-built output array. def _compute(self, windows, dates, assets, mask): """ Call the user's `compute` function on each window with a pre-built output array. """ format_inputs = self._format_inputs compute...
Factory for making Aliased{Filter,Factor,Classifier}. def make_aliased_type(cls, other_base): """ Factory for making Aliased{Filter,Factor,Classifier}. """ docstring = dedent( """ A {t} that names another {t}. Parameters ---------- ...
Ensure that min_extra_rows pushes us back to a computation date. Parameters ---------- all_dates : pd.DatetimeIndex The trading sessions against which ``self`` will be computed. start_date : pd.Timestamp The first date for which final output is requested. ...
Compute by delegating to self._wrapped_term._compute on sample dates. On non-sample dates, forward-fill from previously-computed samples. def _compute(self, inputs, dates, assets, mask): """ Compute by delegating to self._wrapped_term._compute on sample dates. On non-sample dates, for...
Factory for making Downsampled{Filter,Factor,Classifier}. def make_downsampled_type(cls, other_base): """ Factory for making Downsampled{Filter,Factor,Classifier}. """ docstring = dedent( """ A {t} that defers to another {t} at lower-than-daily frequency. ...
Decorator that applies pre-processors to the arguments of a function before calling the function. Parameters ---------- **processors : dict Map from argument name -> processor function. A processor function takes three arguments: (func, argname, argvalue). `func` is the the fu...
Wrap a function in a processor that calls `f` on the argument before passing it along. Useful for creating simple arguments to the `@preprocess` decorator. Parameters ---------- f : function Function accepting a single argument and returning a replacement. Examples -------- >>...
Build a preprocessed function with the same signature as `func`. Uses `exec` internally to build a function that actually has the same signature as `func. def _build_preprocessed_function(func, processors, args_defaults, ...