partition
stringclasses
3 values
func_name
stringlengths
1
134
docstring
stringlengths
1
46.9k
path
stringlengths
4
223
original_string
stringlengths
75
104k
code
stringlengths
75
104k
docstring_tokens
listlengths
1
1.97k
repo
stringlengths
7
55
language
stringclasses
1 value
url
stringlengths
87
315
code_tokens
listlengths
19
28.4k
sha
stringlengths
40
40
train
densenet121
r"""Densenet-121 model from `"Densely Connected Convolutional Networks" <https://arxiv.org/pdf/1608.06993.pdf>`
pretrainedmodels/models/torchvision_models.py
def densenet121(num_classes=1000, pretrained='imagenet'): r"""Densenet-121 model from `"Densely Connected Convolutional Networks" <https://arxiv.org/pdf/1608.06993.pdf>` """ model = models.densenet121(pretrained=False) if pretrained is not None: settings = pretrained_settings['densenet121'][...
def densenet121(num_classes=1000, pretrained='imagenet'): r"""Densenet-121 model from `"Densely Connected Convolutional Networks" <https://arxiv.org/pdf/1608.06993.pdf>` """ model = models.densenet121(pretrained=False) if pretrained is not None: settings = pretrained_settings['densenet121'][...
[ "r", "Densenet", "-", "121", "model", "from", "Densely", "Connected", "Convolutional", "Networks", "<https", ":", "//", "arxiv", ".", "org", "/", "pdf", "/", "1608", ".", "06993", ".", "pdf", ">" ]
Cadene/pretrained-models.pytorch
python
https://github.com/Cadene/pretrained-models.pytorch/blob/021d97897c9aa76ec759deff43d341c4fd45d7ba/pretrainedmodels/models/torchvision_models.py#L205-L214
[ "def", "densenet121", "(", "num_classes", "=", "1000", ",", "pretrained", "=", "'imagenet'", ")", ":", "model", "=", "models", ".", "densenet121", "(", "pretrained", "=", "False", ")", "if", "pretrained", "is", "not", "None", ":", "settings", "=", "pretrai...
021d97897c9aa76ec759deff43d341c4fd45d7ba
train
inceptionv3
r"""Inception v3 model architecture from `"Rethinking the Inception Architecture for Computer Vision" <http://arxiv.org/abs/1512.00567>`_.
pretrainedmodels/models/torchvision_models.py
def inceptionv3(num_classes=1000, pretrained='imagenet'): r"""Inception v3 model architecture from `"Rethinking the Inception Architecture for Computer Vision" <http://arxiv.org/abs/1512.00567>`_. """ model = models.inception_v3(pretrained=False) if pretrained is not None: settings = pretrai...
def inceptionv3(num_classes=1000, pretrained='imagenet'): r"""Inception v3 model architecture from `"Rethinking the Inception Architecture for Computer Vision" <http://arxiv.org/abs/1512.00567>`_. """ model = models.inception_v3(pretrained=False) if pretrained is not None: settings = pretrai...
[ "r", "Inception", "v3", "model", "architecture", "from", "Rethinking", "the", "Inception", "Architecture", "for", "Computer", "Vision", "<http", ":", "//", "arxiv", ".", "org", "/", "abs", "/", "1512", ".", "00567", ">", "_", "." ]
Cadene/pretrained-models.pytorch
python
https://github.com/Cadene/pretrained-models.pytorch/blob/021d97897c9aa76ec759deff43d341c4fd45d7ba/pretrainedmodels/models/torchvision_models.py#L252-L309
[ "def", "inceptionv3", "(", "num_classes", "=", "1000", ",", "pretrained", "=", "'imagenet'", ")", ":", "model", "=", "models", ".", "inception_v3", "(", "pretrained", "=", "False", ")", "if", "pretrained", "is", "not", "None", ":", "settings", "=", "pretra...
021d97897c9aa76ec759deff43d341c4fd45d7ba
train
resnet50
Constructs a ResNet-50 model.
pretrainedmodels/models/torchvision_models.py
def resnet50(num_classes=1000, pretrained='imagenet'): """Constructs a ResNet-50 model. """ model = models.resnet50(pretrained=False) if pretrained is not None: settings = pretrained_settings['resnet50'][pretrained] model = load_pretrained(model, num_classes, settings) model = modify...
def resnet50(num_classes=1000, pretrained='imagenet'): """Constructs a ResNet-50 model. """ model = models.resnet50(pretrained=False) if pretrained is not None: settings = pretrained_settings['resnet50'][pretrained] model = load_pretrained(model, num_classes, settings) model = modify...
[ "Constructs", "a", "ResNet", "-", "50", "model", "." ]
Cadene/pretrained-models.pytorch
python
https://github.com/Cadene/pretrained-models.pytorch/blob/021d97897c9aa76ec759deff43d341c4fd45d7ba/pretrainedmodels/models/torchvision_models.py#L368-L376
[ "def", "resnet50", "(", "num_classes", "=", "1000", ",", "pretrained", "=", "'imagenet'", ")", ":", "model", "=", "models", ".", "resnet50", "(", "pretrained", "=", "False", ")", "if", "pretrained", "is", "not", "None", ":", "settings", "=", "pretrained_se...
021d97897c9aa76ec759deff43d341c4fd45d7ba
train
squeezenet1_0
r"""SqueezeNet model architecture from the `"SqueezeNet: AlexNet-level accuracy with 50x fewer parameters and <0.5MB model size" <https://arxiv.org/abs/1602.07360>`_ paper.
pretrainedmodels/models/torchvision_models.py
def squeezenet1_0(num_classes=1000, pretrained='imagenet'): r"""SqueezeNet model architecture from the `"SqueezeNet: AlexNet-level accuracy with 50x fewer parameters and <0.5MB model size" <https://arxiv.org/abs/1602.07360>`_ paper. """ model = models.squeezenet1_0(pretrained=False) if pretraine...
def squeezenet1_0(num_classes=1000, pretrained='imagenet'): r"""SqueezeNet model architecture from the `"SqueezeNet: AlexNet-level accuracy with 50x fewer parameters and <0.5MB model size" <https://arxiv.org/abs/1602.07360>`_ paper. """ model = models.squeezenet1_0(pretrained=False) if pretraine...
[ "r", "SqueezeNet", "model", "architecture", "from", "the", "SqueezeNet", ":", "AlexNet", "-", "level", "accuracy", "with", "50x", "fewer", "parameters", "and", "<0", ".", "5MB", "model", "size", "<https", ":", "//", "arxiv", ".", "org", "/", "abs", "/", ...
Cadene/pretrained-models.pytorch
python
https://github.com/Cadene/pretrained-models.pytorch/blob/021d97897c9aa76ec759deff43d341c4fd45d7ba/pretrainedmodels/models/torchvision_models.py#L428-L438
[ "def", "squeezenet1_0", "(", "num_classes", "=", "1000", ",", "pretrained", "=", "'imagenet'", ")", ":", "model", "=", "models", ".", "squeezenet1_0", "(", "pretrained", "=", "False", ")", "if", "pretrained", "is", "not", "None", ":", "settings", "=", "pre...
021d97897c9aa76ec759deff43d341c4fd45d7ba
train
vgg11
VGG 11-layer model (configuration "A")
pretrainedmodels/models/torchvision_models.py
def vgg11(num_classes=1000, pretrained='imagenet'): """VGG 11-layer model (configuration "A") """ model = models.vgg11(pretrained=False) if pretrained is not None: settings = pretrained_settings['vgg11'][pretrained] model = load_pretrained(model, num_classes, settings) model = modify...
def vgg11(num_classes=1000, pretrained='imagenet'): """VGG 11-layer model (configuration "A") """ model = models.vgg11(pretrained=False) if pretrained is not None: settings = pretrained_settings['vgg11'][pretrained] model = load_pretrained(model, num_classes, settings) model = modify...
[ "VGG", "11", "-", "layer", "model", "(", "configuration", "A", ")" ]
Cadene/pretrained-models.pytorch
python
https://github.com/Cadene/pretrained-models.pytorch/blob/021d97897c9aa76ec759deff43d341c4fd45d7ba/pretrainedmodels/models/torchvision_models.py#L495-L503
[ "def", "vgg11", "(", "num_classes", "=", "1000", ",", "pretrained", "=", "'imagenet'", ")", ":", "model", "=", "models", ".", "vgg11", "(", "pretrained", "=", "False", ")", "if", "pretrained", "is", "not", "None", ":", "settings", "=", "pretrained_settings...
021d97897c9aa76ec759deff43d341c4fd45d7ba
train
adjust_learning_rate
Sets the learning rate to the initial LR decayed by 10 every 30 epochs
examples/imagenet_eval.py
def adjust_learning_rate(optimizer, epoch): """Sets the learning rate to the initial LR decayed by 10 every 30 epochs""" lr = args.lr * (0.1 ** (epoch // 30)) for param_group in optimizer.param_groups: param_group['lr'] = lr
def adjust_learning_rate(optimizer, epoch): """Sets the learning rate to the initial LR decayed by 10 every 30 epochs""" lr = args.lr * (0.1 ** (epoch // 30)) for param_group in optimizer.param_groups: param_group['lr'] = lr
[ "Sets", "the", "learning", "rate", "to", "the", "initial", "LR", "decayed", "by", "10", "every", "30", "epochs" ]
Cadene/pretrained-models.pytorch
python
https://github.com/Cadene/pretrained-models.pytorch/blob/021d97897c9aa76ec759deff43d341c4fd45d7ba/examples/imagenet_eval.py#L280-L284
[ "def", "adjust_learning_rate", "(", "optimizer", ",", "epoch", ")", ":", "lr", "=", "args", ".", "lr", "*", "(", "0.1", "**", "(", "epoch", "//", "30", ")", ")", "for", "param_group", "in", "optimizer", ".", "param_groups", ":", "param_group", "[", "'l...
021d97897c9aa76ec759deff43d341c4fd45d7ba
train
nasnetalarge
r"""NASNetALarge model architecture from the `"NASNet" <https://arxiv.org/abs/1707.07012>`_ paper.
pretrainedmodels/models/nasnet.py
def nasnetalarge(num_classes=1001, pretrained='imagenet'): r"""NASNetALarge model architecture from the `"NASNet" <https://arxiv.org/abs/1707.07012>`_ paper. """ if pretrained: settings = pretrained_settings['nasnetalarge'][pretrained] assert num_classes == settings['num_classes'], \ ...
def nasnetalarge(num_classes=1001, pretrained='imagenet'): r"""NASNetALarge model architecture from the `"NASNet" <https://arxiv.org/abs/1707.07012>`_ paper. """ if pretrained: settings = pretrained_settings['nasnetalarge'][pretrained] assert num_classes == settings['num_classes'], \ ...
[ "r", "NASNetALarge", "model", "architecture", "from", "the", "NASNet", "<https", ":", "//", "arxiv", ".", "org", "/", "abs", "/", "1707", ".", "07012", ">", "_", "paper", "." ]
Cadene/pretrained-models.pytorch
python
https://github.com/Cadene/pretrained-models.pytorch/blob/021d97897c9aa76ec759deff43d341c4fd45d7ba/pretrainedmodels/models/nasnet.py#L608-L635
[ "def", "nasnetalarge", "(", "num_classes", "=", "1001", ",", "pretrained", "=", "'imagenet'", ")", ":", "if", "pretrained", ":", "settings", "=", "pretrained_settings", "[", "'nasnetalarge'", "]", "[", "pretrained", "]", "assert", "num_classes", "==", "settings"...
021d97897c9aa76ec759deff43d341c4fd45d7ba
train
adaptive_avgmax_pool2d
Selectable global pooling function with dynamic input kernel size
pretrainedmodels/models/dpn.py
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): """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...
[ "Selectable", "global", "pooling", "function", "with", "dynamic", "input", "kernel", "size" ]
Cadene/pretrained-models.pytorch
python
https://github.com/Cadene/pretrained-models.pytorch/blob/021d97897c9aa76ec759deff43d341c4fd45d7ba/pretrainedmodels/models/dpn.py#L407-L428
[ "def", "adaptive_avgmax_pool2d", "(", "x", ",", "pool_type", "=", "'avg'", ",", "padding", "=", "0", ",", "count_include_pad", "=", "False", ")", ":", "if", "pool_type", "==", "'avgmaxc'", ":", "x", "=", "torch", ".", "cat", "(", "[", "F", ".", "avg_po...
021d97897c9aa76ec759deff43d341c4fd45d7ba
train
download_url
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...
pretrainedmodels/datasets/utils.py
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): """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...
[ "Download", "a", "URL", "to", "a", "local", "file", "." ]
Cadene/pretrained-models.pytorch
python
https://github.com/Cadene/pretrained-models.pytorch/blob/021d97897c9aa76ec759deff43d341c4fd45d7ba/pretrainedmodels/datasets/utils.py#L45-L83
[ "def", "download_url", "(", "url", ",", "destination", "=", "None", ",", "progress_bar", "=", "True", ")", ":", "def", "my_hook", "(", "t", ")", ":", "last_b", "=", "[", "0", "]", "def", "inner", "(", "b", "=", "1", ",", "bsize", "=", "1", ",", ...
021d97897c9aa76ec759deff43d341c4fd45d7ba
train
AveragePrecisionMeter.add
Args: output (Tensor): NxK tensor that for each of the N examples indicates the probability of the example belonging to each of the K classes, according to the model. The probabilities should sum to one over all classes target (Tensor): binary NxK ...
pretrainedmodels/datasets/utils.py
def add(self, output, target): """ Args: output (Tensor): NxK tensor that for each of the N examples indicates the probability of the example belonging to each of the K classes, according to the model. The probabilities should sum to one over a...
def add(self, output, target): """ Args: output (Tensor): NxK tensor that for each of the N examples indicates the probability of the example belonging to each of the K classes, according to the model. The probabilities should sum to one over a...
[ "Args", ":", "output", "(", "Tensor", ")", ":", "NxK", "tensor", "that", "for", "each", "of", "the", "N", "examples", "indicates", "the", "probability", "of", "the", "example", "belonging", "to", "each", "of", "the", "K", "classes", "according", "to", "t...
Cadene/pretrained-models.pytorch
python
https://github.com/Cadene/pretrained-models.pytorch/blob/021d97897c9aa76ec759deff43d341c4fd45d7ba/pretrainedmodels/datasets/utils.py#L110-L156
[ "def", "add", "(", "self", ",", "output", ",", "target", ")", ":", "if", "not", "torch", ".", "is_tensor", "(", "output", ")", ":", "output", "=", "torch", ".", "from_numpy", "(", "output", ")", "if", "not", "torch", ".", "is_tensor", "(", "target", ...
021d97897c9aa76ec759deff43d341c4fd45d7ba
train
AveragePrecisionMeter.value
Returns the model's average precision for each class Return: ap (FloatTensor): 1xK tensor, with avg precision for each class k
pretrainedmodels/datasets/utils.py
def value(self): """Returns the model's average precision for each class Return: ap (FloatTensor): 1xK tensor, with avg precision for each class k """ if self.scores.numel() == 0: return 0 ap = torch.zeros(self.scores.size(1)) rg = torch.arange(1,...
def value(self): """Returns the model's average precision for each class Return: ap (FloatTensor): 1xK tensor, with avg precision for each class k """ if self.scores.numel() == 0: return 0 ap = torch.zeros(self.scores.size(1)) rg = torch.arange(1,...
[ "Returns", "the", "model", "s", "average", "precision", "for", "each", "class", "Return", ":", "ap", "(", "FloatTensor", ")", ":", "1xK", "tensor", "with", "avg", "precision", "for", "each", "class", "k" ]
Cadene/pretrained-models.pytorch
python
https://github.com/Cadene/pretrained-models.pytorch/blob/021d97897c9aa76ec759deff43d341c4fd45d7ba/pretrainedmodels/datasets/utils.py#L158-L177
[ "def", "value", "(", "self", ")", ":", "if", "self", ".", "scores", ".", "numel", "(", ")", "==", "0", ":", "return", "0", "ap", "=", "torch", ".", "zeros", "(", "self", ".", "scores", ".", "size", "(", "1", ")", ")", "rg", "=", "torch", ".",...
021d97897c9aa76ec759deff43d341c4fd45d7ba
train
polynet
PolyNet architecture from the paper 'PolyNet: A Pursuit of Structural Diversity in Very Deep Networks' https://arxiv.org/abs/1611.05725
pretrainedmodels/models/polynet.py
def polynet(num_classes=1000, pretrained='imagenet'): """PolyNet architecture from the paper 'PolyNet: A Pursuit of Structural Diversity in Very Deep Networks' https://arxiv.org/abs/1611.05725 """ if pretrained: settings = pretrained_settings['polynet'][pretrained] assert num_classes...
def polynet(num_classes=1000, pretrained='imagenet'): """PolyNet architecture from the paper 'PolyNet: A Pursuit of Structural Diversity in Very Deep Networks' https://arxiv.org/abs/1611.05725 """ if pretrained: settings = pretrained_settings['polynet'][pretrained] assert num_classes...
[ "PolyNet", "architecture", "from", "the", "paper", "PolyNet", ":", "A", "Pursuit", "of", "Structural", "Diversity", "in", "Very", "Deep", "Networks", "https", ":", "//", "arxiv", ".", "org", "/", "abs", "/", "1611", ".", "05725" ]
Cadene/pretrained-models.pytorch
python
https://github.com/Cadene/pretrained-models.pytorch/blob/021d97897c9aa76ec759deff43d341c4fd45d7ba/pretrainedmodels/models/polynet.py#L461-L480
[ "def", "polynet", "(", "num_classes", "=", "1000", ",", "pretrained", "=", "'imagenet'", ")", ":", "if", "pretrained", ":", "settings", "=", "pretrained_settings", "[", "'polynet'", "]", "[", "pretrained", "]", "assert", "num_classes", "==", "settings", "[", ...
021d97897c9aa76ec759deff43d341c4fd45d7ba
train
CachedObject.unwrap
Get the cached value. Returns ------- value : object The cached value. Raises ------ Expired Raised when `dt` is greater than self.expires.
zipline/utils/cache.py
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): """ 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...
[ "Get", "the", "cached", "value", "." ]
quantopian/zipline
python
https://github.com/quantopian/zipline/blob/77ad15e6dc4c1cbcdc133653bac8a63fc704f7fe/zipline/utils/cache.py#L67-L84
[ "def", "unwrap", "(", "self", ",", "dt", ")", ":", "expires", "=", "self", ".", "_expires", "if", "expires", "is", "AlwaysExpired", "or", "expires", "<", "dt", ":", "raise", "Expired", "(", "self", ".", "_expires", ")", "return", "self", ".", "_value" ...
77ad15e6dc4c1cbcdc133653bac8a63fc704f7fe
train
ExpiringCache.get
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 ...
zipline/utils/cache.py
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): """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 ...
[ "Get", "the", "value", "of", "a", "cached", "object", "." ]
quantopian/zipline
python
https://github.com/quantopian/zipline/blob/77ad15e6dc4c1cbcdc133653bac8a63fc704f7fe/zipline/utils/cache.py#L131-L157
[ "def", "get", "(", "self", ",", "key", ",", "dt", ")", ":", "try", ":", "return", "self", ".", "_cache", "[", "key", "]", ".", "unwrap", "(", "dt", ")", "except", "Expired", ":", "self", ".", "cleanup", "(", "self", ".", "_cache", "[", "key", "...
77ad15e6dc4c1cbcdc133653bac8a63fc704f7fe
train
ExpiringCache.set
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...
zipline/utils/cache.py
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): """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...
[ "Adds", "a", "new", "key", "value", "pair", "to", "the", "cache", "." ]
quantopian/zipline
python
https://github.com/quantopian/zipline/blob/77ad15e6dc4c1cbcdc133653bac8a63fc704f7fe/zipline/utils/cache.py#L159-L172
[ "def", "set", "(", "self", ",", "key", ",", "value", ",", "expiration_dt", ")", ":", "self", ".", "_cache", "[", "key", "]", "=", "CachedObject", "(", "value", ",", "expiration_dt", ")" ]
77ad15e6dc4c1cbcdc133653bac8a63fc704f7fe
train
working_dir.ensure_dir
Ensures a subdirectory of the working directory. Parameters ---------- path_parts : iterable[str] The parts of the path after the working directory.
zipline/utils/cache.py
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): """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) ...
[ "Ensures", "a", "subdirectory", "of", "the", "working", "directory", "." ]
quantopian/zipline
python
https://github.com/quantopian/zipline/blob/77ad15e6dc4c1cbcdc133653bac8a63fc704f7fe/zipline/utils/cache.py#L358-L368
[ "def", "ensure_dir", "(", "self", ",", "*", "path_parts", ")", ":", "path", "=", "self", ".", "getpath", "(", "*", "path_parts", ")", "ensure_directory", "(", "path", ")", "return", "path" ]
77ad15e6dc4c1cbcdc133653bac8a63fc704f7fe
train
verify_frames_aligned
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...
zipline/data/in_memory_daily_bars.py
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): """ 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...
[ "Verify", "that", "DataFrames", "in", "frames", "have", "the", "same", "indexing", "scheme", "and", "are", "aligned", "to", "calendar", "." ]
quantopian/zipline
python
https://github.com/quantopian/zipline/blob/77ad15e6dc4c1cbcdc133653bac8a63fc704f7fe/zipline/data/in_memory_daily_bars.py#L124-L152
[ "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"...
77ad15e6dc4c1cbcdc133653bac8a63fc704f7fe
train
InMemoryDailyBarReader.get_value
Parameters ---------- sid : int The asset identifier. day : datetime64-like Midnight of the day for which data is requested. field : string The price field. e.g. ('open', 'high', 'low', 'close', 'volume') Returns ------- float ...
zipline/data/in_memory_daily_bars.py
def get_value(self, sid, dt, field): """ Parameters ---------- sid : int The asset identifier. day : datetime64-like Midnight of the day for which data is requested. field : string The price field. e.g. ('open', 'high', 'low', 'close', ...
def get_value(self, sid, dt, field): """ Parameters ---------- sid : int The asset identifier. day : datetime64-like Midnight of the day for which data is requested. field : string The price field. e.g. ('open', 'high', 'low', 'close', ...
[ "Parameters", "----------", "sid", ":", "int", "The", "asset", "identifier", ".", "day", ":", "datetime64", "-", "like", "Midnight", "of", "the", "day", "for", "which", "data", "is", "requested", ".", "field", ":", "string", "The", "price", "field", ".", ...
quantopian/zipline
python
https://github.com/quantopian/zipline/blob/77ad15e6dc4c1cbcdc133653bac8a63fc704f7fe/zipline/data/in_memory_daily_bars.py#L78-L98
[ "def", "get_value", "(", "self", ",", "sid", ",", "dt", ",", "field", ")", ":", "return", "self", ".", "frames", "[", "field", "]", ".", "loc", "[", "dt", ",", "sid", "]" ]
77ad15e6dc4c1cbcdc133653bac8a63fc704f7fe
train
InMemoryDailyBarReader.get_last_traded_dt
Parameters ---------- asset : zipline.asset.Asset The asset identifier. dt : datetime64-like Midnight of the day for which data is requested. Returns ------- pd.Timestamp : The last know dt for the asset and dt; NaT if no tr...
zipline/data/in_memory_daily_bars.py
def get_last_traded_dt(self, asset, dt): """ Parameters ---------- asset : zipline.asset.Asset The asset identifier. dt : datetime64-like Midnight of the day for which data is requested. Returns ------- pd.Timestamp : The last know...
def get_last_traded_dt(self, asset, dt): """ Parameters ---------- asset : zipline.asset.Asset The asset identifier. dt : datetime64-like Midnight of the day for which data is requested. Returns ------- pd.Timestamp : The last know...
[ "Parameters", "----------", "asset", ":", "zipline", ".", "asset", ".", "Asset", "The", "asset", "identifier", ".", "dt", ":", "datetime64", "-", "like", "Midnight", "of", "the", "day", "for", "which", "data", "is", "requested", "." ]
quantopian/zipline
python
https://github.com/quantopian/zipline/blob/77ad15e6dc4c1cbcdc133653bac8a63fc704f7fe/zipline/data/in_memory_daily_bars.py#L100-L117
[ "def", "get_last_traded_dt", "(", "self", ",", "asset", ",", "dt", ")", ":", "try", ":", "return", "self", ".", "frames", "[", "'close'", "]", ".", "loc", "[", ":", ",", "asset", ".", "sid", "]", ".", "last_valid_index", "(", ")", "except", "IndexErr...
77ad15e6dc4c1cbcdc133653bac8a63fc704f7fe
train
same
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
zipline/utils/functional.py
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): """ 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:] ...
[ "Check", "if", "all", "values", "in", "a", "sequence", "are", "equal", "." ]
quantopian/zipline
python
https://github.com/quantopian/zipline/blob/77ad15e6dc4c1cbcdc133653bac8a63fc704f7fe/zipline/utils/functional.py#L88-L106
[ "def", "same", "(", "*", "values", ")", ":", "if", "not", "values", ":", "return", "True", "first", ",", "rest", "=", "values", "[", "0", "]", ",", "values", "[", "1", ":", "]", "return", "all", "(", "value", "==", "first", "for", "value", "in", ...
77ad15e6dc4c1cbcdc133653bac8a63fc704f7fe
train
dzip_exact
Parameters ---------- *dicts : iterable[dict] A sequence of dicts all sharing the same keys. Returns ------- zipped : dict A dict whose keys are the union of all keys in *dicts, and whose values are tuples of length len(dicts) containing the result of looking up each...
zipline/utils/functional.py
def dzip_exact(*dicts): """ Parameters ---------- *dicts : iterable[dict] A sequence of dicts all sharing the same keys. Returns ------- zipped : dict A dict whose keys are the union of all keys in *dicts, and whose values are tuples of length len(dicts) containing t...
def dzip_exact(*dicts): """ Parameters ---------- *dicts : iterable[dict] A sequence of dicts all sharing the same keys. Returns ------- zipped : dict A dict whose keys are the union of all keys in *dicts, and whose values are tuples of length len(dicts) containing t...
[ "Parameters", "----------", "*", "dicts", ":", "iterable", "[", "dict", "]", "A", "sequence", "of", "dicts", "all", "sharing", "the", "same", "keys", "." ]
quantopian/zipline
python
https://github.com/quantopian/zipline/blob/77ad15e6dc4c1cbcdc133653bac8a63fc704f7fe/zipline/utils/functional.py#L113-L142
[ "def", "dzip_exact", "(", "*", "dicts", ")", ":", "if", "not", "same", "(", "*", "map", "(", "viewkeys", ",", "dicts", ")", ")", ":", "raise", "ValueError", "(", "\"dict keys not all equal:\\n\\n%s\"", "%", "_format_unequal_keys", "(", "dicts", ")", ")", "...
77ad15e6dc4c1cbcdc133653bac8a63fc704f7fe
train
_gen_unzip
Helper for unzip which checks the lengths of each element in it. Parameters ---------- it : iterable[tuple] An iterable of tuples. ``unzip`` should map ensure that these are already tuples. elem_len : int or None The expected element length. If this is None it is infered from the...
zipline/utils/functional.py
def _gen_unzip(it, elem_len): """Helper for unzip which checks the lengths of each element in it. Parameters ---------- it : iterable[tuple] An iterable of tuples. ``unzip`` should map ensure that these are already tuples. elem_len : int or None The expected element length. I...
def _gen_unzip(it, elem_len): """Helper for unzip which checks the lengths of each element in it. Parameters ---------- it : iterable[tuple] An iterable of tuples. ``unzip`` should map ensure that these are already tuples. elem_len : int or None The expected element length. I...
[ "Helper", "for", "unzip", "which", "checks", "the", "lengths", "of", "each", "element", "in", "it", ".", "Parameters", "----------", "it", ":", "iterable", "[", "tuple", "]", "An", "iterable", "of", "tuples", ".", "unzip", "should", "map", "ensure", "that"...
quantopian/zipline
python
https://github.com/quantopian/zipline/blob/77ad15e6dc4c1cbcdc133653bac8a63fc704f7fe/zipline/utils/functional.py#L145-L187
[ "def", "_gen_unzip", "(", "it", ",", "elem_len", ")", ":", "elem", "=", "next", "(", "it", ")", "first_elem_len", "=", "len", "(", "elem", ")", "if", "elem_len", "is", "not", "None", "and", "elem_len", "!=", "first_elem_len", ":", "raise", "ValueError", ...
77ad15e6dc4c1cbcdc133653bac8a63fc704f7fe
train
unzip
Unzip a length n sequence of length m sequences into m seperate length n sequences. Parameters ---------- seq : iterable[iterable] The sequence to unzip. elem_len : int, optional The expected length of each element of ``seq``. If not provided this will be infered from the len...
zipline/utils/functional.py
def unzip(seq, elem_len=None): """Unzip a length n sequence of length m sequences into m seperate length n sequences. Parameters ---------- seq : iterable[iterable] The sequence to unzip. elem_len : int, optional The expected length of each element of ``seq``. If not provided thi...
def unzip(seq, elem_len=None): """Unzip a length n sequence of length m sequences into m seperate length n sequences. Parameters ---------- seq : iterable[iterable] The sequence to unzip. elem_len : int, optional The expected length of each element of ``seq``. If not provided thi...
[ "Unzip", "a", "length", "n", "sequence", "of", "length", "m", "sequences", "into", "m", "seperate", "length", "n", "sequences", ".", "Parameters", "----------", "seq", ":", "iterable", "[", "iterable", "]", "The", "sequence", "to", "unzip", ".", "elem_len", ...
quantopian/zipline
python
https://github.com/quantopian/zipline/blob/77ad15e6dc4c1cbcdc133653bac8a63fc704f7fe/zipline/utils/functional.py#L190-L250
[ "def", "unzip", "(", "seq", ",", "elem_len", "=", "None", ")", ":", "ret", "=", "tuple", "(", "zip", "(", "*", "_gen_unzip", "(", "map", "(", "tuple", ",", "seq", ")", ",", "elem_len", ")", ")", ")", "if", "ret", ":", "return", "ret", "if", "el...
77ad15e6dc4c1cbcdc133653bac8a63fc704f7fe
train
getattrs
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...
zipline/utils/functional.py
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): """ 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. ...
[ "Perform", "a", "chained", "application", "of", "getattr", "on", "value", "with", "the", "values", "in", "attrs", "." ]
quantopian/zipline
python
https://github.com/quantopian/zipline/blob/77ad15e6dc4c1cbcdc133653bac8a63fc704f7fe/zipline/utils/functional.py#L256-L303
[ "def", "getattrs", "(", "value", ",", "attrs", ",", "default", "=", "_no_default", ")", ":", "try", ":", "for", "attr", "in", "attrs", ":", "value", "=", "getattr", "(", "value", ",", "attr", ")", "except", "AttributeError", ":", "if", "default", "is",...
77ad15e6dc4c1cbcdc133653bac8a63fc704f7fe
train
set_attribute
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'
zipline/utils/functional.py
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): """ 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__ ...
[ "Decorator", "factory", "for", "setting", "attributes", "on", "a", "function", "." ]
quantopian/zipline
python
https://github.com/quantopian/zipline/blob/77ad15e6dc4c1cbcdc133653bac8a63fc704f7fe/zipline/utils/functional.py#L307-L327
[ "def", "set_attribute", "(", "name", ",", "value", ")", ":", "def", "decorator", "(", "f", ")", ":", "setattr", "(", "f", ",", "name", ",", "value", ")", "return", "f", "return", "decorator" ]
77ad15e6dc4c1cbcdc133653bac8a63fc704f7fe
train
foldr
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...
zipline/utils/functional.py
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): """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...
[ "Fold", "a", "function", "over", "a", "sequence", "with", "right", "associativity", "." ]
quantopian/zipline
python
https://github.com/quantopian/zipline/blob/77ad15e6dc4c1cbcdc133653bac8a63fc704f7fe/zipline/utils/functional.py#L337-L393
[ "def", "foldr", "(", "f", ",", "seq", ",", "default", "=", "_no_default", ")", ":", "return", "reduce", "(", "flip", "(", "f", ")", ",", "reversed", "(", "seq", ")", ",", "*", "(", "default", ",", ")", "if", "default", "is", "not", "_no_default", ...
77ad15e6dc4c1cbcdc133653bac8a63fc704f7fe
train
invert
Invert a dictionary into a dictionary of sets. >>> invert({'a': 1, 'b': 2, 'c': 1}) # doctest: +SKIP {1: {'a', 'c'}, 2: {'b'}}
zipline/utils/functional.py
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): """ 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
[ "Invert", "a", "dictionary", "into", "a", "dictionary", "of", "sets", "." ]
quantopian/zipline
python
https://github.com/quantopian/zipline/blob/77ad15e6dc4c1cbcdc133653bac8a63fc704f7fe/zipline/utils/functional.py#L396-L409
[ "def", "invert", "(", "d", ")", ":", "out", "=", "{", "}", "for", "k", ",", "v", "in", "iteritems", "(", "d", ")", ":", "try", ":", "out", "[", "v", "]", ".", "add", "(", "k", ")", "except", "KeyError", ":", "out", "[", "v", "]", "=", "{"...
77ad15e6dc4c1cbcdc133653bac8a63fc704f7fe
train
simplex_projection
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} ...
zipline/examples/olmar.py
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): 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...
[ "r", "Projection", "vectors", "to", "the", "simplex", "domain" ]
quantopian/zipline
python
https://github.com/quantopian/zipline/blob/77ad15e6dc4c1cbcdc133653bac8a63fc704f7fe/zipline/examples/olmar.py#L111-L146
[ "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...
77ad15e6dc4c1cbcdc133653bac8a63fc704f7fe
train
run_example
Run an example module from zipline.examples.
zipline/examples/__init__.py
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): """ 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...
[ "Run", "an", "example", "module", "from", "zipline", ".", "examples", "." ]
quantopian/zipline
python
https://github.com/quantopian/zipline/blob/77ad15e6dc4c1cbcdc133653bac8a63fc704f7fe/zipline/examples/__init__.py#L64-L81
[ "def", "run_example", "(", "example_name", ",", "environ", ")", ":", "mod", "=", "EXAMPLE_MODULES", "[", "example_name", "]", "register_calendar", "(", "\"YAHOO\"", ",", "get_calendar", "(", "\"NYSE\"", ")", ",", "force", "=", "True", ")", "return", "run_algor...
77ad15e6dc4c1cbcdc133653bac8a63fc704f7fe
train
vectorized_beta
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...
zipline/pipeline/factors/statistical.py
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): """ 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``. ...
[ "Compute", "slopes", "of", "linear", "regressions", "between", "columns", "of", "dependents", "and", "independent", "." ]
quantopian/zipline
python
https://github.com/quantopian/zipline/blob/77ad15e6dc4c1cbcdc133653bac8a63fc704f7fe/zipline/pipeline/factors/statistical.py#L572-L665
[ "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",...
77ad15e6dc4c1cbcdc133653bac8a63fc704f7fe
train
_format_url
Format a URL for loading data from Bank of Canada.
zipline/data/treasuries_can.py
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): """ Format a URL for loading data from Bank of Canada. """ return ( "http://www.bankofcanada.ca/stats/results/csv" "?lP=lookup_{i...
[ "Format", "a", "URL", "for", "loading", "data", "from", "Bank", "of", "Canada", "." ]
quantopian/zipline
python
https://github.com/quantopian/zipline/blob/77ad15e6dc4c1cbcdc133653bac8a63fc704f7fe/zipline/data/treasuries_can.py#L39-L60
[ "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}\"",...
77ad15e6dc4c1cbcdc133653bac8a63fc704f7fe
train
load_frame
Load a DataFrame of data from a Bank of Canada site.
zipline/data/treasuries_can.py
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): """ 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...
[ "Load", "a", "DataFrame", "of", "data", "from", "a", "Bank", "of", "Canada", "site", "." ]
quantopian/zipline
python
https://github.com/quantopian/zipline/blob/77ad15e6dc4c1cbcdc133653bac8a63fc704f7fe/zipline/data/treasuries_can.py#L67-L80
[ "def", "load_frame", "(", "url", ",", "skiprows", ")", ":", "return", "pd", ".", "read_csv", "(", "url", ",", "skiprows", "=", "skiprows", ",", "skipinitialspace", "=", "True", ",", "na_values", "=", "[", "\"Bank holiday\"", ",", "\"Not available\"", "]", ...
77ad15e6dc4c1cbcdc133653bac8a63fc704f7fe
train
check_known_inconsistencies
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.
zipline/data/treasuries_can.py
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): """ 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 = [ ...
[ "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", "." ]
quantopian/zipline
python
https://github.com/quantopian/zipline/blob/77ad15e6dc4c1cbcdc133653bac8a63fc704f7fe/zipline/data/treasuries_can.py#L83-L119
[ "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...
77ad15e6dc4c1cbcdc133653bac8a63fc704f7fe
train
earliest_possible_date
The earliest date for which we can load data from this module.
zipline/data/treasuries_can.py
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(): """ 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)
[ "The", "earliest", "date", "for", "which", "we", "can", "load", "data", "from", "this", "module", "." ]
quantopian/zipline
python
https://github.com/quantopian/zipline/blob/77ad15e6dc4c1cbcdc133653bac8a63fc704f7fe/zipline/data/treasuries_can.py#L122-L128
[ "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",...
77ad15e6dc4c1cbcdc133653bac8a63fc704f7fe
train
fill_price_worse_than_limit_price
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 (...
zipline/finance/slippage.py
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): """ 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 ...
[ "Checks", "whether", "the", "fill", "price", "is", "worse", "than", "the", "order", "s", "limit", "price", "." ]
quantopian/zipline
python
https://github.com/quantopian/zipline/blob/77ad15e6dc4c1cbcdc133653bac8a63fc704f7fe/zipline/finance/slippage.py#L50-L80
[ "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...
77ad15e6dc4c1cbcdc133653bac8a63fc704f7fe
train
MarketImpactBase._get_window_data
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...
zipline/finance/slippage.py
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): """ 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 ...
[ "Internal", "utility", "method", "to", "return", "the", "trailing", "mean", "volume", "over", "the", "past", "window_length", "days", "and", "volatility", "of", "close", "prices", "for", "a", "specific", "asset", "." ]
quantopian/zipline
python
https://github.com/quantopian/zipline/blob/77ad15e6dc4c1cbcdc133653bac8a63fc704f7fe/zipline/finance/slippage.py#L399-L444
[ "def", "_get_window_data", "(", "self", ",", "data", ",", "asset", ",", "window_length", ")", ":", "try", ":", "values", "=", "self", ".", "_window_data_cache", ".", "get", "(", "asset", ",", "data", ".", "current_session", ")", "except", "KeyError", ":", ...
77ad15e6dc4c1cbcdc133653bac8a63fc704f7fe
train
validate_dtype
Validate a `dtype` and `missing_value` passed to Term.__new__. Ensures that we know how to represent ``dtype``, and that missing_value is specified for types without default missing values. Returns ------- validated_dtype, validated_missing_value : np.dtype, any The dtype and missing_value...
zipline/pipeline/term.py
def validate_dtype(termname, dtype, missing_value): """ Validate a `dtype` and `missing_value` passed to Term.__new__. Ensures that we know how to represent ``dtype``, and that missing_value is specified for types without default missing values. Returns ------- validated_dtype, validated_m...
def validate_dtype(termname, dtype, missing_value): """ Validate a `dtype` and `missing_value` passed to Term.__new__. Ensures that we know how to represent ``dtype``, and that missing_value is specified for types without default missing values. Returns ------- validated_dtype, validated_m...
[ "Validate", "a", "dtype", "and", "missing_value", "passed", "to", "Term", ".", "__new__", "." ]
quantopian/zipline
python
https://github.com/quantopian/zipline/blob/77ad15e6dc4c1cbcdc133653bac8a63fc704f7fe/zipline/pipeline/term.py#L795-L858
[ "def", "validate_dtype", "(", "termname", ",", "dtype", ",", "missing_value", ")", ":", "if", "dtype", "is", "NotSpecified", ":", "raise", "DTypeNotSpecified", "(", "termname", "=", "termname", ")", "try", ":", "dtype", "=", "dtype_class", "(", "dtype", ")",...
77ad15e6dc4c1cbcdc133653bac8a63fc704f7fe
train
_assert_valid_categorical_missing_value
Check that value is a valid categorical missing_value. Raises a TypeError if the value is cannot be used as the missing_value for a categorical_dtype Term.
zipline/pipeline/term.py
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): """ 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...
[ "Check", "that", "value", "is", "a", "valid", "categorical", "missing_value", "." ]
quantopian/zipline
python
https://github.com/quantopian/zipline/blob/77ad15e6dc4c1cbcdc133653bac8a63fc704f7fe/zipline/pipeline/term.py#L861-L875
[ "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...
77ad15e6dc4c1cbcdc133653bac8a63fc704f7fe
train
Term._pop_params
Pop entries from the `kwargs` passed to cls.__new__ based on the values in `cls.params`. Parameters ---------- kwargs : dict The kwargs passed to cls.__new__. Returns ------- params : list[(str, object)] A list of string, value pairs cont...
zipline/pipeline/term.py
def _pop_params(cls, kwargs): """ Pop entries from the `kwargs` passed to cls.__new__ based on the values in `cls.params`. Parameters ---------- kwargs : dict The kwargs passed to cls.__new__. Returns ------- params : list[(str, objec...
def _pop_params(cls, kwargs): """ Pop entries from the `kwargs` passed to cls.__new__ based on the values in `cls.params`. Parameters ---------- kwargs : dict The kwargs passed to cls.__new__. Returns ------- params : list[(str, objec...
[ "Pop", "entries", "from", "the", "kwargs", "passed", "to", "cls", ".", "__new__", "based", "on", "the", "values", "in", "cls", ".", "params", "." ]
quantopian/zipline
python
https://github.com/quantopian/zipline/blob/77ad15e6dc4c1cbcdc133653bac8a63fc704f7fe/zipline/pipeline/term.py#L140-L192
[ "def", "_pop_params", "(", "cls", ",", "kwargs", ")", ":", "params", "=", "cls", ".", "params", "if", "not", "isinstance", "(", "params", ",", "Mapping", ")", ":", "params", "=", "{", "k", ":", "NotSpecified", "for", "k", "in", "params", "}", "param_...
77ad15e6dc4c1cbcdc133653bac8a63fc704f7fe
train
Term._static_identity
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...
zipline/pipeline/term.py
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 the identity of the Term that would be constructed from the...
[ "Return", "the", "identity", "of", "the", "Term", "that", "would", "be", "constructed", "from", "the", "given", "arguments", "." ]
quantopian/zipline
python
https://github.com/quantopian/zipline/blob/77ad15e6dc4c1cbcdc133653bac8a63fc704f7fe/zipline/pipeline/term.py#L217-L235
[ "def", "_static_identity", "(", "cls", ",", "domain", ",", "dtype", ",", "missing_value", ",", "window_safe", ",", "ndim", ",", "params", ")", ":", "return", "(", "cls", ",", "domain", ",", "dtype", ",", "missing_value", ",", "window_safe", ",", "ndim", ...
77ad15e6dc4c1cbcdc133653bac8a63fc704f7fe
train
Term._init
Parameters ---------- domain : zipline.pipeline.domain.Domain The domain of this term. dtype : np.dtype Dtype of this term's output. missing_value : object Missing value for this term. ndim : 1 or 2 The dimensionality of this term. ...
zipline/pipeline/term.py
def _init(self, domain, dtype, missing_value, window_safe, ndim, params): """ Parameters ---------- domain : zipline.pipeline.domain.Domain The domain of this term. dtype : np.dtype Dtype of this term's output. missing_value : object Mi...
def _init(self, domain, dtype, missing_value, window_safe, ndim, params): """ Parameters ---------- domain : zipline.pipeline.domain.Domain The domain of this term. dtype : np.dtype Dtype of this term's output. missing_value : object Mi...
[ "Parameters", "----------", "domain", ":", "zipline", ".", "pipeline", ".", "domain", ".", "Domain", "The", "domain", "of", "this", "term", ".", "dtype", ":", "np", ".", "dtype", "Dtype", "of", "this", "term", "s", "output", ".", "missing_value", ":", "o...
quantopian/zipline
python
https://github.com/quantopian/zipline/blob/77ad15e6dc4c1cbcdc133653bac8a63fc704f7fe/zipline/pipeline/term.py#L237-L285
[ "def", "_init", "(", "self", ",", "domain", ",", "dtype", ",", "missing_value", ",", "window_safe", ",", "ndim", ",", "params", ")", ":", "self", ".", "domain", "=", "domain", "self", ".", "dtype", "=", "dtype", "self", ".", "missing_value", "=", "miss...
77ad15e6dc4c1cbcdc133653bac8a63fc704f7fe
train
ComputableTerm.dependencies
The number of extra rows needed for each of our inputs to compute this term.
zipline/pipeline/term.py
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): """ 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 ...
[ "The", "number", "of", "extra", "rows", "needed", "for", "each", "of", "our", "inputs", "to", "compute", "this", "term", "." ]
quantopian/zipline
python
https://github.com/quantopian/zipline/blob/77ad15e6dc4c1cbcdc133653bac8a63fc704f7fe/zipline/pipeline/term.py#L613-L623
[ "def", "dependencies", "(", "self", ")", ":", "extra_input_rows", "=", "max", "(", "0", ",", "self", ".", "window_length", "-", "1", ")", "out", "=", "{", "}", "for", "term", "in", "self", ".", "inputs", ":", "out", "[", "term", "]", "=", "extra_in...
77ad15e6dc4c1cbcdc133653bac8a63fc704f7fe
train
ComputableTerm.to_workspace_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 ...
zipline/pipeline/term.py
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): """ 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...
[ "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", "." ]
quantopian/zipline
python
https://github.com/quantopian/zipline/blob/77ad15e6dc4c1cbcdc133653bac8a63fc704f7fe/zipline/pipeline/term.py#L638-L661
[ "def", "to_workspace_value", "(", "self", ",", "result", ",", "assets", ")", ":", "return", "result", ".", "unstack", "(", ")", ".", "fillna", "(", "self", ".", "missing_value", ")", ".", "reindex", "(", "columns", "=", "assets", ",", "fill_value", "=", ...
77ad15e6dc4c1cbcdc133653bac8a63fc704f7fe
train
Position.earn_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.
zipline/finance/position.py
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): """ 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...
[ "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", "." ]
quantopian/zipline
python
https://github.com/quantopian/zipline/blob/77ad15e6dc4c1cbcdc133653bac8a63fc704f7fe/zipline/finance/position.py#L79-L89
[ "def", "earn_stock_dividend", "(", "self", ",", "stock_dividend", ")", ":", "return", "{", "'payment_asset'", ":", "stock_dividend", ".", "payment_asset", ",", "'share_count'", ":", "np", ".", "floor", "(", "self", ".", "amount", "*", "float", "(", "stock_divi...
77ad15e6dc4c1cbcdc133653bac8a63fc704f7fe
train
Position.handle_split
Update the position by the split ratio, and return the resulting fractional share that will be converted into cash. Returns the unused cash.
zipline/finance/position.py
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): """ 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...
[ "Update", "the", "position", "by", "the", "split", "ratio", "and", "return", "the", "resulting", "fractional", "share", "that", "will", "be", "converted", "into", "cash", "." ]
quantopian/zipline
python
https://github.com/quantopian/zipline/blob/77ad15e6dc4c1cbcdc133653bac8a63fc704f7fe/zipline/finance/position.py#L91-L129
[ "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...
77ad15e6dc4c1cbcdc133653bac8a63fc704f7fe
train
Position.adjust_commission_cost_basis
A note about cost-basis in zipline: all positions are considered to share a cost basis, even if they were executed in different transactions with different commission costs, different prices, etc. Due to limitations about how zipline handles positions, zipline will currently spread an e...
zipline/finance/position.py
def adjust_commission_cost_basis(self, asset, cost): """ A note about cost-basis in zipline: all positions are considered to share a cost basis, even if they were executed in different transactions with different commission costs, different prices, etc. Due to limitations about ...
def adjust_commission_cost_basis(self, asset, cost): """ A note about cost-basis in zipline: all positions are considered to share a cost basis, even if they were executed in different transactions with different commission costs, different prices, etc. Due to limitations about ...
[ "A", "note", "about", "cost", "-", "basis", "in", "zipline", ":", "all", "positions", "are", "considered", "to", "share", "a", "cost", "basis", "even", "if", "they", "were", "executed", "in", "different", "transactions", "with", "different", "commission", "c...
quantopian/zipline
python
https://github.com/quantopian/zipline/blob/77ad15e6dc4c1cbcdc133653bac8a63fc704f7fe/zipline/finance/position.py#L164-L203
[ "def", "adjust_commission_cost_basis", "(", "self", ",", "asset", ",", "cost", ")", ":", "if", "asset", "!=", "self", ".", "asset", ":", "raise", "Exception", "(", "'Updating a commission for a different asset?'", ")", "if", "cost", "==", "0.0", ":", "return", ...
77ad15e6dc4c1cbcdc133653bac8a63fc704f7fe
train
Position.to_dict
Creates a dictionary representing the state of this position. Returns a dict object of the form:
zipline/finance/position.py
def to_dict(self): """ Creates a dictionary representing the state of this position. Returns a dict object of the form: """ return { 'sid': self.asset, 'amount': self.amount, 'cost_basis': self.cost_basis, 'last_sale_price': self.la...
def to_dict(self): """ Creates a dictionary representing the state of this position. Returns a dict object of the form: """ return { 'sid': self.asset, 'amount': self.amount, 'cost_basis': self.cost_basis, 'last_sale_price': self.la...
[ "Creates", "a", "dictionary", "representing", "the", "state", "of", "this", "position", ".", "Returns", "a", "dict", "object", "of", "the", "form", ":" ]
quantopian/zipline
python
https://github.com/quantopian/zipline/blob/77ad15e6dc4c1cbcdc133653bac8a63fc704f7fe/zipline/finance/position.py#L215-L225
[ "def", "to_dict", "(", "self", ")", ":", "return", "{", "'sid'", ":", "self", ".", "asset", ",", "'amount'", ":", "self", ".", "amount", ",", "'cost_basis'", ":", "self", ".", "cost_basis", ",", "'last_sale_price'", ":", "self", ".", "last_sale_price", "...
77ad15e6dc4c1cbcdc133653bac8a63fc704f7fe
train
_make_bundle_core
Create a family of data bundle functions that read from the same bundle mapping. Returns ------- bundles : mappingproxy The mapping of bundles to bundle payloads. register : callable The function which registers new bundles in the ``bundles`` mapping. unregister : callable ...
zipline/data/bundles/core.py
def _make_bundle_core(): """Create a family of data bundle functions that read from the same bundle mapping. Returns ------- bundles : mappingproxy The mapping of bundles to bundle payloads. register : callable The function which registers new bundles in the ``bundles`` mapping....
def _make_bundle_core(): """Create a family of data bundle functions that read from the same bundle mapping. Returns ------- bundles : mappingproxy The mapping of bundles to bundle payloads. register : callable The function which registers new bundles in the ``bundles`` mapping....
[ "Create", "a", "family", "of", "data", "bundle", "functions", "that", "read", "from", "the", "same", "bundle", "mapping", "." ]
quantopian/zipline
python
https://github.com/quantopian/zipline/blob/77ad15e6dc4c1cbcdc133653bac8a63fc704f7fe/zipline/data/bundles/core.py#L195-L614
[ "def", "_make_bundle_core", "(", ")", ":", "_bundles", "=", "{", "}", "# the registered bundles", "# Expose _bundles through a proxy so that users cannot mutate this", "# accidentally. Users may go through `register` to update this which will", "# warn when trampling another bundle.", "bun...
77ad15e6dc4c1cbcdc133653bac8a63fc704f7fe
train
deprecated
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...
zipline/utils/deprecate.py
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): """ 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....
[ "Used", "to", "mark", "a", "function", "as", "deprecated", "." ]
quantopian/zipline
python
https://github.com/quantopian/zipline/blob/77ad15e6dc4c1cbcdc133653bac8a63fc704f7fe/zipline/utils/deprecate.py#L20-L47
[ "def", "deprecated", "(", "msg", "=", "None", ",", "stacklevel", "=", "2", ")", ":", "def", "deprecated_dec", "(", "fn", ")", ":", "@", "wraps", "(", "fn", ")", "def", "wrapper", "(", "*", "args", ",", "*", "*", "kwargs", ")", ":", "warnings", "....
77ad15e6dc4c1cbcdc133653bac8a63fc704f7fe
train
HistoryCompatibleUSEquityAdjustmentReader.load_pricing_adjustments
Returns ------- adjustments : list[dict[int -> Adjustment]] A list, where each element corresponds to the `columns`, of mappings from index to adjustment objects to apply at that index.
zipline/data/history_loader.py
def load_pricing_adjustments(self, columns, dts, assets): """ Returns ------- adjustments : list[dict[int -> Adjustment]] A list, where each element corresponds to the `columns`, of mappings from index to adjustment objects to apply at that index. """ ...
def load_pricing_adjustments(self, columns, dts, assets): """ Returns ------- adjustments : list[dict[int -> Adjustment]] A list, where each element corresponds to the `columns`, of mappings from index to adjustment objects to apply at that index. """ ...
[ "Returns", "-------", "adjustments", ":", "list", "[", "dict", "[", "int", "-", ">", "Adjustment", "]]", "A", "list", "where", "each", "element", "corresponds", "to", "the", "columns", "of", "mappings", "from", "index", "to", "adjustment", "objects", "to", ...
quantopian/zipline
python
https://github.com/quantopian/zipline/blob/77ad15e6dc4c1cbcdc133653bac8a63fc704f7fe/zipline/data/history_loader.py#L48-L63
[ "def", "load_pricing_adjustments", "(", "self", ",", "columns", ",", "dts", ",", "assets", ")", ":", "out", "=", "[", "None", "]", "*", "len", "(", "columns", ")", "for", "i", ",", "column", "in", "enumerate", "(", "columns", ")", ":", "adjs", "=", ...
77ad15e6dc4c1cbcdc133653bac8a63fc704f7fe
train
HistoryCompatibleUSEquityAdjustmentReader._get_adjustments_in_range
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...
zipline/data/history_loader.py
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): """ 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...
[ "Get", "the", "Float64Multiply", "objects", "to", "pass", "to", "an", "AdjustedArrayWindow", "." ]
quantopian/zipline
python
https://github.com/quantopian/zipline/blob/77ad15e6dc4c1cbcdc133653bac8a63fc704f7fe/zipline/data/history_loader.py#L65-L151
[ "def", "_get_adjustments_in_range", "(", "self", ",", "asset", ",", "dts", ",", "field", ")", ":", "sid", "=", "int", "(", "asset", ")", "start", "=", "normalize_date", "(", "dts", "[", "0", "]", ")", "end", "=", "normalize_date", "(", "dts", "[", "-...
77ad15e6dc4c1cbcdc133653bac8a63fc704f7fe
train
SlidingWindow.get
Returns ------- out : A np.ndarray of the equity pricing up to end_ix after adjustments and rounding have been applied.
zipline/data/history_loader.py
def get(self, end_ix): """ Returns ------- out : A np.ndarray of the equity pricing up to end_ix after adjustments and rounding have been applied. """ if self.most_recent_ix == end_ix: return self.current target = end_ix - self.cal_start...
def get(self, end_ix): """ Returns ------- out : A np.ndarray of the equity pricing up to end_ix after adjustments and rounding have been applied. """ if self.most_recent_ix == end_ix: return self.current target = end_ix - self.cal_start...
[ "Returns", "-------", "out", ":", "A", "np", ".", "ndarray", "of", "the", "equity", "pricing", "up", "to", "end_ix", "after", "adjustments", "and", "rounding", "have", "been", "applied", "." ]
quantopian/zipline
python
https://github.com/quantopian/zipline/blob/77ad15e6dc4c1cbcdc133653bac8a63fc704f7fe/zipline/data/history_loader.py#L279-L293
[ "def", "get", "(", "self", ",", "end_ix", ")", ":", "if", "self", ".", "most_recent_ix", "==", "end_ix", ":", "return", "self", ".", "current", "target", "=", "end_ix", "-", "self", ".", "cal_start", "-", "self", ".", "offset", "+", "1", "self", ".",...
77ad15e6dc4c1cbcdc133653bac8a63fc704f7fe
train
HistoryLoader._ensure_sliding_windows
Ensure that there is a Float64Multiply window for each asset that can provide data for the given parameters. If the corresponding window for the (assets, len(dts), field) does not exist, then create a new one. If a corresponding window does exist for (assets, len(dts), field), but ...
zipline/data/history_loader.py
def _ensure_sliding_windows(self, assets, dts, field, is_perspective_after): """ Ensure that there is a Float64Multiply window for each asset that can provide data for the given parameters. If the corresponding window for the (assets, len(dts), field) does...
def _ensure_sliding_windows(self, assets, dts, field, is_perspective_after): """ Ensure that there is a Float64Multiply window for each asset that can provide data for the given parameters. If the corresponding window for the (assets, len(dts), field) does...
[ "Ensure", "that", "there", "is", "a", "Float64Multiply", "window", "for", "each", "asset", "that", "can", "provide", "data", "for", "the", "given", "parameters", ".", "If", "the", "corresponding", "window", "for", "the", "(", "assets", "len", "(", "dts", "...
quantopian/zipline
python
https://github.com/quantopian/zipline/blob/77ad15e6dc4c1cbcdc133653bac8a63fc704f7fe/zipline/data/history_loader.py#L364-L469
[ "def", "_ensure_sliding_windows", "(", "self", ",", "assets", ",", "dts", ",", "field", ",", "is_perspective_after", ")", ":", "end", "=", "dts", "[", "-", "1", "]", "size", "=", "len", "(", "dts", ")", "asset_windows", "=", "{", "}", "needed_assets", ...
77ad15e6dc4c1cbcdc133653bac8a63fc704f7fe
train
HistoryLoader.history
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...
zipline/data/history_loader.py
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): """ 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 ...
[ "A", "window", "of", "pricing", "data", "with", "adjustments", "applied", "assuming", "that", "the", "end", "of", "the", "window", "is", "the", "day", "before", "the", "current", "simulation", "time", "." ]
quantopian/zipline
python
https://github.com/quantopian/zipline/blob/77ad15e6dc4c1cbcdc133653bac8a63fc704f7fe/zipline/data/history_loader.py#L471-L555
[ "def", "history", "(", "self", ",", "assets", ",", "dts", ",", "field", ",", "is_perspective_after", ")", ":", "block", "=", "self", ".", "_ensure_sliding_windows", "(", "assets", ",", "dts", ",", "field", ",", "is_perspective_after", ")", "end_ix", "=", "...
77ad15e6dc4c1cbcdc133653bac8a63fc704f7fe
train
PandasCSV.parse_date_str_series
Efficient parsing for a 1d Pandas/numpy object containing string representations of dates. Note: pd.to_datetime is significantly faster when no format string is passed, and in pandas 0.12.0 the %p strptime directive is not correctly handled if a format string is explicitly passed, but A...
zipline/sources/requests_csv.py
def parse_date_str_series(format_str, tz, date_str_series, data_frequency, trading_day): """ Efficient parsing for a 1d Pandas/numpy object containing string representations of dates. Note: pd.to_datetime is significantly faster when no format string is ...
def parse_date_str_series(format_str, tz, date_str_series, data_frequency, trading_day): """ Efficient parsing for a 1d Pandas/numpy object containing string representations of dates. Note: pd.to_datetime is significantly faster when no format string is ...
[ "Efficient", "parsing", "for", "a", "1d", "Pandas", "/", "numpy", "object", "containing", "string", "representations", "of", "dates", "." ]
quantopian/zipline
python
https://github.com/quantopian/zipline/blob/77ad15e6dc4c1cbcdc133653bac8a63fc704f7fe/zipline/sources/requests_csv.py#L201-L242
[ "def", "parse_date_str_series", "(", "format_str", ",", "tz", ",", "date_str_series", ",", "data_frequency", ",", "trading_day", ")", ":", "# Explicitly ignoring this parameter. See note above.", "if", "format_str", "is", "not", "None", ":", "logger", ".", "warn", "(...
77ad15e6dc4c1cbcdc133653bac8a63fc704f7fe
train
PandasCSV._lookup_unconflicted_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.
zipline/sources/requests_csv.py
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): """ 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...
[ "Attempt", "to", "find", "a", "unique", "asset", "whose", "symbol", "is", "the", "given", "string", "." ]
quantopian/zipline
python
https://github.com/quantopian/zipline/blob/77ad15e6dc4c1cbcdc133653bac8a63fc704f7fe/zipline/sources/requests_csv.py#L262-L288
[ "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", ...
77ad15e6dc4c1cbcdc133653bac8a63fc704f7fe
train
AlgorithmSimulator.transform
Main generator work loop.
zipline/gens/tradesimulation.py
def transform(self): """ Main generator work loop. """ algo = self.algo metrics_tracker = algo.metrics_tracker emission_rate = metrics_tracker.emission_rate def every_bar(dt_to_use, current_data=self.current_data, handle_data=algo.event_mana...
def transform(self): """ Main generator work loop. """ algo = self.algo metrics_tracker = algo.metrics_tracker emission_rate = metrics_tracker.emission_rate def every_bar(dt_to_use, current_data=self.current_data, handle_data=algo.event_mana...
[ "Main", "generator", "work", "loop", "." ]
quantopian/zipline
python
https://github.com/quantopian/zipline/blob/77ad15e6dc4c1cbcdc133653bac8a63fc704f7fe/zipline/gens/tradesimulation.py#L97-L236
[ "def", "transform", "(", "self", ")", ":", "algo", "=", "self", ".", "algo", "metrics_tracker", "=", "algo", ".", "metrics_tracker", "emission_rate", "=", "metrics_tracker", ".", "emission_rate", "def", "every_bar", "(", "dt_to_use", ",", "current_data", "=", ...
77ad15e6dc4c1cbcdc133653bac8a63fc704f7fe
train
AlgorithmSimulator._cleanup_expired_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_date. 2. Finds all assets for which we have positions and generates ...
zipline/gens/tradesimulation.py
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): """ 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...
[ "Clear", "out", "any", "assets", "that", "have", "expired", "before", "starting", "a", "new", "sim", "day", "." ]
quantopian/zipline
python
https://github.com/quantopian/zipline/blob/77ad15e6dc4c1cbcdc133653bac8a63fc704f7fe/zipline/gens/tradesimulation.py#L238-L281
[ "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", ...
77ad15e6dc4c1cbcdc133653bac8a63fc704f7fe
train
AlgorithmSimulator._get_daily_message
Get a perf message for the given datetime.
zipline/gens/tradesimulation.py
def _get_daily_message(self, dt, algo, metrics_tracker): """ Get a perf message for the given datetime. """ perf_message = metrics_tracker.handle_market_close( dt, self.data_portal, ) perf_message['daily_perf']['recorded_vars'] = algo.recorded_vars...
def _get_daily_message(self, dt, algo, metrics_tracker): """ Get a perf message for the given datetime. """ perf_message = metrics_tracker.handle_market_close( dt, self.data_portal, ) perf_message['daily_perf']['recorded_vars'] = algo.recorded_vars...
[ "Get", "a", "perf", "message", "for", "the", "given", "datetime", "." ]
quantopian/zipline
python
https://github.com/quantopian/zipline/blob/77ad15e6dc4c1cbcdc133653bac8a63fc704f7fe/zipline/gens/tradesimulation.py#L283-L292
[ "def", "_get_daily_message", "(", "self", ",", "dt", ",", "algo", ",", "metrics_tracker", ")", ":", "perf_message", "=", "metrics_tracker", ".", "handle_market_close", "(", "dt", ",", "self", ".", "data_portal", ",", ")", "perf_message", "[", "'daily_perf'", "...
77ad15e6dc4c1cbcdc133653bac8a63fc704f7fe
train
AlgorithmSimulator._get_minute_message
Get a perf message for the given datetime.
zipline/gens/tradesimulation.py
def _get_minute_message(self, dt, algo, metrics_tracker): """ Get a perf message for the given datetime. """ rvars = algo.recorded_vars minute_message = metrics_tracker.handle_minute_close( dt, self.data_portal, ) minute_message['minute_p...
def _get_minute_message(self, dt, algo, metrics_tracker): """ Get a perf message for the given datetime. """ rvars = algo.recorded_vars minute_message = metrics_tracker.handle_minute_close( dt, self.data_portal, ) minute_message['minute_p...
[ "Get", "a", "perf", "message", "for", "the", "given", "datetime", "." ]
quantopian/zipline
python
https://github.com/quantopian/zipline/blob/77ad15e6dc4c1cbcdc133653bac8a63fc704f7fe/zipline/gens/tradesimulation.py#L294-L306
[ "def", "_get_minute_message", "(", "self", ",", "dt", ",", "algo", ",", "metrics_tracker", ")", ":", "rvars", "=", "algo", ".", "recorded_vars", "minute_message", "=", "metrics_tracker", ".", "handle_minute_close", "(", "dt", ",", "self", ".", "data_portal", "...
77ad15e6dc4c1cbcdc133653bac8a63fc704f7fe
train
SQLiteAdjustmentReader.load_adjustments
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 ...
zipline/data/adjustments.py
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): """ Load collection o...
[ "Load", "collection", "of", "Adjustment", "objects", "from", "underlying", "adjustments", "db", "." ]
quantopian/zipline
python
https://github.com/quantopian/zipline/blob/77ad15e6dc4c1cbcdc133653bac8a63fc704f7fe/zipline/data/adjustments.py#L142-L182
[ "def", "load_adjustments", "(", "self", ",", "dates", ",", "assets", ",", "should_include_splits", ",", "should_include_mergers", ",", "should_include_dividends", ",", "adjustment_type", ")", ":", "return", "load_adjustments_from_sqlite", "(", "self", ".", "conn", ","...
77ad15e6dc4c1cbcdc133653bac8a63fc704f7fe
train
SQLiteAdjustmentReader.unpack_db_to_component_dfs
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 ...
zipline/data/adjustments.py
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): """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...
[ "Returns", "the", "set", "of", "known", "tables", "in", "the", "adjustments", "file", "in", "DataFrame", "form", "." ]
quantopian/zipline
python
https://github.com/quantopian/zipline/blob/77ad15e6dc4c1cbcdc133653bac8a63fc704f7fe/zipline/data/adjustments.py#L268-L289
[ "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", ...
77ad15e6dc4c1cbcdc133653bac8a63fc704f7fe
train
SQLiteAdjustmentReader._df_dtypes
Get dtypes to use when unpacking sqlite tables as dataframes.
zipline/data/adjustments.py
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): """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]: ...
[ "Get", "dtypes", "to", "use", "when", "unpacking", "sqlite", "tables", "as", "dataframes", "." ]
quantopian/zipline
python
https://github.com/quantopian/zipline/blob/77ad15e6dc4c1cbcdc133653bac8a63fc704f7fe/zipline/data/adjustments.py#L326-L335
[ "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", "...
77ad15e6dc4c1cbcdc133653bac8a63fc704f7fe
train
SQLiteAdjustmentWriter.calc_dividend_ratios
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...
zipline/data/adjustments.py
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): """ 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 ------- ...
[ "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", ...
quantopian/zipline
python
https://github.com/quantopian/zipline/blob/77ad15e6dc4c1cbcdc133653bac8a63fc704f7fe/zipline/data/adjustments.py#L456-L530
[ "def", "calc_dividend_ratios", "(", "self", ",", "dividends", ")", ":", "if", "dividends", "is", "None", "or", "dividends", ".", "empty", ":", "return", "pd", ".", "DataFrame", "(", "np", ".", "array", "(", "[", "]", ",", "dtype", "=", "[", "(", "'si...
77ad15e6dc4c1cbcdc133653bac8a63fc704f7fe
train
SQLiteAdjustmentWriter.write_dividend_data
Write both dividend payouts and the derived price adjustment ratios.
zipline/data/adjustments.py
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): """ 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...
[ "Write", "both", "dividend", "payouts", "and", "the", "derived", "price", "adjustment", "ratios", "." ]
quantopian/zipline
python
https://github.com/quantopian/zipline/blob/77ad15e6dc4c1cbcdc133653bac8a63fc704f7fe/zipline/data/adjustments.py#L570-L581
[ "def", "write_dividend_data", "(", "self", ",", "dividends", ",", "stock_dividends", "=", "None", ")", ":", "# First write the dividend payouts.", "self", ".", "_write_dividends", "(", "dividends", ")", "self", ".", "_write_stock_dividends", "(", "stock_dividends", ")...
77ad15e6dc4c1cbcdc133653bac8a63fc704f7fe
train
SQLiteAdjustmentWriter.write
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 ...
zipline/data/adjustments.py
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): """ Writes data to a SQLite file to be read by SQLiteAdjustmentReader. Parameters ---------- splits : pandas.DataFrame, optional ...
[ "Writes", "data", "to", "a", "SQLite", "file", "to", "be", "read", "by", "SQLiteAdjustmentReader", "." ]
quantopian/zipline
python
https://github.com/quantopian/zipline/blob/77ad15e6dc4c1cbcdc133653bac8a63fc704f7fe/zipline/data/adjustments.py#L583-L703
[ "def", "write", "(", "self", ",", "splits", "=", "None", ",", "mergers", "=", "None", ",", "dividends", "=", "None", ",", "stock_dividends", "=", "None", ")", ":", "self", ".", "write_frame", "(", "'splits'", ",", "splits", ")", "self", ".", "write_fra...
77ad15e6dc4c1cbcdc133653bac8a63fc704f7fe
train
CustomTermMixin.compute
Override this method with a function that writes a value into `out`.
zipline/pipeline/mixins.py
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): """ 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__ ) )
[ "Override", "this", "method", "with", "a", "function", "that", "writes", "a", "value", "into", "out", "." ]
quantopian/zipline
python
https://github.com/quantopian/zipline/blob/77ad15e6dc4c1cbcdc133653bac8a63fc704f7fe/zipline/pipeline/mixins.py#L143-L151
[ "def", "compute", "(", "self", ",", "today", ",", "assets", ",", "out", ",", "*", "arrays", ")", ":", "raise", "NotImplementedError", "(", "\"{name} must define a compute method\"", ".", "format", "(", "name", "=", "type", "(", "self", ")", ".", "__name__", ...
77ad15e6dc4c1cbcdc133653bac8a63fc704f7fe
train
CustomTermMixin._allocate_output
Allocate an output array whose rows should be passed to `self.compute`. The resulting array must have a shape of ``shape``. If we have standard outputs (i.e. self.outputs is NotSpecified), the default is an empty ndarray whose dtype is ``self.dtype``. If we have an outputs tuple, the ...
zipline/pipeline/mixins.py
def _allocate_output(self, windows, shape): """ Allocate an output array whose rows should be passed to `self.compute`. The resulting array must have a shape of ``shape``. If we have standard outputs (i.e. self.outputs is NotSpecified), the default is an empty ndarray whose dty...
def _allocate_output(self, windows, shape): """ Allocate an output array whose rows should be passed to `self.compute`. The resulting array must have a shape of ``shape``. If we have standard outputs (i.e. self.outputs is NotSpecified), the default is an empty ndarray whose dty...
[ "Allocate", "an", "output", "array", "whose", "rows", "should", "be", "passed", "to", "self", ".", "compute", "." ]
quantopian/zipline
python
https://github.com/quantopian/zipline/blob/77ad15e6dc4c1cbcdc133653bac8a63fc704f7fe/zipline/pipeline/mixins.py#L153-L180
[ "def", "_allocate_output", "(", "self", ",", "windows", ",", "shape", ")", ":", "missing_value", "=", "self", ".", "missing_value", "outputs", "=", "self", ".", "outputs", "if", "outputs", "is", "not", "NotSpecified", ":", "out", "=", "recarray", "(", "sha...
77ad15e6dc4c1cbcdc133653bac8a63fc704f7fe
train
CustomTermMixin._compute
Call the user's `compute` function on each window with a pre-built output array.
zipline/pipeline/mixins.py
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): """ 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...
[ "Call", "the", "user", "s", "compute", "function", "on", "each", "window", "with", "a", "pre", "-", "built", "output", "array", "." ]
quantopian/zipline
python
https://github.com/quantopian/zipline/blob/77ad15e6dc4c1cbcdc133653bac8a63fc704f7fe/zipline/pipeline/mixins.py#L193-L220
[ "def", "_compute", "(", "self", ",", "windows", ",", "dates", ",", "assets", ",", "mask", ")", ":", "format_inputs", "=", "self", ".", "_format_inputs", "compute", "=", "self", ".", "compute", "params", "=", "self", ".", "params", "ndim", "=", "self", ...
77ad15e6dc4c1cbcdc133653bac8a63fc704f7fe
train
AliasedMixin.make_aliased_type
Factory for making Aliased{Filter,Factor,Classifier}.
zipline/pipeline/mixins.py
def make_aliased_type(cls, other_base): """ Factory for making Aliased{Filter,Factor,Classifier}. """ docstring = dedent( """ A {t} that names another {t}. Parameters ---------- term : {t} {{name}} """ ...
def make_aliased_type(cls, other_base): """ Factory for making Aliased{Filter,Factor,Classifier}. """ docstring = dedent( """ A {t} that names another {t}. Parameters ---------- term : {t} {{name}} """ ...
[ "Factory", "for", "making", "Aliased", "{", "Filter", "Factor", "Classifier", "}", "." ]
quantopian/zipline
python
https://github.com/quantopian/zipline/blob/77ad15e6dc4c1cbcdc133653bac8a63fc704f7fe/zipline/pipeline/mixins.py#L297-L323
[ "def", "make_aliased_type", "(", "cls", ",", "other_base", ")", ":", "docstring", "=", "dedent", "(", "\"\"\"\n A {t} that names another {t}.\n\n Parameters\n ----------\n term : {t}\n {{name}}\n \"\"\"", ")", ".", "form...
77ad15e6dc4c1cbcdc133653bac8a63fc704f7fe
train
DownsampledMixin.compute_extra_rows
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. ...
zipline/pipeline/mixins.py
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): """ Ensure that min_extra_rows pushes us back to a computation date. Parameters ---------- a...
[ "Ensure", "that", "min_extra_rows", "pushes", "us", "back", "to", "a", "computation", "date", "." ]
quantopian/zipline
python
https://github.com/quantopian/zipline/blob/77ad15e6dc4c1cbcdc133653bac8a63fc704f7fe/zipline/pipeline/mixins.py#L370-L437
[ "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...
77ad15e6dc4c1cbcdc133653bac8a63fc704f7fe
train
DownsampledMixin._compute
Compute by delegating to self._wrapped_term._compute on sample dates. On non-sample dates, forward-fill from previously-computed samples.
zipline/pipeline/mixins.py
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): """ 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...
[ "Compute", "by", "delegating", "to", "self", ".", "_wrapped_term", ".", "_compute", "on", "sample", "dates", "." ]
quantopian/zipline
python
https://github.com/quantopian/zipline/blob/77ad15e6dc4c1cbcdc133653bac8a63fc704f7fe/zipline/pipeline/mixins.py#L439-L516
[ "def", "_compute", "(", "self", ",", "inputs", ",", "dates", ",", "assets", ",", "mask", ")", ":", "to_sample", "=", "dates", "[", "select_sampling_indices", "(", "dates", ",", "self", ".", "_frequency", ")", "]", "assert", "to_sample", "[", "0", "]", ...
77ad15e6dc4c1cbcdc133653bac8a63fc704f7fe
train
DownsampledMixin.make_downsampled_type
Factory for making Downsampled{Filter,Factor,Classifier}.
zipline/pipeline/mixins.py
def make_downsampled_type(cls, other_base): """ Factory for making Downsampled{Filter,Factor,Classifier}. """ docstring = dedent( """ A {t} that defers to another {t} at lower-than-daily frequency. Parameters ---------- term : ...
def make_downsampled_type(cls, other_base): """ Factory for making Downsampled{Filter,Factor,Classifier}. """ docstring = dedent( """ A {t} that defers to another {t} at lower-than-daily frequency. Parameters ---------- term : ...
[ "Factory", "for", "making", "Downsampled", "{", "Filter", "Factor", "Classifier", "}", "." ]
quantopian/zipline
python
https://github.com/quantopian/zipline/blob/77ad15e6dc4c1cbcdc133653bac8a63fc704f7fe/zipline/pipeline/mixins.py#L519-L545
[ "def", "make_downsampled_type", "(", "cls", ",", "other_base", ")", ":", "docstring", "=", "dedent", "(", "\"\"\"\n A {t} that defers to another {t} at lower-than-daily frequency.\n\n Parameters\n ----------\n term : {t}\n {{frequency}}\...
77ad15e6dc4c1cbcdc133653bac8a63fc704f7fe
train
preprocess
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...
zipline/utils/preprocess.py
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): """ 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...
[ "Decorator", "that", "applies", "pre", "-", "processors", "to", "the", "arguments", "of", "a", "function", "before", "calling", "the", "function", "." ]
quantopian/zipline
python
https://github.com/quantopian/zipline/blob/77ad15e6dc4c1cbcdc133653bac8a63fc704f7fe/zipline/utils/preprocess.py#L35-L112
[ "def", "preprocess", "(", "*", "_unused", ",", "*", "*", "processors", ")", ":", "if", "_unused", ":", "raise", "TypeError", "(", "\"preprocess() doesn't accept positional arguments\"", ")", "def", "_decorator", "(", "f", ")", ":", "args", ",", "varargs", ",",...
77ad15e6dc4c1cbcdc133653bac8a63fc704f7fe
train
call
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 -------- >>...
zipline/utils/preprocess.py
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): """ 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...
[ "Wrap", "a", "function", "in", "a", "processor", "that", "calls", "f", "on", "the", "argument", "before", "passing", "it", "along", "." ]
quantopian/zipline
python
https://github.com/quantopian/zipline/blob/77ad15e6dc4c1cbcdc133653bac8a63fc704f7fe/zipline/utils/preprocess.py#L115-L139
[ "def", "call", "(", "f", ")", ":", "@", "wraps", "(", "f", ")", "def", "processor", "(", "func", ",", "argname", ",", "arg", ")", ":", "return", "f", "(", "arg", ")", "return", "processor" ]
77ad15e6dc4c1cbcdc133653bac8a63fc704f7fe
train
_build_preprocessed_function
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.
zipline/utils/preprocess.py
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): """ Build a preprocessed function with the same signature as `func`. Uses `exec` internally ...
[ "Build", "a", "preprocessed", "function", "with", "the", "same", "signature", "as", "func", "." ]
quantopian/zipline
python
https://github.com/quantopian/zipline/blob/77ad15e6dc4c1cbcdc133653bac8a63fc704f7fe/zipline/utils/preprocess.py#L142-L247
[ "def", "_build_preprocessed_function", "(", "func", ",", "processors", ",", "args_defaults", ",", "varargs", ",", "varkw", ")", ":", "format_kwargs", "=", "{", "'func_name'", ":", "func", ".", "__name__", "}", "def", "mangle", "(", "name", ")", ":", "return"...
77ad15e6dc4c1cbcdc133653bac8a63fc704f7fe
train
get_benchmark_returns
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.
zipline/data/benchmarks.py
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): """ 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", "a", "Series", "of", "benchmark", "returns", "from", "IEX", "associated", "with", "symbol", ".", "Default", "is", "SPY", "." ]
quantopian/zipline
python
https://github.com/quantopian/zipline/blob/77ad15e6dc4c1cbcdc133653bac8a63fc704f7fe/zipline/data/benchmarks.py#L19-L42
[ "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...
77ad15e6dc4c1cbcdc133653bac8a63fc704f7fe
train
delimit
Surround `content` with the first and last characters of `delimiters`. >>> delimit('[]', "foo") # doctest: +SKIP '[foo]' >>> delimit('""', "foo") # doctest: +SKIP '"foo"'
zipline/pipeline/visualize.py
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): """ 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...
[ "Surround", "content", "with", "the", "first", "and", "last", "characters", "of", "delimiters", "." ]
quantopian/zipline
python
https://github.com/quantopian/zipline/blob/77ad15e6dc4c1cbcdc133653bac8a63fc704f7fe/zipline/pipeline/visualize.py#L24-L37
[ "def", "delimit", "(", "delimiters", ",", "content", ")", ":", "if", "len", "(", "delimiters", ")", "!=", "2", ":", "raise", "ValueError", "(", "\"`delimiters` must be of length 2. Got %r\"", "%", "delimiters", ")", "return", "''", ".", "join", "(", "[", "de...
77ad15e6dc4c1cbcdc133653bac8a63fc704f7fe
train
roots
Get nodes from graph G with indegree 0
zipline/pipeline/visualize.py
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): "Get nodes from graph G with indegree 0" return set(n for n, d in iteritems(g.in_degree()) if d == 0)
[ "Get", "nodes", "from", "graph", "G", "with", "indegree", "0" ]
quantopian/zipline
python
https://github.com/quantopian/zipline/blob/77ad15e6dc4c1cbcdc133653bac8a63fc704f7fe/zipline/pipeline/visualize.py#L73-L75
[ "def", "roots", "(", "g", ")", ":", "return", "set", "(", "n", "for", "n", ",", "d", "in", "iteritems", "(", "g", ".", "in_degree", "(", ")", ")", "if", "d", "==", "0", ")" ]
77ad15e6dc4c1cbcdc133653bac8a63fc704f7fe
train
_render
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.
zipline/pipeline/visualize.py
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): """ 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...
[ "Draw", "g", "as", "a", "graph", "to", "out", "in", "format", "format", "." ]
quantopian/zipline
python
https://github.com/quantopian/zipline/blob/77ad15e6dc4c1cbcdc133653bac8a63fc704f7fe/zipline/pipeline/visualize.py#L84-L149
[ "def", "_render", "(", "g", ",", "out", ",", "format_", ",", "include_asset_exists", "=", "False", ")", ":", "graph_attrs", "=", "{", "'rankdir'", ":", "'TB'", ",", "'splines'", ":", "'ortho'", "}", "cluster_attrs", "=", "{", "'style'", ":", "'filled'", ...
77ad15e6dc4c1cbcdc133653bac8a63fc704f7fe
train
display_graph
Display a TermGraph interactively from within IPython.
zipline/pipeline/visualize.py
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): """ 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': ...
[ "Display", "a", "TermGraph", "interactively", "from", "within", "IPython", "." ]
quantopian/zipline
python
https://github.com/quantopian/zipline/blob/77ad15e6dc4c1cbcdc133653bac8a63fc704f7fe/zipline/pipeline/visualize.py#L152-L168
[ "def", "display_graph", "(", "g", ",", "format", "=", "'svg'", ",", "include_asset_exists", "=", "False", ")", ":", "try", ":", "import", "IPython", ".", "display", "as", "display", "except", "ImportError", ":", "raise", "NoIPython", "(", "\"IPython is not ins...
77ad15e6dc4c1cbcdc133653bac8a63fc704f7fe
train
format_attrs
Format key, value pairs from attrs into graphviz attrs format Examples -------- >>> format_attrs({'key1': 'value1', 'key2': 'value2'}) # doctest: +SKIP '[key1=value1, key2=value2]'
zipline/pipeline/visualize.py
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): """ 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...
[ "Format", "key", "value", "pairs", "from", "attrs", "into", "graphviz", "attrs", "format" ]
quantopian/zipline
python
https://github.com/quantopian/zipline/blob/77ad15e6dc4c1cbcdc133653bac8a63fc704f7fe/zipline/pipeline/visualize.py#L215-L227
[ "def", "format_attrs", "(", "attrs", ")", ":", "if", "not", "attrs", ":", "return", "''", "entries", "=", "[", "'='", ".", "join", "(", "(", "key", ",", "value", ")", ")", "for", "key", ",", "value", "in", "iteritems", "(", "attrs", ")", "]", "re...
77ad15e6dc4c1cbcdc133653bac8a63fc704f7fe
train
SequentialPool.apply_async
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 ---...
zipline/utils/pool.py
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): """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...
[ "Apply", "a", "function", "but", "emulate", "the", "API", "of", "an", "asynchronous", "call", "." ]
quantopian/zipline
python
https://github.com/quantopian/zipline/blob/77ad15e6dc4c1cbcdc133653bac8a63fc704f7fe/zipline/utils/pool.py#L84-L116
[ "def", "apply_async", "(", "f", ",", "args", "=", "(", ")", ",", "kwargs", "=", "None", ",", "callback", "=", "None", ")", ":", "try", ":", "value", "=", "(", "identity", "if", "callback", "is", "None", "else", "callback", ")", "(", "f", "(", "*"...
77ad15e6dc4c1cbcdc133653bac8a63fc704f7fe
train
maybe_show_progress
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 ...
zipline/utils/cli.py
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): """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. ...
[ "Optionally", "show", "a", "progress", "bar", "for", "the", "given", "iterator", "." ]
quantopian/zipline
python
https://github.com/quantopian/zipline/blob/77ad15e6dc4c1cbcdc133653bac8a63fc704f7fe/zipline/utils/cli.py#L7-L36
[ "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"...
77ad15e6dc4c1cbcdc133653bac8a63fc704f7fe
train
main
Top level zipline entry point.
zipline/__main__.py
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): """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, ...
[ "Top", "level", "zipline", "entry", "point", "." ]
quantopian/zipline
python
https://github.com/quantopian/zipline/blob/77ad15e6dc4c1cbcdc133653bac8a63fc704f7fe/zipline/__main__.py#L49-L61
[ "def", "main", "(", "extension", ",", "strict_extensions", ",", "default_extension", ",", "x", ")", ":", "# install a logbook handler before performing any other operations", "logbook", ".", "StderrHandler", "(", ")", ".", "push_application", "(", ")", "create_args", "(...
77ad15e6dc4c1cbcdc133653bac8a63fc704f7fe
train
ipython_only
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.
zipline/__main__.py
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): """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...
[ "Mark", "that", "an", "option", "should", "only", "be", "exposed", "in", "IPython", "." ]
quantopian/zipline
python
https://github.com/quantopian/zipline/blob/77ad15e6dc4c1cbcdc133653bac8a63fc704f7fe/zipline/__main__.py#L84-L109
[ "def", "ipython_only", "(", "option", ")", ":", "if", "__IPYTHON__", ":", "return", "option", "argname", "=", "extract_option_object", "(", "option", ")", ".", "name", "def", "d", "(", "f", ")", ":", "@", "wraps", "(", "f", ")", "def", "_", "(", "*",...
77ad15e6dc4c1cbcdc133653bac8a63fc704f7fe
train
run
Run a backtest for the given algorithm.
zipline/__main__.py
def run(ctx, algofile, algotext, define, data_frequency, capital_base, bundle, bundle_timestamp, start, end, output, trading_calendar, print_algo, metrics_set, local_namespace, blotter): """Run a ...
def run(ctx, algofile, algotext, define, data_frequency, capital_base, bundle, bundle_timestamp, start, end, output, trading_calendar, print_algo, metrics_set, local_namespace, blotter): """Run a ...
[ "Run", "a", "backtest", "for", "the", "given", "algorithm", "." ]
quantopian/zipline
python
https://github.com/quantopian/zipline/blob/77ad15e6dc4c1cbcdc133653bac8a63fc704f7fe/zipline/__main__.py#L216-L284
[ "def", "run", "(", "ctx", ",", "algofile", ",", "algotext", ",", "define", ",", "data_frequency", ",", "capital_base", ",", "bundle", ",", "bundle_timestamp", ",", "start", ",", "end", ",", "output", ",", "trading_calendar", ",", "print_algo", ",", "metrics_...
77ad15e6dc4c1cbcdc133653bac8a63fc704f7fe
train
zipline_magic
The zipline IPython cell magic.
zipline/__main__.py
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): """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 ...
[ "The", "zipline", "IPython", "cell", "magic", "." ]
quantopian/zipline
python
https://github.com/quantopian/zipline/blob/77ad15e6dc4c1cbcdc133653bac8a63fc704f7fe/zipline/__main__.py#L287-L317
[ "def", "zipline_magic", "(", "line", ",", "cell", "=", "None", ")", ":", "load_extensions", "(", "default", "=", "True", ",", "extensions", "=", "[", "]", ",", "strict", "=", "True", ",", "environ", "=", "os", ".", "environ", ",", ")", "try", ":", ...
77ad15e6dc4c1cbcdc133653bac8a63fc704f7fe
train
ingest
Ingest the data for the given bundle.
zipline/__main__.py
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): """Ingest the data for the given bundle. """ bundles_module.ingest( bundle, os.environ, pd.Timestamp.utcnow(), assets_version, show_progress, )
[ "Ingest", "the", "data", "for", "the", "given", "bundle", "." ]
quantopian/zipline
python
https://github.com/quantopian/zipline/blob/77ad15e6dc4c1cbcdc133653bac8a63fc704f7fe/zipline/__main__.py#L340-L349
[ "def", "ingest", "(", "bundle", ",", "assets_version", ",", "show_progress", ")", ":", "bundles_module", ".", "ingest", "(", "bundle", ",", "os", ".", "environ", ",", "pd", ".", "Timestamp", ".", "utcnow", "(", ")", ",", "assets_version", ",", "show_progre...
77ad15e6dc4c1cbcdc133653bac8a63fc704f7fe
train
clean
Clean up data downloaded with the ingest command.
zipline/__main__.py
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): """Clean up data downloaded with the ingest command. """ bundles_module.clean( bundle, before, after, keep_last, )
[ "Clean", "up", "data", "downloaded", "with", "the", "ingest", "command", "." ]
quantopian/zipline
python
https://github.com/quantopian/zipline/blob/77ad15e6dc4c1cbcdc133653bac8a63fc704f7fe/zipline/__main__.py#L383-L391
[ "def", "clean", "(", "bundle", ",", "before", ",", "after", ",", "keep_last", ")", ":", "bundles_module", ".", "clean", "(", "bundle", ",", "before", ",", "after", ",", "keep_last", ",", ")" ]
77ad15e6dc4c1cbcdc133653bac8a63fc704f7fe
train
bundles
List all of the available data bundles.
zipline/__main__.py
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(): """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...
[ "List", "all", "of", "the", "available", "data", "bundles", "." ]
quantopian/zipline
python
https://github.com/quantopian/zipline/blob/77ad15e6dc4c1cbcdc133653bac8a63fc704f7fe/zipline/__main__.py#L395-L415
[ "def", "bundles", "(", ")", ":", "for", "bundle", "in", "sorted", "(", "bundles_module", ".", "bundles", ".", "keys", "(", ")", ")", ":", "if", "bundle", ".", "startswith", "(", "'.'", ")", ":", "# hide the test data", "continue", "try", ":", "ingestions...
77ad15e6dc4c1cbcdc133653bac8a63fc704f7fe
train
binary_operator
Factory function for making binary operator methods on a Filter subclass. Returns a function "binary_operator" suitable for implementing functions like __and__ or __or__.
zipline/pipeline/filters/filter.py
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): """ 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...
[ "Factory", "function", "for", "making", "binary", "operator", "methods", "on", "a", "Filter", "subclass", "." ]
quantopian/zipline
python
https://github.com/quantopian/zipline/blob/77ad15e6dc4c1cbcdc133653bac8a63fc704f7fe/zipline/pipeline/filters/filter.py#L62-L112
[ "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_...
77ad15e6dc4c1cbcdc133653bac8a63fc704f7fe
train
unary_operator
Factory function for making unary operator methods for Filters.
zipline/pipeline/filters/filter.py
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): """ 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...
[ "Factory", "function", "for", "making", "unary", "operator", "methods", "for", "Filters", "." ]
quantopian/zipline
python
https://github.com/quantopian/zipline/blob/77ad15e6dc4c1cbcdc133653bac8a63fc704f7fe/zipline/pipeline/filters/filter.py#L115-L136
[ "def", "unary_operator", "(", "op", ")", ":", "valid_ops", "=", "{", "'~'", "}", "if", "op", "not", "in", "valid_ops", ":", "raise", "ValueError", "(", "\"Invalid unary operator %s.\"", "%", "op", ")", "def", "unary_operator", "(", "self", ")", ":", "# Thi...
77ad15e6dc4c1cbcdc133653bac8a63fc704f7fe
train
NumExprFilter.create
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.
zipline/pipeline/filters/filter.py
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): """ 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=...
[ "Helper", "for", "creating", "new", "NumExprFactors", "." ]
quantopian/zipline
python
https://github.com/quantopian/zipline/blob/77ad15e6dc4c1cbcdc133653bac8a63fc704f7fe/zipline/pipeline/filters/filter.py#L237-L245
[ "def", "create", "(", "cls", ",", "expr", ",", "binds", ")", ":", "return", "cls", "(", "expr", "=", "expr", ",", "binds", "=", "binds", ",", "dtype", "=", "bool_dtype", ")" ]
77ad15e6dc4c1cbcdc133653bac8a63fc704f7fe
train
NumExprFilter._compute
Compute our result with numexpr, then re-apply `mask`.
zipline/pipeline/filters/filter.py
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): """ Compute our result with numexpr, then re-apply `mask`. """ return super(NumExprFilter, self)._compute( arrays, dates, assets, mask, ) & mask
[ "Compute", "our", "result", "with", "numexpr", "then", "re", "-", "apply", "mask", "." ]
quantopian/zipline
python
https://github.com/quantopian/zipline/blob/77ad15e6dc4c1cbcdc133653bac8a63fc704f7fe/zipline/pipeline/filters/filter.py#L247-L256
[ "def", "_compute", "(", "self", ",", "arrays", ",", "dates", ",", "assets", ",", "mask", ")", ":", "return", "super", "(", "NumExprFilter", ",", "self", ")", ".", "_compute", "(", "arrays", ",", "dates", ",", "assets", ",", "mask", ",", ")", "&", "...
77ad15e6dc4c1cbcdc133653bac8a63fc704f7fe
train
PercentileFilter._validate
Ensure that our percentile bounds are well-formed.
zipline/pipeline/filters/filter.py
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): """ 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...
[ "Ensure", "that", "our", "percentile", "bounds", "are", "well", "-", "formed", "." ]
quantopian/zipline
python
https://github.com/quantopian/zipline/blob/77ad15e6dc4c1cbcdc133653bac8a63fc704f7fe/zipline/pipeline/filters/filter.py#L344-L354
[ "def", "_validate", "(", "self", ")", ":", "if", "not", "0.0", "<=", "self", ".", "_min_percentile", "<", "self", ".", "_max_percentile", "<=", "100.0", ":", "raise", "BadPercentileBounds", "(", "min_percentile", "=", "self", ".", "_min_percentile", ",", "ma...
77ad15e6dc4c1cbcdc133653bac8a63fc704f7fe
train
PercentileFilter._compute
For each row in the input, compute a mask of all values falling between the given percentiles.
zipline/pipeline/filters/filter.py
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): """ 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...
[ "For", "each", "row", "in", "the", "input", "compute", "a", "mask", "of", "all", "values", "falling", "between", "the", "given", "percentiles", "." ]
quantopian/zipline
python
https://github.com/quantopian/zipline/blob/77ad15e6dc4c1cbcdc133653bac8a63fc704f7fe/zipline/pipeline/filters/filter.py#L356-L382
[ "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...
77ad15e6dc4c1cbcdc133653bac8a63fc704f7fe
train
parse_treasury_csv_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...
zipline/data/treasuries.py
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): """ 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, ...
[ "Parse", "a", "treasury", "CSV", "column", "into", "a", "more", "human", "-", "readable", "format", "." ]
quantopian/zipline
python
https://github.com/quantopian/zipline/blob/77ad15e6dc4c1cbcdc133653bac8a63fc704f7fe/zipline/data/treasuries.py#L25-L47
[ "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"...
77ad15e6dc4c1cbcdc133653bac8a63fc704f7fe
train
get_daily_10yr_treasury_data
Download daily 10 year treasury rates from the Federal Reserve and return a pandas.Series.
zipline/data/treasuries.py
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(): """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...
[ "Download", "daily", "10", "year", "treasury", "rates", "from", "the", "Federal", "Reserve", "and", "return", "a", "pandas", ".", "Series", "." ]
quantopian/zipline
python
https://github.com/quantopian/zipline/blob/77ad15e6dc4c1cbcdc133653bac8a63fc704f7fe/zipline/data/treasuries.py#L93-L101
[ "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"...
77ad15e6dc4c1cbcdc133653bac8a63fc704f7fe
train
_sid_subdir_path
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...
zipline/data/minute_bars.py
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): """ 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 :...
[ "Format", "subdir", "path", "to", "limit", "the", "number", "directories", "in", "any", "given", "subdirectory", "to", "100", "." ]
quantopian/zipline
python
https://github.com/quantopian/zipline/blob/77ad15e6dc4c1cbcdc133653bac8a63fc704f7fe/zipline/data/minute_bars.py#L85-L113
[ "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", "...
77ad15e6dc4c1cbcdc133653bac8a63fc704f7fe