repo
stringlengths
7
55
path
stringlengths
4
223
func_name
stringlengths
1
134
original_string
stringlengths
75
104k
language
stringclasses
1 value
code
stringlengths
75
104k
code_tokens
listlengths
19
28.4k
docstring
stringlengths
1
46.9k
docstring_tokens
listlengths
1
1.97k
sha
stringlengths
40
40
url
stringlengths
87
315
partition
stringclasses
1 value
pypa/pipenv
pipenv/vendor/jinja2/compiler.py
CodeGenerator.pop_assign_tracking
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 not frame.toplevel or not vars: return public_names = [x for x in vars if x[:1] != '_...
python
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 not frame.toplevel or not vars: return public_names = [x for x in vars if x[:1] != '_...
[ "def", "pop_assign_tracking", "(", "self", ",", "frame", ")", ":", "vars", "=", "self", ".", "_assign_stack", ".", "pop", "(", ")", "if", "not", "frame", ".", "toplevel", "or", "not", "vars", ":", "return", "public_names", "=", "[", "x", "for", "x", ...
Pops the topmost level for assignment tracking and updates the context variables if necessary.
[ "Pops", "the", "topmost", "level", "for", "assignment", "tracking", "and", "updates", "the", "context", "variables", "if", "necessary", "." ]
cae8d76c210b9777e90aab76e9c4b0e53bb19cde
https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/vendor/jinja2/compiler.py#L665-L691
train
pypa/pipenv
pipenv/vendor/jinja2/compiler.py
CodeGenerator.visit_Block
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.has_known_extends: return ...
python
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.has_known_extends: return ...
[ "def", "visit_Block", "(", "self", ",", "node", ",", "frame", ")", ":", "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", ".", "has_known_extends", ":", "r...
Call a block and register it for the template.
[ "Call", "a", "block", "and", "register", "it", "for", "the", "template", "." ]
cae8d76c210b9777e90aab76e9c4b0e53bb19cde
https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/vendor/jinja2/compiler.py#L811-L841
train
pypa/pipenv
pipenv/vendor/jinja2/compiler.py
CodeGenerator.visit_Extends
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't have to add a check...
python
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't have to add a check...
[ "def", "visit_Extends", "(", "self", ",", "node", ",", "frame", ")", ":", "if", "not", "frame", ".", "toplevel", ":", "self", ".", "fail", "(", "'cannot use extend from a non top-level scope'", ",", "node", ".", "lineno", ")", "# if the number of extends statement...
Calls the extender.
[ "Calls", "the", "extender", "." ]
cae8d76c210b9777e90aab76e9c4b0e53bb19cde
https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/vendor/jinja2/compiler.py#L843-L888
train
pypa/pipenv
pipenv/vendor/jinja2/compiler.py
CodeGenerator.visit_Include
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.value, string_types)...
python
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.value, string_types)...
[ "def", "visit_Include", "(", "self", ",", "node", ",", "frame", ")", ":", "if", "node", ".", "ignore_missing", ":", "self", ".", "writeline", "(", "'try:'", ")", "self", ".", "indent", "(", ")", "func_name", "=", "'get_or_select_template'", "if", "isinstan...
Handles includes.
[ "Handles", "includes", "." ]
cae8d76c210b9777e90aab76e9c4b0e53bb19cde
https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/vendor/jinja2/compiler.py#L890-L942
train
pypa/pipenv
pipenv/vendor/jinja2/compiler.py
CodeGenerator.visit_Import
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('await ') self.writ...
python
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('await ') self.writ...
[ "def", "visit_Import", "(", "self", ",", "node", ",", "frame", ")", ":", "self", ".", "writeline", "(", "'%s = '", "%", "frame", ".", "symbols", ".", "ref", "(", "node", ".", "target", ")", ",", "node", ")", "if", "frame", ".", "toplevel", ":", "se...
Visit regular imports.
[ "Visit", "regular", "imports", "." ]
cae8d76c210b9777e90aab76e9c4b0e53bb19cde
https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/vendor/jinja2/compiler.py#L944-L963
train
pypa/pipenv
pipenv/vendor/jinja2/compiler.py
CodeGenerator.visit_FromImport
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.write(', %r).' % self.nam...
python
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.write(', %r).' % self.nam...
[ "def", "visit_FromImport", "(", "self", ",", "node", ",", "frame", ")", ":", "self", ".", "newline", "(", "node", ")", "self", ".", "write", "(", "'included_template = %senvironment.get_template('", "%", "(", "self", ".", "environment", ".", "is_async", "and",...
Visit named imports.
[ "Visit", "named", "imports", "." ]
cae8d76c210b9777e90aab76e9c4b0e53bb19cde
https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/vendor/jinja2/compiler.py#L965-L1022
train
pypa/pipenv
pipenv/vendor/backports/weakref.py
finalize.detach
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 not None and self._registry.pop(self, None): return (obj, info.func, info.args, info....
python
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 not None and self._registry.pop(self, None): return (obj, info.func, info.args, info....
[ "def", "detach", "(", "self", ")", ":", "info", "=", "self", ".", "_registry", ".", "get", "(", "self", ")", "obj", "=", "info", "and", "info", ".", "weakref", "(", ")", "if", "obj", "is", "not", "None", "and", "self", ".", "_registry", ".", "pop...
If alive then mark as dead and return (obj, func, args, kwargs); otherwise return None
[ "If", "alive", "then", "mark", "as", "dead", "and", "return", "(", "obj", "func", "args", "kwargs", ")", ";", "otherwise", "return", "None" ]
cae8d76c210b9777e90aab76e9c4b0e53bb19cde
https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/vendor/backports/weakref.py#L69-L75
train
pypa/pipenv
pipenv/vendor/backports/weakref.py
finalize.peek
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, info.func, info.args, info.kwargs or {})
python
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, info.func, info.args, info.kwargs or {})
[ "def", "peek", "(", "self", ")", ":", "info", "=", "self", ".", "_registry", ".", "get", "(", "self", ")", "obj", "=", "info", "and", "info", ".", "weakref", "(", ")", "if", "obj", "is", "not", "None", ":", "return", "(", "obj", ",", "info", "....
If alive then return (obj, func, args, kwargs); otherwise return None
[ "If", "alive", "then", "return", "(", "obj", "func", "args", "kwargs", ")", ";", "otherwise", "return", "None" ]
cae8d76c210b9777e90aab76e9c4b0e53bb19cde
https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/vendor/backports/weakref.py#L77-L83
train
pypa/pipenv
pipenv/vendor/backports/weakref.py
finalize.atexit
def atexit(self): """Whether finalizer should be called at exit""" info = self._registry.get(self) return bool(info) and info.atexit
python
def atexit(self): """Whether finalizer should be called at exit""" info = self._registry.get(self) return bool(info) and info.atexit
[ "def", "atexit", "(", "self", ")", ":", "info", "=", "self", ".", "_registry", ".", "get", "(", "self", ")", "return", "bool", "(", "info", ")", "and", "info", ".", "atexit" ]
Whether finalizer should be called at exit
[ "Whether", "finalizer", "should", "be", "called", "at", "exit" ]
cae8d76c210b9777e90aab76e9c4b0e53bb19cde
https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/vendor/backports/weakref.py#L91-L94
train
pypa/pipenv
pipenv/patched/notpip/_vendor/html5lib/treebuilders/etree_lxml.py
tostring
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: dtd_str = element.docinfo.doctype ...
python
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: dtd_str = element.docinfo.doctype ...
[ "def", "tostring", "(", "element", ")", ":", "rv", "=", "[", "]", "def", "serializeElement", "(", "element", ")", ":", "if", "not", "hasattr", "(", "element", ",", "\"tag\"", ")", ":", "if", "element", ".", "docinfo", ".", "internalDTD", ":", "if", "...
Serialize an element and its child nodes to a string
[ "Serialize", "an", "element", "and", "its", "child", "nodes", "to", "a", "string" ]
cae8d76c210b9777e90aab76e9c4b0e53bb19cde
https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/patched/notpip/_vendor/html5lib/treebuilders/etree_lxml.py#L134-L172
train
pypa/pipenv
pipenv/vendor/jinja2/visitor.py
NodeVisitor.get_visitor
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 generic visit function is used instead. """ method = 'visit_' + node.__class__.__name__ return getattr(self, method, None)
python
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 generic visit function is used instead. """ method = 'visit_' + node.__class__.__name__ return getattr(self, method, None)
[ "def", "get_visitor", "(", "self", ",", "node", ")", ":", "method", "=", "'visit_'", "+", "node", ".", "__class__", ".", "__name__", "return", "getattr", "(", "self", ",", "method", ",", "None", ")" ]
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.
[ "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", "." ]
cae8d76c210b9777e90aab76e9c4b0e53bb19cde
https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/vendor/jinja2/visitor.py#L26-L32
train
pypa/pipenv
pipenv/vendor/jinja2/visitor.py
NodeVisitor.visit
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)
python
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)
[ "def", "visit", "(", "self", ",", "node", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "f", "=", "self", ".", "get_visitor", "(", "node", ")", "if", "f", "is", "not", "None", ":", "return", "f", "(", "node", ",", "*", "args", ",", "*"...
Visit a node.
[ "Visit", "a", "node", "." ]
cae8d76c210b9777e90aab76e9c4b0e53bb19cde
https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/vendor/jinja2/visitor.py#L34-L39
train
pypa/pipenv
pipenv/vendor/jinja2/visitor.py
NodeVisitor.generic_visit
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)
python
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)
[ "def", "generic_visit", "(", "self", ",", "node", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "for", "node", "in", "node", ".", "iter_child_nodes", "(", ")", ":", "self", ".", "visit", "(", "node", ",", "*", "args", ",", "*", "*", "kwarg...
Called if no explicit visitor function exists for a node.
[ "Called", "if", "no", "explicit", "visitor", "function", "exists", "for", "a", "node", "." ]
cae8d76c210b9777e90aab76e9c4b0e53bb19cde
https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/vendor/jinja2/visitor.py#L41-L44
train
pypa/pipenv
pipenv/vendor/jinja2/visitor.py
NodeTransformer.visit_list
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.visit(node, *args, **kwargs) if not isinstance(rv, list): rv = [rv] return rv
python
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.visit(node, *args, **kwargs) if not isinstance(rv, list): rv = [rv] return rv
[ "def", "visit_list", "(", "self", ",", "node", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "rv", "=", "self", ".", "visit", "(", "node", ",", "*", "args", ",", "*", "*", "kwargs", ")", "if", "not", "isinstance", "(", "rv", ",", "list",...
As transformers may return lists in some places this method can be used to enforce a list as return value.
[ "As", "transformers", "may", "return", "lists", "in", "some", "places", "this", "method", "can", "be", "used", "to", "enforce", "a", "list", "as", "return", "value", "." ]
cae8d76c210b9777e90aab76e9c4b0e53bb19cde
https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/vendor/jinja2/visitor.py#L80-L87
train
pypa/pipenv
pipenv/vendor/pep517/wrappers.py
default_subprocess_runner
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)
python
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)
[ "def", "default_subprocess_runner", "(", "cmd", ",", "cwd", "=", "None", ",", "extra_environ", "=", "None", ")", ":", "env", "=", "os", ".", "environ", ".", "copy", "(", ")", "if", "extra_environ", ":", "env", ".", "update", "(", "extra_environ", ")", ...
The default method of calling the wrapper subprocess.
[ "The", "default", "method", "of", "calling", "the", "wrapper", "subprocess", "." ]
cae8d76c210b9777e90aab76e9c4b0e53bb19cde
https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/vendor/pep517/wrappers.py#L31-L37
train
pypa/pipenv
pipenv/vendor/pep517/wrappers.py
Pep517HookCaller.build_wheel
def build_wheel( self, wheel_directory, config_settings=None, metadata_directory=None): """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 previou...
python
def build_wheel( self, wheel_directory, config_settings=None, metadata_directory=None): """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 previou...
[ "def", "build_wheel", "(", "self", ",", "wheel_directory", ",", "config_settings", "=", "None", ",", "metadata_directory", "=", "None", ")", ":", "if", "metadata_directory", "is", "not", "None", ":", "metadata_directory", "=", "abspath", "(", "metadata_directory",...
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...
[ "Build", "a", "wheel", "from", "this", "project", "." ]
cae8d76c210b9777e90aab76e9c4b0e53bb19cde
https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/vendor/pep517/wrappers.py#L89-L107
train
Cadene/pretrained-models.pytorch
pretrainedmodels/models/bninception.py
bninception
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 None: settings = pretrained_settings['bninception'][pretrained] assert n...
python
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 None: settings = pretrained_settings['bninception'][pretrained] assert n...
[ "def", "bninception", "(", "num_classes", "=", "1000", ",", "pretrained", "=", "'imagenet'", ")", ":", "model", "=", "BNInception", "(", "num_classes", "=", "num_classes", ")", "if", "pretrained", "is", "not", "None", ":", "settings", "=", "pretrained_settings...
r"""BNInception model architecture from <https://arxiv.org/pdf/1502.03167.pdf>`_ paper.
[ "r", "BNInception", "model", "architecture", "from", "<https", ":", "//", "arxiv", ".", "org", "/", "pdf", "/", "1502", ".", "03167", ".", "pdf", ">", "_", "paper", "." ]
021d97897c9aa76ec759deff43d341c4fd45d7ba
https://github.com/Cadene/pretrained-models.pytorch/blob/021d97897c9aa76ec759deff43d341c4fd45d7ba/pretrainedmodels/models/bninception.py#L497-L511
train
Cadene/pretrained-models.pytorch
pretrainedmodels/models/fbresnet/resnet152_load.py
conv3x3
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)
python
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)
[ "def", "conv3x3", "(", "in_planes", ",", "out_planes", ",", "stride", "=", "1", ")", ":", "return", "nn", ".", "Conv2d", "(", "in_planes", ",", "out_planes", ",", "kernel_size", "=", "3", ",", "stride", "=", "stride", ",", "padding", "=", "1", ",", "...
3x3 convolution with padding
[ "3x3", "convolution", "with", "padding" ]
021d97897c9aa76ec759deff43d341c4fd45d7ba
https://github.com/Cadene/pretrained-models.pytorch/blob/021d97897c9aa76ec759deff43d341c4fd45d7ba/pretrainedmodels/models/fbresnet/resnet152_load.py#L20-L23
train
Cadene/pretrained-models.pytorch
pretrainedmodels/models/fbresnet/resnet152_load.py
resnet18
def resnet18(pretrained=False, **kwargs): """Constructs a ResNet-18 model. Args: pretrained (bool): If True, returns a model pre-trained on ImageNet """ model = ResNet(BasicBlock, [2, 2, 2, 2], **kwargs) if pretrained: model.load_state_dict(model_zoo.load_url(model_urls['resnet18'])...
python
def resnet18(pretrained=False, **kwargs): """Constructs a ResNet-18 model. Args: pretrained (bool): If True, returns a model pre-trained on ImageNet """ model = ResNet(BasicBlock, [2, 2, 2, 2], **kwargs) if pretrained: model.load_state_dict(model_zoo.load_url(model_urls['resnet18'])...
[ "def", "resnet18", "(", "pretrained", "=", "False", ",", "*", "*", "kwargs", ")", ":", "model", "=", "ResNet", "(", "BasicBlock", ",", "[", "2", ",", "2", ",", "2", ",", "2", "]", ",", "*", "*", "kwargs", ")", "if", "pretrained", ":", "model", ...
Constructs a ResNet-18 model. Args: pretrained (bool): If True, returns a model pre-trained on ImageNet
[ "Constructs", "a", "ResNet", "-", "18", "model", "." ]
021d97897c9aa76ec759deff43d341c4fd45d7ba
https://github.com/Cadene/pretrained-models.pytorch/blob/021d97897c9aa76ec759deff43d341c4fd45d7ba/pretrainedmodels/models/fbresnet/resnet152_load.py#L160-L169
train
Cadene/pretrained-models.pytorch
pretrainedmodels/models/fbresnet/resnet152_load.py
resnet50
def resnet50(pretrained=False, **kwargs): """Constructs a ResNet-50 model. Args: pretrained (bool): If True, returns a model pre-trained on ImageNet """ model = ResNet(Bottleneck, [3, 4, 6, 3], **kwargs) if pretrained: model.load_state_dict(model_zoo.load_url(model_urls['resnet50'])...
python
def resnet50(pretrained=False, **kwargs): """Constructs a ResNet-50 model. Args: pretrained (bool): If True, returns a model pre-trained on ImageNet """ model = ResNet(Bottleneck, [3, 4, 6, 3], **kwargs) if pretrained: model.load_state_dict(model_zoo.load_url(model_urls['resnet50'])...
[ "def", "resnet50", "(", "pretrained", "=", "False", ",", "*", "*", "kwargs", ")", ":", "model", "=", "ResNet", "(", "Bottleneck", ",", "[", "3", ",", "4", ",", "6", ",", "3", "]", ",", "*", "*", "kwargs", ")", "if", "pretrained", ":", "model", ...
Constructs a ResNet-50 model. Args: pretrained (bool): If True, returns a model pre-trained on ImageNet
[ "Constructs", "a", "ResNet", "-", "50", "model", "." ]
021d97897c9aa76ec759deff43d341c4fd45d7ba
https://github.com/Cadene/pretrained-models.pytorch/blob/021d97897c9aa76ec759deff43d341c4fd45d7ba/pretrainedmodels/models/fbresnet/resnet152_load.py#L184-L193
train
Cadene/pretrained-models.pytorch
pretrainedmodels/models/nasnet_mobile.py
nasnetamobile
def nasnetamobile(num_classes=1000, pretrained='imagenet'): r"""NASNetALarge model architecture from the `"NASNet" <https://arxiv.org/abs/1707.07012>`_ paper. """ if pretrained: settings = pretrained_settings['nasnetamobile'][pretrained] assert num_classes == settings['num_classes'], \ ...
python
def nasnetamobile(num_classes=1000, pretrained='imagenet'): r"""NASNetALarge model architecture from the `"NASNet" <https://arxiv.org/abs/1707.07012>`_ paper. """ if pretrained: settings = pretrained_settings['nasnetamobile'][pretrained] assert num_classes == settings['num_classes'], \ ...
[ "def", "nasnetamobile", "(", "num_classes", "=", "1000", ",", "pretrained", "=", "'imagenet'", ")", ":", "if", "pretrained", ":", "settings", "=", "pretrained_settings", "[", "'nasnetamobile'", "]", "[", "pretrained", "]", "assert", "num_classes", "==", "setting...
r"""NASNetALarge model architecture from the `"NASNet" <https://arxiv.org/abs/1707.07012>`_ paper.
[ "r", "NASNetALarge", "model", "architecture", "from", "the", "NASNet", "<https", ":", "//", "arxiv", ".", "org", "/", "abs", "/", "1707", ".", "07012", ">", "_", "paper", "." ]
021d97897c9aa76ec759deff43d341c4fd45d7ba
https://github.com/Cadene/pretrained-models.pytorch/blob/021d97897c9aa76ec759deff43d341c4fd45d7ba/pretrainedmodels/models/nasnet_mobile.py#L618-L652
train
Cadene/pretrained-models.pytorch
pretrainedmodels/models/cafferesnet.py
cafferesnet101
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 = ResNet(Bottleneck, [3, 4, 23, 3], num_classes=num_classes) if pretrained is not None: settings = pretrained...
python
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 = ResNet(Bottleneck, [3, 4, 23, 3], num_classes=num_classes) if pretrained is not None: settings = pretrained...
[ "def", "cafferesnet101", "(", "num_classes", "=", "1000", ",", "pretrained", "=", "'imagenet'", ")", ":", "model", "=", "ResNet", "(", "Bottleneck", ",", "[", "3", ",", "4", ",", "23", ",", "3", "]", ",", "num_classes", "=", "num_classes", ")", "if", ...
Constructs a ResNet-101 model. Args: pretrained (bool): If True, returns a model pre-trained on ImageNet
[ "Constructs", "a", "ResNet", "-", "101", "model", ".", "Args", ":", "pretrained", "(", "bool", ")", ":", "If", "True", "returns", "a", "model", "pre", "-", "trained", "on", "ImageNet" ]
021d97897c9aa76ec759deff43d341c4fd45d7ba
https://github.com/Cadene/pretrained-models.pytorch/blob/021d97897c9aa76ec759deff43d341c4fd45d7ba/pretrainedmodels/models/cafferesnet.py#L168-L184
train
Cadene/pretrained-models.pytorch
pretrainedmodels/models/fbresnet.py
fbresnet152
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 = FBResNet(Bottleneck, [3, 8, 36, 3], num_classes=num_classes) if pretrained is not None: settings = pretra...
python
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 = FBResNet(Bottleneck, [3, 8, 36, 3], num_classes=num_classes) if pretrained is not None: settings = pretra...
[ "def", "fbresnet152", "(", "num_classes", "=", "1000", ",", "pretrained", "=", "'imagenet'", ")", ":", "model", "=", "FBResNet", "(", "Bottleneck", ",", "[", "3", ",", "8", ",", "36", ",", "3", "]", ",", "num_classes", "=", "num_classes", ")", "if", ...
Constructs a ResNet-152 model. Args: pretrained (bool): If True, returns a model pre-trained on ImageNet
[ "Constructs", "a", "ResNet", "-", "152", "model", "." ]
021d97897c9aa76ec759deff43d341c4fd45d7ba
https://github.com/Cadene/pretrained-models.pytorch/blob/021d97897c9aa76ec759deff43d341c4fd45d7ba/pretrainedmodels/models/fbresnet.py#L216-L233
train
Cadene/pretrained-models.pytorch
pretrainedmodels/models/torchvision_models.py
alexnet
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/vision/blob/master/torchvision/models/alexnet.py model = models.alexnet(pretrained=False) if pretrained ...
python
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/vision/blob/master/torchvision/models/alexnet.py model = models.alexnet(pretrained=False) if pretrained ...
[ "def", "alexnet", "(", "num_classes", "=", "1000", ",", "pretrained", "=", "'imagenet'", ")", ":", "# https://github.com/pytorch/vision/blob/master/torchvision/models/alexnet.py", "model", "=", "models", ".", "alexnet", "(", "pretrained", "=", "False", ")", "if", "pre...
r"""AlexNet model architecture from the `"One weird trick..." <https://arxiv.org/abs/1404.5997>`_ paper.
[ "r", "AlexNet", "model", "architecture", "from", "the", "One", "weird", "trick", "...", "<https", ":", "//", "arxiv", ".", "org", "/", "abs", "/", "1404", ".", "5997", ">", "_", "paper", "." ]
021d97897c9aa76ec759deff43d341c4fd45d7ba
https://github.com/Cadene/pretrained-models.pytorch/blob/021d97897c9aa76ec759deff43d341c4fd45d7ba/pretrainedmodels/models/torchvision_models.py#L168-L178
train
Cadene/pretrained-models.pytorch
pretrainedmodels/models/torchvision_models.py
densenet121
def densenet121(num_classes=1000, pretrained='imagenet'): r"""Densenet-121 model from `"Densely Connected Convolutional Networks" <https://arxiv.org/pdf/1608.06993.pdf>` """ model = models.densenet121(pretrained=False) if pretrained is not None: settings = pretrained_settings['densenet121'][...
python
def densenet121(num_classes=1000, pretrained='imagenet'): r"""Densenet-121 model from `"Densely Connected Convolutional Networks" <https://arxiv.org/pdf/1608.06993.pdf>` """ model = models.densenet121(pretrained=False) if pretrained is not None: settings = pretrained_settings['densenet121'][...
[ "def", "densenet121", "(", "num_classes", "=", "1000", ",", "pretrained", "=", "'imagenet'", ")", ":", "model", "=", "models", ".", "densenet121", "(", "pretrained", "=", "False", ")", "if", "pretrained", "is", "not", "None", ":", "settings", "=", "pretrai...
r"""Densenet-121 model from `"Densely Connected Convolutional Networks" <https://arxiv.org/pdf/1608.06993.pdf>`
[ "r", "Densenet", "-", "121", "model", "from", "Densely", "Connected", "Convolutional", "Networks", "<https", ":", "//", "arxiv", ".", "org", "/", "pdf", "/", "1608", ".", "06993", ".", "pdf", ">" ]
021d97897c9aa76ec759deff43d341c4fd45d7ba
https://github.com/Cadene/pretrained-models.pytorch/blob/021d97897c9aa76ec759deff43d341c4fd45d7ba/pretrainedmodels/models/torchvision_models.py#L205-L214
train
Cadene/pretrained-models.pytorch
pretrainedmodels/models/torchvision_models.py
inceptionv3
def inceptionv3(num_classes=1000, pretrained='imagenet'): r"""Inception v3 model architecture from `"Rethinking the Inception Architecture for Computer Vision" <http://arxiv.org/abs/1512.00567>`_. """ model = models.inception_v3(pretrained=False) if pretrained is not None: settings = pretrai...
python
def inceptionv3(num_classes=1000, pretrained='imagenet'): r"""Inception v3 model architecture from `"Rethinking the Inception Architecture for Computer Vision" <http://arxiv.org/abs/1512.00567>`_. """ model = models.inception_v3(pretrained=False) if pretrained is not None: settings = pretrai...
[ "def", "inceptionv3", "(", "num_classes", "=", "1000", ",", "pretrained", "=", "'imagenet'", ")", ":", "model", "=", "models", ".", "inception_v3", "(", "pretrained", "=", "False", ")", "if", "pretrained", "is", "not", "None", ":", "settings", "=", "pretra...
r"""Inception v3 model architecture from `"Rethinking the Inception Architecture for Computer Vision" <http://arxiv.org/abs/1512.00567>`_.
[ "r", "Inception", "v3", "model", "architecture", "from", "Rethinking", "the", "Inception", "Architecture", "for", "Computer", "Vision", "<http", ":", "//", "arxiv", ".", "org", "/", "abs", "/", "1512", ".", "00567", ">", "_", "." ]
021d97897c9aa76ec759deff43d341c4fd45d7ba
https://github.com/Cadene/pretrained-models.pytorch/blob/021d97897c9aa76ec759deff43d341c4fd45d7ba/pretrainedmodels/models/torchvision_models.py#L252-L309
train
Cadene/pretrained-models.pytorch
pretrainedmodels/models/torchvision_models.py
resnet50
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_classes, settings) model = modify...
python
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_classes, settings) model = modify...
[ "def", "resnet50", "(", "num_classes", "=", "1000", ",", "pretrained", "=", "'imagenet'", ")", ":", "model", "=", "models", ".", "resnet50", "(", "pretrained", "=", "False", ")", "if", "pretrained", "is", "not", "None", ":", "settings", "=", "pretrained_se...
Constructs a ResNet-50 model.
[ "Constructs", "a", "ResNet", "-", "50", "model", "." ]
021d97897c9aa76ec759deff43d341c4fd45d7ba
https://github.com/Cadene/pretrained-models.pytorch/blob/021d97897c9aa76ec759deff43d341c4fd45d7ba/pretrainedmodels/models/torchvision_models.py#L368-L376
train
Cadene/pretrained-models.pytorch
pretrainedmodels/models/torchvision_models.py
squeezenet1_0
def squeezenet1_0(num_classes=1000, pretrained='imagenet'): 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. """ model = models.squeezenet1_0(pretrained=False) if pretraine...
python
def squeezenet1_0(num_classes=1000, pretrained='imagenet'): 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. """ model = models.squeezenet1_0(pretrained=False) if pretraine...
[ "def", "squeezenet1_0", "(", "num_classes", "=", "1000", ",", "pretrained", "=", "'imagenet'", ")", ":", "model", "=", "models", ".", "squeezenet1_0", "(", "pretrained", "=", "False", ")", "if", "pretrained", "is", "not", "None", ":", "settings", "=", "pre...
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.
[ "r", "SqueezeNet", "model", "architecture", "from", "the", "SqueezeNet", ":", "AlexNet", "-", "level", "accuracy", "with", "50x", "fewer", "parameters", "and", "<0", ".", "5MB", "model", "size", "<https", ":", "//", "arxiv", ".", "org", "/", "abs", "/", ...
021d97897c9aa76ec759deff43d341c4fd45d7ba
https://github.com/Cadene/pretrained-models.pytorch/blob/021d97897c9aa76ec759deff43d341c4fd45d7ba/pretrainedmodels/models/torchvision_models.py#L428-L438
train
Cadene/pretrained-models.pytorch
pretrainedmodels/models/torchvision_models.py
vgg11
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, num_classes, settings) model = modify...
python
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, num_classes, settings) model = modify...
[ "def", "vgg11", "(", "num_classes", "=", "1000", ",", "pretrained", "=", "'imagenet'", ")", ":", "model", "=", "models", ".", "vgg11", "(", "pretrained", "=", "False", ")", "if", "pretrained", "is", "not", "None", ":", "settings", "=", "pretrained_settings...
VGG 11-layer model (configuration "A")
[ "VGG", "11", "-", "layer", "model", "(", "configuration", "A", ")" ]
021d97897c9aa76ec759deff43d341c4fd45d7ba
https://github.com/Cadene/pretrained-models.pytorch/blob/021d97897c9aa76ec759deff43d341c4fd45d7ba/pretrainedmodels/models/torchvision_models.py#L495-L503
train
Cadene/pretrained-models.pytorch
examples/imagenet_eval.py
adjust_learning_rate
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
python
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
[ "def", "adjust_learning_rate", "(", "optimizer", ",", "epoch", ")", ":", "lr", "=", "args", ".", "lr", "*", "(", "0.1", "**", "(", "epoch", "//", "30", ")", ")", "for", "param_group", "in", "optimizer", ".", "param_groups", ":", "param_group", "[", "'l...
Sets the learning rate to the initial LR decayed by 10 every 30 epochs
[ "Sets", "the", "learning", "rate", "to", "the", "initial", "LR", "decayed", "by", "10", "every", "30", "epochs" ]
021d97897c9aa76ec759deff43d341c4fd45d7ba
https://github.com/Cadene/pretrained-models.pytorch/blob/021d97897c9aa76ec759deff43d341c4fd45d7ba/examples/imagenet_eval.py#L280-L284
train
Cadene/pretrained-models.pytorch
pretrainedmodels/models/nasnet.py
nasnetalarge
def nasnetalarge(num_classes=1001, pretrained='imagenet'): r"""NASNetALarge model architecture from the `"NASNet" <https://arxiv.org/abs/1707.07012>`_ paper. """ if pretrained: settings = pretrained_settings['nasnetalarge'][pretrained] assert num_classes == settings['num_classes'], \ ...
python
def nasnetalarge(num_classes=1001, pretrained='imagenet'): r"""NASNetALarge model architecture from the `"NASNet" <https://arxiv.org/abs/1707.07012>`_ paper. """ if pretrained: settings = pretrained_settings['nasnetalarge'][pretrained] assert num_classes == settings['num_classes'], \ ...
[ "def", "nasnetalarge", "(", "num_classes", "=", "1001", ",", "pretrained", "=", "'imagenet'", ")", ":", "if", "pretrained", ":", "settings", "=", "pretrained_settings", "[", "'nasnetalarge'", "]", "[", "pretrained", "]", "assert", "num_classes", "==", "settings"...
r"""NASNetALarge model architecture from the `"NASNet" <https://arxiv.org/abs/1707.07012>`_ paper.
[ "r", "NASNetALarge", "model", "architecture", "from", "the", "NASNet", "<https", ":", "//", "arxiv", ".", "org", "/", "abs", "/", "1707", ".", "07012", ">", "_", "paper", "." ]
021d97897c9aa76ec759deff43d341c4fd45d7ba
https://github.com/Cadene/pretrained-models.pytorch/blob/021d97897c9aa76ec759deff43d341c4fd45d7ba/pretrainedmodels/models/nasnet.py#L608-L635
train
Cadene/pretrained-models.pytorch
pretrainedmodels/models/dpn.py
adaptive_avgmax_pool2d
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( x, kernel_size=(x.size(2), x.size(3)), padding=padding, co...
python
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( x, kernel_size=(x.size(2), x.size(3)), padding=padding, co...
[ "def", "adaptive_avgmax_pool2d", "(", "x", ",", "pool_type", "=", "'avg'", ",", "padding", "=", "0", ",", "count_include_pad", "=", "False", ")", ":", "if", "pool_type", "==", "'avgmaxc'", ":", "x", "=", "torch", ".", "cat", "(", "[", "F", ".", "avg_po...
Selectable global pooling function with dynamic input kernel size
[ "Selectable", "global", "pooling", "function", "with", "dynamic", "input", "kernel", "size" ]
021d97897c9aa76ec759deff43d341c4fd45d7ba
https://github.com/Cadene/pretrained-models.pytorch/blob/021d97897c9aa76ec759deff43d341c4fd45d7ba/pretrainedmodels/models/dpn.py#L407-L428
train
Cadene/pretrained-models.pytorch
pretrainedmodels/datasets/utils.py
download_url
def download_url(url, destination=None, progress_bar=True): """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 : bo...
python
def download_url(url, destination=None, progress_bar=True): """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 : bo...
[ "def", "download_url", "(", "url", ",", "destination", "=", "None", ",", "progress_bar", "=", "True", ")", ":", "def", "my_hook", "(", "t", ")", ":", "last_b", "=", "[", "0", "]", "def", "inner", "(", "b", "=", "1", ",", "bsize", "=", "1", ",", ...
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...
[ "Download", "a", "URL", "to", "a", "local", "file", "." ]
021d97897c9aa76ec759deff43d341c4fd45d7ba
https://github.com/Cadene/pretrained-models.pytorch/blob/021d97897c9aa76ec759deff43d341c4fd45d7ba/pretrainedmodels/datasets/utils.py#L45-L83
train
Cadene/pretrained-models.pytorch
pretrainedmodels/datasets/utils.py
AveragePrecisionMeter.add
def add(self, output, target): """ 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 a...
python
def add(self, output, target): """ 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 a...
[ "def", "add", "(", "self", ",", "output", ",", "target", ")", ":", "if", "not", "torch", ".", "is_tensor", "(", "output", ")", ":", "output", "=", "torch", ".", "from_numpy", "(", "output", ")", "if", "not", "torch", ".", "is_tensor", "(", "target", ...
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 ...
[ "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", "t...
021d97897c9aa76ec759deff43d341c4fd45d7ba
https://github.com/Cadene/pretrained-models.pytorch/blob/021d97897c9aa76ec759deff43d341c4fd45d7ba/pretrainedmodels/datasets/utils.py#L110-L156
train
Cadene/pretrained-models.pytorch
pretrainedmodels/datasets/utils.py
AveragePrecisionMeter.value
def value(self): """Returns the model's average precision for each class Return: ap (FloatTensor): 1xK tensor, with avg precision for each class k """ if self.scores.numel() == 0: return 0 ap = torch.zeros(self.scores.size(1)) rg = torch.arange(1,...
python
def value(self): """Returns the model's average precision for each class Return: ap (FloatTensor): 1xK tensor, with avg precision for each class k """ if self.scores.numel() == 0: return 0 ap = torch.zeros(self.scores.size(1)) rg = torch.arange(1,...
[ "def", "value", "(", "self", ")", ":", "if", "self", ".", "scores", ".", "numel", "(", ")", "==", "0", ":", "return", "0", "ap", "=", "torch", ".", "zeros", "(", "self", ".", "scores", ".", "size", "(", "1", ")", ")", "rg", "=", "torch", ".",...
Returns the model's average precision for each class Return: ap (FloatTensor): 1xK tensor, with avg precision for each class k
[ "Returns", "the", "model", "s", "average", "precision", "for", "each", "class", "Return", ":", "ap", "(", "FloatTensor", ")", ":", "1xK", "tensor", "with", "avg", "precision", "for", "each", "class", "k" ]
021d97897c9aa76ec759deff43d341c4fd45d7ba
https://github.com/Cadene/pretrained-models.pytorch/blob/021d97897c9aa76ec759deff43d341c4fd45d7ba/pretrainedmodels/datasets/utils.py#L158-L177
train
Cadene/pretrained-models.pytorch
pretrainedmodels/models/polynet.py
polynet
def polynet(num_classes=1000, pretrained='imagenet'): """PolyNet architecture from the paper 'PolyNet: A Pursuit of Structural Diversity in Very Deep Networks' https://arxiv.org/abs/1611.05725 """ if pretrained: settings = pretrained_settings['polynet'][pretrained] assert num_classes...
python
def polynet(num_classes=1000, pretrained='imagenet'): """PolyNet architecture from the paper 'PolyNet: A Pursuit of Structural Diversity in Very Deep Networks' https://arxiv.org/abs/1611.05725 """ if pretrained: settings = pretrained_settings['polynet'][pretrained] assert num_classes...
[ "def", "polynet", "(", "num_classes", "=", "1000", ",", "pretrained", "=", "'imagenet'", ")", ":", "if", "pretrained", ":", "settings", "=", "pretrained_settings", "[", "'polynet'", "]", "[", "pretrained", "]", "assert", "num_classes", "==", "settings", "[", ...
PolyNet architecture from the paper 'PolyNet: A Pursuit of Structural Diversity in Very Deep Networks' https://arxiv.org/abs/1611.05725
[ "PolyNet", "architecture", "from", "the", "paper", "PolyNet", ":", "A", "Pursuit", "of", "Structural", "Diversity", "in", "Very", "Deep", "Networks", "https", ":", "//", "arxiv", ".", "org", "/", "abs", "/", "1611", ".", "05725" ]
021d97897c9aa76ec759deff43d341c4fd45d7ba
https://github.com/Cadene/pretrained-models.pytorch/blob/021d97897c9aa76ec759deff43d341c4fd45d7ba/pretrainedmodels/models/polynet.py#L461-L480
train
quantopian/zipline
zipline/utils/cache.py
CachedObject.unwrap
def unwrap(self, dt): """ Get the cached value. Returns ------- value : object The cached value. Raises ------ Expired Raised when `dt` is greater than self.expires. """ expires = self._expires if expires i...
python
def unwrap(self, dt): """ Get the cached value. Returns ------- value : object The cached value. Raises ------ Expired Raised when `dt` is greater than self.expires. """ expires = self._expires if expires i...
[ "def", "unwrap", "(", "self", ",", "dt", ")", ":", "expires", "=", "self", ".", "_expires", "if", "expires", "is", "AlwaysExpired", "or", "expires", "<", "dt", ":", "raise", "Expired", "(", "self", ".", "_expires", ")", "return", "self", ".", "_value" ...
Get the cached value. Returns ------- value : object The cached value. Raises ------ Expired Raised when `dt` is greater than self.expires.
[ "Get", "the", "cached", "value", "." ]
77ad15e6dc4c1cbcdc133653bac8a63fc704f7fe
https://github.com/quantopian/zipline/blob/77ad15e6dc4c1cbcdc133653bac8a63fc704f7fe/zipline/utils/cache.py#L67-L84
train
quantopian/zipline
zipline/utils/cache.py
ExpiringCache.get
def get(self, key, dt): """Get the value of a cached object. Parameters ---------- key : any The key to lookup. dt : datetime The time of the lookup. Returns ------- result : any The value for ``key``. Raises ...
python
def get(self, key, dt): """Get the value of a cached object. Parameters ---------- key : any The key to lookup. dt : datetime The time of the lookup. Returns ------- result : any The value for ``key``. Raises ...
[ "def", "get", "(", "self", ",", "key", ",", "dt", ")", ":", "try", ":", "return", "self", ".", "_cache", "[", "key", "]", ".", "unwrap", "(", "dt", ")", "except", "Expired", ":", "self", ".", "cleanup", "(", "self", ".", "_cache", "[", "key", "...
Get the value of a cached object. Parameters ---------- key : any The key to lookup. dt : datetime The time of the lookup. Returns ------- result : any The value for ``key``. Raises ------ KeyError ...
[ "Get", "the", "value", "of", "a", "cached", "object", "." ]
77ad15e6dc4c1cbcdc133653bac8a63fc704f7fe
https://github.com/quantopian/zipline/blob/77ad15e6dc4c1cbcdc133653bac8a63fc704f7fe/zipline/utils/cache.py#L131-L157
train
quantopian/zipline
zipline/utils/cache.py
ExpiringCache.set
def set(self, key, value, expiration_dt): """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 shou...
python
def set(self, key, value, expiration_dt): """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 shou...
[ "def", "set", "(", "self", ",", "key", ",", "value", ",", "expiration_dt", ")", ":", "self", ".", "_cache", "[", "key", "]", "=", "CachedObject", "(", "value", ",", "expiration_dt", ")" ]
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...
[ "Adds", "a", "new", "key", "value", "pair", "to", "the", "cache", "." ]
77ad15e6dc4c1cbcdc133653bac8a63fc704f7fe
https://github.com/quantopian/zipline/blob/77ad15e6dc4c1cbcdc133653bac8a63fc704f7fe/zipline/utils/cache.py#L159-L172
train
quantopian/zipline
zipline/utils/cache.py
working_dir.ensure_dir
def ensure_dir(self, *path_parts): """Ensures a subdirectory of the working directory. Parameters ---------- path_parts : iterable[str] The parts of the path after the working directory. """ path = self.getpath(*path_parts) ensure_directory(path) ...
python
def ensure_dir(self, *path_parts): """Ensures a subdirectory of the working directory. Parameters ---------- path_parts : iterable[str] The parts of the path after the working directory. """ path = self.getpath(*path_parts) ensure_directory(path) ...
[ "def", "ensure_dir", "(", "self", ",", "*", "path_parts", ")", ":", "path", "=", "self", ".", "getpath", "(", "*", "path_parts", ")", "ensure_directory", "(", "path", ")", "return", "path" ]
Ensures a subdirectory of the working directory. Parameters ---------- path_parts : iterable[str] The parts of the path after the working directory.
[ "Ensures", "a", "subdirectory", "of", "the", "working", "directory", "." ]
77ad15e6dc4c1cbcdc133653bac8a63fc704f7fe
https://github.com/quantopian/zipline/blob/77ad15e6dc4c1cbcdc133653bac8a63fc704f7fe/zipline/utils/cache.py#L358-L368
train
quantopian/zipline
zipline/data/in_memory_daily_bars.py
verify_frames_aligned
def verify_frames_aligned(frames, calendar): """ 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 I...
python
def verify_frames_aligned(frames, calendar): """ 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 I...
[ "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"...
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...
[ "Verify", "that", "DataFrames", "in", "frames", "have", "the", "same", "indexing", "scheme", "and", "are", "aligned", "to", "calendar", "." ]
77ad15e6dc4c1cbcdc133653bac8a63fc704f7fe
https://github.com/quantopian/zipline/blob/77ad15e6dc4c1cbcdc133653bac8a63fc704f7fe/zipline/data/in_memory_daily_bars.py#L124-L152
train
quantopian/zipline
zipline/data/in_memory_daily_bars.py
InMemoryDailyBarReader.get_value
def get_value(self, sid, dt, field): """ 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', ...
python
def get_value(self, sid, dt, field): """ 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', ...
[ "def", "get_value", "(", "self", ",", "sid", ",", "dt", ",", "field", ")", ":", "return", "self", ".", "frames", "[", "field", "]", ".", "loc", "[", "dt", ",", "sid", "]" ]
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", "----------", "sid", ":", "int", "The", "asset", "identifier", ".", "day", ":", "datetime64", "-", "like", "Midnight", "of", "the", "day", "for", "which", "data", "is", "requested", ".", "field", ":", "string", "The", "price", "field", ".", ...
77ad15e6dc4c1cbcdc133653bac8a63fc704f7fe
https://github.com/quantopian/zipline/blob/77ad15e6dc4c1cbcdc133653bac8a63fc704f7fe/zipline/data/in_memory_daily_bars.py#L78-L98
train
quantopian/zipline
zipline/data/in_memory_daily_bars.py
InMemoryDailyBarReader.get_last_traded_dt
def get_last_traded_dt(self, asset, dt): """ 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...
python
def get_last_traded_dt(self, asset, dt): """ 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...
[ "def", "get_last_traded_dt", "(", "self", ",", "asset", ",", "dt", ")", ":", "try", ":", "return", "self", ".", "frames", "[", "'close'", "]", ".", "loc", "[", ":", ",", "asset", ".", "sid", "]", ".", "last_valid_index", "(", ")", "except", "IndexErr...
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...
[ "Parameters", "----------", "asset", ":", "zipline", ".", "asset", ".", "Asset", "The", "asset", "identifier", ".", "dt", ":", "datetime64", "-", "like", "Midnight", "of", "the", "day", "for", "which", "data", "is", "requested", "." ]
77ad15e6dc4c1cbcdc133653bac8a63fc704f7fe
https://github.com/quantopian/zipline/blob/77ad15e6dc4c1cbcdc133653bac8a63fc704f7fe/zipline/data/in_memory_daily_bars.py#L100-L117
train
quantopian/zipline
zipline/utils/functional.py
same
def same(*values): """ 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 """ if not values: return True first, rest = values[0], values[1:] ...
python
def same(*values): """ 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 """ if not values: return True first, rest = values[0], values[1:] ...
[ "def", "same", "(", "*", "values", ")", ":", "if", "not", "values", ":", "return", "True", "first", ",", "rest", "=", "values", "[", "0", "]", ",", "values", "[", "1", ":", "]", "return", "all", "(", "value", "==", "first", "for", "value", "in", ...
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
[ "Check", "if", "all", "values", "in", "a", "sequence", "are", "equal", "." ]
77ad15e6dc4c1cbcdc133653bac8a63fc704f7fe
https://github.com/quantopian/zipline/blob/77ad15e6dc4c1cbcdc133653bac8a63fc704f7fe/zipline/utils/functional.py#L88-L106
train
quantopian/zipline
zipline/utils/functional.py
dzip_exact
def dzip_exact(*dicts): """ 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 t...
python
def dzip_exact(*dicts): """ 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 t...
[ "def", "dzip_exact", "(", "*", "dicts", ")", ":", "if", "not", "same", "(", "*", "map", "(", "viewkeys", ",", "dicts", ")", ")", ":", "raise", "ValueError", "(", "\"dict keys not all equal:\\n\\n%s\"", "%", "_format_unequal_keys", "(", "dicts", ")", ")", "...
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...
[ "Parameters", "----------", "*", "dicts", ":", "iterable", "[", "dict", "]", "A", "sequence", "of", "dicts", "all", "sharing", "the", "same", "keys", "." ]
77ad15e6dc4c1cbcdc133653bac8a63fc704f7fe
https://github.com/quantopian/zipline/blob/77ad15e6dc4c1cbcdc133653bac8a63fc704f7fe/zipline/utils/functional.py#L113-L142
train
quantopian/zipline
zipline/utils/functional.py
_gen_unzip
def _gen_unzip(it, elem_len): """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. I...
python
def _gen_unzip(it, elem_len): """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. I...
[ "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", ...
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...
[ "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"...
77ad15e6dc4c1cbcdc133653bac8a63fc704f7fe
https://github.com/quantopian/zipline/blob/77ad15e6dc4c1cbcdc133653bac8a63fc704f7fe/zipline/utils/functional.py#L145-L187
train
quantopian/zipline
zipline/utils/functional.py
unzip
def unzip(seq, elem_len=None): """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 thi...
python
def unzip(seq, elem_len=None): """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 thi...
[ "def", "unzip", "(", "seq", ",", "elem_len", "=", "None", ")", ":", "ret", "=", "tuple", "(", "zip", "(", "*", "_gen_unzip", "(", "map", "(", "tuple", ",", "seq", ")", ",", "elem_len", ")", ")", ")", "if", "ret", ":", "return", "ret", "if", "el...
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...
[ "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", ...
77ad15e6dc4c1cbcdc133653bac8a63fc704f7fe
https://github.com/quantopian/zipline/blob/77ad15e6dc4c1cbcdc133653bac8a63fc704f7fe/zipline/utils/functional.py#L190-L250
train
quantopian/zipline
zipline/utils/functional.py
getattrs
def getattrs(value, attrs, default=_no_default): """ 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. ...
python
def getattrs(value, attrs, default=_no_default): """ 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. ...
[ "def", "getattrs", "(", "value", ",", "attrs", ",", "default", "=", "_no_default", ")", ":", "try", ":", "for", "attr", "in", "attrs", ":", "value", "=", "getattr", "(", "value", ",", "attr", ")", "except", "AttributeError", ":", "if", "default", "is",...
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...
[ "Perform", "a", "chained", "application", "of", "getattr", "on", "value", "with", "the", "values", "in", "attrs", "." ]
77ad15e6dc4c1cbcdc133653bac8a63fc704f7fe
https://github.com/quantopian/zipline/blob/77ad15e6dc4c1cbcdc133653bac8a63fc704f7fe/zipline/utils/functional.py#L256-L303
train
quantopian/zipline
zipline/utils/functional.py
set_attribute
def set_attribute(name, value): """ 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__ ...
python
def set_attribute(name, value): """ 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__ ...
[ "def", "set_attribute", "(", "name", ",", "value", ")", ":", "def", "decorator", "(", "f", ")", ":", "setattr", "(", "f", ",", "name", ",", "value", ")", "return", "f", "return", "decorator" ]
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'
[ "Decorator", "factory", "for", "setting", "attributes", "on", "a", "function", "." ]
77ad15e6dc4c1cbcdc133653bac8a63fc704f7fe
https://github.com/quantopian/zipline/blob/77ad15e6dc4c1cbcdc133653bac8a63fc704f7fe/zipline/utils/functional.py#L307-L327
train
quantopian/zipline
zipline/utils/functional.py
foldr
def foldr(f, seq, default=_no_default): """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 acc...
python
def foldr(f, seq, default=_no_default): """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 acc...
[ "def", "foldr", "(", "f", ",", "seq", ",", "default", "=", "_no_default", ")", ":", "return", "reduce", "(", "flip", "(", "f", ")", ",", "reversed", "(", "seq", ")", ",", "*", "(", "default", ",", ")", "if", "default", "is", "not", "_no_default", ...
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...
[ "Fold", "a", "function", "over", "a", "sequence", "with", "right", "associativity", "." ]
77ad15e6dc4c1cbcdc133653bac8a63fc704f7fe
https://github.com/quantopian/zipline/blob/77ad15e6dc4c1cbcdc133653bac8a63fc704f7fe/zipline/utils/functional.py#L337-L393
train
quantopian/zipline
zipline/utils/functional.py
invert
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 = {} for k, v in iteritems(d): try: out[v].add(k) except KeyError: out[v] = {k} return out
python
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 = {} for k, v in iteritems(d): try: out[v].add(k) except KeyError: out[v] = {k} return out
[ "def", "invert", "(", "d", ")", ":", "out", "=", "{", "}", "for", "k", ",", "v", "in", "iteritems", "(", "d", ")", ":", "try", ":", "out", "[", "v", "]", ".", "add", "(", "k", ")", "except", "KeyError", ":", "out", "[", "v", "]", "=", "{"...
Invert a dictionary into a dictionary of sets. >>> invert({'a': 1, 'b': 2, 'c': 1}) # doctest: +SKIP {1: {'a', 'c'}, 2: {'b'}}
[ "Invert", "a", "dictionary", "into", "a", "dictionary", "of", "sets", "." ]
77ad15e6dc4c1cbcdc133653bac8a63fc704f7fe
https://github.com/quantopian/zipline/blob/77ad15e6dc4c1cbcdc133653bac8a63fc704f7fe/zipline/utils/functional.py#L396-L409
train
quantopian/zipline
zipline/examples/olmar.py
simplex_projection
def simplex_projection(v, b=1): 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 Prob...
python
def simplex_projection(v, b=1): 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 Prob...
[ "def", "simplex_projection", "(", "v", ",", "b", "=", "1", ")", ":", "v", "=", "np", ".", "asarray", "(", "v", ")", "p", "=", "len", "(", "v", ")", "# Sort v into u in descending order", "v", "=", "(", "v", ">", "0", ")", "*", "v", "u", "=", "n...
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} ...
[ "r", "Projection", "vectors", "to", "the", "simplex", "domain" ]
77ad15e6dc4c1cbcdc133653bac8a63fc704f7fe
https://github.com/quantopian/zipline/blob/77ad15e6dc4c1cbcdc133653bac8a63fc704f7fe/zipline/examples/olmar.py#L111-L146
train
quantopian/zipline
zipline/examples/__init__.py
run_example
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, 'initialize', None), handle_data=getattr(m...
python
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, 'initialize', None), handle_data=getattr(m...
[ "def", "run_example", "(", "example_name", ",", "environ", ")", ":", "mod", "=", "EXAMPLE_MODULES", "[", "example_name", "]", "register_calendar", "(", "\"YAHOO\"", ",", "get_calendar", "(", "\"NYSE\"", ")", ",", "force", "=", "True", ")", "return", "run_algor...
Run an example module from zipline.examples.
[ "Run", "an", "example", "module", "from", "zipline", ".", "examples", "." ]
77ad15e6dc4c1cbcdc133653bac8a63fc704f7fe
https://github.com/quantopian/zipline/blob/77ad15e6dc4c1cbcdc133653bac8a63fc704f7fe/zipline/examples/__init__.py#L64-L81
train
quantopian/zipline
zipline/pipeline/factors/statistical.py
vectorized_beta
def vectorized_beta(dependents, independent, allowed_missing, out=None): """ 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``. ...
python
def vectorized_beta(dependents, independent, allowed_missing, out=None): """ 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``. ...
[ "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",...
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...
[ "Compute", "slopes", "of", "linear", "regressions", "between", "columns", "of", "dependents", "and", "independent", "." ]
77ad15e6dc4c1cbcdc133653bac8a63fc704f7fe
https://github.com/quantopian/zipline/blob/77ad15e6dc4c1cbcdc133653bac8a63fc704f7fe/zipline/pipeline/factors/statistical.py#L572-L665
train
quantopian/zipline
zipline/data/treasuries_can.py
_format_url
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.bankofcanada.ca/stats/results/csv" "?lP=lookup_{i...
python
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.bankofcanada.ca/stats/results/csv" "?lP=lookup_{i...
[ "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}_yields.php\"", "\"&sR={restrict}\"",...
Format a URL for loading data from Bank of Canada.
[ "Format", "a", "URL", "for", "loading", "data", "from", "Bank", "of", "Canada", "." ]
77ad15e6dc4c1cbcdc133653bac8a63fc704f7fe
https://github.com/quantopian/zipline/blob/77ad15e6dc4c1cbcdc133653bac8a63fc704f7fe/zipline/data/treasuries_can.py#L39-L60
train
quantopian/zipline
zipline/data/treasuries_can.py
load_frame
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_dates=["Date"], index_col="Date", ).dropna...
python
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_dates=["Date"], index_col="Date", ).dropna...
[ "def", "load_frame", "(", "url", ",", "skiprows", ")", ":", "return", "pd", ".", "read_csv", "(", "url", ",", "skiprows", "=", "skiprows", ",", "skipinitialspace", "=", "True", ",", "na_values", "=", "[", "\"Bank holiday\"", ",", "\"Not available\"", "]", ...
Load a DataFrame of data from a Bank of Canada site.
[ "Load", "a", "DataFrame", "of", "data", "from", "a", "Bank", "of", "Canada", "site", "." ]
77ad15e6dc4c1cbcdc133653bac8a63fc704f7fe
https://github.com/quantopian/zipline/blob/77ad15e6dc4c1cbcdc133653bac8a63fc704f7fe/zipline/data/treasuries_can.py#L67-L80
train
quantopian/zipline
zipline/data/treasuries_can.py
check_known_inconsistencies
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 introduced in the latest download. """ inconsistent_dates = bill_data.index.sym_diff(bond_data.index) known_inconsistencies = [ ...
python
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 introduced in the latest download. """ inconsistent_dates = bill_data.index.sym_diff(bond_data.index) known_inconsistencies = [ ...
[ "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, w...
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.
[ "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", "." ]
77ad15e6dc4c1cbcdc133653bac8a63fc704f7fe
https://github.com/quantopian/zipline/blob/77ad15e6dc4c1cbcdc133653bac8a63fc704f7fe/zipline/data/treasuries_can.py#L83-L119
train
quantopian/zipline
zipline/data/treasuries_can.py
earliest_possible_date
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 today.replace(year=today.year - 10)
python
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 today.replace(year=today.year - 10)
[ "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",...
The earliest date for which we can load data from this module.
[ "The", "earliest", "date", "for", "which", "we", "can", "load", "data", "from", "this", "module", "." ]
77ad15e6dc4c1cbcdc133653bac8a63fc704f7fe
https://github.com/quantopian/zipline/blob/77ad15e6dc4c1cbcdc133653bac8a63fc704f7fe/zipline/data/treasuries_can.py#L122-L128
train
quantopian/zipline
zipline/finance/slippage.py
fill_price_worse_than_limit_price
def fill_price_worse_than_limit_price(fill_price, order): """ 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 ...
python
def fill_price_worse_than_limit_price(fill_price, order): """ 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 ...
[ "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 pric...
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 (...
[ "Checks", "whether", "the", "fill", "price", "is", "worse", "than", "the", "order", "s", "limit", "price", "." ]
77ad15e6dc4c1cbcdc133653bac8a63fc704f7fe
https://github.com/quantopian/zipline/blob/77ad15e6dc4c1cbcdc133653bac8a63fc704f7fe/zipline/finance/slippage.py#L50-L80
train
quantopian/zipline
zipline/finance/slippage.py
MarketImpactBase._get_window_data
def _get_window_data(self, data, asset, window_length): """ 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 ...
python
def _get_window_data(self, data, asset, window_length): """ 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 ...
[ "def", "_get_window_data", "(", "self", ",", "data", ",", "asset", ",", "window_length", ")", ":", "try", ":", "values", "=", "self", ".", "_window_data_cache", ".", "get", "(", "asset", ",", "data", ".", "current_session", ")", "except", "KeyError", ":", ...
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...
[ "Internal", "utility", "method", "to", "return", "the", "trailing", "mean", "volume", "over", "the", "past", "window_length", "days", "and", "volatility", "of", "close", "prices", "for", "a", "specific", "asset", "." ]
77ad15e6dc4c1cbcdc133653bac8a63fc704f7fe
https://github.com/quantopian/zipline/blob/77ad15e6dc4c1cbcdc133653bac8a63fc704f7fe/zipline/finance/slippage.py#L399-L444
train
quantopian/zipline
zipline/pipeline/term.py
validate_dtype
def validate_dtype(termname, dtype, missing_value): """ 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_m...
python
def validate_dtype(termname, dtype, missing_value): """ 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_m...
[ "def", "validate_dtype", "(", "termname", ",", "dtype", ",", "missing_value", ")", ":", "if", "dtype", "is", "NotSpecified", ":", "raise", "DTypeNotSpecified", "(", "termname", "=", "termname", ")", "try", ":", "dtype", "=", "dtype_class", "(", "dtype", ")",...
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...
[ "Validate", "a", "dtype", "and", "missing_value", "passed", "to", "Term", ".", "__new__", "." ]
77ad15e6dc4c1cbcdc133653bac8a63fc704f7fe
https://github.com/quantopian/zipline/blob/77ad15e6dc4c1cbcdc133653bac8a63fc704f7fe/zipline/pipeline/term.py#L795-L858
train
quantopian/zipline
zipline/pipeline/term.py
_assert_valid_categorical_missing_value
def _assert_valid_categorical_missing_value(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. """ label_types = LabelArray.SUPPORTED_SCALAR_TYPES if not isinstance(value, la...
python
def _assert_valid_categorical_missing_value(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. """ label_types = LabelArray.SUPPORTED_SCALAR_TYPES if not isinstance(value, la...
[ "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 mi...
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.
[ "Check", "that", "value", "is", "a", "valid", "categorical", "missing_value", "." ]
77ad15e6dc4c1cbcdc133653bac8a63fc704f7fe
https://github.com/quantopian/zipline/blob/77ad15e6dc4c1cbcdc133653bac8a63fc704f7fe/zipline/pipeline/term.py#L861-L875
train
quantopian/zipline
zipline/pipeline/term.py
Term._pop_params
def _pop_params(cls, kwargs): """ 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, objec...
python
def _pop_params(cls, kwargs): """ 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, objec...
[ "def", "_pop_params", "(", "cls", ",", "kwargs", ")", ":", "params", "=", "cls", ".", "params", "if", "not", "isinstance", "(", "params", ",", "Mapping", ")", ":", "params", "=", "{", "k", ":", "NotSpecified", "for", "k", "in", "params", "}", "param_...
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...
[ "Pop", "entries", "from", "the", "kwargs", "passed", "to", "cls", ".", "__new__", "based", "on", "the", "values", "in", "cls", ".", "params", "." ]
77ad15e6dc4c1cbcdc133653bac8a63fc704f7fe
https://github.com/quantopian/zipline/blob/77ad15e6dc4c1cbcdc133653bac8a63fc704f7fe/zipline/pipeline/term.py#L140-L192
train
quantopian/zipline
zipline/pipeline/term.py
Term._static_identity
def _static_identity(cls, domain, dtype, missing_value, window_safe, ndim, params): """ Return the identity of the Term that would be constructed from the...
python
def _static_identity(cls, domain, dtype, missing_value, window_safe, ndim, params): """ Return the identity of the Term that would be constructed from the...
[ "def", "_static_identity", "(", "cls", ",", "domain", ",", "dtype", ",", "missing_value", ",", "window_safe", ",", "ndim", ",", "params", ")", ":", "return", "(", "cls", ",", "domain", ",", "dtype", ",", "missing_value", ",", "window_safe", ",", "ndim", ...
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...
[ "Return", "the", "identity", "of", "the", "Term", "that", "would", "be", "constructed", "from", "the", "given", "arguments", "." ]
77ad15e6dc4c1cbcdc133653bac8a63fc704f7fe
https://github.com/quantopian/zipline/blob/77ad15e6dc4c1cbcdc133653bac8a63fc704f7fe/zipline/pipeline/term.py#L217-L235
train
quantopian/zipline
zipline/pipeline/term.py
Term._init
def _init(self, domain, dtype, missing_value, window_safe, ndim, params): """ Parameters ---------- domain : zipline.pipeline.domain.Domain The domain of this term. dtype : np.dtype Dtype of this term's output. missing_value : object Mi...
python
def _init(self, domain, dtype, missing_value, window_safe, ndim, params): """ Parameters ---------- domain : zipline.pipeline.domain.Domain The domain of this term. dtype : np.dtype Dtype of this term's output. missing_value : object Mi...
[ "def", "_init", "(", "self", ",", "domain", ",", "dtype", ",", "missing_value", ",", "window_safe", ",", "ndim", ",", "params", ")", ":", "self", ".", "domain", "=", "domain", "self", ".", "dtype", "=", "dtype", "self", ".", "missing_value", "=", "miss...
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. ...
[ "Parameters", "----------", "domain", ":", "zipline", ".", "pipeline", ".", "domain", ".", "Domain", "The", "domain", "of", "this", "term", ".", "dtype", ":", "np", ".", "dtype", "Dtype", "of", "this", "term", "s", "output", ".", "missing_value", ":", "o...
77ad15e6dc4c1cbcdc133653bac8a63fc704f7fe
https://github.com/quantopian/zipline/blob/77ad15e6dc4c1cbcdc133653bac8a63fc704f7fe/zipline/pipeline/term.py#L237-L285
train
quantopian/zipline
zipline/pipeline/term.py
ComputableTerm.dependencies
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 in self.inputs: out[term] = extra_input_rows out[self.mask] = 0 ...
python
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 in self.inputs: out[term] = extra_input_rows out[self.mask] = 0 ...
[ "def", "dependencies", "(", "self", ")", ":", "extra_input_rows", "=", "max", "(", "0", ",", "self", ".", "window_length", "-", "1", ")", "out", "=", "{", "}", "for", "term", "in", "self", ".", "inputs", ":", "out", "[", "term", "]", "=", "extra_in...
The number of extra rows needed for each of our inputs to compute this term.
[ "The", "number", "of", "extra", "rows", "needed", "for", "each", "of", "our", "inputs", "to", "compute", "this", "term", "." ]
77ad15e6dc4c1cbcdc133653bac8a63fc704f7fe
https://github.com/quantopian/zipline/blob/77ad15e6dc4c1cbcdc133653bac8a63fc704f7fe/zipline/pipeline/term.py#L613-L623
train
quantopian/zipline
zipline/pipeline/term.py
ComputableTerm.to_workspace_value
def to_workspace_value(self, result, assets): """ 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 mul...
python
def to_workspace_value(self, result, assets): """ 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 mul...
[ "def", "to_workspace_value", "(", "self", ",", "result", ",", "assets", ")", ":", "return", "result", ".", "unstack", "(", ")", ".", "fillna", "(", "self", ".", "missing_value", ")", ".", "reindex", "(", "columns", "=", "assets", ",", "fill_value", "=", ...
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 ...
[ "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", "." ]
77ad15e6dc4c1cbcdc133653bac8a63fc704f7fe
https://github.com/quantopian/zipline/blob/77ad15e6dc4c1cbcdc133653bac8a63fc704f7fe/zipline/pipeline/term.py#L638-L661
train
quantopian/zipline
zipline/finance/position.py
Position.earn_stock_dividend
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 amount on the dividend's pay date. """ return { 'payment_asset': stock_dividend.payment_asset, 'share_cou...
python
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 amount on the dividend's pay date. """ return { 'payment_asset': stock_dividend.payment_asset, 'share_cou...
[ "def", "earn_stock_dividend", "(", "self", ",", "stock_dividend", ")", ":", "return", "{", "'payment_asset'", ":", "stock_dividend", ".", "payment_asset", ",", "'share_count'", ":", "np", ".", "floor", "(", "self", ".", "amount", "*", "float", "(", "stock_divi...
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.
[ "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", "." ]
77ad15e6dc4c1cbcdc133653bac8a63fc704f7fe
https://github.com/quantopian/zipline/blob/77ad15e6dc4c1cbcdc133653bac8a63fc704f7fe/zipline/finance/position.py#L79-L89
train
quantopian/zipline
zipline/finance/position.py
Position.handle_split
def handle_split(self, asset, ratio): """ Update the position by the split ratio, and return the resulting fractional share that will be converted into cash. Returns the unused cash. """ if self.asset != asset: raise Exception("updating split with the wrong a...
python
def handle_split(self, asset, ratio): """ Update the position by the split ratio, and return the resulting fractional share that will be converted into cash. Returns the unused cash. """ if self.asset != asset: raise Exception("updating split with the wrong a...
[ "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 t...
Update the position by the split ratio, and return the resulting fractional share that will be converted into cash. Returns the unused cash.
[ "Update", "the", "position", "by", "the", "split", "ratio", "and", "return", "the", "resulting", "fractional", "share", "that", "will", "be", "converted", "into", "cash", "." ]
77ad15e6dc4c1cbcdc133653bac8a63fc704f7fe
https://github.com/quantopian/zipline/blob/77ad15e6dc4c1cbcdc133653bac8a63fc704f7fe/zipline/finance/position.py#L91-L129
train
quantopian/zipline
zipline/finance/position.py
Position.adjust_commission_cost_basis
def adjust_commission_cost_basis(self, asset, cost): """ 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 ...
python
def adjust_commission_cost_basis(self, asset, cost): """ 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 ...
[ "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", ...
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...
[ "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", "c...
77ad15e6dc4c1cbcdc133653bac8a63fc704f7fe
https://github.com/quantopian/zipline/blob/77ad15e6dc4c1cbcdc133653bac8a63fc704f7fe/zipline/finance/position.py#L164-L203
train
quantopian/zipline
zipline/finance/position.py
Position.to_dict
def to_dict(self): """ Creates a dictionary representing the state of this position. Returns a dict object of the form: """ return { 'sid': self.asset, 'amount': self.amount, 'cost_basis': self.cost_basis, 'last_sale_price': self.la...
python
def to_dict(self): """ Creates a dictionary representing the state of this position. Returns a dict object of the form: """ return { 'sid': self.asset, 'amount': self.amount, 'cost_basis': self.cost_basis, 'last_sale_price': self.la...
[ "def", "to_dict", "(", "self", ")", ":", "return", "{", "'sid'", ":", "self", ".", "asset", ",", "'amount'", ":", "self", ".", "amount", ",", "'cost_basis'", ":", "self", ".", "cost_basis", ",", "'last_sale_price'", ":", "self", ".", "last_sale_price", "...
Creates a dictionary representing the state of this position. Returns a dict object of the form:
[ "Creates", "a", "dictionary", "representing", "the", "state", "of", "this", "position", ".", "Returns", "a", "dict", "object", "of", "the", "form", ":" ]
77ad15e6dc4c1cbcdc133653bac8a63fc704f7fe
https://github.com/quantopian/zipline/blob/77ad15e6dc4c1cbcdc133653bac8a63fc704f7fe/zipline/finance/position.py#L215-L225
train
quantopian/zipline
zipline/data/bundles/core.py
_make_bundle_core
def _make_bundle_core(): """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....
python
def _make_bundle_core(): """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....
[ "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.", "bun...
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 ...
[ "Create", "a", "family", "of", "data", "bundle", "functions", "that", "read", "from", "the", "same", "bundle", "mapping", "." ]
77ad15e6dc4c1cbcdc133653bac8a63fc704f7fe
https://github.com/quantopian/zipline/blob/77ad15e6dc4c1cbcdc133653bac8a63fc704f7fe/zipline/data/bundles/core.py#L195-L614
train
quantopian/zipline
zipline/utils/deprecate.py
deprecated
def deprecated(msg=None, stacklevel=2): """ Used to mark a function as deprecated. Parameters ---------- msg : str The message to display in the deprecation warning. stacklevel : int How far up the stack the warning needs to go, before showing the relevant calling lines....
python
def deprecated(msg=None, stacklevel=2): """ Used to mark a function as deprecated. Parameters ---------- msg : str The message to display in the deprecation warning. stacklevel : int How far up the stack the warning needs to go, before showing the relevant calling lines....
[ "def", "deprecated", "(", "msg", "=", "None", ",", "stacklevel", "=", "2", ")", ":", "def", "deprecated_dec", "(", "fn", ")", ":", "@", "wraps", "(", "fn", ")", "def", "wrapper", "(", "*", "args", ",", "*", "*", "kwargs", ")", ":", "warnings", "....
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...
[ "Used", "to", "mark", "a", "function", "as", "deprecated", "." ]
77ad15e6dc4c1cbcdc133653bac8a63fc704f7fe
https://github.com/quantopian/zipline/blob/77ad15e6dc4c1cbcdc133653bac8a63fc704f7fe/zipline/utils/deprecate.py#L20-L47
train
quantopian/zipline
zipline/data/history_loader.py
HistoryCompatibleUSEquityAdjustmentReader.load_pricing_adjustments
def load_pricing_adjustments(self, columns, dts, assets): """ 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. """ ...
python
def load_pricing_adjustments(self, columns, dts, assets): """ 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", ")", ":", "out", "=", "[", "None", "]", "*", "len", "(", "columns", ")", "for", "i", ",", "column", "in", "enumerate", "(", "columns", ")", ":", "adjs", "=", ...
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.
[ "Returns", "-------", "adjustments", ":", "list", "[", "dict", "[", "int", "-", ">", "Adjustment", "]]", "A", "list", "where", "each", "element", "corresponds", "to", "the", "columns", "of", "mappings", "from", "index", "to", "adjustment", "objects", "to", ...
77ad15e6dc4c1cbcdc133653bac8a63fc704f7fe
https://github.com/quantopian/zipline/blob/77ad15e6dc4c1cbcdc133653bac8a63fc704f7fe/zipline/data/history_loader.py#L48-L63
train
quantopian/zipline
zipline/data/history_loader.py
HistoryCompatibleUSEquityAdjustmentReader._get_adjustments_in_range
def _get_adjustments_in_range(self, asset, dts, field): """ 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 wi...
python
def _get_adjustments_in_range(self, asset, dts, field): """ 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 wi...
[ "def", "_get_adjustments_in_range", "(", "self", ",", "asset", ",", "dts", ",", "field", ")", ":", "sid", "=", "int", "(", "asset", ")", "start", "=", "normalize_date", "(", "dts", "[", "0", "]", ")", "end", "=", "normalize_date", "(", "dts", "[", "-...
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...
[ "Get", "the", "Float64Multiply", "objects", "to", "pass", "to", "an", "AdjustedArrayWindow", "." ]
77ad15e6dc4c1cbcdc133653bac8a63fc704f7fe
https://github.com/quantopian/zipline/blob/77ad15e6dc4c1cbcdc133653bac8a63fc704f7fe/zipline/data/history_loader.py#L65-L151
train
quantopian/zipline
zipline/data/history_loader.py
SlidingWindow.get
def get(self, end_ix): """ Returns ------- out : A np.ndarray of the equity pricing up to end_ix after adjustments and rounding have been applied. """ if self.most_recent_ix == end_ix: return self.current target = end_ix - self.cal_start...
python
def get(self, end_ix): """ Returns ------- out : A np.ndarray of the equity pricing up to end_ix after adjustments and rounding have been applied. """ if self.most_recent_ix == end_ix: return self.current target = end_ix - self.cal_start...
[ "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", ".",...
Returns ------- out : A np.ndarray of the equity pricing up to end_ix after adjustments and rounding have been applied.
[ "Returns", "-------", "out", ":", "A", "np", ".", "ndarray", "of", "the", "equity", "pricing", "up", "to", "end_ix", "after", "adjustments", "and", "rounding", "have", "been", "applied", "." ]
77ad15e6dc4c1cbcdc133653bac8a63fc704f7fe
https://github.com/quantopian/zipline/blob/77ad15e6dc4c1cbcdc133653bac8a63fc704f7fe/zipline/data/history_loader.py#L279-L293
train
quantopian/zipline
zipline/data/history_loader.py
HistoryLoader._ensure_sliding_windows
def _ensure_sliding_windows(self, assets, dts, field, is_perspective_after): """ 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...
python
def _ensure_sliding_windows(self, assets, dts, field, is_perspective_after): """ 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...
[ "def", "_ensure_sliding_windows", "(", "self", ",", "assets", ",", "dts", ",", "field", ",", "is_perspective_after", ")", ":", "end", "=", "dts", "[", "-", "1", "]", "size", "=", "len", "(", "dts", ")", "asset_windows", "=", "{", "}", "needed_assets", ...
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 ...
[ "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", "...
77ad15e6dc4c1cbcdc133653bac8a63fc704f7fe
https://github.com/quantopian/zipline/blob/77ad15e6dc4c1cbcdc133653bac8a63fc704f7fe/zipline/data/history_loader.py#L364-L469
train
quantopian/zipline
zipline/data/history_loader.py
HistoryLoader.history
def history(self, assets, dts, field, is_perspective_after): """ 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 ...
python
def history(self, assets, dts, field, is_perspective_after): """ 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 ...
[ "def", "history", "(", "self", ",", "assets", ",", "dts", ",", "field", ",", "is_perspective_after", ")", ":", "block", "=", "self", ".", "_ensure_sliding_windows", "(", "assets", ",", "dts", ",", "field", ",", "is_perspective_after", ")", "end_ix", "=", "...
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...
[ "A", "window", "of", "pricing", "data", "with", "adjustments", "applied", "assuming", "that", "the", "end", "of", "the", "window", "is", "the", "day", "before", "the", "current", "simulation", "time", "." ]
77ad15e6dc4c1cbcdc133653bac8a63fc704f7fe
https://github.com/quantopian/zipline/blob/77ad15e6dc4c1cbcdc133653bac8a63fc704f7fe/zipline/data/history_loader.py#L471-L555
train
quantopian/zipline
zipline/sources/requests_csv.py
PandasCSV.parse_date_str_series
def parse_date_str_series(format_str, tz, date_str_series, data_frequency, trading_day): """ Efficient parsing for a 1d Pandas/numpy object containing string representations of dates. Note: pd.to_datetime is significantly faster when no format string is ...
python
def parse_date_str_series(format_str, tz, date_str_series, data_frequency, trading_day): """ Efficient parsing for a 1d Pandas/numpy object containing string representations of dates. Note: pd.to_datetime is significantly faster when no format string is ...
[ "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", "(...
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...
[ "Efficient", "parsing", "for", "a", "1d", "Pandas", "/", "numpy", "object", "containing", "string", "representations", "of", "dates", "." ]
77ad15e6dc4c1cbcdc133653bac8a63fc704f7fe
https://github.com/quantopian/zipline/blob/77ad15e6dc4c1cbcdc133653bac8a63fc704f7fe/zipline/sources/requests_csv.py#L201-L242
train
quantopian/zipline
zipline/sources/requests_csv.py
PandasCSV._lookup_unconflicted_symbol
def _lookup_unconflicted_symbol(self, symbol): """ Attempt to find a unique asset whose symbol is the given string. If multiple assets have held the given symbol, return a 0. If no asset has held the given symbol, return a NaN. """ try: uppered = symbol.upp...
python
def _lookup_unconflicted_symbol(self, symbol): """ Attempt to find a unique asset whose symbol is the given string. If multiple assets have held the given symbol, return a 0. If no asset has held the given symbol, return a NaN. """ try: uppered = symbol.upp...
[ "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", ...
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.
[ "Attempt", "to", "find", "a", "unique", "asset", "whose", "symbol", "is", "the", "given", "string", "." ]
77ad15e6dc4c1cbcdc133653bac8a63fc704f7fe
https://github.com/quantopian/zipline/blob/77ad15e6dc4c1cbcdc133653bac8a63fc704f7fe/zipline/sources/requests_csv.py#L262-L288
train
quantopian/zipline
zipline/gens/tradesimulation.py
AlgorithmSimulator.transform
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, handle_data=algo.event_mana...
python
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, handle_data=algo.event_mana...
[ "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", "=", ...
Main generator work loop.
[ "Main", "generator", "work", "loop", "." ]
77ad15e6dc4c1cbcdc133653bac8a63fc704f7fe
https://github.com/quantopian/zipline/blob/77ad15e6dc4c1cbcdc133653bac8a63fc704f7fe/zipline/gens/tradesimulation.py#L97-L236
train
quantopian/zipline
zipline/gens/tradesimulation.py
AlgorithmSimulator._cleanup_expired_assets
def _cleanup_expired_assets(self, dt, position_assets): """ 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_dat...
python
def _cleanup_expired_assets(self, dt, position_assets): """ 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_dat...
[ "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", ...
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 ...
[ "Clear", "out", "any", "assets", "that", "have", "expired", "before", "starting", "a", "new", "sim", "day", "." ]
77ad15e6dc4c1cbcdc133653bac8a63fc704f7fe
https://github.com/quantopian/zipline/blob/77ad15e6dc4c1cbcdc133653bac8a63fc704f7fe/zipline/gens/tradesimulation.py#L238-L281
train
quantopian/zipline
zipline/gens/tradesimulation.py
AlgorithmSimulator._get_daily_message
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_perf']['recorded_vars'] = algo.recorded_vars...
python
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_perf']['recorded_vars'] = algo.recorded_vars...
[ "def", "_get_daily_message", "(", "self", ",", "dt", ",", "algo", ",", "metrics_tracker", ")", ":", "perf_message", "=", "metrics_tracker", ".", "handle_market_close", "(", "dt", ",", "self", ".", "data_portal", ",", ")", "perf_message", "[", "'daily_perf'", "...
Get a perf message for the given datetime.
[ "Get", "a", "perf", "message", "for", "the", "given", "datetime", "." ]
77ad15e6dc4c1cbcdc133653bac8a63fc704f7fe
https://github.com/quantopian/zipline/blob/77ad15e6dc4c1cbcdc133653bac8a63fc704f7fe/zipline/gens/tradesimulation.py#L283-L292
train
quantopian/zipline
zipline/gens/tradesimulation.py
AlgorithmSimulator._get_minute_message
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, ) minute_message['minute_p...
python
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, ) minute_message['minute_p...
[ "def", "_get_minute_message", "(", "self", ",", "dt", ",", "algo", ",", "metrics_tracker", ")", ":", "rvars", "=", "algo", ".", "recorded_vars", "minute_message", "=", "metrics_tracker", ".", "handle_minute_close", "(", "dt", ",", "self", ".", "data_portal", "...
Get a perf message for the given datetime.
[ "Get", "a", "perf", "message", "for", "the", "given", "datetime", "." ]
77ad15e6dc4c1cbcdc133653bac8a63fc704f7fe
https://github.com/quantopian/zipline/blob/77ad15e6dc4c1cbcdc133653bac8a63fc704f7fe/zipline/gens/tradesimulation.py#L294-L306
train
quantopian/zipline
zipline/data/adjustments.py
SQLiteAdjustmentReader.load_adjustments
def load_adjustments(self, dates, assets, should_include_splits, should_include_mergers, should_include_dividends, adjustment_type): """ Load collection o...
python
def load_adjustments(self, dates, assets, should_include_splits, should_include_mergers, should_include_dividends, adjustment_type): """ Load collection o...
[ "def", "load_adjustments", "(", "self", ",", "dates", ",", "assets", ",", "should_include_splits", ",", "should_include_mergers", ",", "should_include_dividends", ",", "adjustment_type", ")", ":", "return", "load_adjustments_from_sqlite", "(", "self", ".", "conn", ","...
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 ...
[ "Load", "collection", "of", "Adjustment", "objects", "from", "underlying", "adjustments", "db", "." ]
77ad15e6dc4c1cbcdc133653bac8a63fc704f7fe
https://github.com/quantopian/zipline/blob/77ad15e6dc4c1cbcdc133653bac8a63fc704f7fe/zipline/data/adjustments.py#L142-L182
train
quantopian/zipline
zipline/data/adjustments.py
SQLiteAdjustmentReader.unpack_db_to_component_dfs
def unpack_db_to_component_dfs(self, convert_dates=False): """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...
python
def unpack_db_to_component_dfs(self, convert_dates=False): """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...
[ "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 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 ...
[ "Returns", "the", "set", "of", "known", "tables", "in", "the", "adjustments", "file", "in", "DataFrame", "form", "." ]
77ad15e6dc4c1cbcdc133653bac8a63fc704f7fe
https://github.com/quantopian/zipline/blob/77ad15e6dc4c1cbcdc133653bac8a63fc704f7fe/zipline/data/adjustments.py#L268-L289
train
quantopian/zipline
zipline/data/adjustments.py
SQLiteAdjustmentReader._df_dtypes
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 date_column in self._datetime_int_cols[table_name]: ...
python
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 date_column in self._datetime_int_cols[table_name]: ...
[ "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", "...
Get dtypes to use when unpacking sqlite tables as dataframes.
[ "Get", "dtypes", "to", "use", "when", "unpacking", "sqlite", "tables", "as", "dataframes", "." ]
77ad15e6dc4c1cbcdc133653bac8a63fc704f7fe
https://github.com/quantopian/zipline/blob/77ad15e6dc4c1cbcdc133653bac8a63fc704f7fe/zipline/data/adjustments.py#L326-L335
train
quantopian/zipline
zipline/data/adjustments.py
SQLiteAdjustmentWriter.calc_dividend_ratios
def calc_dividend_ratios(self, dividends): """ 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 ------- ...
python
def calc_dividend_ratios(self, dividends): """ 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 ------- ...
[ "def", "calc_dividend_ratios", "(", "self", ",", "dividends", ")", ":", "if", "dividends", "is", "None", "or", "dividends", ".", "empty", ":", "return", "pd", ".", "DataFrame", "(", "np", ".", "array", "(", "[", "]", ",", "dtype", "=", "[", "(", "'si...
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...
[ "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", ...
77ad15e6dc4c1cbcdc133653bac8a63fc704f7fe
https://github.com/quantopian/zipline/blob/77ad15e6dc4c1cbcdc133653bac8a63fc704f7fe/zipline/data/adjustments.py#L456-L530
train
quantopian/zipline
zipline/data/adjustments.py
SQLiteAdjustmentWriter.write_dividend_data
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) self._write_stock_dividends(stock_dividends) # Secon...
python
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) self._write_stock_dividends(stock_dividends) # Secon...
[ "def", "write_dividend_data", "(", "self", ",", "dividends", ",", "stock_dividends", "=", "None", ")", ":", "# First write the dividend payouts.", "self", ".", "_write_dividends", "(", "dividends", ")", "self", ".", "_write_stock_dividends", "(", "stock_dividends", ")...
Write both dividend payouts and the derived price adjustment ratios.
[ "Write", "both", "dividend", "payouts", "and", "the", "derived", "price", "adjustment", "ratios", "." ]
77ad15e6dc4c1cbcdc133653bac8a63fc704f7fe
https://github.com/quantopian/zipline/blob/77ad15e6dc4c1cbcdc133653bac8a63fc704f7fe/zipline/data/adjustments.py#L570-L581
train
quantopian/zipline
zipline/data/adjustments.py
SQLiteAdjustmentWriter.write
def write(self, splits=None, mergers=None, dividends=None, stock_dividends=None): """ Writes data to a SQLite file to be read by SQLiteAdjustmentReader. Parameters ---------- splits : pandas.DataFrame, optional ...
python
def write(self, splits=None, mergers=None, dividends=None, stock_dividends=None): """ Writes data to a SQLite file to be read by SQLiteAdjustmentReader. Parameters ---------- splits : pandas.DataFrame, optional ...
[ "def", "write", "(", "self", ",", "splits", "=", "None", ",", "mergers", "=", "None", ",", "dividends", "=", "None", ",", "stock_dividends", "=", "None", ")", ":", "self", ".", "write_frame", "(", "'splits'", ",", "splits", ")", "self", ".", "write_fra...
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 ...
[ "Writes", "data", "to", "a", "SQLite", "file", "to", "be", "read", "by", "SQLiteAdjustmentReader", "." ]
77ad15e6dc4c1cbcdc133653bac8a63fc704f7fe
https://github.com/quantopian/zipline/blob/77ad15e6dc4c1cbcdc133653bac8a63fc704f7fe/zipline/data/adjustments.py#L583-L703
train
quantopian/zipline
zipline/pipeline/mixins.py
CustomTermMixin.compute
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( name=type(self).__name__ ) )
python
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( name=type(self).__name__ ) )
[ "def", "compute", "(", "self", ",", "today", ",", "assets", ",", "out", ",", "*", "arrays", ")", ":", "raise", "NotImplementedError", "(", "\"{name} must define a compute method\"", ".", "format", "(", "name", "=", "type", "(", "self", ")", ".", "__name__", ...
Override this method with a function that writes a value into `out`.
[ "Override", "this", "method", "with", "a", "function", "that", "writes", "a", "value", "into", "out", "." ]
77ad15e6dc4c1cbcdc133653bac8a63fc704f7fe
https://github.com/quantopian/zipline/blob/77ad15e6dc4c1cbcdc133653bac8a63fc704f7fe/zipline/pipeline/mixins.py#L143-L151
train
quantopian/zipline
zipline/pipeline/mixins.py
CustomTermMixin._allocate_output
def _allocate_output(self, windows, shape): """ 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 dty...
python
def _allocate_output(self, windows, shape): """ 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 dty...
[ "def", "_allocate_output", "(", "self", ",", "windows", ",", "shape", ")", ":", "missing_value", "=", "self", ".", "missing_value", "outputs", "=", "self", ".", "outputs", "if", "outputs", "is", "not", "NotSpecified", ":", "out", "=", "recarray", "(", "sha...
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 ...
[ "Allocate", "an", "output", "array", "whose", "rows", "should", "be", "passed", "to", "self", ".", "compute", "." ]
77ad15e6dc4c1cbcdc133653bac8a63fc704f7fe
https://github.com/quantopian/zipline/blob/77ad15e6dc4c1cbcdc133653bac8a63fc704f7fe/zipline/pipeline/mixins.py#L153-L180
train
quantopian/zipline
zipline/pipeline/mixins.py
CustomTermMixin._compute
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 = self.compute params = self.params ndim = self.ndim shape = (le...
python
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 = self.compute params = self.params ndim = self.ndim shape = (le...
[ "def", "_compute", "(", "self", ",", "windows", ",", "dates", ",", "assets", ",", "mask", ")", ":", "format_inputs", "=", "self", ".", "_format_inputs", "compute", "=", "self", ".", "compute", "params", "=", "self", ".", "params", "ndim", "=", "self", ...
Call the user's `compute` function on each window with a pre-built output array.
[ "Call", "the", "user", "s", "compute", "function", "on", "each", "window", "with", "a", "pre", "-", "built", "output", "array", "." ]
77ad15e6dc4c1cbcdc133653bac8a63fc704f7fe
https://github.com/quantopian/zipline/blob/77ad15e6dc4c1cbcdc133653bac8a63fc704f7fe/zipline/pipeline/mixins.py#L193-L220
train
quantopian/zipline
zipline/pipeline/mixins.py
AliasedMixin.make_aliased_type
def make_aliased_type(cls, other_base): """ Factory for making Aliased{Filter,Factor,Classifier}. """ docstring = dedent( """ A {t} that names another {t}. Parameters ---------- term : {t} {{name}} """ ...
python
def make_aliased_type(cls, other_base): """ Factory for making Aliased{Filter,Factor,Classifier}. """ docstring = dedent( """ A {t} that names another {t}. Parameters ---------- term : {t} {{name}} """ ...
[ "def", "make_aliased_type", "(", "cls", ",", "other_base", ")", ":", "docstring", "=", "dedent", "(", "\"\"\"\n A {t} that names another {t}.\n\n Parameters\n ----------\n term : {t}\n {{name}}\n \"\"\"", ")", ".", "form...
Factory for making Aliased{Filter,Factor,Classifier}.
[ "Factory", "for", "making", "Aliased", "{", "Filter", "Factor", "Classifier", "}", "." ]
77ad15e6dc4c1cbcdc133653bac8a63fc704f7fe
https://github.com/quantopian/zipline/blob/77ad15e6dc4c1cbcdc133653bac8a63fc704f7fe/zipline/pipeline/mixins.py#L297-L323
train
quantopian/zipline
zipline/pipeline/mixins.py
DownsampledMixin.compute_extra_rows
def compute_extra_rows(self, all_dates, start_date, end_date, min_extra_rows): """ Ensure that min_extra_rows pushes us back to a computation date. Parameters ---------- a...
python
def compute_extra_rows(self, all_dates, start_date, end_date, min_extra_rows): """ Ensure that min_extra_rows pushes us back to a computation date. Parameters ---------- a...
[ "def", "compute_extra_rows", "(", "self", ",", "all_dates", ",", "start_date", ",", "end_date", ",", "min_extra_rows", ")", ":", "try", ":", "current_start_pos", "=", "all_dates", ".", "get_loc", "(", "start_date", ")", "-", "min_extra_rows", "if", "current_star...
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. ...
[ "Ensure", "that", "min_extra_rows", "pushes", "us", "back", "to", "a", "computation", "date", "." ]
77ad15e6dc4c1cbcdc133653bac8a63fc704f7fe
https://github.com/quantopian/zipline/blob/77ad15e6dc4c1cbcdc133653bac8a63fc704f7fe/zipline/pipeline/mixins.py#L370-L437
train
quantopian/zipline
zipline/pipeline/mixins.py
DownsampledMixin._compute
def _compute(self, inputs, dates, assets, mask): """ Compute by delegating to self._wrapped_term._compute on sample dates. On non-sample dates, forward-fill from previously-computed samples. """ to_sample = dates[select_sampling_indices(dates, self._frequency)] assert to...
python
def _compute(self, inputs, dates, assets, mask): """ Compute by delegating to self._wrapped_term._compute on sample dates. On non-sample dates, forward-fill from previously-computed samples. """ to_sample = dates[select_sampling_indices(dates, self._frequency)] assert to...
[ "def", "_compute", "(", "self", ",", "inputs", ",", "dates", ",", "assets", ",", "mask", ")", ":", "to_sample", "=", "dates", "[", "select_sampling_indices", "(", "dates", ",", "self", ".", "_frequency", ")", "]", "assert", "to_sample", "[", "0", "]", ...
Compute by delegating to self._wrapped_term._compute on sample dates. On non-sample dates, forward-fill from previously-computed samples.
[ "Compute", "by", "delegating", "to", "self", ".", "_wrapped_term", ".", "_compute", "on", "sample", "dates", "." ]
77ad15e6dc4c1cbcdc133653bac8a63fc704f7fe
https://github.com/quantopian/zipline/blob/77ad15e6dc4c1cbcdc133653bac8a63fc704f7fe/zipline/pipeline/mixins.py#L439-L516
train
quantopian/zipline
zipline/pipeline/mixins.py
DownsampledMixin.make_downsampled_type
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. Parameters ---------- term : ...
python
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. Parameters ---------- term : ...
[ "def", "make_downsampled_type", "(", "cls", ",", "other_base", ")", ":", "docstring", "=", "dedent", "(", "\"\"\"\n A {t} that defers to another {t} at lower-than-daily frequency.\n\n Parameters\n ----------\n term : {t}\n {{frequency}}\...
Factory for making Downsampled{Filter,Factor,Classifier}.
[ "Factory", "for", "making", "Downsampled", "{", "Filter", "Factor", "Classifier", "}", "." ]
77ad15e6dc4c1cbcdc133653bac8a63fc704f7fe
https://github.com/quantopian/zipline/blob/77ad15e6dc4c1cbcdc133653bac8a63fc704f7fe/zipline/pipeline/mixins.py#L519-L545
train
quantopian/zipline
zipline/utils/preprocess.py
preprocess
def preprocess(*_unused, **processors): """ 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: (fun...
python
def preprocess(*_unused, **processors): """ 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: (fun...
[ "def", "preprocess", "(", "*", "_unused", ",", "*", "*", "processors", ")", ":", "if", "_unused", ":", "raise", "TypeError", "(", "\"preprocess() doesn't accept positional arguments\"", ")", "def", "_decorator", "(", "f", ")", ":", "args", ",", "varargs", ",",...
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...
[ "Decorator", "that", "applies", "pre", "-", "processors", "to", "the", "arguments", "of", "a", "function", "before", "calling", "the", "function", "." ]
77ad15e6dc4c1cbcdc133653bac8a63fc704f7fe
https://github.com/quantopian/zipline/blob/77ad15e6dc4c1cbcdc133653bac8a63fc704f7fe/zipline/utils/preprocess.py#L35-L112
train
quantopian/zipline
zipline/utils/preprocess.py
call
def call(f): """ 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. Exa...
python
def call(f): """ 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. Exa...
[ "def", "call", "(", "f", ")", ":", "@", "wraps", "(", "f", ")", "def", "processor", "(", "func", ",", "argname", ",", "arg", ")", ":", "return", "f", "(", "arg", ")", "return", "processor" ]
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 -------- >>...
[ "Wrap", "a", "function", "in", "a", "processor", "that", "calls", "f", "on", "the", "argument", "before", "passing", "it", "along", "." ]
77ad15e6dc4c1cbcdc133653bac8a63fc704f7fe
https://github.com/quantopian/zipline/blob/77ad15e6dc4c1cbcdc133653bac8a63fc704f7fe/zipline/utils/preprocess.py#L115-L139
train
quantopian/zipline
zipline/utils/preprocess.py
_build_preprocessed_function
def _build_preprocessed_function(func, processors, args_defaults, varargs, varkw): """ Build a preprocessed function with the same signature as `func`. Uses `exec` internally ...
python
def _build_preprocessed_function(func, processors, args_defaults, varargs, varkw): """ Build a preprocessed function with the same signature as `func`. Uses `exec` internally ...
[ "def", "_build_preprocessed_function", "(", "func", ",", "processors", ",", "args_defaults", ",", "varargs", ",", "varkw", ")", ":", "format_kwargs", "=", "{", "'func_name'", ":", "func", ".", "__name__", "}", "def", "mangle", "(", "name", ")", ":", "return"...
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.
[ "Build", "a", "preprocessed", "function", "with", "the", "same", "signature", "as", "func", "." ]
77ad15e6dc4c1cbcdc133653bac8a63fc704f7fe
https://github.com/quantopian/zipline/blob/77ad15e6dc4c1cbcdc133653bac8a63fc704f7fe/zipline/utils/preprocess.py#L142-L247
train