id
int32
0
252k
repo
stringlengths
7
55
path
stringlengths
4
127
func_name
stringlengths
1
88
original_string
stringlengths
75
19.8k
language
stringclasses
1 value
code
stringlengths
75
19.8k
code_tokens
list
docstring
stringlengths
3
17.3k
docstring_tokens
list
sha
stringlengths
40
40
url
stringlengths
87
242
25,700
pypa/pipenv
pipenv/vendor/jinja2/compiler.py
find_undeclared
def find_undeclared(nodes, names): """Check if the names passed are accessed undeclared. The return value is a set of all the undeclared names from the sequence of names found. """ visitor = UndeclaredNameVisitor(names) try: for node in nodes: visitor.visit(node) except Visi...
python
def find_undeclared(nodes, names): """Check if the names passed are accessed undeclared. The return value is a set of all the undeclared names from the sequence of names found. """ visitor = UndeclaredNameVisitor(names) try: for node in nodes: visitor.visit(node) except Visi...
[ "def", "find_undeclared", "(", "nodes", ",", "names", ")", ":", "visitor", "=", "UndeclaredNameVisitor", "(", "names", ")", "try", ":", "for", "node", "in", "nodes", ":", "visitor", ".", "visit", "(", "node", ")", "except", "VisitorExit", ":", "pass", "r...
Check if the names passed are accessed undeclared. The return value is a set of all the undeclared names from the sequence of names found.
[ "Check", "if", "the", "names", "passed", "are", "accessed", "undeclared", ".", "The", "return", "value", "is", "a", "set", "of", "all", "the", "undeclared", "names", "from", "the", "sequence", "of", "names", "found", "." ]
cae8d76c210b9777e90aab76e9c4b0e53bb19cde
https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/vendor/jinja2/compiler.py#L108-L118
25,701
pypa/pipenv
pipenv/vendor/jinja2/compiler.py
Frame.inner
def inner(self, isolated=False): """Return an inner frame.""" if isolated: return Frame(self.eval_ctx, level=self.symbols.level + 1) return Frame(self.eval_ctx, self)
python
def inner(self, isolated=False): """Return an inner frame.""" if isolated: return Frame(self.eval_ctx, level=self.symbols.level + 1) return Frame(self.eval_ctx, self)
[ "def", "inner", "(", "self", ",", "isolated", "=", "False", ")", ":", "if", "isolated", ":", "return", "Frame", "(", "self", ".", "eval_ctx", ",", "level", "=", "self", ".", "symbols", ".", "level", "+", "1", ")", "return", "Frame", "(", "self", "....
Return an inner frame.
[ "Return", "an", "inner", "frame", "." ]
cae8d76c210b9777e90aab76e9c4b0e53bb19cde
https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/vendor/jinja2/compiler.py#L172-L176
25,702
pypa/pipenv
pipenv/vendor/jinja2/compiler.py
CodeGenerator.buffer
def buffer(self, frame): """Enable buffering for the frame from that point onwards.""" frame.buffer = self.temporary_identifier() self.writeline('%s = []' % frame.buffer)
python
def buffer(self, frame): """Enable buffering for the frame from that point onwards.""" frame.buffer = self.temporary_identifier() self.writeline('%s = []' % frame.buffer)
[ "def", "buffer", "(", "self", ",", "frame", ")", ":", "frame", ".", "buffer", "=", "self", ".", "temporary_identifier", "(", ")", "self", ".", "writeline", "(", "'%s = []'", "%", "frame", ".", "buffer", ")" ]
Enable buffering for the frame from that point onwards.
[ "Enable", "buffering", "for", "the", "frame", "from", "that", "point", "onwards", "." ]
cae8d76c210b9777e90aab76e9c4b0e53bb19cde
https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/vendor/jinja2/compiler.py#L322-L325
25,703
pypa/pipenv
pipenv/vendor/jinja2/compiler.py
CodeGenerator.return_buffer_contents
def return_buffer_contents(self, frame, force_unescaped=False): """Return the buffer contents of the frame.""" if not force_unescaped: if frame.eval_ctx.volatile: self.writeline('if context.eval_ctx.autoescape:') self.indent() self.writeline('r...
python
def return_buffer_contents(self, frame, force_unescaped=False): """Return the buffer contents of the frame.""" if not force_unescaped: if frame.eval_ctx.volatile: self.writeline('if context.eval_ctx.autoescape:') self.indent() self.writeline('r...
[ "def", "return_buffer_contents", "(", "self", ",", "frame", ",", "force_unescaped", "=", "False", ")", ":", "if", "not", "force_unescaped", ":", "if", "frame", ".", "eval_ctx", ".", "volatile", ":", "self", ".", "writeline", "(", "'if context.eval_ctx.autoescape...
Return the buffer contents of the frame.
[ "Return", "the", "buffer", "contents", "of", "the", "frame", "." ]
cae8d76c210b9777e90aab76e9c4b0e53bb19cde
https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/vendor/jinja2/compiler.py#L327-L343
25,704
pypa/pipenv
pipenv/vendor/jinja2/compiler.py
CodeGenerator.start_write
def start_write(self, frame, node=None): """Yield or write into the frame buffer.""" if frame.buffer is None: self.writeline('yield ', node) else: self.writeline('%s.append(' % frame.buffer, node)
python
def start_write(self, frame, node=None): """Yield or write into the frame buffer.""" if frame.buffer is None: self.writeline('yield ', node) else: self.writeline('%s.append(' % frame.buffer, node)
[ "def", "start_write", "(", "self", ",", "frame", ",", "node", "=", "None", ")", ":", "if", "frame", ".", "buffer", "is", "None", ":", "self", ".", "writeline", "(", "'yield '", ",", "node", ")", "else", ":", "self", ".", "writeline", "(", "'%s.append...
Yield or write into the frame buffer.
[ "Yield", "or", "write", "into", "the", "frame", "buffer", "." ]
cae8d76c210b9777e90aab76e9c4b0e53bb19cde
https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/vendor/jinja2/compiler.py#L353-L358
25,705
pypa/pipenv
pipenv/vendor/jinja2/compiler.py
CodeGenerator.simple_write
def simple_write(self, s, frame, node=None): """Simple shortcut for start_write + write + end_write.""" self.start_write(frame, node) self.write(s) self.end_write(frame)
python
def simple_write(self, s, frame, node=None): """Simple shortcut for start_write + write + end_write.""" self.start_write(frame, node) self.write(s) self.end_write(frame)
[ "def", "simple_write", "(", "self", ",", "s", ",", "frame", ",", "node", "=", "None", ")", ":", "self", ".", "start_write", "(", "frame", ",", "node", ")", "self", ".", "write", "(", "s", ")", "self", ".", "end_write", "(", "frame", ")" ]
Simple shortcut for start_write + write + end_write.
[ "Simple", "shortcut", "for", "start_write", "+", "write", "+", "end_write", "." ]
cae8d76c210b9777e90aab76e9c4b0e53bb19cde
https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/vendor/jinja2/compiler.py#L365-L369
25,706
pypa/pipenv
pipenv/vendor/jinja2/compiler.py
CodeGenerator.write
def write(self, x): """Write a string into the output stream.""" if self._new_lines: if not self._first_write: self.stream.write('\n' * self._new_lines) self.code_lineno += self._new_lines if self._write_debug_info is not None: ...
python
def write(self, x): """Write a string into the output stream.""" if self._new_lines: if not self._first_write: self.stream.write('\n' * self._new_lines) self.code_lineno += self._new_lines if self._write_debug_info is not None: ...
[ "def", "write", "(", "self", ",", "x", ")", ":", "if", "self", ".", "_new_lines", ":", "if", "not", "self", ".", "_first_write", ":", "self", ".", "stream", ".", "write", "(", "'\\n'", "*", "self", ".", "_new_lines", ")", "self", ".", "code_lineno", ...
Write a string into the output stream.
[ "Write", "a", "string", "into", "the", "output", "stream", "." ]
cae8d76c210b9777e90aab76e9c4b0e53bb19cde
https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/vendor/jinja2/compiler.py#L382-L395
25,707
pypa/pipenv
pipenv/vendor/jinja2/compiler.py
CodeGenerator.writeline
def writeline(self, x, node=None, extra=0): """Combination of newline and write.""" self.newline(node, extra) self.write(x)
python
def writeline(self, x, node=None, extra=0): """Combination of newline and write.""" self.newline(node, extra) self.write(x)
[ "def", "writeline", "(", "self", ",", "x", ",", "node", "=", "None", ",", "extra", "=", "0", ")", ":", "self", ".", "newline", "(", "node", ",", "extra", ")", "self", ".", "write", "(", "x", ")" ]
Combination of newline and write.
[ "Combination", "of", "newline", "and", "write", "." ]
cae8d76c210b9777e90aab76e9c4b0e53bb19cde
https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/vendor/jinja2/compiler.py#L397-L400
25,708
pypa/pipenv
pipenv/vendor/jinja2/compiler.py
CodeGenerator.newline
def newline(self, node=None, extra=0): """Add one or more newlines before the next write.""" self._new_lines = max(self._new_lines, 1 + extra) if node is not None and node.lineno != self._last_line: self._write_debug_info = node.lineno self._last_line = node.lineno
python
def newline(self, node=None, extra=0): """Add one or more newlines before the next write.""" self._new_lines = max(self._new_lines, 1 + extra) if node is not None and node.lineno != self._last_line: self._write_debug_info = node.lineno self._last_line = node.lineno
[ "def", "newline", "(", "self", ",", "node", "=", "None", ",", "extra", "=", "0", ")", ":", "self", ".", "_new_lines", "=", "max", "(", "self", ".", "_new_lines", ",", "1", "+", "extra", ")", "if", "node", "is", "not", "None", "and", "node", ".", ...
Add one or more newlines before the next write.
[ "Add", "one", "or", "more", "newlines", "before", "the", "next", "write", "." ]
cae8d76c210b9777e90aab76e9c4b0e53bb19cde
https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/vendor/jinja2/compiler.py#L402-L407
25,709
pypa/pipenv
pipenv/vendor/jinja2/compiler.py
CodeGenerator.signature
def signature(self, node, frame, extra_kwargs=None): """Writes a function call to the stream for the current node. A leading comma is added automatically. The extra keyword arguments may not include python keywords otherwise a syntax error could occour. The extra keyword arguments shou...
python
def signature(self, node, frame, extra_kwargs=None): """Writes a function call to the stream for the current node. A leading comma is added automatically. The extra keyword arguments may not include python keywords otherwise a syntax error could occour. The extra keyword arguments shou...
[ "def", "signature", "(", "self", ",", "node", ",", "frame", ",", "extra_kwargs", "=", "None", ")", ":", "# if any of the given keyword arguments is a python keyword", "# we have to make sure that no invalid call is created.", "kwarg_workaround", "=", "False", "for", "kwarg", ...
Writes a function call to the stream for the current node. A leading comma is added automatically. The extra keyword arguments may not include python keywords otherwise a syntax error could occour. The extra keyword arguments should be given as python dict.
[ "Writes", "a", "function", "call", "to", "the", "stream", "for", "the", "current", "node", ".", "A", "leading", "comma", "is", "added", "automatically", ".", "The", "extra", "keyword", "arguments", "may", "not", "include", "python", "keywords", "otherwise", ...
cae8d76c210b9777e90aab76e9c4b0e53bb19cde
https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/vendor/jinja2/compiler.py#L409-L460
25,710
pypa/pipenv
pipenv/vendor/jinja2/compiler.py
CodeGenerator.pull_dependencies
def pull_dependencies(self, nodes): """Pull all the dependencies.""" visitor = DependencyFinderVisitor() for node in nodes: visitor.visit(node) for dependency in 'filters', 'tests': mapping = getattr(self, dependency) for name in getattr(visitor, depen...
python
def pull_dependencies(self, nodes): """Pull all the dependencies.""" visitor = DependencyFinderVisitor() for node in nodes: visitor.visit(node) for dependency in 'filters', 'tests': mapping = getattr(self, dependency) for name in getattr(visitor, depen...
[ "def", "pull_dependencies", "(", "self", ",", "nodes", ")", ":", "visitor", "=", "DependencyFinderVisitor", "(", ")", "for", "node", "in", "nodes", ":", "visitor", ".", "visit", "(", "node", ")", "for", "dependency", "in", "'filters'", ",", "'tests'", ":",...
Pull all the dependencies.
[ "Pull", "all", "the", "dependencies", "." ]
cae8d76c210b9777e90aab76e9c4b0e53bb19cde
https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/vendor/jinja2/compiler.py#L462-L473
25,711
pypa/pipenv
pipenv/vendor/jinja2/compiler.py
CodeGenerator.position
def position(self, node): """Return a human readable position for the node.""" rv = 'line %d' % node.lineno if self.name is not None: rv += ' in ' + repr(self.name) return rv
python
def position(self, node): """Return a human readable position for the node.""" rv = 'line %d' % node.lineno if self.name is not None: rv += ' in ' + repr(self.name) return rv
[ "def", "position", "(", "self", ",", "node", ")", ":", "rv", "=", "'line %d'", "%", "node", ".", "lineno", "if", "self", ".", "name", "is", "not", "None", ":", "rv", "+=", "' in '", "+", "repr", "(", "self", ".", "name", ")", "return", "rv" ]
Return a human readable position for the node.
[ "Return", "a", "human", "readable", "position", "for", "the", "node", "." ]
cae8d76c210b9777e90aab76e9c4b0e53bb19cde
https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/vendor/jinja2/compiler.py#L593-L598
25,712
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
25,713
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
25,714
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
25,715
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
25,716
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
25,717
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
25,718
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
25,719
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
25,720
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
25,721
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
25,722
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
25,723
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
25,724
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
25,725
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
25,726
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
25,727
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
25,728
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
25,729
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
25,730
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
25,731
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
25,732
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
25,733
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
25,734
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
25,735
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
25,736
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
25,737
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
25,738
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
25,739
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
25,740
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
25,741
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
25,742
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
25,743
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
25,744
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
25,745
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
25,746
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
25,747
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
25,748
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
25,749
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
25,750
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
25,751
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
25,752
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
25,753
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
25,754
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
25,755
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
25,756
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
25,757
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
25,758
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
25,759
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
25,760
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
25,761
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
25,762
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
25,763
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
25,764
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
25,765
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
25,766
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
25,767
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
25,768
quantopian/zipline
zipline/data/benchmarks.py
get_benchmark_returns
def get_benchmark_returns(symbol): """ Get a Series of benchmark returns from IEX associated with `symbol`. Default is `SPY`. Parameters ---------- symbol : str Benchmark symbol for which we're getting the returns. The data is provided by IEX (https://iextrading.com/), and we can ...
python
def get_benchmark_returns(symbol): """ Get a Series of benchmark returns from IEX associated with `symbol`. Default is `SPY`. Parameters ---------- symbol : str Benchmark symbol for which we're getting the returns. The data is provided by IEX (https://iextrading.com/), and we can ...
[ "def", "get_benchmark_returns", "(", "symbol", ")", ":", "r", "=", "requests", ".", "get", "(", "'https://api.iextrading.com/1.0/stock/{}/chart/5y'", ".", "format", "(", "symbol", ")", ")", "data", "=", "r", ".", "json", "(", ")", "df", "=", "pd", ".", "Da...
Get a Series of benchmark returns from IEX associated with `symbol`. Default is `SPY`. Parameters ---------- symbol : str Benchmark symbol for which we're getting the returns. The data is provided by IEX (https://iextrading.com/), and we can get up to 5 years worth of data.
[ "Get", "a", "Series", "of", "benchmark", "returns", "from", "IEX", "associated", "with", "symbol", ".", "Default", "is", "SPY", "." ]
77ad15e6dc4c1cbcdc133653bac8a63fc704f7fe
https://github.com/quantopian/zipline/blob/77ad15e6dc4c1cbcdc133653bac8a63fc704f7fe/zipline/data/benchmarks.py#L19-L42
25,769
quantopian/zipline
zipline/pipeline/visualize.py
delimit
def delimit(delimiters, content): """ Surround `content` with the first and last characters of `delimiters`. >>> delimit('[]', "foo") # doctest: +SKIP '[foo]' >>> delimit('""', "foo") # doctest: +SKIP '"foo"' """ if len(delimiters) != 2: raise ValueError( "`delimit...
python
def delimit(delimiters, content): """ Surround `content` with the first and last characters of `delimiters`. >>> delimit('[]', "foo") # doctest: +SKIP '[foo]' >>> delimit('""', "foo") # doctest: +SKIP '"foo"' """ if len(delimiters) != 2: raise ValueError( "`delimit...
[ "def", "delimit", "(", "delimiters", ",", "content", ")", ":", "if", "len", "(", "delimiters", ")", "!=", "2", ":", "raise", "ValueError", "(", "\"`delimiters` must be of length 2. Got %r\"", "%", "delimiters", ")", "return", "''", ".", "join", "(", "[", "de...
Surround `content` with the first and last characters of `delimiters`. >>> delimit('[]', "foo") # doctest: +SKIP '[foo]' >>> delimit('""', "foo") # doctest: +SKIP '"foo"'
[ "Surround", "content", "with", "the", "first", "and", "last", "characters", "of", "delimiters", "." ]
77ad15e6dc4c1cbcdc133653bac8a63fc704f7fe
https://github.com/quantopian/zipline/blob/77ad15e6dc4c1cbcdc133653bac8a63fc704f7fe/zipline/pipeline/visualize.py#L24-L37
25,770
quantopian/zipline
zipline/pipeline/visualize.py
roots
def roots(g): "Get nodes from graph G with indegree 0" return set(n for n, d in iteritems(g.in_degree()) if d == 0)
python
def roots(g): "Get nodes from graph G with indegree 0" return set(n for n, d in iteritems(g.in_degree()) if d == 0)
[ "def", "roots", "(", "g", ")", ":", "return", "set", "(", "n", "for", "n", ",", "d", "in", "iteritems", "(", "g", ".", "in_degree", "(", ")", ")", "if", "d", "==", "0", ")" ]
Get nodes from graph G with indegree 0
[ "Get", "nodes", "from", "graph", "G", "with", "indegree", "0" ]
77ad15e6dc4c1cbcdc133653bac8a63fc704f7fe
https://github.com/quantopian/zipline/blob/77ad15e6dc4c1cbcdc133653bac8a63fc704f7fe/zipline/pipeline/visualize.py#L73-L75
25,771
quantopian/zipline
zipline/pipeline/visualize.py
_render
def _render(g, out, format_, include_asset_exists=False): """ Draw `g` as a graph to `out`, in format `format`. Parameters ---------- g : zipline.pipeline.graph.TermGraph Graph to render. out : file-like object format_ : str {'png', 'svg'} Output format. include_asset_ex...
python
def _render(g, out, format_, include_asset_exists=False): """ Draw `g` as a graph to `out`, in format `format`. Parameters ---------- g : zipline.pipeline.graph.TermGraph Graph to render. out : file-like object format_ : str {'png', 'svg'} Output format. include_asset_ex...
[ "def", "_render", "(", "g", ",", "out", ",", "format_", ",", "include_asset_exists", "=", "False", ")", ":", "graph_attrs", "=", "{", "'rankdir'", ":", "'TB'", ",", "'splines'", ":", "'ortho'", "}", "cluster_attrs", "=", "{", "'style'", ":", "'filled'", ...
Draw `g` as a graph to `out`, in format `format`. Parameters ---------- g : zipline.pipeline.graph.TermGraph Graph to render. out : file-like object format_ : str {'png', 'svg'} Output format. include_asset_exists : bool Whether to filter out `AssetExists()` nodes.
[ "Draw", "g", "as", "a", "graph", "to", "out", "in", "format", "format", "." ]
77ad15e6dc4c1cbcdc133653bac8a63fc704f7fe
https://github.com/quantopian/zipline/blob/77ad15e6dc4c1cbcdc133653bac8a63fc704f7fe/zipline/pipeline/visualize.py#L84-L149
25,772
quantopian/zipline
zipline/pipeline/visualize.py
display_graph
def display_graph(g, format='svg', include_asset_exists=False): """ Display a TermGraph interactively from within IPython. """ try: import IPython.display as display except ImportError: raise NoIPython("IPython is not installed. Can't display graph.") if format == 'svg': ...
python
def display_graph(g, format='svg', include_asset_exists=False): """ Display a TermGraph interactively from within IPython. """ try: import IPython.display as display except ImportError: raise NoIPython("IPython is not installed. Can't display graph.") if format == 'svg': ...
[ "def", "display_graph", "(", "g", ",", "format", "=", "'svg'", ",", "include_asset_exists", "=", "False", ")", ":", "try", ":", "import", "IPython", ".", "display", "as", "display", "except", "ImportError", ":", "raise", "NoIPython", "(", "\"IPython is not ins...
Display a TermGraph interactively from within IPython.
[ "Display", "a", "TermGraph", "interactively", "from", "within", "IPython", "." ]
77ad15e6dc4c1cbcdc133653bac8a63fc704f7fe
https://github.com/quantopian/zipline/blob/77ad15e6dc4c1cbcdc133653bac8a63fc704f7fe/zipline/pipeline/visualize.py#L152-L168
25,773
quantopian/zipline
zipline/pipeline/visualize.py
format_attrs
def format_attrs(attrs): """ Format key, value pairs from attrs into graphviz attrs format Examples -------- >>> format_attrs({'key1': 'value1', 'key2': 'value2'}) # doctest: +SKIP '[key1=value1, key2=value2]' """ if not attrs: return '' entries = ['='.join((key, value)) fo...
python
def format_attrs(attrs): """ Format key, value pairs from attrs into graphviz attrs format Examples -------- >>> format_attrs({'key1': 'value1', 'key2': 'value2'}) # doctest: +SKIP '[key1=value1, key2=value2]' """ if not attrs: return '' entries = ['='.join((key, value)) fo...
[ "def", "format_attrs", "(", "attrs", ")", ":", "if", "not", "attrs", ":", "return", "''", "entries", "=", "[", "'='", ".", "join", "(", "(", "key", ",", "value", ")", ")", "for", "key", ",", "value", "in", "iteritems", "(", "attrs", ")", "]", "re...
Format key, value pairs from attrs into graphviz attrs format Examples -------- >>> format_attrs({'key1': 'value1', 'key2': 'value2'}) # doctest: +SKIP '[key1=value1, key2=value2]'
[ "Format", "key", "value", "pairs", "from", "attrs", "into", "graphviz", "attrs", "format" ]
77ad15e6dc4c1cbcdc133653bac8a63fc704f7fe
https://github.com/quantopian/zipline/blob/77ad15e6dc4c1cbcdc133653bac8a63fc704f7fe/zipline/pipeline/visualize.py#L215-L227
25,774
quantopian/zipline
zipline/utils/pool.py
SequentialPool.apply_async
def apply_async(f, args=(), kwargs=None, callback=None): """Apply a function but emulate the API of an asynchronous call. Parameters ---------- f : callable The function to call. args : tuple, optional The positional arguments. kwargs : dict, opti...
python
def apply_async(f, args=(), kwargs=None, callback=None): """Apply a function but emulate the API of an asynchronous call. Parameters ---------- f : callable The function to call. args : tuple, optional The positional arguments. kwargs : dict, opti...
[ "def", "apply_async", "(", "f", ",", "args", "=", "(", ")", ",", "kwargs", "=", "None", ",", "callback", "=", "None", ")", ":", "try", ":", "value", "=", "(", "identity", "if", "callback", "is", "None", "else", "callback", ")", "(", "f", "(", "*"...
Apply a function but emulate the API of an asynchronous call. Parameters ---------- f : callable The function to call. args : tuple, optional The positional arguments. kwargs : dict, optional The keyword arguments. Returns ---...
[ "Apply", "a", "function", "but", "emulate", "the", "API", "of", "an", "asynchronous", "call", "." ]
77ad15e6dc4c1cbcdc133653bac8a63fc704f7fe
https://github.com/quantopian/zipline/blob/77ad15e6dc4c1cbcdc133653bac8a63fc704f7fe/zipline/utils/pool.py#L84-L116
25,775
quantopian/zipline
zipline/utils/cli.py
maybe_show_progress
def maybe_show_progress(it, show_progress, **kwargs): """Optionally show a progress bar for the given iterator. Parameters ---------- it : iterable The underlying iterator. show_progress : bool Should progress be shown. **kwargs Forwarded to the click progress bar. ...
python
def maybe_show_progress(it, show_progress, **kwargs): """Optionally show a progress bar for the given iterator. Parameters ---------- it : iterable The underlying iterator. show_progress : bool Should progress be shown. **kwargs Forwarded to the click progress bar. ...
[ "def", "maybe_show_progress", "(", "it", ",", "show_progress", ",", "*", "*", "kwargs", ")", ":", "if", "show_progress", ":", "return", "click", ".", "progressbar", "(", "it", ",", "*", "*", "kwargs", ")", "# context manager that just return `it` when we enter it"...
Optionally show a progress bar for the given iterator. Parameters ---------- it : iterable The underlying iterator. show_progress : bool Should progress be shown. **kwargs Forwarded to the click progress bar. Returns ------- itercontext : context manager ...
[ "Optionally", "show", "a", "progress", "bar", "for", "the", "given", "iterator", "." ]
77ad15e6dc4c1cbcdc133653bac8a63fc704f7fe
https://github.com/quantopian/zipline/blob/77ad15e6dc4c1cbcdc133653bac8a63fc704f7fe/zipline/utils/cli.py#L7-L36
25,776
quantopian/zipline
zipline/__main__.py
main
def main(extension, strict_extensions, default_extension, x): """Top level zipline entry point. """ # install a logbook handler before performing any other operations logbook.StderrHandler().push_application() create_args(x, zipline.extension_args) load_extensions( default_extension, ...
python
def main(extension, strict_extensions, default_extension, x): """Top level zipline entry point. """ # install a logbook handler before performing any other operations logbook.StderrHandler().push_application() create_args(x, zipline.extension_args) load_extensions( default_extension, ...
[ "def", "main", "(", "extension", ",", "strict_extensions", ",", "default_extension", ",", "x", ")", ":", "# install a logbook handler before performing any other operations", "logbook", ".", "StderrHandler", "(", ")", ".", "push_application", "(", ")", "create_args", "(...
Top level zipline entry point.
[ "Top", "level", "zipline", "entry", "point", "." ]
77ad15e6dc4c1cbcdc133653bac8a63fc704f7fe
https://github.com/quantopian/zipline/blob/77ad15e6dc4c1cbcdc133653bac8a63fc704f7fe/zipline/__main__.py#L49-L61
25,777
quantopian/zipline
zipline/__main__.py
ipython_only
def ipython_only(option): """Mark that an option should only be exposed in IPython. Parameters ---------- option : decorator A click.option decorator. Returns ------- ipython_only_dec : decorator A decorator that correctly applies the argument even when not using IP...
python
def ipython_only(option): """Mark that an option should only be exposed in IPython. Parameters ---------- option : decorator A click.option decorator. Returns ------- ipython_only_dec : decorator A decorator that correctly applies the argument even when not using IP...
[ "def", "ipython_only", "(", "option", ")", ":", "if", "__IPYTHON__", ":", "return", "option", "argname", "=", "extract_option_object", "(", "option", ")", ".", "name", "def", "d", "(", "f", ")", ":", "@", "wraps", "(", "f", ")", "def", "_", "(", "*",...
Mark that an option should only be exposed in IPython. Parameters ---------- option : decorator A click.option decorator. Returns ------- ipython_only_dec : decorator A decorator that correctly applies the argument even when not using IPython mode.
[ "Mark", "that", "an", "option", "should", "only", "be", "exposed", "in", "IPython", "." ]
77ad15e6dc4c1cbcdc133653bac8a63fc704f7fe
https://github.com/quantopian/zipline/blob/77ad15e6dc4c1cbcdc133653bac8a63fc704f7fe/zipline/__main__.py#L84-L109
25,778
quantopian/zipline
zipline/__main__.py
zipline_magic
def zipline_magic(line, cell=None): """The zipline IPython cell magic. """ load_extensions( default=True, extensions=[], strict=True, environ=os.environ, ) try: return run.main( # put our overrides at the start of the parameter list so that ...
python
def zipline_magic(line, cell=None): """The zipline IPython cell magic. """ load_extensions( default=True, extensions=[], strict=True, environ=os.environ, ) try: return run.main( # put our overrides at the start of the parameter list so that ...
[ "def", "zipline_magic", "(", "line", ",", "cell", "=", "None", ")", ":", "load_extensions", "(", "default", "=", "True", ",", "extensions", "=", "[", "]", ",", "strict", "=", "True", ",", "environ", "=", "os", ".", "environ", ",", ")", "try", ":", ...
The zipline IPython cell magic.
[ "The", "zipline", "IPython", "cell", "magic", "." ]
77ad15e6dc4c1cbcdc133653bac8a63fc704f7fe
https://github.com/quantopian/zipline/blob/77ad15e6dc4c1cbcdc133653bac8a63fc704f7fe/zipline/__main__.py#L287-L317
25,779
quantopian/zipline
zipline/__main__.py
ingest
def ingest(bundle, assets_version, show_progress): """Ingest the data for the given bundle. """ bundles_module.ingest( bundle, os.environ, pd.Timestamp.utcnow(), assets_version, show_progress, )
python
def ingest(bundle, assets_version, show_progress): """Ingest the data for the given bundle. """ bundles_module.ingest( bundle, os.environ, pd.Timestamp.utcnow(), assets_version, show_progress, )
[ "def", "ingest", "(", "bundle", ",", "assets_version", ",", "show_progress", ")", ":", "bundles_module", ".", "ingest", "(", "bundle", ",", "os", ".", "environ", ",", "pd", ".", "Timestamp", ".", "utcnow", "(", ")", ",", "assets_version", ",", "show_progre...
Ingest the data for the given bundle.
[ "Ingest", "the", "data", "for", "the", "given", "bundle", "." ]
77ad15e6dc4c1cbcdc133653bac8a63fc704f7fe
https://github.com/quantopian/zipline/blob/77ad15e6dc4c1cbcdc133653bac8a63fc704f7fe/zipline/__main__.py#L340-L349
25,780
quantopian/zipline
zipline/__main__.py
clean
def clean(bundle, before, after, keep_last): """Clean up data downloaded with the ingest command. """ bundles_module.clean( bundle, before, after, keep_last, )
python
def clean(bundle, before, after, keep_last): """Clean up data downloaded with the ingest command. """ bundles_module.clean( bundle, before, after, keep_last, )
[ "def", "clean", "(", "bundle", ",", "before", ",", "after", ",", "keep_last", ")", ":", "bundles_module", ".", "clean", "(", "bundle", ",", "before", ",", "after", ",", "keep_last", ",", ")" ]
Clean up data downloaded with the ingest command.
[ "Clean", "up", "data", "downloaded", "with", "the", "ingest", "command", "." ]
77ad15e6dc4c1cbcdc133653bac8a63fc704f7fe
https://github.com/quantopian/zipline/blob/77ad15e6dc4c1cbcdc133653bac8a63fc704f7fe/zipline/__main__.py#L383-L391
25,781
quantopian/zipline
zipline/__main__.py
bundles
def bundles(): """List all of the available data bundles. """ for bundle in sorted(bundles_module.bundles.keys()): if bundle.startswith('.'): # hide the test data continue try: ingestions = list( map(text_type, bundles_module.ingestions_for...
python
def bundles(): """List all of the available data bundles. """ for bundle in sorted(bundles_module.bundles.keys()): if bundle.startswith('.'): # hide the test data continue try: ingestions = list( map(text_type, bundles_module.ingestions_for...
[ "def", "bundles", "(", ")", ":", "for", "bundle", "in", "sorted", "(", "bundles_module", ".", "bundles", ".", "keys", "(", ")", ")", ":", "if", "bundle", ".", "startswith", "(", "'.'", ")", ":", "# hide the test data", "continue", "try", ":", "ingestions...
List all of the available data bundles.
[ "List", "all", "of", "the", "available", "data", "bundles", "." ]
77ad15e6dc4c1cbcdc133653bac8a63fc704f7fe
https://github.com/quantopian/zipline/blob/77ad15e6dc4c1cbcdc133653bac8a63fc704f7fe/zipline/__main__.py#L395-L415
25,782
quantopian/zipline
zipline/pipeline/filters/filter.py
binary_operator
def binary_operator(op): """ Factory function for making binary operator methods on a Filter subclass. Returns a function "binary_operator" suitable for implementing functions like __and__ or __or__. """ # When combining a Filter with a NumericalExpression, we use this # attrgetter instance...
python
def binary_operator(op): """ Factory function for making binary operator methods on a Filter subclass. Returns a function "binary_operator" suitable for implementing functions like __and__ or __or__. """ # When combining a Filter with a NumericalExpression, we use this # attrgetter instance...
[ "def", "binary_operator", "(", "op", ")", ":", "# When combining a Filter with a NumericalExpression, we use this", "# attrgetter instance to defer to the commuted interpretation of the", "# NumericalExpression operator.", "commuted_method_getter", "=", "attrgetter", "(", "method_name_for_...
Factory function for making binary operator methods on a Filter subclass. Returns a function "binary_operator" suitable for implementing functions like __and__ or __or__.
[ "Factory", "function", "for", "making", "binary", "operator", "methods", "on", "a", "Filter", "subclass", "." ]
77ad15e6dc4c1cbcdc133653bac8a63fc704f7fe
https://github.com/quantopian/zipline/blob/77ad15e6dc4c1cbcdc133653bac8a63fc704f7fe/zipline/pipeline/filters/filter.py#L62-L112
25,783
quantopian/zipline
zipline/pipeline/filters/filter.py
unary_operator
def unary_operator(op): """ Factory function for making unary operator methods for Filters. """ valid_ops = {'~'} if op not in valid_ops: raise ValueError("Invalid unary operator %s." % op) def unary_operator(self): # This can't be hoisted up a scope because the types returned b...
python
def unary_operator(op): """ Factory function for making unary operator methods for Filters. """ valid_ops = {'~'} if op not in valid_ops: raise ValueError("Invalid unary operator %s." % op) def unary_operator(self): # This can't be hoisted up a scope because the types returned b...
[ "def", "unary_operator", "(", "op", ")", ":", "valid_ops", "=", "{", "'~'", "}", "if", "op", "not", "in", "valid_ops", ":", "raise", "ValueError", "(", "\"Invalid unary operator %s.\"", "%", "op", ")", "def", "unary_operator", "(", "self", ")", ":", "# Thi...
Factory function for making unary operator methods for Filters.
[ "Factory", "function", "for", "making", "unary", "operator", "methods", "for", "Filters", "." ]
77ad15e6dc4c1cbcdc133653bac8a63fc704f7fe
https://github.com/quantopian/zipline/blob/77ad15e6dc4c1cbcdc133653bac8a63fc704f7fe/zipline/pipeline/filters/filter.py#L115-L136
25,784
quantopian/zipline
zipline/pipeline/filters/filter.py
NumExprFilter.create
def create(cls, expr, binds): """ Helper for creating new NumExprFactors. This is just a wrapper around NumericalExpression.__new__ that always forwards `bool` as the dtype, since Filters can only be of boolean dtype. """ return cls(expr=expr, binds=binds, dtype=...
python
def create(cls, expr, binds): """ Helper for creating new NumExprFactors. This is just a wrapper around NumericalExpression.__new__ that always forwards `bool` as the dtype, since Filters can only be of boolean dtype. """ return cls(expr=expr, binds=binds, dtype=...
[ "def", "create", "(", "cls", ",", "expr", ",", "binds", ")", ":", "return", "cls", "(", "expr", "=", "expr", ",", "binds", "=", "binds", ",", "dtype", "=", "bool_dtype", ")" ]
Helper for creating new NumExprFactors. This is just a wrapper around NumericalExpression.__new__ that always forwards `bool` as the dtype, since Filters can only be of boolean dtype.
[ "Helper", "for", "creating", "new", "NumExprFactors", "." ]
77ad15e6dc4c1cbcdc133653bac8a63fc704f7fe
https://github.com/quantopian/zipline/blob/77ad15e6dc4c1cbcdc133653bac8a63fc704f7fe/zipline/pipeline/filters/filter.py#L237-L245
25,785
quantopian/zipline
zipline/pipeline/filters/filter.py
NumExprFilter._compute
def _compute(self, arrays, dates, assets, mask): """ Compute our result with numexpr, then re-apply `mask`. """ return super(NumExprFilter, self)._compute( arrays, dates, assets, mask, ) & mask
python
def _compute(self, arrays, dates, assets, mask): """ Compute our result with numexpr, then re-apply `mask`. """ return super(NumExprFilter, self)._compute( arrays, dates, assets, mask, ) & mask
[ "def", "_compute", "(", "self", ",", "arrays", ",", "dates", ",", "assets", ",", "mask", ")", ":", "return", "super", "(", "NumExprFilter", ",", "self", ")", ".", "_compute", "(", "arrays", ",", "dates", ",", "assets", ",", "mask", ",", ")", "&", "...
Compute our result with numexpr, then re-apply `mask`.
[ "Compute", "our", "result", "with", "numexpr", "then", "re", "-", "apply", "mask", "." ]
77ad15e6dc4c1cbcdc133653bac8a63fc704f7fe
https://github.com/quantopian/zipline/blob/77ad15e6dc4c1cbcdc133653bac8a63fc704f7fe/zipline/pipeline/filters/filter.py#L247-L256
25,786
quantopian/zipline
zipline/pipeline/filters/filter.py
PercentileFilter._validate
def _validate(self): """ Ensure that our percentile bounds are well-formed. """ if not 0.0 <= self._min_percentile < self._max_percentile <= 100.0: raise BadPercentileBounds( min_percentile=self._min_percentile, max_percentile=self._max_percent...
python
def _validate(self): """ Ensure that our percentile bounds are well-formed. """ if not 0.0 <= self._min_percentile < self._max_percentile <= 100.0: raise BadPercentileBounds( min_percentile=self._min_percentile, max_percentile=self._max_percent...
[ "def", "_validate", "(", "self", ")", ":", "if", "not", "0.0", "<=", "self", ".", "_min_percentile", "<", "self", ".", "_max_percentile", "<=", "100.0", ":", "raise", "BadPercentileBounds", "(", "min_percentile", "=", "self", ".", "_min_percentile", ",", "ma...
Ensure that our percentile bounds are well-formed.
[ "Ensure", "that", "our", "percentile", "bounds", "are", "well", "-", "formed", "." ]
77ad15e6dc4c1cbcdc133653bac8a63fc704f7fe
https://github.com/quantopian/zipline/blob/77ad15e6dc4c1cbcdc133653bac8a63fc704f7fe/zipline/pipeline/filters/filter.py#L344-L354
25,787
quantopian/zipline
zipline/pipeline/filters/filter.py
PercentileFilter._compute
def _compute(self, arrays, dates, assets, mask): """ For each row in the input, compute a mask of all values falling between the given percentiles. """ # TODO: Review whether there's a better way of handling small numbers # of columns. data = arrays[0].copy().asty...
python
def _compute(self, arrays, dates, assets, mask): """ For each row in the input, compute a mask of all values falling between the given percentiles. """ # TODO: Review whether there's a better way of handling small numbers # of columns. data = arrays[0].copy().asty...
[ "def", "_compute", "(", "self", ",", "arrays", ",", "dates", ",", "assets", ",", "mask", ")", ":", "# TODO: Review whether there's a better way of handling small numbers", "# of columns.", "data", "=", "arrays", "[", "0", "]", ".", "copy", "(", ")", ".", "astype...
For each row in the input, compute a mask of all values falling between the given percentiles.
[ "For", "each", "row", "in", "the", "input", "compute", "a", "mask", "of", "all", "values", "falling", "between", "the", "given", "percentiles", "." ]
77ad15e6dc4c1cbcdc133653bac8a63fc704f7fe
https://github.com/quantopian/zipline/blob/77ad15e6dc4c1cbcdc133653bac8a63fc704f7fe/zipline/pipeline/filters/filter.py#L356-L382
25,788
quantopian/zipline
zipline/data/treasuries.py
parse_treasury_csv_column
def parse_treasury_csv_column(column): """ Parse a treasury CSV column into a more human-readable format. Columns start with 'RIFLGFC', followed by Y or M (year or month), followed by a two-digit number signifying number of years/months, followed by _N.B. We only care about the middle two entries, ...
python
def parse_treasury_csv_column(column): """ Parse a treasury CSV column into a more human-readable format. Columns start with 'RIFLGFC', followed by Y or M (year or month), followed by a two-digit number signifying number of years/months, followed by _N.B. We only care about the middle two entries, ...
[ "def", "parse_treasury_csv_column", "(", "column", ")", ":", "column_re", "=", "re", ".", "compile", "(", "r\"^(?P<prefix>RIFLGFC)\"", "\"(?P<unit>[YM])\"", "\"(?P<periods>[0-9]{2})\"", "\"(?P<suffix>_N.B)$\"", ")", "match", "=", "column_re", ".", "match", "(", "column"...
Parse a treasury CSV column into a more human-readable format. Columns start with 'RIFLGFC', followed by Y or M (year or month), followed by a two-digit number signifying number of years/months, followed by _N.B. We only care about the middle two entries, which we turn into a string like 3month or 30ye...
[ "Parse", "a", "treasury", "CSV", "column", "into", "a", "more", "human", "-", "readable", "format", "." ]
77ad15e6dc4c1cbcdc133653bac8a63fc704f7fe
https://github.com/quantopian/zipline/blob/77ad15e6dc4c1cbcdc133653bac8a63fc704f7fe/zipline/data/treasuries.py#L25-L47
25,789
quantopian/zipline
zipline/data/treasuries.py
get_daily_10yr_treasury_data
def get_daily_10yr_treasury_data(): """Download daily 10 year treasury rates from the Federal Reserve and return a pandas.Series.""" url = "https://www.federalreserve.gov/datadownload/Output.aspx?rel=H15" \ "&series=bcb44e57fb57efbe90002369321bfb3f&lastObs=&from=&to=" \ "&filetype=csv&la...
python
def get_daily_10yr_treasury_data(): """Download daily 10 year treasury rates from the Federal Reserve and return a pandas.Series.""" url = "https://www.federalreserve.gov/datadownload/Output.aspx?rel=H15" \ "&series=bcb44e57fb57efbe90002369321bfb3f&lastObs=&from=&to=" \ "&filetype=csv&la...
[ "def", "get_daily_10yr_treasury_data", "(", ")", ":", "url", "=", "\"https://www.federalreserve.gov/datadownload/Output.aspx?rel=H15\"", "\"&series=bcb44e57fb57efbe90002369321bfb3f&lastObs=&from=&to=\"", "\"&filetype=csv&label=include&layout=seriescolumn\"", "return", "pd", ".", "read_csv"...
Download daily 10 year treasury rates from the Federal Reserve and return a pandas.Series.
[ "Download", "daily", "10", "year", "treasury", "rates", "from", "the", "Federal", "Reserve", "and", "return", "a", "pandas", ".", "Series", "." ]
77ad15e6dc4c1cbcdc133653bac8a63fc704f7fe
https://github.com/quantopian/zipline/blob/77ad15e6dc4c1cbcdc133653bac8a63fc704f7fe/zipline/data/treasuries.py#L93-L101
25,790
quantopian/zipline
zipline/data/minute_bars.py
_sid_subdir_path
def _sid_subdir_path(sid): """ Format subdir path to limit the number directories in any given subdirectory to 100. The number in each directory is designed to support at least 100000 equities. Parameters ---------- sid : int Asset identifier. Returns ------- out :...
python
def _sid_subdir_path(sid): """ Format subdir path to limit the number directories in any given subdirectory to 100. The number in each directory is designed to support at least 100000 equities. Parameters ---------- sid : int Asset identifier. Returns ------- out :...
[ "def", "_sid_subdir_path", "(", "sid", ")", ":", "padded_sid", "=", "format", "(", "sid", ",", "'06'", ")", "return", "os", ".", "path", ".", "join", "(", "# subdir 1 00/XX", "padded_sid", "[", "0", ":", "2", "]", ",", "# subdir 2 XX/00", "padded_sid", "...
Format subdir path to limit the number directories in any given subdirectory to 100. The number in each directory is designed to support at least 100000 equities. Parameters ---------- sid : int Asset identifier. Returns ------- out : string A path for the bcolz ro...
[ "Format", "subdir", "path", "to", "limit", "the", "number", "directories", "in", "any", "given", "subdirectory", "to", "100", "." ]
77ad15e6dc4c1cbcdc133653bac8a63fc704f7fe
https://github.com/quantopian/zipline/blob/77ad15e6dc4c1cbcdc133653bac8a63fc704f7fe/zipline/data/minute_bars.py#L85-L113
25,791
quantopian/zipline
zipline/data/minute_bars.py
convert_cols
def convert_cols(cols, scale_factor, sid, invalid_data_behavior): """Adapt OHLCV columns into uint32 columns. Parameters ---------- cols : dict A dict mapping each column name (open, high, low, close, volume) to a float column to convert to uint32. scale_factor : int Factor ...
python
def convert_cols(cols, scale_factor, sid, invalid_data_behavior): """Adapt OHLCV columns into uint32 columns. Parameters ---------- cols : dict A dict mapping each column name (open, high, low, close, volume) to a float column to convert to uint32. scale_factor : int Factor ...
[ "def", "convert_cols", "(", "cols", ",", "scale_factor", ",", "sid", ",", "invalid_data_behavior", ")", ":", "scaled_opens", "=", "(", "np", ".", "nan_to_num", "(", "cols", "[", "'open'", "]", ")", "*", "scale_factor", ")", ".", "round", "(", ")", "scale...
Adapt OHLCV columns into uint32 columns. Parameters ---------- cols : dict A dict mapping each column name (open, high, low, close, volume) to a float column to convert to uint32. scale_factor : int Factor to use to scale float values before converting to uint32. sid : int ...
[ "Adapt", "OHLCV", "columns", "into", "uint32", "columns", "." ]
77ad15e6dc4c1cbcdc133653bac8a63fc704f7fe
https://github.com/quantopian/zipline/blob/77ad15e6dc4c1cbcdc133653bac8a63fc704f7fe/zipline/data/minute_bars.py#L116-L180
25,792
quantopian/zipline
zipline/data/minute_bars.py
BcolzMinuteBarMetadata.write
def write(self, rootdir): """ Write the metadata to a JSON file in the rootdir. Values contained in the metadata are: version : int The value of FORMAT_VERSION of this class. ohlc_ratio : int The default ratio by which to multiply the pricing data to ...
python
def write(self, rootdir): """ Write the metadata to a JSON file in the rootdir. Values contained in the metadata are: version : int The value of FORMAT_VERSION of this class. ohlc_ratio : int The default ratio by which to multiply the pricing data to ...
[ "def", "write", "(", "self", ",", "rootdir", ")", ":", "calendar", "=", "self", ".", "calendar", "slicer", "=", "calendar", ".", "schedule", ".", "index", ".", "slice_indexer", "(", "self", ".", "start_session", ",", "self", ".", "end_session", ",", ")",...
Write the metadata to a JSON file in the rootdir. Values contained in the metadata are: version : int The value of FORMAT_VERSION of this class. ohlc_ratio : int The default ratio by which to multiply the pricing data to convert the floats from floats to an ...
[ "Write", "the", "metadata", "to", "a", "JSON", "file", "in", "the", "rootdir", "." ]
77ad15e6dc4c1cbcdc133653bac8a63fc704f7fe
https://github.com/quantopian/zipline/blob/77ad15e6dc4c1cbcdc133653bac8a63fc704f7fe/zipline/data/minute_bars.py#L280-L349
25,793
quantopian/zipline
zipline/data/minute_bars.py
BcolzMinuteBarWriter.open
def open(cls, rootdir, end_session=None): """ Open an existing ``rootdir`` for writing. Parameters ---------- end_session : Timestamp (optional) When appending, the intended new ``end_session``. """ metadata = BcolzMinuteBarMetadata.read(rootdir) ...
python
def open(cls, rootdir, end_session=None): """ Open an existing ``rootdir`` for writing. Parameters ---------- end_session : Timestamp (optional) When appending, the intended new ``end_session``. """ metadata = BcolzMinuteBarMetadata.read(rootdir) ...
[ "def", "open", "(", "cls", ",", "rootdir", ",", "end_session", "=", "None", ")", ":", "metadata", "=", "BcolzMinuteBarMetadata", ".", "read", "(", "rootdir", ")", "return", "BcolzMinuteBarWriter", "(", "rootdir", ",", "metadata", ".", "calendar", ",", "metad...
Open an existing ``rootdir`` for writing. Parameters ---------- end_session : Timestamp (optional) When appending, the intended new ``end_session``.
[ "Open", "an", "existing", "rootdir", "for", "writing", "." ]
77ad15e6dc4c1cbcdc133653bac8a63fc704f7fe
https://github.com/quantopian/zipline/blob/77ad15e6dc4c1cbcdc133653bac8a63fc704f7fe/zipline/data/minute_bars.py#L482-L501
25,794
quantopian/zipline
zipline/data/minute_bars.py
BcolzMinuteBarWriter._init_ctable
def _init_ctable(self, path): """ Create empty ctable for given path. Parameters ---------- path : string The path to rootdir of the new ctable. """ # Only create the containing subdir on creation. # This is not to be confused with the `.bcolz...
python
def _init_ctable(self, path): """ Create empty ctable for given path. Parameters ---------- path : string The path to rootdir of the new ctable. """ # Only create the containing subdir on creation. # This is not to be confused with the `.bcolz...
[ "def", "_init_ctable", "(", "self", ",", "path", ")", ":", "# Only create the containing subdir on creation.", "# This is not to be confused with the `.bcolz` directory, but is the", "# directory up one level from the `.bcolz` directories.", "sid_containing_dirname", "=", "os", ".", "p...
Create empty ctable for given path. Parameters ---------- path : string The path to rootdir of the new ctable.
[ "Create", "empty", "ctable", "for", "given", "path", "." ]
77ad15e6dc4c1cbcdc133653bac8a63fc704f7fe
https://github.com/quantopian/zipline/blob/77ad15e6dc4c1cbcdc133653bac8a63fc704f7fe/zipline/data/minute_bars.py#L560-L597
25,795
quantopian/zipline
zipline/data/minute_bars.py
BcolzMinuteBarWriter._ensure_ctable
def _ensure_ctable(self, sid): """Ensure that a ctable exists for ``sid``, then return it.""" sidpath = self.sidpath(sid) if not os.path.exists(sidpath): return self._init_ctable(sidpath) return bcolz.ctable(rootdir=sidpath, mode='a')
python
def _ensure_ctable(self, sid): """Ensure that a ctable exists for ``sid``, then return it.""" sidpath = self.sidpath(sid) if not os.path.exists(sidpath): return self._init_ctable(sidpath) return bcolz.ctable(rootdir=sidpath, mode='a')
[ "def", "_ensure_ctable", "(", "self", ",", "sid", ")", ":", "sidpath", "=", "self", ".", "sidpath", "(", "sid", ")", "if", "not", "os", ".", "path", ".", "exists", "(", "sidpath", ")", ":", "return", "self", ".", "_init_ctable", "(", "sidpath", ")", ...
Ensure that a ctable exists for ``sid``, then return it.
[ "Ensure", "that", "a", "ctable", "exists", "for", "sid", "then", "return", "it", "." ]
77ad15e6dc4c1cbcdc133653bac8a63fc704f7fe
https://github.com/quantopian/zipline/blob/77ad15e6dc4c1cbcdc133653bac8a63fc704f7fe/zipline/data/minute_bars.py#L599-L604
25,796
quantopian/zipline
zipline/data/minute_bars.py
BcolzMinuteBarWriter.pad
def pad(self, sid, date): """ Fill sid container with empty data through the specified date. If the last recorded trade is not at the close, then that day will be padded with zeros until its close. Any day after that (up to and including the specified date) will be padded with `...
python
def pad(self, sid, date): """ Fill sid container with empty data through the specified date. If the last recorded trade is not at the close, then that day will be padded with zeros until its close. Any day after that (up to and including the specified date) will be padded with `...
[ "def", "pad", "(", "self", ",", "sid", ",", "date", ")", ":", "table", "=", "self", ".", "_ensure_ctable", "(", "sid", ")", "last_date", "=", "self", ".", "last_date_in_output_for_sid", "(", "sid", ")", "tds", "=", "self", ".", "_session_labels", "if", ...
Fill sid container with empty data through the specified date. If the last recorded trade is not at the close, then that day will be padded with zeros until its close. Any day after that (up to and including the specified date) will be padded with `minute_per_day` worth of zeros ...
[ "Fill", "sid", "container", "with", "empty", "data", "through", "the", "specified", "date", "." ]
77ad15e6dc4c1cbcdc133653bac8a63fc704f7fe
https://github.com/quantopian/zipline/blob/77ad15e6dc4c1cbcdc133653bac8a63fc704f7fe/zipline/data/minute_bars.py#L618-L659
25,797
quantopian/zipline
zipline/data/minute_bars.py
BcolzMinuteBarWriter.set_sid_attrs
def set_sid_attrs(self, sid, **kwargs): """Write all the supplied kwargs as attributes of the sid's file. """ table = self._ensure_ctable(sid) for k, v in kwargs.items(): table.attrs[k] = v
python
def set_sid_attrs(self, sid, **kwargs): """Write all the supplied kwargs as attributes of the sid's file. """ table = self._ensure_ctable(sid) for k, v in kwargs.items(): table.attrs[k] = v
[ "def", "set_sid_attrs", "(", "self", ",", "sid", ",", "*", "*", "kwargs", ")", ":", "table", "=", "self", ".", "_ensure_ctable", "(", "sid", ")", "for", "k", ",", "v", "in", "kwargs", ".", "items", "(", ")", ":", "table", ".", "attrs", "[", "k", ...
Write all the supplied kwargs as attributes of the sid's file.
[ "Write", "all", "the", "supplied", "kwargs", "as", "attributes", "of", "the", "sid", "s", "file", "." ]
77ad15e6dc4c1cbcdc133653bac8a63fc704f7fe
https://github.com/quantopian/zipline/blob/77ad15e6dc4c1cbcdc133653bac8a63fc704f7fe/zipline/data/minute_bars.py#L661-L666
25,798
quantopian/zipline
zipline/data/minute_bars.py
BcolzMinuteBarWriter.write
def write(self, data, show_progress=False, invalid_data_behavior='warn'): """Write a stream of minute data. Parameters ---------- data : iterable[(int, pd.DataFrame)] The data to write. Each element should be a tuple of sid, data where data has the following form...
python
def write(self, data, show_progress=False, invalid_data_behavior='warn'): """Write a stream of minute data. Parameters ---------- data : iterable[(int, pd.DataFrame)] The data to write. Each element should be a tuple of sid, data where data has the following form...
[ "def", "write", "(", "self", ",", "data", ",", "show_progress", "=", "False", ",", "invalid_data_behavior", "=", "'warn'", ")", ":", "ctx", "=", "maybe_show_progress", "(", "data", ",", "show_progress", "=", "show_progress", ",", "item_show_func", "=", "lambda...
Write a stream of minute data. Parameters ---------- data : iterable[(int, pd.DataFrame)] The data to write. Each element should be a tuple of sid, data where data has the following format: columns : ('open', 'high', 'low', 'close', 'volume') ...
[ "Write", "a", "stream", "of", "minute", "data", "." ]
77ad15e6dc4c1cbcdc133653bac8a63fc704f7fe
https://github.com/quantopian/zipline/blob/77ad15e6dc4c1cbcdc133653bac8a63fc704f7fe/zipline/data/minute_bars.py#L668-L697
25,799
quantopian/zipline
zipline/data/minute_bars.py
BcolzMinuteBarWriter.data_len_for_day
def data_len_for_day(self, day): """ Return the number of data points up to and including the provided day. """ day_ix = self._session_labels.get_loc(day) # Add one to the 0-indexed day_ix to get the number of days. num_days = day_ix + 1 return num_days * ...
python
def data_len_for_day(self, day): """ Return the number of data points up to and including the provided day. """ day_ix = self._session_labels.get_loc(day) # Add one to the 0-indexed day_ix to get the number of days. num_days = day_ix + 1 return num_days * ...
[ "def", "data_len_for_day", "(", "self", ",", "day", ")", ":", "day_ix", "=", "self", ".", "_session_labels", ".", "get_loc", "(", "day", ")", "# Add one to the 0-indexed day_ix to get the number of days.", "num_days", "=", "day_ix", "+", "1", "return", "num_days", ...
Return the number of data points up to and including the provided day.
[ "Return", "the", "number", "of", "data", "points", "up", "to", "and", "including", "the", "provided", "day", "." ]
77ad15e6dc4c1cbcdc133653bac8a63fc704f7fe
https://github.com/quantopian/zipline/blob/77ad15e6dc4c1cbcdc133653bac8a63fc704f7fe/zipline/data/minute_bars.py#L846-L854