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'][pretrained] model = load_pretrained(model, num_classes, settings) model = modify_densenets(model) return model
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'][pretrained] model = load_pretrained(model, num_classes, settings) model = modify_densenets(model) return model
[ "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 = pretrained_settings['inceptionv3'][pretrained] model = load_pretrained(model, num_classes, settings) # Modify attributs model.last_linear = model.fc del model.fc def features(self, input): # 299 x 299 x 3 x = self.Conv2d_1a_3x3(input) # 149 x 149 x 32 x = self.Conv2d_2a_3x3(x) # 147 x 147 x 32 x = self.Conv2d_2b_3x3(x) # 147 x 147 x 64 x = F.max_pool2d(x, kernel_size=3, stride=2) # 73 x 73 x 64 x = self.Conv2d_3b_1x1(x) # 73 x 73 x 80 x = self.Conv2d_4a_3x3(x) # 71 x 71 x 192 x = F.max_pool2d(x, kernel_size=3, stride=2) # 35 x 35 x 192 x = self.Mixed_5b(x) # 35 x 35 x 256 x = self.Mixed_5c(x) # 35 x 35 x 288 x = self.Mixed_5d(x) # 35 x 35 x 288 x = self.Mixed_6a(x) # 17 x 17 x 768 x = self.Mixed_6b(x) # 17 x 17 x 768 x = self.Mixed_6c(x) # 17 x 17 x 768 x = self.Mixed_6d(x) # 17 x 17 x 768 x = self.Mixed_6e(x) # 17 x 17 x 768 if self.training and self.aux_logits: self._out_aux = self.AuxLogits(x) # 17 x 17 x 768 x = self.Mixed_7a(x) # 8 x 8 x 1280 x = self.Mixed_7b(x) # 8 x 8 x 2048 x = self.Mixed_7c(x) # 8 x 8 x 2048 return x def logits(self, features): x = F.avg_pool2d(features, kernel_size=8) # 1 x 1 x 2048 x = F.dropout(x, training=self.training) # 1 x 1 x 2048 x = x.view(x.size(0), -1) # 2048 x = self.last_linear(x) # 1000 (num_classes) if self.training and self.aux_logits: aux = self._out_aux self._out_aux = None return x, aux return x def forward(self, input): x = self.features(input) x = self.logits(x) return x # Modify methods model.features = types.MethodType(features, model) model.logits = types.MethodType(logits, model) model.forward = types.MethodType(forward, model) return model
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 = pretrained_settings['inceptionv3'][pretrained] model = load_pretrained(model, num_classes, settings) # Modify attributs model.last_linear = model.fc del model.fc def features(self, input): # 299 x 299 x 3 x = self.Conv2d_1a_3x3(input) # 149 x 149 x 32 x = self.Conv2d_2a_3x3(x) # 147 x 147 x 32 x = self.Conv2d_2b_3x3(x) # 147 x 147 x 64 x = F.max_pool2d(x, kernel_size=3, stride=2) # 73 x 73 x 64 x = self.Conv2d_3b_1x1(x) # 73 x 73 x 80 x = self.Conv2d_4a_3x3(x) # 71 x 71 x 192 x = F.max_pool2d(x, kernel_size=3, stride=2) # 35 x 35 x 192 x = self.Mixed_5b(x) # 35 x 35 x 256 x = self.Mixed_5c(x) # 35 x 35 x 288 x = self.Mixed_5d(x) # 35 x 35 x 288 x = self.Mixed_6a(x) # 17 x 17 x 768 x = self.Mixed_6b(x) # 17 x 17 x 768 x = self.Mixed_6c(x) # 17 x 17 x 768 x = self.Mixed_6d(x) # 17 x 17 x 768 x = self.Mixed_6e(x) # 17 x 17 x 768 if self.training and self.aux_logits: self._out_aux = self.AuxLogits(x) # 17 x 17 x 768 x = self.Mixed_7a(x) # 8 x 8 x 1280 x = self.Mixed_7b(x) # 8 x 8 x 2048 x = self.Mixed_7c(x) # 8 x 8 x 2048 return x def logits(self, features): x = F.avg_pool2d(features, kernel_size=8) # 1 x 1 x 2048 x = F.dropout(x, training=self.training) # 1 x 1 x 2048 x = x.view(x.size(0), -1) # 2048 x = self.last_linear(x) # 1000 (num_classes) if self.training and self.aux_logits: aux = self._out_aux self._out_aux = None return x, aux return x def forward(self, input): x = self.features(input) x = self.logits(x) return x # Modify methods model.features = types.MethodType(features, model) model.logits = types.MethodType(logits, model) model.forward = types.MethodType(forward, model) return model
[ "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_resnets(model) return model
def resnet50(num_classes=1000, pretrained='imagenet'): """Constructs a ResNet-50 model. """ model = models.resnet50(pretrained=False) if pretrained is not None: settings = pretrained_settings['resnet50'][pretrained] model = load_pretrained(model, num_classes, settings) model = modify_resnets(model) return model
[ "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 pretrained is not None: settings = pretrained_settings['squeezenet1_0'][pretrained] model = load_pretrained(model, num_classes, settings) model = modify_squeezenets(model) return model
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 pretrained is not None: settings = pretrained_settings['squeezenet1_0'][pretrained] model = load_pretrained(model, num_classes, settings) model = modify_squeezenets(model) return model
[ "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_vggs(model) return model
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_vggs(model) return model
[ "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'], \ "num_classes should be {}, but is {}".format(settings['num_classes'], num_classes) # both 'imagenet'&'imagenet+background' are loaded from same parameters model = NASNetALarge(num_classes=1001) model.load_state_dict(model_zoo.load_url(settings['url'])) if pretrained == 'imagenet': new_last_linear = nn.Linear(model.last_linear.in_features, 1000) new_last_linear.weight.data = model.last_linear.weight.data[1:] new_last_linear.bias.data = model.last_linear.bias.data[1:] model.last_linear = new_last_linear model.input_space = settings['input_space'] model.input_size = settings['input_size'] model.input_range = settings['input_range'] model.mean = settings['mean'] model.std = settings['std'] else: model = NASNetALarge(num_classes=num_classes) return model
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'], \ "num_classes should be {}, but is {}".format(settings['num_classes'], num_classes) # both 'imagenet'&'imagenet+background' are loaded from same parameters model = NASNetALarge(num_classes=1001) model.load_state_dict(model_zoo.load_url(settings['url'])) if pretrained == 'imagenet': new_last_linear = nn.Linear(model.last_linear.in_features, 1000) new_last_linear.weight.data = model.last_linear.weight.data[1:] new_last_linear.bias.data = model.last_linear.bias.data[1:] model.last_linear = new_last_linear model.input_space = settings['input_space'] model.input_size = settings['input_size'] model.input_range = settings['input_range'] model.mean = settings['mean'] model.std = settings['std'] else: model = NASNetALarge(num_classes=num_classes) return model
[ "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, count_include_pad=count_include_pad), F.max_pool2d(x, kernel_size=(x.size(2), x.size(3)), padding=padding) ], dim=1) elif pool_type == 'avgmax': x_avg = F.avg_pool2d( x, kernel_size=(x.size(2), x.size(3)), padding=padding, count_include_pad=count_include_pad) x_max = F.max_pool2d(x, kernel_size=(x.size(2), x.size(3)), padding=padding) x = 0.5 * (x_avg + x_max) elif pool_type == 'max': x = F.max_pool2d(x, kernel_size=(x.size(2), x.size(3)), padding=padding) else: if pool_type != 'avg': print('Invalid pool type %s specified. Defaulting to average pooling.' % pool_type) x = F.avg_pool2d( x, kernel_size=(x.size(2), x.size(3)), padding=padding, count_include_pad=count_include_pad) return x
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, count_include_pad=count_include_pad), F.max_pool2d(x, kernel_size=(x.size(2), x.size(3)), padding=padding) ], dim=1) elif pool_type == 'avgmax': x_avg = F.avg_pool2d( x, kernel_size=(x.size(2), x.size(3)), padding=padding, count_include_pad=count_include_pad) x_max = F.max_pool2d(x, kernel_size=(x.size(2), x.size(3)), padding=padding) x = 0.5 * (x_avg + x_max) elif pool_type == 'max': x = F.max_pool2d(x, kernel_size=(x.size(2), x.size(3)), padding=padding) else: if pool_type != 'avg': print('Invalid pool type %s specified. Defaulting to average pooling.' % pool_type) x = F.avg_pool2d( x, kernel_size=(x.size(2), x.size(3)), padding=padding, count_include_pad=count_include_pad) return x
[ "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 downloading. Returns ------- filename : str The location of the downloaded file. Notes ----- Progress bar use/example adapted from tqdm documentation: https://github.com/tqdm/tqdm
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 : bool Whether to show a command-line progress bar while downloading. Returns ------- filename : str The location of the downloaded file. Notes ----- Progress bar use/example adapted from tqdm documentation: https://github.com/tqdm/tqdm """ def my_hook(t): last_b = [0] def inner(b=1, bsize=1, tsize=None): if tsize is not None: t.total = tsize if b > 0: t.update((b - last_b[0]) * bsize) last_b[0] = b return inner if progress_bar: with tqdm(unit='B', unit_scale=True, miniters=1, desc=url.split('/')[-1]) as t: filename, _ = urlretrieve(url, filename=destination, reporthook=my_hook(t)) else: filename, _ = urlretrieve(url, filename=destination)
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 : bool Whether to show a command-line progress bar while downloading. Returns ------- filename : str The location of the downloaded file. Notes ----- Progress bar use/example adapted from tqdm documentation: https://github.com/tqdm/tqdm """ def my_hook(t): last_b = [0] def inner(b=1, bsize=1, tsize=None): if tsize is not None: t.total = tsize if b > 0: t.update((b - last_b[0]) * bsize) last_b[0] = b return inner if progress_bar: with tqdm(unit='B', unit_scale=True, miniters=1, desc=url.split('/')[-1]) as t: filename, _ = urlretrieve(url, filename=destination, reporthook=my_hook(t)) else: filename, _ = urlretrieve(url, filename=destination)
[ "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 tensort that encodes which of the K classes are associated with the N-th input (eg: a row [0, 1, 0, 1] indicates that the example is associated with classes 2 and 4) weight (optional, Tensor): Nx1 tensor representing the weight for each example (each weight > 0)
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 all classes target (Tensor): binary NxK tensort that encodes which of the K classes are associated with the N-th input (eg: a row [0, 1, 0, 1] indicates that the example is associated with classes 2 and 4) weight (optional, Tensor): Nx1 tensor representing the weight for each example (each weight > 0) """ if not torch.is_tensor(output): output = torch.from_numpy(output) if not torch.is_tensor(target): target = torch.from_numpy(target) if output.dim() == 1: output = output.view(-1, 1) else: assert output.dim() == 2, \ 'wrong output size (should be 1D or 2D with one column \ per class)' if target.dim() == 1: target = target.view(-1, 1) else: assert target.dim() == 2, \ 'wrong target size (should be 1D or 2D with one column \ per class)' if self.scores.numel() > 0: assert target.size(1) == self.targets.size(1), \ 'dimensions for output should match previously added examples.' # make sure storage is of sufficient size if self.scores.storage().size() < self.scores.numel() + output.numel(): new_size = math.ceil(self.scores.storage().size() * 1.5) self.scores.storage().resize_(int(new_size + output.numel())) self.targets.storage().resize_(int(new_size + output.numel())) # store scores and targets offset = self.scores.size(0) if self.scores.dim() > 0 else 0 self.scores.resize_(offset + output.size(0), output.size(1)) self.targets.resize_(offset + target.size(0), target.size(1)) self.scores.narrow(0, offset, output.size(0)).copy_(output) self.targets.narrow(0, offset, target.size(0)).copy_(target)
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 all classes target (Tensor): binary NxK tensort that encodes which of the K classes are associated with the N-th input (eg: a row [0, 1, 0, 1] indicates that the example is associated with classes 2 and 4) weight (optional, Tensor): Nx1 tensor representing the weight for each example (each weight > 0) """ if not torch.is_tensor(output): output = torch.from_numpy(output) if not torch.is_tensor(target): target = torch.from_numpy(target) if output.dim() == 1: output = output.view(-1, 1) else: assert output.dim() == 2, \ 'wrong output size (should be 1D or 2D with one column \ per class)' if target.dim() == 1: target = target.view(-1, 1) else: assert target.dim() == 2, \ 'wrong target size (should be 1D or 2D with one column \ per class)' if self.scores.numel() > 0: assert target.size(1) == self.targets.size(1), \ 'dimensions for output should match previously added examples.' # make sure storage is of sufficient size if self.scores.storage().size() < self.scores.numel() + output.numel(): new_size = math.ceil(self.scores.storage().size() * 1.5) self.scores.storage().resize_(int(new_size + output.numel())) self.targets.storage().resize_(int(new_size + output.numel())) # store scores and targets offset = self.scores.size(0) if self.scores.dim() > 0 else 0 self.scores.resize_(offset + output.size(0), output.size(1)) self.targets.resize_(offset + target.size(0), target.size(1)) self.scores.narrow(0, offset, output.size(0)).copy_(output) self.targets.narrow(0, offset, target.size(0)).copy_(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", "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, self.scores.size(0)).float() # compute average precision for each class for k in range(self.scores.size(1)): # sort scores scores = self.scores[:, k] targets = self.targets[:, k] # compute average precision ap[k] = AveragePrecisionMeter.average_precision(scores, targets, self.difficult_examples) return ap
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, self.scores.size(0)).float() # compute average precision for each class for k in range(self.scores.size(1)): # sort scores scores = self.scores[:, k] targets = self.targets[:, k] # compute average precision ap[k] = AveragePrecisionMeter.average_precision(scores, targets, self.difficult_examples) return ap
[ "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 == settings['num_classes'], \ 'num_classes should be {}, but is {}'.format( settings['num_classes'], num_classes) model = PolyNet(num_classes=num_classes) model.load_state_dict(model_zoo.load_url(settings['url'])) model.input_space = settings['input_space'] model.input_size = settings['input_size'] model.input_range = settings['input_range'] model.mean = settings['mean'] model.std = settings['std'] else: model = PolyNet(num_classes=num_classes) return model
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 == settings['num_classes'], \ 'num_classes should be {}, but is {}'.format( settings['num_classes'], num_classes) model = PolyNet(num_classes=num_classes) model.load_state_dict(model_zoo.load_url(settings['url'])) model.input_space = settings['input_space'] model.input_size = settings['input_size'] model.input_range = settings['input_range'] model.mean = settings['mean'] model.std = settings['std'] else: model = PolyNet(num_classes=num_classes) return model
[ "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 is AlwaysExpired or expires < dt: raise Expired(self._expires) return self._value
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 is AlwaysExpired or expires < dt: raise Expired(self._expires) return self._value
[ "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 Raised if the key is not in the cache or the value for the key has expired.
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 ------ KeyError Raised if the key is not in the cache or the value for the key has expired. """ try: return self._cache[key].unwrap(dt) except Expired: self.cleanup(self._cache[key]._unsafe_get_value()) del self._cache[key] raise KeyError(key)
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 ------ KeyError Raised if the key is not in the cache or the value for the key has expired. """ try: return self._cache[key].unwrap(dt) except Expired: self.cleanup(self._cache[key]._unsafe_get_value()) del self._cache[key] raise KeyError(key)
[ "Get", "the", "value", "of", "a", "cached", "object", "." ]
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 invalid for dates **strictly greater** than ``expiration_dt``.
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 should this mapping expire? The cache is considered invalid for dates **strictly greater** than ``expiration_dt``. """ self._cache[key] = CachedObject(value, expiration_dt)
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 should this mapping expire? The cache is considered invalid for dates **strictly greater** than ``expiration_dt``. """ self._cache[key] = CachedObject(value, expiration_dt)
[ "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) return 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) return 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 indexes do not match a contiguous region of ``calendar``.
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 If frames have different indexes/columns, or if frame indexes do not match a contiguous region of ``calendar``. """ indexes = [f.index for f in frames] check_indexes_all_same(indexes, message="DataFrame indexes don't match:") columns = [f.columns for f in frames] check_indexes_all_same(columns, message="DataFrame columns don't match:") start, end = indexes[0][[0, -1]] cal_sessions = calendar.sessions_in_range(start, end) check_indexes_all_same( [indexes[0], cal_sessions], "DataFrame index doesn't match {} calendar:".format(calendar.name), )
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 If frames have different indexes/columns, or if frame indexes do not match a contiguous region of ``calendar``. """ indexes = [f.index for f in frames] check_indexes_all_same(indexes, message="DataFrame indexes don't match:") columns = [f.columns for f in frames] check_indexes_all_same(columns, message="DataFrame columns don't match:") start, end = indexes[0][[0, -1]] cal_sessions = calendar.sessions_in_range(start, end) check_indexes_all_same( [indexes[0], cal_sessions], "DataFrame index doesn't match {} calendar:".format(calendar.name), )
[ "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 The spot price for colname of the given sid on the given day. Raises a NoDataOnDate exception if the given day and sid is before or after the date range of the equity. Returns -1 if the day is within the date range, but the price is 0.
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', 'volume') Returns ------- float The spot price for colname of the given sid on the given day. Raises a NoDataOnDate exception if the given day and sid is before or after the date range of the equity. Returns -1 if the day is within the date range, but the price is 0. """ return self.frames[field].loc[dt, sid]
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', 'volume') Returns ------- float The spot price for colname of the given sid on the given day. Raises a NoDataOnDate exception if the given day and sid is before or after the date range of the equity. Returns -1 if the day is within the date range, but the price is 0. """ return self.frames[field].loc[dt, sid]
[ "Parameters", "----------", "sid", ":", "int", "The", "asset", "identifier", ".", "day", ":", "datetime64", "-", "like", "Midnight", "of", "the", "day", "for", "which", "data", "is", "requested", ".", "field", ":", "string", "The", "price", "field", ".", ...
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 trade is found before the given dt.
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 dt for the asset and dt; NaT if no trade is found before the given dt. """ try: return self.frames['close'].loc[:, asset.sid].last_valid_index() except IndexError: return NaT
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 dt for the asset and dt; NaT if no trade is found before the given dt. """ try: return self.frames['close'].loc[:, asset.sid].last_valid_index() except IndexError: return NaT
[ "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:] return all(value == first for value in rest)
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:] return all(value == first for value in rest)
[ "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 key in each dict. Raises ------ ValueError If dicts don't all have the same keys. Examples -------- >>> result = dzip_exact({'a': 1, 'b': 2}, {'a': 3, 'b': 4}) >>> result == {'a': (1, 3), 'b': (2, 4)} True
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 the result of looking up each key in each dict. Raises ------ ValueError If dicts don't all have the same keys. Examples -------- >>> result = dzip_exact({'a': 1, 'b': 2}, {'a': 3, 'b': 4}) >>> result == {'a': (1, 3), 'b': (2, 4)} True """ if not same(*map(viewkeys, dicts)): raise ValueError( "dict keys not all equal:\n\n%s" % _format_unequal_keys(dicts) ) return {k: tuple(d[k] for d in dicts) for k in dicts[0]}
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 the result of looking up each key in each dict. Raises ------ ValueError If dicts don't all have the same keys. Examples -------- >>> result = dzip_exact({'a': 1, 'b': 2}, {'a': 3, 'b': 4}) >>> result == {'a': (1, 3), 'b': (2, 4)} True """ if not same(*map(viewkeys, dicts)): raise ValueError( "dict keys not all equal:\n\n%s" % _format_unequal_keys(dicts) ) return {k: tuple(d[k] for d in dicts) for k in dicts[0]}
[ "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 length of the first element. Yields ------ elem : tuple Each element of ``it``. Raises ------ ValueError Raised when the lengths do not match the ``elem_len``.
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. If this is None it is infered from the length of the first element. Yields ------ elem : tuple Each element of ``it``. Raises ------ ValueError Raised when the lengths do not match the ``elem_len``. """ elem = next(it) first_elem_len = len(elem) if elem_len is not None and elem_len != first_elem_len: raise ValueError( 'element at index 0 was length %d, expected %d' % ( first_elem_len, elem_len, ) ) else: elem_len = first_elem_len yield elem for n, elem in enumerate(it, 1): if len(elem) != elem_len: raise ValueError( 'element at index %d was length %d, expected %d' % ( n, len(elem), elem_len, ), ) yield elem
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. If this is None it is infered from the length of the first element. Yields ------ elem : tuple Each element of ``it``. Raises ------ ValueError Raised when the lengths do not match the ``elem_len``. """ elem = next(it) first_elem_len = len(elem) if elem_len is not None and elem_len != first_elem_len: raise ValueError( 'element at index 0 was length %d, expected %d' % ( first_elem_len, elem_len, ) ) else: elem_len = first_elem_len yield elem for n, elem in enumerate(it, 1): if len(elem) != elem_len: raise ValueError( 'element at index %d was length %d, expected %d' % ( n, len(elem), elem_len, ), ) yield elem
[ "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 length of the first element of ``seq``. This can be used to ensure that code like: ``a, b = unzip(seq)`` does not fail even when ``seq`` is empty. Returns ------- seqs : iterable[iterable] The new sequences pulled out of the first iterable. Raises ------ ValueError Raised when ``seq`` is empty and ``elem_len`` is not provided. Raised when elements of ``seq`` do not match the given ``elem_len`` or the length of the first element of ``seq``. Examples -------- >>> seq = [('a', 1), ('b', 2), ('c', 3)] >>> cs, ns = unzip(seq) >>> cs ('a', 'b', 'c') >>> ns (1, 2, 3) # checks that the elements are the same length >>> seq = [('a', 1), ('b', 2), ('c', 3, 'extra')] >>> cs, ns = unzip(seq) Traceback (most recent call last): ... ValueError: element at index 2 was length 3, expected 2 # allows an explicit element length instead of infering >>> seq = [('a', 1, 'extra'), ('b', 2), ('c', 3)] >>> cs, ns = unzip(seq, 2) Traceback (most recent call last): ... ValueError: element at index 0 was length 3, expected 2 # handles empty sequences when a length is given >>> cs, ns = unzip([], elem_len=2) >>> cs == ns == () True Notes ----- This function will force ``seq`` to completion.
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 this will be infered from the length of the first element of ``seq``. This can be used to ensure that code like: ``a, b = unzip(seq)`` does not fail even when ``seq`` is empty. Returns ------- seqs : iterable[iterable] The new sequences pulled out of the first iterable. Raises ------ ValueError Raised when ``seq`` is empty and ``elem_len`` is not provided. Raised when elements of ``seq`` do not match the given ``elem_len`` or the length of the first element of ``seq``. Examples -------- >>> seq = [('a', 1), ('b', 2), ('c', 3)] >>> cs, ns = unzip(seq) >>> cs ('a', 'b', 'c') >>> ns (1, 2, 3) # checks that the elements are the same length >>> seq = [('a', 1), ('b', 2), ('c', 3, 'extra')] >>> cs, ns = unzip(seq) Traceback (most recent call last): ... ValueError: element at index 2 was length 3, expected 2 # allows an explicit element length instead of infering >>> seq = [('a', 1, 'extra'), ('b', 2), ('c', 3)] >>> cs, ns = unzip(seq, 2) Traceback (most recent call last): ... ValueError: element at index 0 was length 3, expected 2 # handles empty sequences when a length is given >>> cs, ns = unzip([], elem_len=2) >>> cs == ns == () True Notes ----- This function will force ``seq`` to completion. """ ret = tuple(zip(*_gen_unzip(map(tuple, seq), elem_len))) if ret: return ret if elem_len is None: raise ValueError("cannot unzip empty sequence without 'elem_len'") return ((),) * elem_len
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 this will be infered from the length of the first element of ``seq``. This can be used to ensure that code like: ``a, b = unzip(seq)`` does not fail even when ``seq`` is empty. Returns ------- seqs : iterable[iterable] The new sequences pulled out of the first iterable. Raises ------ ValueError Raised when ``seq`` is empty and ``elem_len`` is not provided. Raised when elements of ``seq`` do not match the given ``elem_len`` or the length of the first element of ``seq``. Examples -------- >>> seq = [('a', 1), ('b', 2), ('c', 3)] >>> cs, ns = unzip(seq) >>> cs ('a', 'b', 'c') >>> ns (1, 2, 3) # checks that the elements are the same length >>> seq = [('a', 1), ('b', 2), ('c', 3, 'extra')] >>> cs, ns = unzip(seq) Traceback (most recent call last): ... ValueError: element at index 2 was length 3, expected 2 # allows an explicit element length instead of infering >>> seq = [('a', 1, 'extra'), ('b', 2), ('c', 3)] >>> cs, ns = unzip(seq, 2) Traceback (most recent call last): ... ValueError: element at index 0 was length 3, expected 2 # handles empty sequences when a length is given >>> cs, ns = unzip([], elem_len=2) >>> cs == ns == () True Notes ----- This function will force ``seq`` to completion. """ ret = tuple(zip(*_gen_unzip(map(tuple, seq), elem_len))) if ret: return ret if elem_len is None: raise ValueError("cannot unzip empty sequence without 'elem_len'") return ((),) * elem_len
[ "Unzip", "a", "length", "n", "sequence", "of", "length", "m", "sequences", "into", "m", "seperate", "length", "n", "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 look up. default : object, optional Value to return if any of the lookups fail. Returns ------- result : object Result of the lookup sequence. Examples -------- >>> class EmptyObject(object): ... pass ... >>> obj = EmptyObject() >>> obj.foo = EmptyObject() >>> obj.foo.bar = "value" >>> getattrs(obj, ('foo', 'bar')) 'value' >>> getattrs(obj, ('foo', 'buzz')) Traceback (most recent call last): ... AttributeError: 'EmptyObject' object has no attribute 'buzz' >>> getattrs(obj, ('foo', 'buzz'), 'default') 'default'
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. attrs : iterable[str] Sequence of attributes to look up. default : object, optional Value to return if any of the lookups fail. Returns ------- result : object Result of the lookup sequence. Examples -------- >>> class EmptyObject(object): ... pass ... >>> obj = EmptyObject() >>> obj.foo = EmptyObject() >>> obj.foo.bar = "value" >>> getattrs(obj, ('foo', 'bar')) 'value' >>> getattrs(obj, ('foo', 'buzz')) Traceback (most recent call last): ... AttributeError: 'EmptyObject' object has no attribute 'buzz' >>> getattrs(obj, ('foo', 'buzz'), 'default') 'default' """ try: for attr in attrs: value = getattr(value, attr) except AttributeError: if default is _no_default: raise value = default return value
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. attrs : iterable[str] Sequence of attributes to look up. default : object, optional Value to return if any of the lookups fail. Returns ------- result : object Result of the lookup sequence. Examples -------- >>> class EmptyObject(object): ... pass ... >>> obj = EmptyObject() >>> obj.foo = EmptyObject() >>> obj.foo.bar = "value" >>> getattrs(obj, ('foo', 'bar')) 'value' >>> getattrs(obj, ('foo', 'buzz')) Traceback (most recent call last): ... AttributeError: 'EmptyObject' object has no attribute 'buzz' >>> getattrs(obj, ('foo', 'buzz'), 'default') 'default' """ try: for attr in attrs: value = getattr(value, attr) except AttributeError: if default is _no_default: raise value = default return value
[ "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__ 'foo' """ def decorator(f): setattr(f, name, value) return f return decorator
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__ 'foo' """ def decorator(f): setattr(f, name, value) return f return decorator
[ "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 sequence to reduce. default : any, optional The starting value to reduce with. If not provided, the sequence cannot be empty, and the last value of the sequence will be used. Returns ------- folded : any The folded value. Notes ----- This functions works by reducing the list in a right associative way. For example, imagine we are folding with ``operator.add`` or ``+``: .. code-block:: python foldr(add, seq) -> seq[0] + (seq[1] + (seq[2] + (...seq[-1], default))) In the more general case with an arbitrary function, ``foldr`` will expand like so: .. code-block:: python foldr(f, seq) -> f(seq[0], f(seq[1], f(seq[2], ...f(seq[-1], default)))) For a more in depth discussion of left and right folds, see: `https://en.wikipedia.org/wiki/Fold_(higher-order_function)`_ The images in that page are very good for showing the differences between ``foldr`` and ``foldl`` (``reduce``). .. note:: For performance reasons is is best to pass a strict (non-lazy) sequence, for example, a list. See Also -------- :func:`functools.reduce` :func:`sum`
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 accumulator. seq : iterable[any] The sequence to reduce. default : any, optional The starting value to reduce with. If not provided, the sequence cannot be empty, and the last value of the sequence will be used. Returns ------- folded : any The folded value. Notes ----- This functions works by reducing the list in a right associative way. For example, imagine we are folding with ``operator.add`` or ``+``: .. code-block:: python foldr(add, seq) -> seq[0] + (seq[1] + (seq[2] + (...seq[-1], default))) In the more general case with an arbitrary function, ``foldr`` will expand like so: .. code-block:: python foldr(f, seq) -> f(seq[0], f(seq[1], f(seq[2], ...f(seq[-1], default)))) For a more in depth discussion of left and right folds, see: `https://en.wikipedia.org/wiki/Fold_(higher-order_function)`_ The images in that page are very good for showing the differences between ``foldr`` and ``foldl`` (``reduce``). .. note:: For performance reasons is is best to pass a strict (non-lazy) sequence, for example, a list. See Also -------- :func:`functools.reduce` :func:`sum` """ return reduce( flip(f), reversed(seq), *(default,) if default is not _no_default else () )
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 accumulator. seq : iterable[any] The sequence to reduce. default : any, optional The starting value to reduce with. If not provided, the sequence cannot be empty, and the last value of the sequence will be used. Returns ------- folded : any The folded value. Notes ----- This functions works by reducing the list in a right associative way. For example, imagine we are folding with ``operator.add`` or ``+``: .. code-block:: python foldr(add, seq) -> seq[0] + (seq[1] + (seq[2] + (...seq[-1], default))) In the more general case with an arbitrary function, ``foldr`` will expand like so: .. code-block:: python foldr(f, seq) -> f(seq[0], f(seq[1], f(seq[2], ...f(seq[-1], default)))) For a more in depth discussion of left and right folds, see: `https://en.wikipedia.org/wiki/Fold_(higher-order_function)`_ The images in that page are very good for showing the differences between ``foldr`` and ``foldl`` (``reduce``). .. note:: For performance reasons is is best to pass a strict (non-lazy) sequence, for example, a list. See Also -------- :func:`functools.reduce` :func:`sum` """ return reduce( flip(f), reversed(seq), *(default,) if default is not _no_default else () )
[ "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} s.t. sum_{i=1}^{m}=z, w_{i}\geq 0 Input: A vector v \in R^{m}, and a scalar z > 0 (default=1) Output: Projection vector w :Example: >>> proj = simplex_projection([.4 ,.3, -.4, .5]) >>> proj # doctest: +NORMALIZE_WHITESPACE array([ 0.33333333, 0.23333333, 0. , 0.43333333]) >>> print(proj.sum()) 1.0 Original matlab implementation: John Duchi (jduchi@cs.berkeley.edu) Python-port: Copyright 2013 by Thomas Wiecki (thomas.wiecki@gmail.com).
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 Problem: min_{w}\| w - v \|_{2}^{2} s.t. sum_{i=1}^{m}=z, w_{i}\geq 0 Input: A vector v \in R^{m}, and a scalar z > 0 (default=1) Output: Projection vector w :Example: >>> proj = simplex_projection([.4 ,.3, -.4, .5]) >>> proj # doctest: +NORMALIZE_WHITESPACE array([ 0.33333333, 0.23333333, 0. , 0.43333333]) >>> print(proj.sum()) 1.0 Original matlab implementation: John Duchi (jduchi@cs.berkeley.edu) Python-port: Copyright 2013 by Thomas Wiecki (thomas.wiecki@gmail.com). """ v = np.asarray(v) p = len(v) # Sort v into u in descending order v = (v > 0) * v u = np.sort(v)[::-1] sv = np.cumsum(u) rho = np.where(u > (sv - b) / np.arange(1, p + 1))[0][-1] theta = np.max([0, (sv[rho] - b) / (rho + 1)]) w = (v - theta) w[w < 0] = 0 return w
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 Problem: min_{w}\| w - v \|_{2}^{2} s.t. sum_{i=1}^{m}=z, w_{i}\geq 0 Input: A vector v \in R^{m}, and a scalar z > 0 (default=1) Output: Projection vector w :Example: >>> proj = simplex_projection([.4 ,.3, -.4, .5]) >>> proj # doctest: +NORMALIZE_WHITESPACE array([ 0.33333333, 0.23333333, 0. , 0.43333333]) >>> print(proj.sum()) 1.0 Original matlab implementation: John Duchi (jduchi@cs.berkeley.edu) Python-port: Copyright 2013 by Thomas Wiecki (thomas.wiecki@gmail.com). """ v = np.asarray(v) p = len(v) # Sort v into u in descending order v = (v > 0) * v u = np.sort(v)[::-1] sv = np.cumsum(u) rho = np.where(u > (sv - b) / np.arange(1, p + 1))[0][-1] theta = np.max([0, (sv[rho] - b) / (rho + 1)]) w = (v - theta) w[w < 0] = 0 return w
[ "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(mod, 'handle_data', None), before_trading_start=getattr(mod, 'before_trading_start', None), analyze=getattr(mod, 'analyze', None), bundle='test', environ=environ, # Provide a default capital base, but allow the test to override. **merge({'capital_base': 1e7}, mod._test_args()) )
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(mod, 'handle_data', None), before_trading_start=getattr(mod, 'before_trading_start', None), analyze=getattr(mod, 'analyze', None), bundle='test', environ=environ, # Provide a default capital base, but allow the test to override. **merge({'capital_base': 1e7}, mod._test_args()) )
[ "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 allowed_missing : int Number of allowed missing (NaN) observations per column. Columns with more than this many non-nan observations in both ``dependents`` and ``independents`` will output NaN as the regression coefficient. Returns ------- slopes : np.array[M] Linear regression coefficients for each column of ``dependents``.
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``. independent : np.array[N, 1] Independent variable of the regression allowed_missing : int Number of allowed missing (NaN) observations per column. Columns with more than this many non-nan observations in both ``dependents`` and ``independents`` will output NaN as the regression coefficient. Returns ------- slopes : np.array[M] Linear regression coefficients for each column of ``dependents``. """ # Cache these as locals since we're going to call them multiple times. nan = np.nan isnan = np.isnan N, M = dependents.shape if out is None: out = np.full(M, nan) # Copy N times as a column vector and fill with nans to have the same # missing value pattern as the dependent variable. # # PERF_TODO: We could probably avoid the space blowup by doing this in # Cython. # shape: (N, M) independent = np.where( isnan(dependents), nan, independent, ) # Calculate beta as Cov(X, Y) / Cov(X, X). # https://en.wikipedia.org/wiki/Simple_linear_regression#Fitting_the_regression_line # noqa # # NOTE: The usual formula for covariance is:: # # mean((X - mean(X)) * (Y - mean(Y))) # # However, we don't actually need to take the mean of both sides of the # product, because of the folllowing equivalence:: # # Let X_res = (X - mean(X)). # We have: # # mean(X_res * (Y - mean(Y))) = mean(X_res * (Y - mean(Y))) # (1) = mean((X_res * Y) - (X_res * mean(Y))) # (2) = mean(X_res * Y) - mean(X_res * mean(Y)) # (3) = mean(X_res * Y) - mean(X_res) * mean(Y) # (4) = mean(X_res * Y) - 0 * mean(Y) # (5) = mean(X_res * Y) # # # The tricky step in the above derivation is step (4). We know that # mean(X_res) is zero because, for any X: # # mean(X - mean(X)) = mean(X) - mean(X) = 0. # # The upshot of this is that we only have to center one of `independent` # and `dependent` when calculating covariances. Since we need the centered # `independent` to calculate its variance in the next step, we choose to # center `independent`. # shape: (N, M) ind_residual = independent - nanmean(independent, axis=0) # shape: (M,) covariances = nanmean(ind_residual * dependents, axis=0) # We end up with different variances in each column here because each # column may have a different subset of the data dropped due to missing # data in the corresponding dependent column. # shape: (M,) independent_variances = nanmean(ind_residual ** 2, axis=0) # shape: (M,) np.divide(covariances, independent_variances, out=out) # Write nans back to locations where we have more then allowed number of # missing entries. nanlocs = isnan(independent).sum(axis=0) > allowed_missing out[nanlocs] = nan return out
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``. independent : np.array[N, 1] Independent variable of the regression allowed_missing : int Number of allowed missing (NaN) observations per column. Columns with more than this many non-nan observations in both ``dependents`` and ``independents`` will output NaN as the regression coefficient. Returns ------- slopes : np.array[M] Linear regression coefficients for each column of ``dependents``. """ # Cache these as locals since we're going to call them multiple times. nan = np.nan isnan = np.isnan N, M = dependents.shape if out is None: out = np.full(M, nan) # Copy N times as a column vector and fill with nans to have the same # missing value pattern as the dependent variable. # # PERF_TODO: We could probably avoid the space blowup by doing this in # Cython. # shape: (N, M) independent = np.where( isnan(dependents), nan, independent, ) # Calculate beta as Cov(X, Y) / Cov(X, X). # https://en.wikipedia.org/wiki/Simple_linear_regression#Fitting_the_regression_line # noqa # # NOTE: The usual formula for covariance is:: # # mean((X - mean(X)) * (Y - mean(Y))) # # However, we don't actually need to take the mean of both sides of the # product, because of the folllowing equivalence:: # # Let X_res = (X - mean(X)). # We have: # # mean(X_res * (Y - mean(Y))) = mean(X_res * (Y - mean(Y))) # (1) = mean((X_res * Y) - (X_res * mean(Y))) # (2) = mean(X_res * Y) - mean(X_res * mean(Y)) # (3) = mean(X_res * Y) - mean(X_res) * mean(Y) # (4) = mean(X_res * Y) - 0 * mean(Y) # (5) = mean(X_res * Y) # # # The tricky step in the above derivation is step (4). We know that # mean(X_res) is zero because, for any X: # # mean(X - mean(X)) = mean(X) - mean(X) = 0. # # The upshot of this is that we only have to center one of `independent` # and `dependent` when calculating covariances. Since we need the centered # `independent` to calculate its variance in the next step, we choose to # center `independent`. # shape: (N, M) ind_residual = independent - nanmean(independent, axis=0) # shape: (M,) covariances = nanmean(ind_residual * dependents, axis=0) # We end up with different variances in each column here because each # column may have a different subset of the data dropped due to missing # data in the corresponding dependent column. # shape: (M,) independent_variances = nanmean(ind_residual ** 2, axis=0) # shape: (M,) np.divide(covariances, independent_variances, out=out) # Write nans back to locations where we have more then allowed number of # missing entries. nanlocs = isnan(independent).sum(axis=0) > allowed_missing out[nanlocs] = nan return out
[ "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_{instrument_type}_yields.php" "&sR={restrict}" "&se={instrument_ids}" "&dF={start}" "&dT={end}".format( instrument_type=instrument_type, instrument_ids='-'.join(map(prepend("L_"), instrument_ids)), restrict=earliest_allowed_date.strftime("%Y-%m-%d"), start=start_date.strftime("%Y-%m-%d"), end=end_date.strftime("%Y-%m-%d"), ) )
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_{instrument_type}_yields.php" "&sR={restrict}" "&se={instrument_ids}" "&dF={start}" "&dT={end}".format( instrument_type=instrument_type, instrument_ids='-'.join(map(prepend("L_"), instrument_ids)), restrict=earliest_allowed_date.strftime("%Y-%m-%d"), start=start_date.strftime("%Y-%m-%d"), end=end_date.strftime("%Y-%m-%d"), ) )
[ "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(how='all') \ .tz_localize('UTC') \ .rename(columns=COLUMN_NAMES)
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(how='all') \ .tz_localize('UTC') \ .rename(columns=COLUMN_NAMES)
[ "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 = [ # bill_data has an entry for 2010-02-15, which bond_data doesn't. # bond_data has an entry for 2006-09-04, which bill_data doesn't. # Both of these dates are bank holidays (Flag Day and Labor Day, # respectively). pd.Timestamp('2006-09-04', tz='UTC'), pd.Timestamp('2010-02-15', tz='UTC'), # 2013-07-25 comes back as "Not available" from the bills endpoint. # This date doesn't seem to be a bank holiday, but the previous # calendar implementation dropped this entry, so we drop it as well. # If someone cares deeply about the integrity of the Canadian trading # calendar, they may want to consider forward-filling here rather than # dropping the row. pd.Timestamp('2013-07-25', tz='UTC'), ] unexpected_inconsistences = inconsistent_dates.drop(known_inconsistencies) if len(unexpected_inconsistences): in_bills = bill_data.index.difference(bond_data.index).difference( known_inconsistencies ) in_bonds = bond_data.index.difference(bill_data.index).difference( known_inconsistencies ) raise ValueError( "Inconsistent dates for Canadian treasury bills vs bonds. \n" "Dates with bills but not bonds: {in_bills}.\n" "Dates with bonds but not bills: {in_bonds}.".format( in_bills=in_bills, in_bonds=in_bonds, ) )
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 = [ # bill_data has an entry for 2010-02-15, which bond_data doesn't. # bond_data has an entry for 2006-09-04, which bill_data doesn't. # Both of these dates are bank holidays (Flag Day and Labor Day, # respectively). pd.Timestamp('2006-09-04', tz='UTC'), pd.Timestamp('2010-02-15', tz='UTC'), # 2013-07-25 comes back as "Not available" from the bills endpoint. # This date doesn't seem to be a bank holiday, but the previous # calendar implementation dropped this entry, so we drop it as well. # If someone cares deeply about the integrity of the Canadian trading # calendar, they may want to consider forward-filling here rather than # dropping the row. pd.Timestamp('2013-07-25', tz='UTC'), ] unexpected_inconsistences = inconsistent_dates.drop(known_inconsistencies) if len(unexpected_inconsistences): in_bills = bill_data.index.difference(bond_data.index).difference( known_inconsistencies ) in_bonds = bond_data.index.difference(bill_data.index).difference( known_inconsistencies ) raise ValueError( "Inconsistent dates for Canadian treasury bills vs bonds. \n" "Dates with bills but not bonds: {in_bills}.\n" "Dates with bonds but not bills: {in_bonds}.".format( in_bills=in_bills, in_bonds=in_bonds, ) )
[ "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 (for a buy) or below the limit price (for a sell).
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 ------- bool: Whether the fill price is above the limit price (for a buy) or below the limit price (for a sell). """ if order.limit: # this is tricky! if an order with a limit price has reached # the limit price, we will try to fill the order. do not fill # these shares if the impacted price is worse than the limit # price. return early to avoid creating the transaction. # buy order is worse if the impacted price is greater than # the limit price. sell order is worse if the impacted price # is less than the limit price if (order.direction > 0 and fill_price > order.limit) or \ (order.direction < 0 and fill_price < order.limit): return True return False
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 ------- bool: Whether the fill price is above the limit price (for a buy) or below the limit price (for a sell). """ if order.limit: # this is tricky! if an order with a limit price has reached # the limit price, we will try to fill the order. do not fill # these shares if the impacted price is worse than the limit # price. return early to avoid creating the transaction. # buy order is worse if the impacted price is greater than # the limit price. sell order is worse if the impacted price # is less than the limit price if (order.direction > 0 and fill_price > order.limit) or \ (order.direction < 0 and fill_price < order.limit): return True return False
[ "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 fetching. window_length : Number of days of history used to calculate the mean volume and close price volatility. Returns ------- (mean volume, volatility)
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 fetch the daily windows. asset : The Asset whose data we are fetching. window_length : Number of days of history used to calculate the mean volume and close price volatility. Returns ------- (mean volume, volatility) """ try: values = self._window_data_cache.get(asset, data.current_session) except KeyError: try: # Add a day because we want 'window_length' complete days, # excluding the current day. volume_history = data.history( asset, 'volume', window_length + 1, '1d', ) close_history = data.history( asset, 'close', window_length + 1, '1d', ) except HistoryWindowStartsBeforeData: # If there is not enough data to do a full history call, return # values as if there was no data. return 0, np.NaN # Exclude the first value of the percent change array because it is # always just NaN. close_volatility = close_history[:-1].pct_change()[1:].std( skipna=False, ) values = { 'volume': volume_history[:-1].mean(), 'close': close_volatility * SQRT_252, } self._window_data_cache.set(asset, values, data.current_session) return values['volume'], values['close']
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 fetch the daily windows. asset : The Asset whose data we are fetching. window_length : Number of days of history used to calculate the mean volume and close price volatility. Returns ------- (mean volume, volatility) """ try: values = self._window_data_cache.get(asset, data.current_session) except KeyError: try: # Add a day because we want 'window_length' complete days, # excluding the current day. volume_history = data.history( asset, 'volume', window_length + 1, '1d', ) close_history = data.history( asset, 'close', window_length + 1, '1d', ) except HistoryWindowStartsBeforeData: # If there is not enough data to do a full history call, return # values as if there was no data. return 0, np.NaN # Exclude the first value of the percent change array because it is # always just NaN. close_volatility = close_history[:-1].pct_change()[1:].std( skipna=False, ) values = { 'volume': volume_history[:-1].mean(), 'close': close_volatility * SQRT_252, } self._window_data_cache.set(asset, values, data.current_session) return values['volume'], values['close']
[ "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 to use for the new term. Raises ------ DTypeNotSpecified When no dtype was passed to the instance, and the class doesn't provide a default. NotDType When either the class or the instance provides a value not coercible to a numpy dtype. NoDefaultMissingValue When dtype requires an explicit missing_value, but ``missing_value`` is NotSpecified.
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_missing_value : np.dtype, any The dtype and missing_value to use for the new term. Raises ------ DTypeNotSpecified When no dtype was passed to the instance, and the class doesn't provide a default. NotDType When either the class or the instance provides a value not coercible to a numpy dtype. NoDefaultMissingValue When dtype requires an explicit missing_value, but ``missing_value`` is NotSpecified. """ if dtype is NotSpecified: raise DTypeNotSpecified(termname=termname) try: dtype = dtype_class(dtype) except TypeError: raise NotDType(dtype=dtype, termname=termname) if not can_represent_dtype(dtype): raise UnsupportedDType(dtype=dtype, termname=termname) if missing_value is NotSpecified: missing_value = default_missing_value_for_dtype(dtype) try: if (dtype == categorical_dtype): # This check is necessary because we use object dtype for # categoricals, and numpy will allow us to promote numerical # values to object even though we don't support them. _assert_valid_categorical_missing_value(missing_value) # For any other type, we can check if the missing_value is safe by # making an array of that value and trying to safely convert it to # the desired type. # 'same_kind' allows casting between things like float32 and # float64, but not str and int. array([missing_value]).astype(dtype=dtype, casting='same_kind') except TypeError as e: raise TypeError( "Missing value {value!r} is not a valid choice " "for term {termname} with dtype {dtype}.\n\n" "Coercion attempt failed with: {error}".format( termname=termname, value=missing_value, dtype=dtype, error=e, ) ) return dtype, missing_value
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_missing_value : np.dtype, any The dtype and missing_value to use for the new term. Raises ------ DTypeNotSpecified When no dtype was passed to the instance, and the class doesn't provide a default. NotDType When either the class or the instance provides a value not coercible to a numpy dtype. NoDefaultMissingValue When dtype requires an explicit missing_value, but ``missing_value`` is NotSpecified. """ if dtype is NotSpecified: raise DTypeNotSpecified(termname=termname) try: dtype = dtype_class(dtype) except TypeError: raise NotDType(dtype=dtype, termname=termname) if not can_represent_dtype(dtype): raise UnsupportedDType(dtype=dtype, termname=termname) if missing_value is NotSpecified: missing_value = default_missing_value_for_dtype(dtype) try: if (dtype == categorical_dtype): # This check is necessary because we use object dtype for # categoricals, and numpy will allow us to promote numerical # values to object even though we don't support them. _assert_valid_categorical_missing_value(missing_value) # For any other type, we can check if the missing_value is safe by # making an array of that value and trying to safely convert it to # the desired type. # 'same_kind' allows casting between things like float32 and # float64, but not str and int. array([missing_value]).astype(dtype=dtype, casting='same_kind') except TypeError as e: raise TypeError( "Missing value {value!r} is not a valid choice " "for term {termname} with dtype {dtype}.\n\n" "Coercion attempt failed with: {error}".format( termname=termname, value=missing_value, dtype=dtype, error=e, ) ) return dtype, missing_value
[ "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, label_types): raise TypeError( "Categorical terms must have missing values of type " "{types}.".format( types=' or '.join([t.__name__ for t in label_types]), ) )
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, label_types): raise TypeError( "Categorical terms must have missing values of type " "{types}.".format( types=' or '.join([t.__name__ for t in label_types]), ) )
[ "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 containing the entries in cls.params. Raises ------ TypeError Raised if any parameter values are not passed or not hashable.
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, object)] A list of string, value pairs containing the entries in cls.params. Raises ------ TypeError Raised if any parameter values are not passed or not hashable. """ params = cls.params if not isinstance(params, Mapping): params = {k: NotSpecified for k in params} param_values = [] for key, default_value in params.items(): try: value = kwargs.pop(key, default_value) if value is NotSpecified: raise KeyError(key) # Check here that the value is hashable so that we fail here # instead of trying to hash the param values tuple later. hash(value) except KeyError: raise TypeError( "{typename} expected a keyword parameter {name!r}.".format( typename=cls.__name__, name=key ) ) except TypeError: # Value wasn't hashable. raise TypeError( "{typename} expected a hashable value for parameter " "{name!r}, but got {value!r} instead.".format( typename=cls.__name__, name=key, value=value, ) ) param_values.append((key, value)) return tuple(param_values)
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, object)] A list of string, value pairs containing the entries in cls.params. Raises ------ TypeError Raised if any parameter values are not passed or not hashable. """ params = cls.params if not isinstance(params, Mapping): params = {k: NotSpecified for k in params} param_values = [] for key, default_value in params.items(): try: value = kwargs.pop(key, default_value) if value is NotSpecified: raise KeyError(key) # Check here that the value is hashable so that we fail here # instead of trying to hash the param values tuple later. hash(value) except KeyError: raise TypeError( "{typename} expected a keyword parameter {name!r}.".format( typename=cls.__name__, name=key ) ) except TypeError: # Value wasn't hashable. raise TypeError( "{typename} expected a hashable value for parameter " "{name!r}, but got {value!r} instead.".format( typename=cls.__name__, name=key, value=value, ) ) param_values.append((key, value)) return tuple(param_values)
[ "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 classmethod so that it can be called from Term.__new__ to determine whether to produce a new instance.
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 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 classmethod so that it can be called from Term.__new__ to determine whether to produce a new instance. """ return (cls, domain, dtype, missing_value, window_safe, ndim, params)
def _static_identity(cls, domain, dtype, missing_value, window_safe, ndim, params): """ 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 classmethod so that it can be called from Term.__new__ to determine whether to produce a new instance. """ return (cls, domain, dtype, missing_value, window_safe, ndim, params)
[ "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. params : tuple[(str, hashable)] Tuple of key/value pairs of additional parameters.
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 Missing value for this term. ndim : 1 or 2 The dimensionality of this term. params : tuple[(str, hashable)] Tuple of key/value pairs of additional parameters. """ self.domain = domain self.dtype = dtype self.missing_value = missing_value self.window_safe = window_safe self.ndim = ndim for name, value in params: if hasattr(self, name): raise TypeError( "Parameter {name!r} conflicts with already-present" " attribute with value {value!r}.".format( name=name, value=getattr(self, name), ) ) # TODO: Consider setting these values as attributes and replacing # the boilerplate in NumericalExpression, Rank, and # PercentileFilter. self.params = dict(params) # Make sure that subclasses call super() in their _validate() methods # by setting this flag. The base class implementation of _validate # should set this flag to True. self._subclass_called_super_validate = False self._validate() assert self._subclass_called_super_validate, ( "Term._validate() was not called.\n" "This probably means that you overrode _validate" " without calling super()." ) del self._subclass_called_super_validate return self
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 Missing value for this term. ndim : 1 or 2 The dimensionality of this term. params : tuple[(str, hashable)] Tuple of key/value pairs of additional parameters. """ self.domain = domain self.dtype = dtype self.missing_value = missing_value self.window_safe = window_safe self.ndim = ndim for name, value in params: if hasattr(self, name): raise TypeError( "Parameter {name!r} conflicts with already-present" " attribute with value {value!r}.".format( name=name, value=getattr(self, name), ) ) # TODO: Consider setting these values as attributes and replacing # the boilerplate in NumericalExpression, Rank, and # PercentileFilter. self.params = dict(params) # Make sure that subclasses call super() in their _validate() methods # by setting this flag. The base class implementation of _validate # should set this flag to True. self._subclass_called_super_validate = False self._validate() assert self._subclass_called_super_validate, ( "Term._validate() was not called.\n" "This probably means that you overrode _validate" " without calling super()." ) del self._subclass_called_super_validate return self
[ "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 return out
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 return out
[ "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 results of running this pipeline term over the dates. assets : pd.Index All of the assets being requested. This allows us to correctly shape the workspace value. Returns ------- workspace_value : array-like An array like value that the engine can consume.
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 multiindexed series with (dates, assets) whose values are the results of running this pipeline term over the dates. assets : pd.Index All of the assets being requested. This allows us to correctly shape the workspace value. Returns ------- workspace_value : array-like An array like value that the engine can consume. """ return result.unstack().fillna(self.missing_value).reindex( columns=assets, fill_value=self.missing_value, ).values
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 multiindexed series with (dates, assets) whose values are the results of running this pipeline term over the dates. assets : pd.Index All of the assets being requested. This allows us to correctly shape the workspace value. Returns ------- workspace_value : array-like An array like value that the engine can consume. """ return result.unstack().fillna(self.missing_value).reindex( columns=assets, fill_value=self.missing_value, ).values
[ "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_count': np.floor( self.amount * float(stock_dividend.ratio) ) }
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_count': np.floor( self.amount * float(stock_dividend.ratio) ) }
[ "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 asset!") # adjust the # of shares by the ratio # (if we had 100 shares, and the ratio is 3, # we now have 33 shares) # (old_share_count / ratio = new_share_count) # (old_price * ratio = new_price) # e.g., 33.333 raw_share_count = self.amount / float(ratio) # e.g., 33 full_share_count = np.floor(raw_share_count) # e.g., 0.333 fractional_share_count = raw_share_count - full_share_count # adjust the cost basis to the nearest cent, e.g., 60.0 new_cost_basis = round(self.cost_basis * ratio, 2) self.cost_basis = new_cost_basis self.amount = full_share_count return_cash = round(float(fractional_share_count * new_cost_basis), 2) log.info("after split: " + str(self)) log.info("returning cash: " + str(return_cash)) # return the leftover cash, which will be converted into cash # (rounded to the nearest cent) return return_cash
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 asset!") # adjust the # of shares by the ratio # (if we had 100 shares, and the ratio is 3, # we now have 33 shares) # (old_share_count / ratio = new_share_count) # (old_price * ratio = new_price) # e.g., 33.333 raw_share_count = self.amount / float(ratio) # e.g., 33 full_share_count = np.floor(raw_share_count) # e.g., 0.333 fractional_share_count = raw_share_count - full_share_count # adjust the cost basis to the nearest cent, e.g., 60.0 new_cost_basis = round(self.cost_basis * ratio, 2) self.cost_basis = new_cost_basis self.amount = full_share_count return_cash = round(float(fractional_share_count * new_cost_basis), 2) log.info("after split: " + str(self)) log.info("returning cash: " + str(return_cash)) # return the leftover cash, which will be converted into cash # (rounded to the nearest cent) return return_cash
[ "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 externally-delivered commission charge across all shares in a position.
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 how zipline handles positions, zipline will currently spread an externally-delivered commission charge across all shares in a position. """ if asset != self.asset: raise Exception('Updating a commission for a different asset?') if cost == 0.0: return # If we no longer hold this position, there is no cost basis to # adjust. if self.amount == 0: return # We treat cost basis as the share price where we have broken even. # For longs, commissions cause a relatively straight forward increase # in the cost basis. # # For shorts, you actually want to decrease the cost basis because you # break even and earn a profit when the share price decreases. # # Shorts are represented as having a negative `amount`. # # The multiplication and division by `amount` cancel out leaving the # cost_basis positive, while subtracting the commission. prev_cost = self.cost_basis * self.amount if isinstance(asset, Future): cost_to_use = cost / asset.price_multiplier else: cost_to_use = cost new_cost = prev_cost + cost_to_use self.cost_basis = new_cost / self.amount
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 how zipline handles positions, zipline will currently spread an externally-delivered commission charge across all shares in a position. """ if asset != self.asset: raise Exception('Updating a commission for a different asset?') if cost == 0.0: return # If we no longer hold this position, there is no cost basis to # adjust. if self.amount == 0: return # We treat cost basis as the share price where we have broken even. # For longs, commissions cause a relatively straight forward increase # in the cost basis. # # For shorts, you actually want to decrease the cost basis because you # break even and earn a profit when the share price decreases. # # Shorts are represented as having a negative `amount`. # # The multiplication and division by `amount` cancel out leaving the # cost_basis positive, while subtracting the commission. prev_cost = self.cost_basis * self.amount if isinstance(asset, Future): cost_to_use = cost / asset.price_multiplier else: cost_to_use = cost new_cost = prev_cost + cost_to_use self.cost_basis = new_cost / self.amount
[ "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.last_sale_price }
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.last_sale_price }
[ "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 The function which deregisters bundles from the ``bundles`` mapping. ingest : callable The function which downloads and write data for a given data bundle. load : callable The function which loads the ingested bundles back into memory. clean : callable The function which cleans up data written with ``ingest``.
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. unregister : callable The function which deregisters bundles from the ``bundles`` mapping. ingest : callable The function which downloads and write data for a given data bundle. load : callable The function which loads the ingested bundles back into memory. clean : callable The function which cleans up data written with ``ingest``. """ _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. bundles = mappingproxy(_bundles) @curry def register(name, f, calendar_name='NYSE', start_session=None, end_session=None, minutes_per_day=390, create_writers=True): """Register a data bundle ingest function. Parameters ---------- name : str The name of the bundle. f : callable The ingest function. This function will be passed: environ : mapping The environment this is being run with. asset_db_writer : AssetDBWriter The asset db writer to write into. minute_bar_writer : BcolzMinuteBarWriter The minute bar writer to write into. daily_bar_writer : BcolzDailyBarWriter The daily bar writer to write into. adjustment_writer : SQLiteAdjustmentWriter The adjustment db writer to write into. calendar : trading_calendars.TradingCalendar The trading calendar to ingest for. start_session : pd.Timestamp The first session of data to ingest. end_session : pd.Timestamp The last session of data to ingest. cache : DataFrameCache A mapping object to temporarily store dataframes. This should be used to cache intermediates in case the load fails. This will be automatically cleaned up after a successful load. show_progress : bool Show the progress for the current load where possible. calendar_name : str, optional The name of a calendar used to align bundle data. Default is 'NYSE'. start_session : pd.Timestamp, optional The first session for which we want data. If not provided, or if the date lies outside the range supported by the calendar, the first_session of the calendar is used. end_session : pd.Timestamp, optional The last session for which we want data. If not provided, or if the date lies outside the range supported by the calendar, the last_session of the calendar is used. minutes_per_day : int, optional The number of minutes in each normal trading day. create_writers : bool, optional Should the ingest machinery create the writers for the ingest function. This can be disabled as an optimization for cases where they are not needed, like the ``quantopian-quandl`` bundle. Notes ----- This function my be used as a decorator, for example: .. code-block:: python @register('quandl') def quandl_ingest_function(...): ... See Also -------- zipline.data.bundles.bundles """ if name in bundles: warnings.warn( 'Overwriting bundle with name %r' % name, stacklevel=3, ) # NOTE: We don't eagerly compute calendar values here because # `register` is called at module scope in zipline, and creating a # calendar currently takes between 0.5 and 1 seconds, which causes a # noticeable delay on the zipline CLI. _bundles[name] = RegisteredBundle( calendar_name=calendar_name, start_session=start_session, end_session=end_session, minutes_per_day=minutes_per_day, ingest=f, create_writers=create_writers, ) return f def unregister(name): """Unregister a bundle. Parameters ---------- name : str The name of the bundle to unregister. Raises ------ UnknownBundle Raised when no bundle has been registered with the given name. See Also -------- zipline.data.bundles.bundles """ try: del _bundles[name] except KeyError: raise UnknownBundle(name) def ingest(name, environ=os.environ, timestamp=None, assets_versions=(), show_progress=False): """Ingest data for a given bundle. Parameters ---------- name : str The name of the bundle. environ : mapping, optional The environment variables. By default this is os.environ. timestamp : datetime, optional The timestamp to use for the load. By default this is the current time. assets_versions : Iterable[int], optional Versions of the assets db to which to downgrade. show_progress : bool, optional Tell the ingest function to display the progress where possible. """ try: bundle = bundles[name] except KeyError: raise UnknownBundle(name) calendar = get_calendar(bundle.calendar_name) start_session = bundle.start_session end_session = bundle.end_session if start_session is None or start_session < calendar.first_session: start_session = calendar.first_session if end_session is None or end_session > calendar.last_session: end_session = calendar.last_session if timestamp is None: timestamp = pd.Timestamp.utcnow() timestamp = timestamp.tz_convert('utc').tz_localize(None) timestr = to_bundle_ingest_dirname(timestamp) cachepath = cache_path(name, environ=environ) pth.ensure_directory(pth.data_path([name, timestr], environ=environ)) pth.ensure_directory(cachepath) with dataframe_cache(cachepath, clean_on_failure=False) as cache, \ ExitStack() as stack: # we use `cleanup_on_failure=False` so that we don't purge the # cache directory if the load fails in the middle if bundle.create_writers: wd = stack.enter_context(working_dir( pth.data_path([], environ=environ)) ) daily_bars_path = wd.ensure_dir( *daily_equity_relative( name, timestr, environ=environ, ) ) daily_bar_writer = BcolzDailyBarWriter( daily_bars_path, calendar, start_session, end_session, ) # Do an empty write to ensure that the daily ctables exist # when we create the SQLiteAdjustmentWriter below. The # SQLiteAdjustmentWriter needs to open the daily ctables so # that it can compute the adjustment ratios for the dividends. daily_bar_writer.write(()) minute_bar_writer = BcolzMinuteBarWriter( wd.ensure_dir(*minute_equity_relative( name, timestr, environ=environ) ), calendar, start_session, end_session, minutes_per_day=bundle.minutes_per_day, ) assets_db_path = wd.getpath(*asset_db_relative( name, timestr, environ=environ, )) asset_db_writer = AssetDBWriter(assets_db_path) adjustment_db_writer = stack.enter_context( SQLiteAdjustmentWriter( wd.getpath(*adjustment_db_relative( name, timestr, environ=environ)), BcolzDailyBarReader(daily_bars_path), overwrite=True, ) ) else: daily_bar_writer = None minute_bar_writer = None asset_db_writer = None adjustment_db_writer = None if assets_versions: raise ValueError('Need to ingest a bundle that creates ' 'writers in order to downgrade the assets' ' db.') bundle.ingest( environ, asset_db_writer, minute_bar_writer, daily_bar_writer, adjustment_db_writer, calendar, start_session, end_session, cache, show_progress, pth.data_path([name, timestr], environ=environ), ) for version in sorted(set(assets_versions), reverse=True): version_path = wd.getpath(*asset_db_relative( name, timestr, environ=environ, db_version=version, )) with working_file(version_path) as wf: shutil.copy2(assets_db_path, wf.path) downgrade(wf.path, version) def most_recent_data(bundle_name, timestamp, environ=None): """Get the path to the most recent data after ``date``for the given bundle. Parameters ---------- bundle_name : str The name of the bundle to lookup. timestamp : datetime The timestamp to begin searching on or before. environ : dict, optional An environment dict to forward to zipline_root. """ if bundle_name not in bundles: raise UnknownBundle(bundle_name) try: candidates = os.listdir( pth.data_path([bundle_name], environ=environ), ) return pth.data_path( [bundle_name, max( filter(complement(pth.hidden), candidates), key=from_bundle_ingest_dirname, )], environ=environ, ) except (ValueError, OSError) as e: if getattr(e, 'errno', errno.ENOENT) != errno.ENOENT: raise raise ValueError( 'no data for bundle {bundle!r} on or before {timestamp}\n' 'maybe you need to run: $ zipline ingest -b {bundle}'.format( bundle=bundle_name, timestamp=timestamp, ), ) def load(name, environ=os.environ, timestamp=None): """Loads a previously ingested bundle. Parameters ---------- name : str The name of the bundle. environ : mapping, optional The environment variables. Defaults of os.environ. timestamp : datetime, optional The timestamp of the data to lookup. Defaults to the current time. Returns ------- bundle_data : BundleData The raw data readers for this bundle. """ if timestamp is None: timestamp = pd.Timestamp.utcnow() timestr = most_recent_data(name, timestamp, environ=environ) return BundleData( asset_finder=AssetFinder( asset_db_path(name, timestr, environ=environ), ), equity_minute_bar_reader=BcolzMinuteBarReader( minute_equity_path(name, timestr, environ=environ), ), equity_daily_bar_reader=BcolzDailyBarReader( daily_equity_path(name, timestr, environ=environ), ), adjustment_reader=SQLiteAdjustmentReader( adjustment_db_path(name, timestr, environ=environ), ), ) @preprocess( before=optionally(ensure_timestamp), after=optionally(ensure_timestamp), ) def clean(name, before=None, after=None, keep_last=None, environ=os.environ): """Clean up data that was created with ``ingest`` or ``$ python -m zipline ingest`` Parameters ---------- name : str The name of the bundle to remove data for. before : datetime, optional Remove data ingested before this date. This argument is mutually exclusive with: keep_last after : datetime, optional Remove data ingested after this date. This argument is mutually exclusive with: keep_last keep_last : int, optional Remove all but the last ``keep_last`` ingestions. This argument is mutually exclusive with: before after environ : mapping, optional The environment variables. Defaults of os.environ. Returns ------- cleaned : set[str] The names of the runs that were removed. Raises ------ BadClean Raised when ``before`` and or ``after`` are passed with ``keep_last``. This is a subclass of ``ValueError``. """ try: all_runs = sorted( filter( complement(pth.hidden), os.listdir(pth.data_path([name], environ=environ)), ), key=from_bundle_ingest_dirname, ) except OSError as e: if e.errno != errno.ENOENT: raise raise UnknownBundle(name) if ((before is not None or after is not None) and keep_last is not None): raise BadClean(before, after, keep_last) if keep_last is None: def should_clean(name): dt = from_bundle_ingest_dirname(name) return ( (before is not None and dt < before) or (after is not None and dt > after) ) elif keep_last >= 0: last_n_dts = set(take(keep_last, reversed(all_runs))) def should_clean(name): return name not in last_n_dts else: raise BadClean(before, after, keep_last) cleaned = set() for run in all_runs: if should_clean(run): path = pth.data_path([name, run], environ=environ) shutil.rmtree(path) cleaned.add(path) return cleaned return BundleCore(bundles, register, unregister, ingest, load, clean)
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. unregister : callable The function which deregisters bundles from the ``bundles`` mapping. ingest : callable The function which downloads and write data for a given data bundle. load : callable The function which loads the ingested bundles back into memory. clean : callable The function which cleans up data written with ``ingest``. """ _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. bundles = mappingproxy(_bundles) @curry def register(name, f, calendar_name='NYSE', start_session=None, end_session=None, minutes_per_day=390, create_writers=True): """Register a data bundle ingest function. Parameters ---------- name : str The name of the bundle. f : callable The ingest function. This function will be passed: environ : mapping The environment this is being run with. asset_db_writer : AssetDBWriter The asset db writer to write into. minute_bar_writer : BcolzMinuteBarWriter The minute bar writer to write into. daily_bar_writer : BcolzDailyBarWriter The daily bar writer to write into. adjustment_writer : SQLiteAdjustmentWriter The adjustment db writer to write into. calendar : trading_calendars.TradingCalendar The trading calendar to ingest for. start_session : pd.Timestamp The first session of data to ingest. end_session : pd.Timestamp The last session of data to ingest. cache : DataFrameCache A mapping object to temporarily store dataframes. This should be used to cache intermediates in case the load fails. This will be automatically cleaned up after a successful load. show_progress : bool Show the progress for the current load where possible. calendar_name : str, optional The name of a calendar used to align bundle data. Default is 'NYSE'. start_session : pd.Timestamp, optional The first session for which we want data. If not provided, or if the date lies outside the range supported by the calendar, the first_session of the calendar is used. end_session : pd.Timestamp, optional The last session for which we want data. If not provided, or if the date lies outside the range supported by the calendar, the last_session of the calendar is used. minutes_per_day : int, optional The number of minutes in each normal trading day. create_writers : bool, optional Should the ingest machinery create the writers for the ingest function. This can be disabled as an optimization for cases where they are not needed, like the ``quantopian-quandl`` bundle. Notes ----- This function my be used as a decorator, for example: .. code-block:: python @register('quandl') def quandl_ingest_function(...): ... See Also -------- zipline.data.bundles.bundles """ if name in bundles: warnings.warn( 'Overwriting bundle with name %r' % name, stacklevel=3, ) # NOTE: We don't eagerly compute calendar values here because # `register` is called at module scope in zipline, and creating a # calendar currently takes between 0.5 and 1 seconds, which causes a # noticeable delay on the zipline CLI. _bundles[name] = RegisteredBundle( calendar_name=calendar_name, start_session=start_session, end_session=end_session, minutes_per_day=minutes_per_day, ingest=f, create_writers=create_writers, ) return f def unregister(name): """Unregister a bundle. Parameters ---------- name : str The name of the bundle to unregister. Raises ------ UnknownBundle Raised when no bundle has been registered with the given name. See Also -------- zipline.data.bundles.bundles """ try: del _bundles[name] except KeyError: raise UnknownBundle(name) def ingest(name, environ=os.environ, timestamp=None, assets_versions=(), show_progress=False): """Ingest data for a given bundle. Parameters ---------- name : str The name of the bundle. environ : mapping, optional The environment variables. By default this is os.environ. timestamp : datetime, optional The timestamp to use for the load. By default this is the current time. assets_versions : Iterable[int], optional Versions of the assets db to which to downgrade. show_progress : bool, optional Tell the ingest function to display the progress where possible. """ try: bundle = bundles[name] except KeyError: raise UnknownBundle(name) calendar = get_calendar(bundle.calendar_name) start_session = bundle.start_session end_session = bundle.end_session if start_session is None or start_session < calendar.first_session: start_session = calendar.first_session if end_session is None or end_session > calendar.last_session: end_session = calendar.last_session if timestamp is None: timestamp = pd.Timestamp.utcnow() timestamp = timestamp.tz_convert('utc').tz_localize(None) timestr = to_bundle_ingest_dirname(timestamp) cachepath = cache_path(name, environ=environ) pth.ensure_directory(pth.data_path([name, timestr], environ=environ)) pth.ensure_directory(cachepath) with dataframe_cache(cachepath, clean_on_failure=False) as cache, \ ExitStack() as stack: # we use `cleanup_on_failure=False` so that we don't purge the # cache directory if the load fails in the middle if bundle.create_writers: wd = stack.enter_context(working_dir( pth.data_path([], environ=environ)) ) daily_bars_path = wd.ensure_dir( *daily_equity_relative( name, timestr, environ=environ, ) ) daily_bar_writer = BcolzDailyBarWriter( daily_bars_path, calendar, start_session, end_session, ) # Do an empty write to ensure that the daily ctables exist # when we create the SQLiteAdjustmentWriter below. The # SQLiteAdjustmentWriter needs to open the daily ctables so # that it can compute the adjustment ratios for the dividends. daily_bar_writer.write(()) minute_bar_writer = BcolzMinuteBarWriter( wd.ensure_dir(*minute_equity_relative( name, timestr, environ=environ) ), calendar, start_session, end_session, minutes_per_day=bundle.minutes_per_day, ) assets_db_path = wd.getpath(*asset_db_relative( name, timestr, environ=environ, )) asset_db_writer = AssetDBWriter(assets_db_path) adjustment_db_writer = stack.enter_context( SQLiteAdjustmentWriter( wd.getpath(*adjustment_db_relative( name, timestr, environ=environ)), BcolzDailyBarReader(daily_bars_path), overwrite=True, ) ) else: daily_bar_writer = None minute_bar_writer = None asset_db_writer = None adjustment_db_writer = None if assets_versions: raise ValueError('Need to ingest a bundle that creates ' 'writers in order to downgrade the assets' ' db.') bundle.ingest( environ, asset_db_writer, minute_bar_writer, daily_bar_writer, adjustment_db_writer, calendar, start_session, end_session, cache, show_progress, pth.data_path([name, timestr], environ=environ), ) for version in sorted(set(assets_versions), reverse=True): version_path = wd.getpath(*asset_db_relative( name, timestr, environ=environ, db_version=version, )) with working_file(version_path) as wf: shutil.copy2(assets_db_path, wf.path) downgrade(wf.path, version) def most_recent_data(bundle_name, timestamp, environ=None): """Get the path to the most recent data after ``date``for the given bundle. Parameters ---------- bundle_name : str The name of the bundle to lookup. timestamp : datetime The timestamp to begin searching on or before. environ : dict, optional An environment dict to forward to zipline_root. """ if bundle_name not in bundles: raise UnknownBundle(bundle_name) try: candidates = os.listdir( pth.data_path([bundle_name], environ=environ), ) return pth.data_path( [bundle_name, max( filter(complement(pth.hidden), candidates), key=from_bundle_ingest_dirname, )], environ=environ, ) except (ValueError, OSError) as e: if getattr(e, 'errno', errno.ENOENT) != errno.ENOENT: raise raise ValueError( 'no data for bundle {bundle!r} on or before {timestamp}\n' 'maybe you need to run: $ zipline ingest -b {bundle}'.format( bundle=bundle_name, timestamp=timestamp, ), ) def load(name, environ=os.environ, timestamp=None): """Loads a previously ingested bundle. Parameters ---------- name : str The name of the bundle. environ : mapping, optional The environment variables. Defaults of os.environ. timestamp : datetime, optional The timestamp of the data to lookup. Defaults to the current time. Returns ------- bundle_data : BundleData The raw data readers for this bundle. """ if timestamp is None: timestamp = pd.Timestamp.utcnow() timestr = most_recent_data(name, timestamp, environ=environ) return BundleData( asset_finder=AssetFinder( asset_db_path(name, timestr, environ=environ), ), equity_minute_bar_reader=BcolzMinuteBarReader( minute_equity_path(name, timestr, environ=environ), ), equity_daily_bar_reader=BcolzDailyBarReader( daily_equity_path(name, timestr, environ=environ), ), adjustment_reader=SQLiteAdjustmentReader( adjustment_db_path(name, timestr, environ=environ), ), ) @preprocess( before=optionally(ensure_timestamp), after=optionally(ensure_timestamp), ) def clean(name, before=None, after=None, keep_last=None, environ=os.environ): """Clean up data that was created with ``ingest`` or ``$ python -m zipline ingest`` Parameters ---------- name : str The name of the bundle to remove data for. before : datetime, optional Remove data ingested before this date. This argument is mutually exclusive with: keep_last after : datetime, optional Remove data ingested after this date. This argument is mutually exclusive with: keep_last keep_last : int, optional Remove all but the last ``keep_last`` ingestions. This argument is mutually exclusive with: before after environ : mapping, optional The environment variables. Defaults of os.environ. Returns ------- cleaned : set[str] The names of the runs that were removed. Raises ------ BadClean Raised when ``before`` and or ``after`` are passed with ``keep_last``. This is a subclass of ``ValueError``. """ try: all_runs = sorted( filter( complement(pth.hidden), os.listdir(pth.data_path([name], environ=environ)), ), key=from_bundle_ingest_dirname, ) except OSError as e: if e.errno != errno.ENOENT: raise raise UnknownBundle(name) if ((before is not None or after is not None) and keep_last is not None): raise BadClean(before, after, keep_last) if keep_last is None: def should_clean(name): dt = from_bundle_ingest_dirname(name) return ( (before is not None and dt < before) or (after is not None and dt > after) ) elif keep_last >= 0: last_n_dts = set(take(keep_last, reversed(all_runs))) def should_clean(name): return name not in last_n_dts else: raise BadClean(before, after, keep_last) cleaned = set() for run in all_runs: if should_clean(run): path = pth.data_path([name, run], environ=environ) shutil.rmtree(path) cleaned.add(path) return cleaned return BundleCore(bundles, register, unregister, ingest, load, clean)
[ "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='function_a is deprecated! Use function_b instead.') def function_a(*args, **kwargs):
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. Examples -------- @deprecated(msg='function_a is deprecated! Use function_b instead.') def function_a(*args, **kwargs): """ def deprecated_dec(fn): @wraps(fn) def wrapper(*args, **kwargs): warnings.warn( msg or "Function %s is deprecated." % fn.__name__, category=DeprecationWarning, stacklevel=stacklevel ) return fn(*args, **kwargs) return wrapper return deprecated_dec
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. Examples -------- @deprecated(msg='function_a is deprecated! Use function_b instead.') def function_a(*args, **kwargs): """ def deprecated_dec(fn): @wraps(fn) def wrapper(*args, **kwargs): warnings.warn( msg or "Function %s is deprecated." % fn.__name__, category=DeprecationWarning, stacklevel=stacklevel ) return fn(*args, **kwargs) return wrapper return deprecated_dec
[ "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. """ out = [None] * len(columns) for i, column in enumerate(columns): adjs = {} for asset in assets: adjs.update(self._get_adjustments_in_range( asset, dts, column)) out[i] = adjs return out
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. """ out = [None] * len(columns) for i, column in enumerate(columns): adjs = {} for asset in assets: adjs.update(self._get_adjustments_in_range( asset, dts, column)) out[i] = adjs return out
[ "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 the day from which the window is being viewed. - the start of all multiply objects is always 0 (in each window all adjustments are overlapping) - the end of the multiply object is the location before the calendar location of the adjustment action, making all days before the event adjusted. Parameters ---------- asset : Asset The assets for which to get adjustments. dts : iterable of datetime64-like The dts for which adjustment data is needed. field : str OHLCV field for which to get the adjustments. Returns ------- out : dict[loc -> Float64Multiply] The adjustments as a dict of loc -> Float64Multiply
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 with: - the key into the dictionary for adjustments is the location of the day from which the window is being viewed. - the start of all multiply objects is always 0 (in each window all adjustments are overlapping) - the end of the multiply object is the location before the calendar location of the adjustment action, making all days before the event adjusted. Parameters ---------- asset : Asset The assets for which to get adjustments. dts : iterable of datetime64-like The dts for which adjustment data is needed. field : str OHLCV field for which to get the adjustments. Returns ------- out : dict[loc -> Float64Multiply] The adjustments as a dict of loc -> Float64Multiply """ sid = int(asset) start = normalize_date(dts[0]) end = normalize_date(dts[-1]) adjs = {} if field != 'volume': mergers = self._adjustments_reader.get_adjustments_for_sid( 'mergers', sid) for m in mergers: dt = m[0] if start < dt <= end: end_loc = dts.searchsorted(dt) adj_loc = end_loc mult = Float64Multiply(0, end_loc - 1, 0, 0, m[1]) try: adjs[adj_loc].append(mult) except KeyError: adjs[adj_loc] = [mult] divs = self._adjustments_reader.get_adjustments_for_sid( 'dividends', sid) for d in divs: dt = d[0] if start < dt <= end: end_loc = dts.searchsorted(dt) adj_loc = end_loc mult = Float64Multiply(0, end_loc - 1, 0, 0, d[1]) try: adjs[adj_loc].append(mult) except KeyError: adjs[adj_loc] = [mult] splits = self._adjustments_reader.get_adjustments_for_sid( 'splits', sid) for s in splits: dt = s[0] if start < dt <= end: if field == 'volume': ratio = 1.0 / s[1] else: ratio = s[1] end_loc = dts.searchsorted(dt) adj_loc = end_loc mult = Float64Multiply(0, end_loc - 1, 0, 0, ratio) try: adjs[adj_loc].append(mult) except KeyError: adjs[adj_loc] = [mult] return adjs
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 with: - the key into the dictionary for adjustments is the location of the day from which the window is being viewed. - the start of all multiply objects is always 0 (in each window all adjustments are overlapping) - the end of the multiply object is the location before the calendar location of the adjustment action, making all days before the event adjusted. Parameters ---------- asset : Asset The assets for which to get adjustments. dts : iterable of datetime64-like The dts for which adjustment data is needed. field : str OHLCV field for which to get the adjustments. Returns ------- out : dict[loc -> Float64Multiply] The adjustments as a dict of loc -> Float64Multiply """ sid = int(asset) start = normalize_date(dts[0]) end = normalize_date(dts[-1]) adjs = {} if field != 'volume': mergers = self._adjustments_reader.get_adjustments_for_sid( 'mergers', sid) for m in mergers: dt = m[0] if start < dt <= end: end_loc = dts.searchsorted(dt) adj_loc = end_loc mult = Float64Multiply(0, end_loc - 1, 0, 0, m[1]) try: adjs[adj_loc].append(mult) except KeyError: adjs[adj_loc] = [mult] divs = self._adjustments_reader.get_adjustments_for_sid( 'dividends', sid) for d in divs: dt = d[0] if start < dt <= end: end_loc = dts.searchsorted(dt) adj_loc = end_loc mult = Float64Multiply(0, end_loc - 1, 0, 0, d[1]) try: adjs[adj_loc].append(mult) except KeyError: adjs[adj_loc] = [mult] splits = self._adjustments_reader.get_adjustments_for_sid( 'splits', sid) for s in splits: dt = s[0] if start < dt <= end: if field == 'volume': ratio = 1.0 / s[1] else: ratio = s[1] end_loc = dts.searchsorted(dt) adj_loc = end_loc mult = Float64Multiply(0, end_loc - 1, 0, 0, ratio) try: adjs[adj_loc].append(mult) except KeyError: adjs[adj_loc] = [mult] return adjs
[ "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 - self.offset + 1 self.current = self.window.seek(target) self.most_recent_ix = end_ix return self.current
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 - self.offset + 1 self.current = self.window.seek(target) self.most_recent_ix = end_ix return self.current
[ "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 can not provide data for the current dts range, then create a new one and replace the expired window. Parameters ---------- assets : iterable of Assets The assets in the window dts : iterable of datetime64-like The datetimes for which to fetch data. Makes an assumption that all dts are present and contiguous, in the calendar. field : str The OHLCV field for which to retrieve data. is_perspective_after : bool see: `PricingHistoryLoader.history` Returns ------- out : list of Float64Window with sufficient data so that each asset's window can provide `get` for the index corresponding with the last value in `dts`
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 not exist, then create a new one. If a corresponding window does exist for (assets, len(dts), field), but can not provide data for the current dts range, then create a new one and replace the expired window. Parameters ---------- assets : iterable of Assets The assets in the window dts : iterable of datetime64-like The datetimes for which to fetch data. Makes an assumption that all dts are present and contiguous, in the calendar. field : str The OHLCV field for which to retrieve data. is_perspective_after : bool see: `PricingHistoryLoader.history` Returns ------- out : list of Float64Window with sufficient data so that each asset's window can provide `get` for the index corresponding with the last value in `dts` """ end = dts[-1] size = len(dts) asset_windows = {} needed_assets = [] cal = self._calendar assets = self._asset_finder.retrieve_all(assets) end_ix = find_in_sorted_index(cal, end) for asset in assets: try: window = self._window_blocks[field].get( (asset, size, is_perspective_after), end) except KeyError: needed_assets.append(asset) else: if end_ix < window.most_recent_ix: # Window needs reset. Requested end index occurs before the # end index from the previous history call for this window. # Grab new window instead of rewinding adjustments. needed_assets.append(asset) else: asset_windows[asset] = window if needed_assets: offset = 0 start_ix = find_in_sorted_index(cal, dts[0]) prefetch_end_ix = min(end_ix + self._prefetch_length, len(cal) - 1) prefetch_end = cal[prefetch_end_ix] prefetch_dts = cal[start_ix:prefetch_end_ix + 1] if is_perspective_after: adj_end_ix = min(prefetch_end_ix + 1, len(cal) - 1) adj_dts = cal[start_ix:adj_end_ix + 1] else: adj_dts = prefetch_dts prefetch_len = len(prefetch_dts) array = self._array(prefetch_dts, needed_assets, field) if field == 'sid': window_type = Int64Window else: window_type = Float64Window view_kwargs = {} if field == 'volume': array = array.astype(float64_dtype) for i, asset in enumerate(needed_assets): adj_reader = None try: adj_reader = self._adjustment_readers[type(asset)] except KeyError: adj_reader = None if adj_reader is not None: adjs = adj_reader.load_pricing_adjustments( [field], adj_dts, [asset])[0] else: adjs = {} window = window_type( array[:, i].reshape(prefetch_len, 1), view_kwargs, adjs, offset, size, int(is_perspective_after), self._decimal_places_for_asset(asset, dts[-1]), ) sliding_window = SlidingWindow(window, size, start_ix, offset) asset_windows[asset] = sliding_window self._window_blocks[field].set( (asset, size, is_perspective_after), sliding_window, prefetch_end) return [asset_windows[asset] for asset in assets]
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 not exist, then create a new one. If a corresponding window does exist for (assets, len(dts), field), but can not provide data for the current dts range, then create a new one and replace the expired window. Parameters ---------- assets : iterable of Assets The assets in the window dts : iterable of datetime64-like The datetimes for which to fetch data. Makes an assumption that all dts are present and contiguous, in the calendar. field : str The OHLCV field for which to retrieve data. is_perspective_after : bool see: `PricingHistoryLoader.history` Returns ------- out : list of Float64Window with sufficient data so that each asset's window can provide `get` for the index corresponding with the last value in `dts` """ end = dts[-1] size = len(dts) asset_windows = {} needed_assets = [] cal = self._calendar assets = self._asset_finder.retrieve_all(assets) end_ix = find_in_sorted_index(cal, end) for asset in assets: try: window = self._window_blocks[field].get( (asset, size, is_perspective_after), end) except KeyError: needed_assets.append(asset) else: if end_ix < window.most_recent_ix: # Window needs reset. Requested end index occurs before the # end index from the previous history call for this window. # Grab new window instead of rewinding adjustments. needed_assets.append(asset) else: asset_windows[asset] = window if needed_assets: offset = 0 start_ix = find_in_sorted_index(cal, dts[0]) prefetch_end_ix = min(end_ix + self._prefetch_length, len(cal) - 1) prefetch_end = cal[prefetch_end_ix] prefetch_dts = cal[start_ix:prefetch_end_ix + 1] if is_perspective_after: adj_end_ix = min(prefetch_end_ix + 1, len(cal) - 1) adj_dts = cal[start_ix:adj_end_ix + 1] else: adj_dts = prefetch_dts prefetch_len = len(prefetch_dts) array = self._array(prefetch_dts, needed_assets, field) if field == 'sid': window_type = Int64Window else: window_type = Float64Window view_kwargs = {} if field == 'volume': array = array.astype(float64_dtype) for i, asset in enumerate(needed_assets): adj_reader = None try: adj_reader = self._adjustment_readers[type(asset)] except KeyError: adj_reader = None if adj_reader is not None: adjs = adj_reader.load_pricing_adjustments( [field], adj_dts, [asset])[0] else: adjs = {} window = window_type( array[:, i].reshape(prefetch_len, 1), view_kwargs, adjs, offset, size, int(is_perspective_after), self._decimal_places_for_asset(asset, dts[-1]), ) sliding_window = SlidingWindow(window, size, start_ix, offset) asset_windows[asset] = sliding_window self._window_blocks[field].set( (asset, size, is_perspective_after), sliding_window, prefetch_end) return [asset_windows[asset] for asset in assets]
[ "Ensure", "that", "there", "is", "a", "Float64Multiply", "window", "for", "each", "asset", "that", "can", "provide", "data", "for", "the", "given", "parameters", ".", "If", "the", "corresponding", "window", "for", "the", "(", "assets", "len", "(", "dts", "...
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 datetimes for which to fetch data. Makes an assumption that all dts are present and contiguous, in the calendar. field : str The OHLCV field for which to retrieve data. is_perspective_after : bool True, if the window is being viewed immediately after the last dt in the sliding window. False, if the window is viewed on the last dt. This flag is used for handling the case where the last dt in the requested window immediately precedes a corporate action, e.g.: - is_perspective_after is True When the viewpoint is after the last dt in the window, as when a daily history window is accessed from a simulation that uses a minute data frequency, the history call to this loader will not include the current simulation dt. At that point in time, the raw data for the last day in the window will require adjustment, so the most recent adjustment with respect to the simulation time is applied to the last dt in the requested window. An example equity which has a 0.5 split ratio dated for 05-27, with the dts for a history call of 5 bars with a '1d' frequency at 05-27 9:31. Simulation frequency is 'minute'. (In this case this function is called with 4 daily dts, and the calling function is responsible for stitching back on the 'current' dt) | | | | | last dt | <-- viewer is here | | | 05-23 | 05-24 | 05-25 | 05-26 | 05-27 9:31 | | raw | 10.10 | 10.20 | 10.30 | 10.40 | | | adj | 5.05 | 5.10 | 5.15 | 5.25 | | The adjustment is applied to the last dt, 05-26, and all previous dts. - is_perspective_after is False, daily When the viewpoint is the same point in time as the last dt in the window, as when a daily history window is accessed from a simulation that uses a daily data frequency, the history call will include the current dt. At that point in time, the raw data for the last day in the window will be post-adjustment, so no adjustment is applied to the last dt. An example equity which has a 0.5 split ratio dated for 05-27, with the dts for a history call of 5 bars with a '1d' frequency at 05-27 0:00. Simulation frequency is 'daily'. | | | | | | <-- viewer is here | | | | | | | last dt | | | 05-23 | 05-24 | 05-25 | 05-26 | 05-27 | | raw | 10.10 | 10.20 | 10.30 | 10.40 | 5.25 | | adj | 5.05 | 5.10 | 5.15 | 5.20 | 5.25 | Adjustments are applied 05-23 through 05-26 but not to the last dt, 05-27 Returns ------- out : np.ndarray with shape(len(days between start, end), len(assets))
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 in the window. dts : iterable of datetime64-like The datetimes for which to fetch data. Makes an assumption that all dts are present and contiguous, in the calendar. field : str The OHLCV field for which to retrieve data. is_perspective_after : bool True, if the window is being viewed immediately after the last dt in the sliding window. False, if the window is viewed on the last dt. This flag is used for handling the case where the last dt in the requested window immediately precedes a corporate action, e.g.: - is_perspective_after is True When the viewpoint is after the last dt in the window, as when a daily history window is accessed from a simulation that uses a minute data frequency, the history call to this loader will not include the current simulation dt. At that point in time, the raw data for the last day in the window will require adjustment, so the most recent adjustment with respect to the simulation time is applied to the last dt in the requested window. An example equity which has a 0.5 split ratio dated for 05-27, with the dts for a history call of 5 bars with a '1d' frequency at 05-27 9:31. Simulation frequency is 'minute'. (In this case this function is called with 4 daily dts, and the calling function is responsible for stitching back on the 'current' dt) | | | | | last dt | <-- viewer is here | | | 05-23 | 05-24 | 05-25 | 05-26 | 05-27 9:31 | | raw | 10.10 | 10.20 | 10.30 | 10.40 | | | adj | 5.05 | 5.10 | 5.15 | 5.25 | | The adjustment is applied to the last dt, 05-26, and all previous dts. - is_perspective_after is False, daily When the viewpoint is the same point in time as the last dt in the window, as when a daily history window is accessed from a simulation that uses a daily data frequency, the history call will include the current dt. At that point in time, the raw data for the last day in the window will be post-adjustment, so no adjustment is applied to the last dt. An example equity which has a 0.5 split ratio dated for 05-27, with the dts for a history call of 5 bars with a '1d' frequency at 05-27 0:00. Simulation frequency is 'daily'. | | | | | | <-- viewer is here | | | | | | | last dt | | | 05-23 | 05-24 | 05-25 | 05-26 | 05-27 | | raw | 10.10 | 10.20 | 10.30 | 10.40 | 5.25 | | adj | 5.05 | 5.10 | 5.15 | 5.20 | 5.25 | Adjustments are applied 05-23 through 05-26 but not to the last dt, 05-27 Returns ------- out : np.ndarray with shape(len(days between start, end), len(assets)) """ block = self._ensure_sliding_windows(assets, dts, field, is_perspective_after) end_ix = self._calendar.searchsorted(dts[-1]) return concatenate( [window.get(end_ix) for window in block], axis=1, )
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 in the window. dts : iterable of datetime64-like The datetimes for which to fetch data. Makes an assumption that all dts are present and contiguous, in the calendar. field : str The OHLCV field for which to retrieve data. is_perspective_after : bool True, if the window is being viewed immediately after the last dt in the sliding window. False, if the window is viewed on the last dt. This flag is used for handling the case where the last dt in the requested window immediately precedes a corporate action, e.g.: - is_perspective_after is True When the viewpoint is after the last dt in the window, as when a daily history window is accessed from a simulation that uses a minute data frequency, the history call to this loader will not include the current simulation dt. At that point in time, the raw data for the last day in the window will require adjustment, so the most recent adjustment with respect to the simulation time is applied to the last dt in the requested window. An example equity which has a 0.5 split ratio dated for 05-27, with the dts for a history call of 5 bars with a '1d' frequency at 05-27 9:31. Simulation frequency is 'minute'. (In this case this function is called with 4 daily dts, and the calling function is responsible for stitching back on the 'current' dt) | | | | | last dt | <-- viewer is here | | | 05-23 | 05-24 | 05-25 | 05-26 | 05-27 9:31 | | raw | 10.10 | 10.20 | 10.30 | 10.40 | | | adj | 5.05 | 5.10 | 5.15 | 5.25 | | The adjustment is applied to the last dt, 05-26, and all previous dts. - is_perspective_after is False, daily When the viewpoint is the same point in time as the last dt in the window, as when a daily history window is accessed from a simulation that uses a daily data frequency, the history call will include the current dt. At that point in time, the raw data for the last day in the window will be post-adjustment, so no adjustment is applied to the last dt. An example equity which has a 0.5 split ratio dated for 05-27, with the dts for a history call of 5 bars with a '1d' frequency at 05-27 0:00. Simulation frequency is 'daily'. | | | | | | <-- viewer is here | | | | | | | last dt | | | 05-23 | 05-24 | 05-25 | 05-26 | 05-27 | | raw | 10.10 | 10.20 | 10.30 | 10.40 | 5.25 | | adj | 5.05 | 5.10 | 5.15 | 5.20 | 5.25 | Adjustments are applied 05-23 through 05-26 but not to the last dt, 05-27 Returns ------- out : np.ndarray with shape(len(days between start, end), len(assets)) """ block = self._ensure_sliding_windows(assets, dts, field, is_perspective_after) end_ix = self._calendar.searchsorted(dts[-1]) return concatenate( [window.get(end_ix) for window in block], axis=1, )
[ "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 AM/PM is handled properly if format=None. Moreover, we were previously ignoring this parameter unintentionally because we were incorrectly passing it as a positional. For all these reasons, we ignore the format_str parameter when parsing datetimes.
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 passed, and in pandas 0.12.0 the %p strptime directive is not correctly handled if a format string is explicitly passed, but AM/PM is handled properly if format=None. Moreover, we were previously ignoring this parameter unintentionally because we were incorrectly passing it as a positional. For all these reasons, we ignore the format_str parameter when parsing datetimes. """ # Explicitly ignoring this parameter. See note above. if format_str is not None: logger.warn( "The 'format_str' parameter to fetch_csv is deprecated. " "Ignoring and defaulting to pandas default date parsing." ) format_str = None tz_str = str(tz) if tz_str == pytz.utc.zone: parsed = pd.to_datetime( date_str_series.values, format=format_str, utc=True, errors='coerce', ) else: parsed = pd.to_datetime( date_str_series.values, format=format_str, errors='coerce', ).tz_localize(tz_str).tz_convert('UTC') if data_frequency == 'daily': parsed = roll_dts_to_midnight(parsed, trading_day) return parsed
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 passed, and in pandas 0.12.0 the %p strptime directive is not correctly handled if a format string is explicitly passed, but AM/PM is handled properly if format=None. Moreover, we were previously ignoring this parameter unintentionally because we were incorrectly passing it as a positional. For all these reasons, we ignore the format_str parameter when parsing datetimes. """ # Explicitly ignoring this parameter. See note above. if format_str is not None: logger.warn( "The 'format_str' parameter to fetch_csv is deprecated. " "Ignoring and defaulting to pandas default date parsing." ) format_str = None tz_str = str(tz) if tz_str == pytz.utc.zone: parsed = pd.to_datetime( date_str_series.values, format=format_str, utc=True, errors='coerce', ) else: parsed = pd.to_datetime( date_str_series.values, format=format_str, errors='coerce', ).tz_localize(tz_str).tz_convert('UTC') if data_frequency == 'daily': parsed = roll_dts_to_midnight(parsed, trading_day) return parsed
[ "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.upper() except AttributeError: # The mapping fails because symbol was a non-string return numpy.nan try: return self.finder.lookup_symbol( uppered, as_of_date=None, country_code=self.country_code, ) except MultipleSymbolsFound: # Fill conflicted entries with zeros to mark that they need to be # resolved by date. return 0 except SymbolNotFound: # Fill not found entries with nans. return numpy.nan
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.upper() except AttributeError: # The mapping fails because symbol was a non-string return numpy.nan try: return self.finder.lookup_symbol( uppered, as_of_date=None, country_code=self.country_code, ) except MultipleSymbolsFound: # Fill conflicted entries with zeros to mark that they need to be # resolved by date. return 0 except SymbolNotFound: # Fill not found entries with nans. return numpy.nan
[ "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_manager.handle_data): for capital_change in calculate_minute_capital_changes(dt_to_use): yield capital_change self.simulation_dt = dt_to_use # called every tick (minute or day). algo.on_dt_changed(dt_to_use) blotter = algo.blotter # handle any transactions and commissions coming out new orders # placed in the last bar new_transactions, new_commissions, closed_orders = \ blotter.get_transactions(current_data) blotter.prune_orders(closed_orders) for transaction in new_transactions: metrics_tracker.process_transaction(transaction) # since this order was modified, record it order = blotter.orders[transaction.order_id] metrics_tracker.process_order(order) for commission in new_commissions: metrics_tracker.process_commission(commission) handle_data(algo, current_data, dt_to_use) # grab any new orders from the blotter, then clear the list. # this includes cancelled orders. new_orders = blotter.new_orders blotter.new_orders = [] # if we have any new orders, record them so that we know # in what perf period they were placed. for new_order in new_orders: metrics_tracker.process_order(new_order) def once_a_day(midnight_dt, current_data=self.current_data, data_portal=self.data_portal): # process any capital changes that came overnight for capital_change in algo.calculate_capital_changes( midnight_dt, emission_rate=emission_rate, is_interday=True): yield capital_change # set all the timestamps self.simulation_dt = midnight_dt algo.on_dt_changed(midnight_dt) metrics_tracker.handle_market_open( midnight_dt, algo.data_portal, ) # handle any splits that impact any positions or any open orders. assets_we_care_about = ( viewkeys(metrics_tracker.positions) | viewkeys(algo.blotter.open_orders) ) if assets_we_care_about: splits = data_portal.get_splits(assets_we_care_about, midnight_dt) if splits: algo.blotter.process_splits(splits) metrics_tracker.handle_splits(splits) def on_exit(): # Remove references to algo, data portal, et al to break cycles # and ensure deterministic cleanup of these objects when the # simulation finishes. self.algo = None self.benchmark_source = self.current_data = self.data_portal = None with ExitStack() as stack: stack.callback(on_exit) stack.enter_context(self.processor) stack.enter_context(ZiplineAPI(self.algo)) if algo.data_frequency == 'minute': def execute_order_cancellation_policy(): algo.blotter.execute_cancel_policy(SESSION_END) def calculate_minute_capital_changes(dt): # process any capital changes that came between the last # and current minutes return algo.calculate_capital_changes( dt, emission_rate=emission_rate, is_interday=False) else: def execute_order_cancellation_policy(): pass def calculate_minute_capital_changes(dt): return [] for dt, action in self.clock: if action == BAR: for capital_change_packet in every_bar(dt): yield capital_change_packet elif action == SESSION_START: for capital_change_packet in once_a_day(dt): yield capital_change_packet elif action == SESSION_END: # End of the session. positions = metrics_tracker.positions position_assets = algo.asset_finder.retrieve_all(positions) self._cleanup_expired_assets(dt, position_assets) execute_order_cancellation_policy() algo.validate_account_controls() yield self._get_daily_message(dt, algo, metrics_tracker) elif action == BEFORE_TRADING_START_BAR: self.simulation_dt = dt algo.on_dt_changed(dt) algo.before_trading_start(self.current_data) elif action == MINUTE_END: minute_msg = self._get_minute_message( dt, algo, metrics_tracker, ) yield minute_msg risk_message = metrics_tracker.handle_simulation_end( self.data_portal, ) yield risk_message
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_manager.handle_data): for capital_change in calculate_minute_capital_changes(dt_to_use): yield capital_change self.simulation_dt = dt_to_use # called every tick (minute or day). algo.on_dt_changed(dt_to_use) blotter = algo.blotter # handle any transactions and commissions coming out new orders # placed in the last bar new_transactions, new_commissions, closed_orders = \ blotter.get_transactions(current_data) blotter.prune_orders(closed_orders) for transaction in new_transactions: metrics_tracker.process_transaction(transaction) # since this order was modified, record it order = blotter.orders[transaction.order_id] metrics_tracker.process_order(order) for commission in new_commissions: metrics_tracker.process_commission(commission) handle_data(algo, current_data, dt_to_use) # grab any new orders from the blotter, then clear the list. # this includes cancelled orders. new_orders = blotter.new_orders blotter.new_orders = [] # if we have any new orders, record them so that we know # in what perf period they were placed. for new_order in new_orders: metrics_tracker.process_order(new_order) def once_a_day(midnight_dt, current_data=self.current_data, data_portal=self.data_portal): # process any capital changes that came overnight for capital_change in algo.calculate_capital_changes( midnight_dt, emission_rate=emission_rate, is_interday=True): yield capital_change # set all the timestamps self.simulation_dt = midnight_dt algo.on_dt_changed(midnight_dt) metrics_tracker.handle_market_open( midnight_dt, algo.data_portal, ) # handle any splits that impact any positions or any open orders. assets_we_care_about = ( viewkeys(metrics_tracker.positions) | viewkeys(algo.blotter.open_orders) ) if assets_we_care_about: splits = data_portal.get_splits(assets_we_care_about, midnight_dt) if splits: algo.blotter.process_splits(splits) metrics_tracker.handle_splits(splits) def on_exit(): # Remove references to algo, data portal, et al to break cycles # and ensure deterministic cleanup of these objects when the # simulation finishes. self.algo = None self.benchmark_source = self.current_data = self.data_portal = None with ExitStack() as stack: stack.callback(on_exit) stack.enter_context(self.processor) stack.enter_context(ZiplineAPI(self.algo)) if algo.data_frequency == 'minute': def execute_order_cancellation_policy(): algo.blotter.execute_cancel_policy(SESSION_END) def calculate_minute_capital_changes(dt): # process any capital changes that came between the last # and current minutes return algo.calculate_capital_changes( dt, emission_rate=emission_rate, is_interday=False) else: def execute_order_cancellation_policy(): pass def calculate_minute_capital_changes(dt): return [] for dt, action in self.clock: if action == BAR: for capital_change_packet in every_bar(dt): yield capital_change_packet elif action == SESSION_START: for capital_change_packet in once_a_day(dt): yield capital_change_packet elif action == SESSION_END: # End of the session. positions = metrics_tracker.positions position_assets = algo.asset_finder.retrieve_all(positions) self._cleanup_expired_assets(dt, position_assets) execute_order_cancellation_policy() algo.validate_account_controls() yield self._get_daily_message(dt, algo, metrics_tracker) elif action == BEFORE_TRADING_START_BAR: self.simulation_dt = dt algo.on_dt_changed(dt) algo.before_trading_start(self.current_data) elif action == MINUTE_END: minute_msg = self._get_minute_message( dt, algo, metrics_tracker, ) yield minute_msg risk_message = metrics_tracker.handle_simulation_end( self.data_portal, ) yield risk_message
[ "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 close_position events for any assets that have reached their auto_close_date.
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_date. 2. Finds all assets for which we have positions and generates close_position events for any assets that have reached their auto_close_date. """ algo = self.algo def past_auto_close_date(asset): acd = asset.auto_close_date return acd is not None and acd <= dt # Remove positions in any sids that have reached their auto_close date. assets_to_clear = \ [asset for asset in position_assets if past_auto_close_date(asset)] metrics_tracker = algo.metrics_tracker data_portal = self.data_portal for asset in assets_to_clear: metrics_tracker.process_close_position(asset, dt, data_portal) # Remove open orders for any sids that have reached their auto close # date. These orders get processed immediately because otherwise they # would not be processed until the first bar of the next day. blotter = algo.blotter assets_to_cancel = [ asset for asset in blotter.open_orders if past_auto_close_date(asset) ] for asset in assets_to_cancel: blotter.cancel_all_orders_for_asset(asset) # Make a copy here so that we are not modifying the list that is being # iterated over. for order in copy(blotter.new_orders): if order.status == ORDER_STATUS.CANCELLED: metrics_tracker.process_order(order) blotter.new_orders.remove(order)
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_date. 2. Finds all assets for which we have positions and generates close_position events for any assets that have reached their auto_close_date. """ algo = self.algo def past_auto_close_date(asset): acd = asset.auto_close_date return acd is not None and acd <= dt # Remove positions in any sids that have reached their auto_close date. assets_to_clear = \ [asset for asset in position_assets if past_auto_close_date(asset)] metrics_tracker = algo.metrics_tracker data_portal = self.data_portal for asset in assets_to_clear: metrics_tracker.process_close_position(asset, dt, data_portal) # Remove open orders for any sids that have reached their auto close # date. These orders get processed immediately because otherwise they # would not be processed until the first bar of the next day. blotter = algo.blotter assets_to_cancel = [ asset for asset in blotter.open_orders if past_auto_close_date(asset) ] for asset in assets_to_cancel: blotter.cancel_all_orders_for_asset(asset) # Make a copy here so that we are not modifying the list that is being # iterated over. for order in copy(blotter.new_orders): if order.status == ORDER_STATUS.CANCELLED: metrics_tracker.process_order(order) blotter.new_orders.remove(order)
[ "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 return perf_message
def _get_daily_message(self, dt, algo, metrics_tracker): """ Get a perf message for the given datetime. """ perf_message = metrics_tracker.handle_market_close( dt, self.data_portal, ) perf_message['daily_perf']['recorded_vars'] = algo.recorded_vars return perf_message
[ "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_perf']['recorded_vars'] = rvars return minute_message
def _get_minute_message(self, dt, algo, metrics_tracker): """ Get a perf message for the given datetime. """ rvars = algo.recorded_vars minute_message = metrics_tracker.handle_minute_close( dt, self.data_portal, ) minute_message['minute_perf']['recorded_vars'] = rvars return minute_message
[ "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 Whether split adjustments should be included. should_include_mergers : bool Whether merger adjustments should be included. should_include_dividends : bool Whether dividend adjustments should be included. adjustment_type : str Whether price adjustments, volume adjustments, or both, should be included in the output. Returns ------- adjustments : dict[str -> dict[int -> Adjustment]] A dictionary containing price and/or volume adjustment mappings from index to adjustment objects to apply at that index.
zipline/data/adjustments.py
def load_adjustments(self, dates, assets, should_include_splits, should_include_mergers, should_include_dividends, adjustment_type): """ 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 Whether split adjustments should be included. should_include_mergers : bool Whether merger adjustments should be included. should_include_dividends : bool Whether dividend adjustments should be included. adjustment_type : str Whether price adjustments, volume adjustments, or both, should be included in the output. Returns ------- adjustments : dict[str -> dict[int -> Adjustment]] A dictionary containing price and/or volume adjustment mappings from index to adjustment objects to apply at that index. """ return load_adjustments_from_sqlite( self.conn, dates, assets, should_include_splits, should_include_mergers, should_include_dividends, adjustment_type, )
def load_adjustments(self, dates, assets, should_include_splits, should_include_mergers, should_include_dividends, adjustment_type): """ 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 Whether split adjustments should be included. should_include_mergers : bool Whether merger adjustments should be included. should_include_dividends : bool Whether dividend adjustments should be included. adjustment_type : str Whether price adjustments, volume adjustments, or both, should be included in the output. Returns ------- adjustments : dict[str -> dict[int -> Adjustment]] A dictionary containing price and/or volume adjustment mappings from index to adjustment objects to apply at that index. """ return load_adjustments_from_sqlite( self.conn, dates, assets, should_include_splits, should_include_mergers, should_include_dividends, adjustment_type, )
[ "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 to datetimes. Returns ------- dfs : dict{str->DataFrame} Dictionary which maps table name to the corresponding DataFrame version of the table, where all date columns have been coerced back from int to datetime.
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_dates is True, all ints in date columns will be converted to datetimes. Returns ------- dfs : dict{str->DataFrame} Dictionary which maps table name to the corresponding DataFrame version of the table, where all date columns have been coerced back from int to datetime. """ return { t_name: self.get_df_from_table(t_name, convert_dates) for t_name in self._datetime_int_cols }
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_dates is True, all ints in date columns will be converted to datetimes. Returns ------- dfs : dict{str->DataFrame} Dictionary which maps table name to the corresponding DataFrame version of the table, where all date columns have been coerced back from int to datetime. """ return { t_name: self.get_df_from_table(t_name, convert_dates) for t_name in self._datetime_int_cols }
[ "Returns", "the", "set", "of", "known", "tables", "in", "the", "adjustments", "file", "in", "DataFrame", "form", "." ]
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]: out[date_column] = datetime64ns_dtype return out
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]: out[date_column] = datetime64ns_dtype return out
[ "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 splits and mergers, with keys - sid, the id of the equity - effective_date, the date in seconds on which to apply the ratio. - ratio, the ratio to apply to backwards looking pricing data.
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 ------- DataFrame A frame in the same format as splits and mergers, with keys - sid, the id of the equity - effective_date, the date in seconds on which to apply the ratio. - ratio, the ratio to apply to backwards looking pricing data. """ if dividends is None or dividends.empty: return pd.DataFrame(np.array( [], dtype=[ ('sid', uint64_dtype), ('effective_date', uint32_dtype), ('ratio', float64_dtype), ], )) pricing_reader = self._equity_daily_bar_reader input_sids = dividends.sid.values unique_sids, sids_ix = np.unique(input_sids, return_inverse=True) dates = pricing_reader.sessions.values close, = pricing_reader.load_raw_arrays( ['close'], pd.Timestamp(dates[0], tz='UTC'), pd.Timestamp(dates[-1], tz='UTC'), unique_sids, ) date_ix = np.searchsorted(dates, dividends.ex_date.values) mask = date_ix > 0 date_ix = date_ix[mask] sids_ix = sids_ix[mask] input_dates = dividends.ex_date.values[mask] # subtract one day to get the close on the day prior to the merger previous_close = close[date_ix - 1, sids_ix] input_sids = input_sids[mask] amount = dividends.amount.values[mask] ratio = 1.0 - amount / previous_close non_nan_ratio_mask = ~np.isnan(ratio) for ix in np.flatnonzero(~non_nan_ratio_mask): log.warn( "Couldn't compute ratio for dividend" " sid={sid}, ex_date={ex_date:%Y-%m-%d}, amount={amount:.3f}", sid=input_sids[ix], ex_date=pd.Timestamp(input_dates[ix]), amount=amount[ix], ) positive_ratio_mask = ratio > 0 for ix in np.flatnonzero(~positive_ratio_mask & non_nan_ratio_mask): log.warn( "Dividend ratio <= 0 for dividend" " sid={sid}, ex_date={ex_date:%Y-%m-%d}, amount={amount:.3f}", sid=input_sids[ix], ex_date=pd.Timestamp(input_dates[ix]), amount=amount[ix], ) valid_ratio_mask = non_nan_ratio_mask & positive_ratio_mask return pd.DataFrame({ 'sid': input_sids[valid_ratio_mask], 'effective_date': input_dates[valid_ratio_mask], 'ratio': ratio[valid_ratio_mask], })
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 ------- DataFrame A frame in the same format as splits and mergers, with keys - sid, the id of the equity - effective_date, the date in seconds on which to apply the ratio. - ratio, the ratio to apply to backwards looking pricing data. """ if dividends is None or dividends.empty: return pd.DataFrame(np.array( [], dtype=[ ('sid', uint64_dtype), ('effective_date', uint32_dtype), ('ratio', float64_dtype), ], )) pricing_reader = self._equity_daily_bar_reader input_sids = dividends.sid.values unique_sids, sids_ix = np.unique(input_sids, return_inverse=True) dates = pricing_reader.sessions.values close, = pricing_reader.load_raw_arrays( ['close'], pd.Timestamp(dates[0], tz='UTC'), pd.Timestamp(dates[-1], tz='UTC'), unique_sids, ) date_ix = np.searchsorted(dates, dividends.ex_date.values) mask = date_ix > 0 date_ix = date_ix[mask] sids_ix = sids_ix[mask] input_dates = dividends.ex_date.values[mask] # subtract one day to get the close on the day prior to the merger previous_close = close[date_ix - 1, sids_ix] input_sids = input_sids[mask] amount = dividends.amount.values[mask] ratio = 1.0 - amount / previous_close non_nan_ratio_mask = ~np.isnan(ratio) for ix in np.flatnonzero(~non_nan_ratio_mask): log.warn( "Couldn't compute ratio for dividend" " sid={sid}, ex_date={ex_date:%Y-%m-%d}, amount={amount:.3f}", sid=input_sids[ix], ex_date=pd.Timestamp(input_dates[ix]), amount=amount[ix], ) positive_ratio_mask = ratio > 0 for ix in np.flatnonzero(~positive_ratio_mask & non_nan_ratio_mask): log.warn( "Dividend ratio <= 0 for dividend" " sid={sid}, ex_date={ex_date:%Y-%m-%d}, amount={amount:.3f}", sid=input_sids[ix], ex_date=pd.Timestamp(input_dates[ix]), amount=amount[ix], ) valid_ratio_mask = non_nan_ratio_mask & positive_ratio_mask return pd.DataFrame({ 'sid': input_sids[valid_ratio_mask], 'effective_date': input_dates[valid_ratio_mask], 'ratio': ratio[valid_ratio_mask], })
[ "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) # Second from the dividend payouts, calculate ratios. dividend_ratios = self.calc_dividend_ratios(dividends) self.write_frame('dividends', dividend_ratios)
def write_dividend_data(self, dividends, stock_dividends=None): """ Write both dividend payouts and the derived price adjustment ratios. """ # First write the dividend payouts. self._write_dividends(dividends) self._write_stock_dividends(stock_dividends) # Second from the dividend payouts, calculate ratios. dividend_ratios = self.calc_dividend_ratios(dividends) self.write_frame('dividends', dividend_ratios)
[ "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 Unix epoch, on which the adjustment should be applied. ratio : float A value to apply to all data earlier than the effective date. For open, high, low, and close those values are multiplied by the ratio. Volume is divided by this value. sid : int The asset id associated with this adjustment. mergers : pandas.DataFrame, optional DataFrame containing merger data. The format of this dataframe is: effective_date : int The date, represented as seconds since Unix epoch, on which the adjustment should be applied. ratio : float A value to apply to all data earlier than the effective date. For open, high, low, and close those values are multiplied by the ratio. Volume is unaffected. sid : int The asset id associated with this adjustment. dividends : pandas.DataFrame, optional DataFrame containing dividend data. The format of the dataframe is: sid : int The asset id associated with this adjustment. ex_date : datetime64 The date on which an equity must be held to be eligible to receive payment. declared_date : datetime64 The date on which the dividend is announced to the public. pay_date : datetime64 The date on which the dividend is distributed. record_date : datetime64 The date on which the stock ownership is checked to determine distribution of dividends. amount : float The cash amount paid for each share. Dividend ratios are calculated as: ``1.0 - (dividend_value / "close on day prior to ex_date")`` stock_dividends : pandas.DataFrame, optional DataFrame containing stock dividend data. The format of the dataframe is: sid : int The asset id associated with this adjustment. ex_date : datetime64 The date on which an equity must be held to be eligible to receive payment. declared_date : datetime64 The date on which the dividend is announced to the public. pay_date : datetime64 The date on which the dividend is distributed. record_date : datetime64 The date on which the stock ownership is checked to determine distribution of dividends. payment_sid : int The asset id of the shares that should be paid instead of cash. ratio : float The ratio of currently held shares in the held sid that should be paid with new shares of the payment_sid. See Also -------- zipline.data.adjustments.SQLiteAdjustmentReader
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 Dataframe containing split data. The format of this dataframe is: effective_date : int The date, represented as seconds since Unix epoch, on which the adjustment should be applied. ratio : float A value to apply to all data earlier than the effective date. For open, high, low, and close those values are multiplied by the ratio. Volume is divided by this value. sid : int The asset id associated with this adjustment. mergers : pandas.DataFrame, optional DataFrame containing merger data. The format of this dataframe is: effective_date : int The date, represented as seconds since Unix epoch, on which the adjustment should be applied. ratio : float A value to apply to all data earlier than the effective date. For open, high, low, and close those values are multiplied by the ratio. Volume is unaffected. sid : int The asset id associated with this adjustment. dividends : pandas.DataFrame, optional DataFrame containing dividend data. The format of the dataframe is: sid : int The asset id associated with this adjustment. ex_date : datetime64 The date on which an equity must be held to be eligible to receive payment. declared_date : datetime64 The date on which the dividend is announced to the public. pay_date : datetime64 The date on which the dividend is distributed. record_date : datetime64 The date on which the stock ownership is checked to determine distribution of dividends. amount : float The cash amount paid for each share. Dividend ratios are calculated as: ``1.0 - (dividend_value / "close on day prior to ex_date")`` stock_dividends : pandas.DataFrame, optional DataFrame containing stock dividend data. The format of the dataframe is: sid : int The asset id associated with this adjustment. ex_date : datetime64 The date on which an equity must be held to be eligible to receive payment. declared_date : datetime64 The date on which the dividend is announced to the public. pay_date : datetime64 The date on which the dividend is distributed. record_date : datetime64 The date on which the stock ownership is checked to determine distribution of dividends. payment_sid : int The asset id of the shares that should be paid instead of cash. ratio : float The ratio of currently held shares in the held sid that should be paid with new shares of the payment_sid. See Also -------- zipline.data.adjustments.SQLiteAdjustmentReader """ self.write_frame('splits', splits) self.write_frame('mergers', mergers) self.write_dividend_data(dividends, stock_dividends) # Use IF NOT EXISTS here to allow multiple writes if desired. self.conn.execute( "CREATE INDEX IF NOT EXISTS splits_sids " "ON splits(sid)" ) self.conn.execute( "CREATE INDEX IF NOT EXISTS splits_effective_date " "ON splits(effective_date)" ) self.conn.execute( "CREATE INDEX IF NOT EXISTS mergers_sids " "ON mergers(sid)" ) self.conn.execute( "CREATE INDEX IF NOT EXISTS mergers_effective_date " "ON mergers(effective_date)" ) self.conn.execute( "CREATE INDEX IF NOT EXISTS dividends_sid " "ON dividends(sid)" ) self.conn.execute( "CREATE INDEX IF NOT EXISTS dividends_effective_date " "ON dividends(effective_date)" ) self.conn.execute( "CREATE INDEX IF NOT EXISTS dividend_payouts_sid " "ON dividend_payouts(sid)" ) self.conn.execute( "CREATE INDEX IF NOT EXISTS dividends_payouts_ex_date " "ON dividend_payouts(ex_date)" ) self.conn.execute( "CREATE INDEX IF NOT EXISTS stock_dividend_payouts_sid " "ON stock_dividend_payouts(sid)" ) self.conn.execute( "CREATE INDEX IF NOT EXISTS stock_dividends_payouts_ex_date " "ON stock_dividend_payouts(ex_date)" )
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 Dataframe containing split data. The format of this dataframe is: effective_date : int The date, represented as seconds since Unix epoch, on which the adjustment should be applied. ratio : float A value to apply to all data earlier than the effective date. For open, high, low, and close those values are multiplied by the ratio. Volume is divided by this value. sid : int The asset id associated with this adjustment. mergers : pandas.DataFrame, optional DataFrame containing merger data. The format of this dataframe is: effective_date : int The date, represented as seconds since Unix epoch, on which the adjustment should be applied. ratio : float A value to apply to all data earlier than the effective date. For open, high, low, and close those values are multiplied by the ratio. Volume is unaffected. sid : int The asset id associated with this adjustment. dividends : pandas.DataFrame, optional DataFrame containing dividend data. The format of the dataframe is: sid : int The asset id associated with this adjustment. ex_date : datetime64 The date on which an equity must be held to be eligible to receive payment. declared_date : datetime64 The date on which the dividend is announced to the public. pay_date : datetime64 The date on which the dividend is distributed. record_date : datetime64 The date on which the stock ownership is checked to determine distribution of dividends. amount : float The cash amount paid for each share. Dividend ratios are calculated as: ``1.0 - (dividend_value / "close on day prior to ex_date")`` stock_dividends : pandas.DataFrame, optional DataFrame containing stock dividend data. The format of the dataframe is: sid : int The asset id associated with this adjustment. ex_date : datetime64 The date on which an equity must be held to be eligible to receive payment. declared_date : datetime64 The date on which the dividend is announced to the public. pay_date : datetime64 The date on which the dividend is distributed. record_date : datetime64 The date on which the stock ownership is checked to determine distribution of dividends. payment_sid : int The asset id of the shares that should be paid instead of cash. ratio : float The ratio of currently held shares in the held sid that should be paid with new shares of the payment_sid. See Also -------- zipline.data.adjustments.SQLiteAdjustmentReader """ self.write_frame('splits', splits) self.write_frame('mergers', mergers) self.write_dividend_data(dividends, stock_dividends) # Use IF NOT EXISTS here to allow multiple writes if desired. self.conn.execute( "CREATE INDEX IF NOT EXISTS splits_sids " "ON splits(sid)" ) self.conn.execute( "CREATE INDEX IF NOT EXISTS splits_effective_date " "ON splits(effective_date)" ) self.conn.execute( "CREATE INDEX IF NOT EXISTS mergers_sids " "ON mergers(sid)" ) self.conn.execute( "CREATE INDEX IF NOT EXISTS mergers_effective_date " "ON mergers(effective_date)" ) self.conn.execute( "CREATE INDEX IF NOT EXISTS dividends_sid " "ON dividends(sid)" ) self.conn.execute( "CREATE INDEX IF NOT EXISTS dividends_effective_date " "ON dividends(effective_date)" ) self.conn.execute( "CREATE INDEX IF NOT EXISTS dividend_payouts_sid " "ON dividend_payouts(sid)" ) self.conn.execute( "CREATE INDEX IF NOT EXISTS dividends_payouts_ex_date " "ON dividend_payouts(ex_date)" ) self.conn.execute( "CREATE INDEX IF NOT EXISTS stock_dividend_payouts_sid " "ON stock_dividend_payouts(sid)" ) self.conn.execute( "CREATE INDEX IF NOT EXISTS stock_dividends_payouts_ex_date " "ON stock_dividend_payouts(ex_date)" )
[ "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 default is an empty recarray with ``self.outputs`` as field names. Each field will have dtype ``self.dtype``. This can be overridden to control the kind of array constructed (e.g. to produce a LabelArray instead of an ndarray).
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 dtype is ``self.dtype``. If we have an outputs tuple, the default is an empty recarray with ``self.outputs`` as field names. Each field will have dtype ``self.dtype``. This can be overridden to control the kind of array constructed (e.g. to produce a LabelArray instead of an ndarray). """ missing_value = self.missing_value outputs = self.outputs if outputs is not NotSpecified: out = recarray( shape, formats=[self.dtype.str] * len(outputs), names=outputs, ) out[:] = missing_value else: out = full(shape, missing_value, dtype=self.dtype) return out
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 dtype is ``self.dtype``. If we have an outputs tuple, the default is an empty recarray with ``self.outputs`` as field names. Each field will have dtype ``self.dtype``. This can be overridden to control the kind of array constructed (e.g. to produce a LabelArray instead of an ndarray). """ missing_value = self.missing_value outputs = self.outputs if outputs is not NotSpecified: out = recarray( shape, formats=[self.dtype.str] * len(outputs), names=outputs, ) out[:] = missing_value else: out = full(shape, missing_value, dtype=self.dtype) return out
[ "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 = (len(mask), 1) if ndim == 1 else mask.shape out = self._allocate_output(windows, shape) with self.ctx: for idx, date in enumerate(dates): # Never apply a mask to 1D outputs. out_mask = array([True]) if ndim == 1 else mask[idx] # Mask our inputs as usual. inputs_mask = mask[idx] masked_assets = assets[inputs_mask] out_row = out[idx][out_mask] inputs = format_inputs(windows, inputs_mask) compute(date, masked_assets, out_row, *inputs, **params) out[idx][out_mask] = out_row return out
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 = (len(mask), 1) if ndim == 1 else mask.shape out = self._allocate_output(windows, shape) with self.ctx: for idx, date in enumerate(dates): # Never apply a mask to 1D outputs. out_mask = array([True]) if ndim == 1 else mask[idx] # Mask our inputs as usual. inputs_mask = mask[idx] masked_assets = assets[inputs_mask] out_row = out[idx][out_mask] inputs = format_inputs(windows, inputs_mask) compute(date, masked_assets, out_row, *inputs, **params) out[idx][out_mask] = out_row return out
[ "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}} """ ).format(t=other_base.__name__) doc = format_docstring( owner_name=other_base.__name__, docstring=docstring, formatters={'name': PIPELINE_ALIAS_NAME_DOC}, ) return type( 'Aliased' + other_base.__name__, (cls, other_base), {'__doc__': doc, '__module__': other_base.__module__}, )
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}} """ ).format(t=other_base.__name__) doc = format_docstring( owner_name=other_base.__name__, docstring=docstring, formatters={'name': PIPELINE_ALIAS_NAME_DOC}, ) return type( 'Aliased' + other_base.__name__, (cls, other_base), {'__doc__': doc, '__module__': other_base.__module__}, )
[ "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. end_date : pd.Timestamp The last date for which final output is requested. min_extra_rows : int The minimum number of extra rows required of ``self``, as determined by other terms that depend on ``self``. Returns ------- extra_rows : int The number of extra rows to compute. This will be the minimum number of rows required to make our computed start_date fall on a recomputation date.
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 ---------- 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. end_date : pd.Timestamp The last date for which final output is requested. min_extra_rows : int The minimum number of extra rows required of ``self``, as determined by other terms that depend on ``self``. Returns ------- extra_rows : int The number of extra rows to compute. This will be the minimum number of rows required to make our computed start_date fall on a recomputation date. """ try: current_start_pos = all_dates.get_loc(start_date) - min_extra_rows if current_start_pos < 0: raise NoFurtherDataError.from_lookback_window( initial_message="Insufficient data to compute Pipeline:", first_date=all_dates[0], lookback_start=start_date, lookback_length=min_extra_rows, ) except KeyError: before, after = nearest_unequal_elements(all_dates, start_date) raise ValueError( "Pipeline start_date {start_date} is not in calendar.\n" "Latest date before start_date is {before}.\n" "Earliest date after start_date is {after}.".format( start_date=start_date, before=before, after=after, ) ) # Our possible target dates are all the dates on or before the current # starting position. # TODO: Consider bounding this below by self.window_length candidates = all_dates[:current_start_pos + 1] # Choose the latest date in the candidates that is the start of a new # period at our frequency. choices = select_sampling_indices(candidates, self._frequency) # If we have choices, the last choice is the first date if the # period containing current_start_date. Choose it. new_start_date = candidates[choices[-1]] # Add the difference between the new and old start dates to get the # number of rows for the new start_date. new_start_pos = all_dates.get_loc(new_start_date) assert new_start_pos <= current_start_pos, \ "Computed negative extra rows!" return min_extra_rows + (current_start_pos - new_start_pos)
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 ---------- 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. end_date : pd.Timestamp The last date for which final output is requested. min_extra_rows : int The minimum number of extra rows required of ``self``, as determined by other terms that depend on ``self``. Returns ------- extra_rows : int The number of extra rows to compute. This will be the minimum number of rows required to make our computed start_date fall on a recomputation date. """ try: current_start_pos = all_dates.get_loc(start_date) - min_extra_rows if current_start_pos < 0: raise NoFurtherDataError.from_lookback_window( initial_message="Insufficient data to compute Pipeline:", first_date=all_dates[0], lookback_start=start_date, lookback_length=min_extra_rows, ) except KeyError: before, after = nearest_unequal_elements(all_dates, start_date) raise ValueError( "Pipeline start_date {start_date} is not in calendar.\n" "Latest date before start_date is {before}.\n" "Earliest date after start_date is {after}.".format( start_date=start_date, before=before, after=after, ) ) # Our possible target dates are all the dates on or before the current # starting position. # TODO: Consider bounding this below by self.window_length candidates = all_dates[:current_start_pos + 1] # Choose the latest date in the candidates that is the start of a new # period at our frequency. choices = select_sampling_indices(candidates, self._frequency) # If we have choices, the last choice is the first date if the # period containing current_start_date. Choose it. new_start_date = candidates[choices[-1]] # Add the difference between the new and old start dates to get the # number of rows for the new start_date. new_start_pos = all_dates.get_loc(new_start_date) assert new_start_pos <= current_start_pos, \ "Computed negative extra rows!" return min_extra_rows + (current_start_pos - new_start_pos)
[ "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_sample[0] == dates[0], \ "Misaligned sampling dates in %s." % type(self).__name__ real_compute = self._wrapped_term._compute # Inputs will contain different kinds of values depending on whether or # not we're a windowed computation. # If we're windowed, then `inputs` is a list of iterators of ndarrays. # If we're not windowed, then `inputs` is just a list of ndarrays. # There are two things we care about doing with the input: # 1. Preparing an input to be passed to our wrapped term. # 2. Skipping an input if we're going to use an already-computed row. # We perform these actions differently based on the expected kind of # input, and we encapsulate these actions with closures so that we # don't clutter the code below with lots of branching. if self.windowed: # If we're windowed, inputs are stateful AdjustedArrays. We don't # need to do any preparation before forwarding to real_compute, but # we need to call `next` on them if we want to skip an iteration. def prepare_inputs(): return inputs def skip_this_input(): for w in inputs: next(w) else: # If we're not windowed, inputs are just ndarrays. We need to # slice out a single row when forwarding to real_compute, but we # don't need to do anything to skip an input. def prepare_inputs(): # i is the loop iteration variable below. return [a[[i]] for a in inputs] def skip_this_input(): pass results = [] samples = iter(to_sample) next_sample = next(samples) for i, compute_date in enumerate(dates): if next_sample == compute_date: results.append( real_compute( prepare_inputs(), dates[i:i + 1], assets, mask[i:i + 1], ) ) try: next_sample = next(samples) except StopIteration: # No more samples to take. Set next_sample to Nat, which # compares False with any other datetime. next_sample = pd_NaT else: skip_this_input() # Copy results from previous sample period. results.append(results[-1]) # We should have exhausted our sample dates. try: next_sample = next(samples) except StopIteration: pass else: raise AssertionError("Unconsumed sample date: %s" % next_sample) # Concatenate stored results. return vstack(results)
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_sample[0] == dates[0], \ "Misaligned sampling dates in %s." % type(self).__name__ real_compute = self._wrapped_term._compute # Inputs will contain different kinds of values depending on whether or # not we're a windowed computation. # If we're windowed, then `inputs` is a list of iterators of ndarrays. # If we're not windowed, then `inputs` is just a list of ndarrays. # There are two things we care about doing with the input: # 1. Preparing an input to be passed to our wrapped term. # 2. Skipping an input if we're going to use an already-computed row. # We perform these actions differently based on the expected kind of # input, and we encapsulate these actions with closures so that we # don't clutter the code below with lots of branching. if self.windowed: # If we're windowed, inputs are stateful AdjustedArrays. We don't # need to do any preparation before forwarding to real_compute, but # we need to call `next` on them if we want to skip an iteration. def prepare_inputs(): return inputs def skip_this_input(): for w in inputs: next(w) else: # If we're not windowed, inputs are just ndarrays. We need to # slice out a single row when forwarding to real_compute, but we # don't need to do anything to skip an input. def prepare_inputs(): # i is the loop iteration variable below. return [a[[i]] for a in inputs] def skip_this_input(): pass results = [] samples = iter(to_sample) next_sample = next(samples) for i, compute_date in enumerate(dates): if next_sample == compute_date: results.append( real_compute( prepare_inputs(), dates[i:i + 1], assets, mask[i:i + 1], ) ) try: next_sample = next(samples) except StopIteration: # No more samples to take. Set next_sample to Nat, which # compares False with any other datetime. next_sample = pd_NaT else: skip_this_input() # Copy results from previous sample period. results.append(results[-1]) # We should have exhausted our sample dates. try: next_sample = next(samples) except StopIteration: pass else: raise AssertionError("Unconsumed sample date: %s" % next_sample) # Concatenate stored results. return vstack(results)
[ "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 : {t} {{frequency}} """ ).format(t=other_base.__name__) doc = format_docstring( owner_name=other_base.__name__, docstring=docstring, formatters={'frequency': PIPELINE_DOWNSAMPLING_FREQUENCY_DOC}, ) return type( 'Downsampled' + other_base.__name__, (cls, other_base,), {'__doc__': doc, '__module__': other_base.__module__}, )
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 : {t} {{frequency}} """ ).format(t=other_base.__name__) doc = format_docstring( owner_name=other_base.__name__, docstring=docstring, formatters={'frequency': PIPELINE_DOWNSAMPLING_FREQUENCY_DOC}, ) return type( 'Downsampled' + other_base.__name__, (cls, other_base,), {'__doc__': doc, '__module__': other_base.__module__}, )
[ "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 function for which we're processing args. `argname` is the name of the argument we're processing. `argvalue` is the value of the argument we're processing. Examples -------- >>> def _ensure_tuple(func, argname, arg): ... if isinstance(arg, tuple): ... return argvalue ... try: ... return tuple(arg) ... except TypeError: ... raise TypeError( ... "%s() expected argument '%s' to" ... " be iterable, but got %s instead." % ( ... func.__name__, argname, arg, ... ) ... ) ... >>> @preprocess(arg=_ensure_tuple) ... def foo(arg): ... return arg ... >>> foo([1, 2, 3]) (1, 2, 3) >>> foo("a") ('a',) >>> foo(2) Traceback (most recent call last): ... TypeError: foo() expected argument 'arg' to be iterable, but got 2 instead.
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: (func, argname, argvalue). `func` is the the function for which we're processing args. `argname` is the name of the argument we're processing. `argvalue` is the value of the argument we're processing. Examples -------- >>> def _ensure_tuple(func, argname, arg): ... if isinstance(arg, tuple): ... return argvalue ... try: ... return tuple(arg) ... except TypeError: ... raise TypeError( ... "%s() expected argument '%s' to" ... " be iterable, but got %s instead." % ( ... func.__name__, argname, arg, ... ) ... ) ... >>> @preprocess(arg=_ensure_tuple) ... def foo(arg): ... return arg ... >>> foo([1, 2, 3]) (1, 2, 3) >>> foo("a") ('a',) >>> foo(2) Traceback (most recent call last): ... TypeError: foo() expected argument 'arg' to be iterable, but got 2 instead. """ if _unused: raise TypeError("preprocess() doesn't accept positional arguments") def _decorator(f): args, varargs, varkw, defaults = argspec = getargspec(f) if defaults is None: defaults = () no_defaults = (NO_DEFAULT,) * (len(args) - len(defaults)) args_defaults = list(zip(args, no_defaults + defaults)) if varargs: args_defaults.append((varargs, NO_DEFAULT)) if varkw: args_defaults.append((varkw, NO_DEFAULT)) argset = set(args) | {varargs, varkw} - {None} # Arguments can be declared as tuples in Python 2. if not all(isinstance(arg, str) for arg in args): raise TypeError( "Can't validate functions using tuple unpacking: %s" % (argspec,) ) # Ensure that all processors map to valid names. bad_names = viewkeys(processors) - argset if bad_names: raise TypeError( "Got processors for unknown arguments: %s." % bad_names ) return _build_preprocessed_function( f, processors, args_defaults, varargs, varkw, ) return _decorator
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: (func, argname, argvalue). `func` is the the function for which we're processing args. `argname` is the name of the argument we're processing. `argvalue` is the value of the argument we're processing. Examples -------- >>> def _ensure_tuple(func, argname, arg): ... if isinstance(arg, tuple): ... return argvalue ... try: ... return tuple(arg) ... except TypeError: ... raise TypeError( ... "%s() expected argument '%s' to" ... " be iterable, but got %s instead." % ( ... func.__name__, argname, arg, ... ) ... ) ... >>> @preprocess(arg=_ensure_tuple) ... def foo(arg): ... return arg ... >>> foo([1, 2, 3]) (1, 2, 3) >>> foo("a") ('a',) >>> foo(2) Traceback (most recent call last): ... TypeError: foo() expected argument 'arg' to be iterable, but got 2 instead. """ if _unused: raise TypeError("preprocess() doesn't accept positional arguments") def _decorator(f): args, varargs, varkw, defaults = argspec = getargspec(f) if defaults is None: defaults = () no_defaults = (NO_DEFAULT,) * (len(args) - len(defaults)) args_defaults = list(zip(args, no_defaults + defaults)) if varargs: args_defaults.append((varargs, NO_DEFAULT)) if varkw: args_defaults.append((varkw, NO_DEFAULT)) argset = set(args) | {varargs, varkw} - {None} # Arguments can be declared as tuples in Python 2. if not all(isinstance(arg, str) for arg in args): raise TypeError( "Can't validate functions using tuple unpacking: %s" % (argspec,) ) # Ensure that all processors map to valid names. bad_names = viewkeys(processors) - argset if bad_names: raise TypeError( "Got processors for unknown arguments: %s." % bad_names ) return _build_preprocessed_function( f, processors, args_defaults, varargs, varkw, ) return _decorator
[ "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 -------- >>> @preprocess(x=call(lambda x: x + 1)) ... def foo(x): ... return x ... >>> foo(1) 2
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. Examples -------- >>> @preprocess(x=call(lambda x: x + 1)) ... def foo(x): ... return x ... >>> foo(1) 2 """ @wraps(f) def processor(func, argname, arg): return f(arg) return processor
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. Examples -------- >>> @preprocess(x=call(lambda x: x + 1)) ... def foo(x): ... return x ... >>> foo(1) 2 """ @wraps(f) def processor(func, argname, arg): return f(arg) return processor
[ "Wrap", "a", "function", "in", "a", "processor", "that", "calls", "f", "on", "the", "argument", "before", "passing", "it", "along", "." ]
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 to build a function that actually has the same signature as `func. """ format_kwargs = {'func_name': func.__name__} def mangle(name): return 'a' + uuid4().hex + name format_kwargs['mangled_func'] = mangled_funcname = mangle(func.__name__) def make_processor_assignment(arg, processor_name): template = "{arg} = {processor}({func}, '{arg}', {arg})" return template.format( arg=arg, processor=processor_name, func=mangled_funcname, ) exec_globals = {mangled_funcname: func, 'wraps': wraps} defaults_seen = 0 default_name_template = 'a' + uuid4().hex + '_%d' signature = [] call_args = [] assignments = [] star_map = { varargs: '*', varkw: '**', } def name_as_arg(arg): return star_map.get(arg, '') + arg for arg, default in args_defaults: if default is NO_DEFAULT: signature.append(name_as_arg(arg)) else: default_name = default_name_template % defaults_seen exec_globals[default_name] = default signature.append('='.join([name_as_arg(arg), default_name])) defaults_seen += 1 if arg in processors: procname = mangle('_processor_' + arg) exec_globals[procname] = processors[arg] assignments.append(make_processor_assignment(arg, procname)) call_args.append(name_as_arg(arg)) exec_str = dedent( """\ @wraps({wrapped_funcname}) def {func_name}({signature}): {assignments} return {wrapped_funcname}({call_args}) """ ).format( func_name=func.__name__, signature=', '.join(signature), assignments='\n '.join(assignments), wrapped_funcname=mangled_funcname, call_args=', '.join(call_args), ) compiled = compile( exec_str, func.__code__.co_filename, mode='exec', ) exec_locals = {} exec_(compiled, exec_globals, exec_locals) new_func = exec_locals[func.__name__] code = new_func.__code__ args = { attr: getattr(code, attr) for attr in dir(code) if attr.startswith('co_') } # Copy the firstlineno out of the underlying function so that exceptions # get raised with the correct traceback. # This also makes dynamic source inspection (like IPython `??` operator) # work as intended. try: # Try to get the pycode object from the underlying function. original_code = func.__code__ except AttributeError: try: # The underlying callable was not a function, try to grab the # `__func__.__code__` which exists on method objects. original_code = func.__func__.__code__ except AttributeError: # The underlying callable does not have a `__code__`. There is # nothing for us to correct. return new_func args['co_firstlineno'] = original_code.co_firstlineno new_func.__code__ = CodeType(*map(getitem(args), _code_argorder)) return new_func
def _build_preprocessed_function(func, processors, args_defaults, varargs, varkw): """ 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. """ format_kwargs = {'func_name': func.__name__} def mangle(name): return 'a' + uuid4().hex + name format_kwargs['mangled_func'] = mangled_funcname = mangle(func.__name__) def make_processor_assignment(arg, processor_name): template = "{arg} = {processor}({func}, '{arg}', {arg})" return template.format( arg=arg, processor=processor_name, func=mangled_funcname, ) exec_globals = {mangled_funcname: func, 'wraps': wraps} defaults_seen = 0 default_name_template = 'a' + uuid4().hex + '_%d' signature = [] call_args = [] assignments = [] star_map = { varargs: '*', varkw: '**', } def name_as_arg(arg): return star_map.get(arg, '') + arg for arg, default in args_defaults: if default is NO_DEFAULT: signature.append(name_as_arg(arg)) else: default_name = default_name_template % defaults_seen exec_globals[default_name] = default signature.append('='.join([name_as_arg(arg), default_name])) defaults_seen += 1 if arg in processors: procname = mangle('_processor_' + arg) exec_globals[procname] = processors[arg] assignments.append(make_processor_assignment(arg, procname)) call_args.append(name_as_arg(arg)) exec_str = dedent( """\ @wraps({wrapped_funcname}) def {func_name}({signature}): {assignments} return {wrapped_funcname}({call_args}) """ ).format( func_name=func.__name__, signature=', '.join(signature), assignments='\n '.join(assignments), wrapped_funcname=mangled_funcname, call_args=', '.join(call_args), ) compiled = compile( exec_str, func.__code__.co_filename, mode='exec', ) exec_locals = {} exec_(compiled, exec_globals, exec_locals) new_func = exec_locals[func.__name__] code = new_func.__code__ args = { attr: getattr(code, attr) for attr in dir(code) if attr.startswith('co_') } # Copy the firstlineno out of the underlying function so that exceptions # get raised with the correct traceback. # This also makes dynamic source inspection (like IPython `??` operator) # work as intended. try: # Try to get the pycode object from the underlying function. original_code = func.__code__ except AttributeError: try: # The underlying callable was not a function, try to grab the # `__func__.__code__` which exists on method objects. original_code = func.__func__.__code__ except AttributeError: # The underlying callable does not have a `__code__`. There is # nothing for us to correct. return new_func args['co_firstlineno'] = original_code.co_firstlineno new_func.__code__ = CodeType(*map(getitem(args), _code_argorder)) return new_func
[ "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 get up to 5 years worth of data. """ r = requests.get( 'https://api.iextrading.com/1.0/stock/{}/chart/5y'.format(symbol) ) data = r.json() df = pd.DataFrame(data) df.index = pd.DatetimeIndex(df['date']) df = df['close'] return df.sort_index().tz_localize('UTC').pct_change(1).iloc[1:]
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 up to 5 years worth of data. """ r = requests.get( 'https://api.iextrading.com/1.0/stock/{}/chart/5y'.format(symbol) ) data = r.json() df = pd.DataFrame(data) df.index = pd.DatetimeIndex(df['date']) df = df['close'] return df.sort_index().tz_localize('UTC').pct_change(1).iloc[1:]
[ "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( "`delimiters` must be of length 2. Got %r" % delimiters ) return ''.join([delimiters[0], content, delimiters[1]])
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( "`delimiters` must be of length 2. Got %r" % delimiters ) return ''.join([delimiters[0], content, delimiters[1]])
[ "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_exists : bool Whether to filter out `AssetExists()` nodes. """ graph_attrs = {'rankdir': 'TB', 'splines': 'ortho'} cluster_attrs = {'style': 'filled', 'color': 'lightgoldenrod1'} in_nodes = g.loadable_terms out_nodes = list(g.outputs.values()) f = BytesIO() with graph(f, "G", **graph_attrs): # Write outputs cluster. with cluster(f, 'Output', labelloc='b', **cluster_attrs): for term in filter_nodes(include_asset_exists, out_nodes): add_term_node(f, term) # Write inputs cluster. with cluster(f, 'Input', **cluster_attrs): for term in filter_nodes(include_asset_exists, in_nodes): add_term_node(f, term) # Write intermediate results. for term in filter_nodes(include_asset_exists, topological_sort(g.graph)): if term in in_nodes or term in out_nodes: continue add_term_node(f, term) # Write edges for source, dest in g.graph.edges(): if source is AssetExists() and not include_asset_exists: continue add_edge(f, id(source), id(dest)) cmd = ['dot', '-T', format_] try: proc = Popen(cmd, stdin=PIPE, stdout=PIPE, stderr=PIPE) except OSError as e: if e.errno == errno.ENOENT: raise RuntimeError( "Couldn't find `dot` graph layout program. " "Make sure Graphviz is installed and `dot` is on your path." ) else: raise f.seek(0) proc_stdout, proc_stderr = proc.communicate(f.read()) if proc_stderr: raise RuntimeError( "Error(s) while rendering graph: %s" % proc_stderr.decode('utf-8') ) out.write(proc_stdout)
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_exists : bool Whether to filter out `AssetExists()` nodes. """ graph_attrs = {'rankdir': 'TB', 'splines': 'ortho'} cluster_attrs = {'style': 'filled', 'color': 'lightgoldenrod1'} in_nodes = g.loadable_terms out_nodes = list(g.outputs.values()) f = BytesIO() with graph(f, "G", **graph_attrs): # Write outputs cluster. with cluster(f, 'Output', labelloc='b', **cluster_attrs): for term in filter_nodes(include_asset_exists, out_nodes): add_term_node(f, term) # Write inputs cluster. with cluster(f, 'Input', **cluster_attrs): for term in filter_nodes(include_asset_exists, in_nodes): add_term_node(f, term) # Write intermediate results. for term in filter_nodes(include_asset_exists, topological_sort(g.graph)): if term in in_nodes or term in out_nodes: continue add_term_node(f, term) # Write edges for source, dest in g.graph.edges(): if source is AssetExists() and not include_asset_exists: continue add_edge(f, id(source), id(dest)) cmd = ['dot', '-T', format_] try: proc = Popen(cmd, stdin=PIPE, stdout=PIPE, stderr=PIPE) except OSError as e: if e.errno == errno.ENOENT: raise RuntimeError( "Couldn't find `dot` graph layout program. " "Make sure Graphviz is installed and `dot` is on your path." ) else: raise f.seek(0) proc_stdout, proc_stderr = proc.communicate(f.read()) if proc_stderr: raise RuntimeError( "Error(s) while rendering graph: %s" % proc_stderr.decode('utf-8') ) out.write(proc_stdout)
[ "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': display_cls = display.SVG elif format in ("jpeg", "png"): display_cls = partial(display.Image, format=format, embed=True) out = BytesIO() _render(g, out, format, include_asset_exists=include_asset_exists) return display_cls(data=out.getvalue())
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_cls = display.SVG elif format in ("jpeg", "png"): display_cls = partial(display.Image, format=format, embed=True) out = BytesIO() _render(g, out, format, include_asset_exists=include_asset_exists) return display_cls(data=out.getvalue())
[ "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)) for key, value in iteritems(attrs)] return '[' + ', '.join(entries) + ']'
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)) for key, value in iteritems(attrs)] return '[' + ', '.join(entries) + ']'
[ "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 ------- future : ApplyAsyncResult The result of calling the function boxed in a future-like api. Notes ----- This calls the function eagerly but wraps it so that ``SequentialPool`` can be used where a :class:`multiprocessing.Pool` or :class:`gevent.pool.Pool` would be used.
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, optional The keyword arguments. Returns ------- future : ApplyAsyncResult The result of calling the function boxed in a future-like api. Notes ----- This calls the function eagerly but wraps it so that ``SequentialPool`` can be used where a :class:`multiprocessing.Pool` or :class:`gevent.pool.Pool` would be used. """ try: value = (identity if callback is None else callback)( f(*args, **kwargs or {}), ) successful = True except Exception as e: value = e successful = False return ApplyAsyncResult(value, successful)
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, optional The keyword arguments. Returns ------- future : ApplyAsyncResult The result of calling the function boxed in a future-like api. Notes ----- This calls the function eagerly but wraps it so that ``SequentialPool`` can be used where a :class:`multiprocessing.Pool` or :class:`gevent.pool.Pool` would be used. """ try: value = (identity if callback is None else callback)( f(*args, **kwargs or {}), ) successful = True except Exception as e: value = e successful = False return ApplyAsyncResult(value, successful)
[ "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 A context manager whose enter is the actual iterator to use. Examples -------- .. code-block:: python with maybe_show_progress([1, 2, 3], True) as ns: for n in ns: ...
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. Returns ------- itercontext : context manager A context manager whose enter is the actual iterator to use. Examples -------- .. code-block:: python with maybe_show_progress([1, 2, 3], True) as ns: for n in ns: ... """ if show_progress: return click.progressbar(it, **kwargs) # context manager that just return `it` when we enter it return CallbackManager(lambda it=it: it)
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. Returns ------- itercontext : context manager A context manager whose enter is the actual iterator to use. Examples -------- .. code-block:: python with maybe_show_progress([1, 2, 3], True) as ns: for n in ns: ... """ if show_progress: return click.progressbar(it, **kwargs) # context manager that just return `it` when we enter it return CallbackManager(lambda it=it: it)
[ "Optionally", "show", "a", "progress", "bar", "for", "the", "given", "iterator", "." ]
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, extension, strict_extensions, os.environ, )
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, extension, strict_extensions, os.environ, )
[ "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 IPython mode. """ if __IPYTHON__: return option argname = extract_option_object(option).name def d(f): @wraps(f) def _(*args, **kwargs): kwargs[argname] = None return f(*args, **kwargs) return _ return d
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 IPython mode. """ if __IPYTHON__: return option argname = extract_option_object(option).name def d(f): @wraps(f) def _(*args, **kwargs): kwargs[argname] = None return f(*args, **kwargs) return _ return d
[ "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 backtest for the given algorithm. """ # check that the start and end dates are passed correctly if start is None and end is None: # check both at the same time to avoid the case where a user # does not pass either of these and then passes the first only # to be told they need to pass the second argument also ctx.fail( "must specify dates with '-s' / '--start' and '-e' / '--end'", ) if start is None: ctx.fail("must specify a start date with '-s' / '--start'") if end is None: ctx.fail("must specify an end date with '-e' / '--end'") if (algotext is not None) == (algofile is not None): ctx.fail( "must specify exactly one of '-f' / '--algofile' or" " '-t' / '--algotext'", ) trading_calendar = get_calendar(trading_calendar) perf = _run( initialize=None, handle_data=None, before_trading_start=None, analyze=None, algofile=algofile, algotext=algotext, defines=define, data_frequency=data_frequency, capital_base=capital_base, bundle=bundle, bundle_timestamp=bundle_timestamp, start=start, end=end, output=output, trading_calendar=trading_calendar, print_algo=print_algo, metrics_set=metrics_set, local_namespace=local_namespace, environ=os.environ, blotter=blotter, benchmark_returns=None, ) if output == '-': click.echo(str(perf)) elif output != os.devnull: # make the zipline magic not write any data perf.to_pickle(output) return perf
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 backtest for the given algorithm. """ # check that the start and end dates are passed correctly if start is None and end is None: # check both at the same time to avoid the case where a user # does not pass either of these and then passes the first only # to be told they need to pass the second argument also ctx.fail( "must specify dates with '-s' / '--start' and '-e' / '--end'", ) if start is None: ctx.fail("must specify a start date with '-s' / '--start'") if end is None: ctx.fail("must specify an end date with '-e' / '--end'") if (algotext is not None) == (algofile is not None): ctx.fail( "must specify exactly one of '-f' / '--algofile' or" " '-t' / '--algotext'", ) trading_calendar = get_calendar(trading_calendar) perf = _run( initialize=None, handle_data=None, before_trading_start=None, analyze=None, algofile=algofile, algotext=algotext, defines=define, data_frequency=data_frequency, capital_base=capital_base, bundle=bundle, bundle_timestamp=bundle_timestamp, start=start, end=end, output=output, trading_calendar=trading_calendar, print_algo=print_algo, metrics_set=metrics_set, local_namespace=local_namespace, environ=os.environ, blotter=blotter, benchmark_returns=None, ) if output == '-': click.echo(str(perf)) elif output != os.devnull: # make the zipline magic not write any data perf.to_pickle(output) return perf
[ "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 # users may pass values with higher precedence [ '--algotext', cell, '--output', os.devnull, # don't write the results by default ] + ([ # these options are set when running in line magic mode # set a non None algo text to use the ipython user_ns '--algotext', '', '--local-namespace', ] if cell is None else []) + line.split(), '%s%%zipline' % ((cell or '') and '%'), # don't use system exit and propogate errors to the caller standalone_mode=False, ) except SystemExit as e: # https://github.com/mitsuhiko/click/pull/533 # even in standalone_mode=False `--help` really wants to kill us ;_; if e.code: raise ValueError('main returned non-zero status code: %d' % e.code)
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 # users may pass values with higher precedence [ '--algotext', cell, '--output', os.devnull, # don't write the results by default ] + ([ # these options are set when running in line magic mode # set a non None algo text to use the ipython user_ns '--algotext', '', '--local-namespace', ] if cell is None else []) + line.split(), '%s%%zipline' % ((cell or '') and '%'), # don't use system exit and propogate errors to the caller standalone_mode=False, ) except SystemExit as e: # https://github.com/mitsuhiko/click/pull/533 # even in standalone_mode=False `--help` really wants to kill us ;_; if e.code: raise ValueError('main returned non-zero status code: %d' % e.code)
[ "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_bundle(bundle)) ) except OSError as e: if e.errno != errno.ENOENT: raise ingestions = [] # If we got no ingestions, either because the directory didn't exist or # because there were no entries, print a single message indicating that # no ingestions have yet been made. for timestamp in ingestions or ["<no ingestions>"]: click.echo("%s %s" % (bundle, timestamp))
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_bundle(bundle)) ) except OSError as e: if e.errno != errno.ENOENT: raise ingestions = [] # If we got no ingestions, either because the directory didn't exist or # because there were no entries, print a single message indicating that # no ingestions have yet been made. for timestamp in ingestions or ["<no ingestions>"]: click.echo("%s %s" % (bundle, timestamp))
[ "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 to defer to the commuted interpretation of the # NumericalExpression operator. commuted_method_getter = attrgetter(method_name_for_op(op, commute=True)) def binary_operator(self, other): if isinstance(self, NumericalExpression): self_expr, other_expr, new_inputs = self.build_binary_op( op, other, ) return NumExprFilter.create( "({left}) {op} ({right})".format( left=self_expr, op=op, right=other_expr, ), new_inputs, ) elif isinstance(other, NumericalExpression): # NumericalExpression overrides numerical ops to correctly handle # merging of inputs. Look up and call the appropriate # right-binding operator with ourself as the input. return commuted_method_getter(other)(self) elif isinstance(other, Term): if other.dtype != bool_dtype: raise BadBinaryOperator(op, self, other) if self is other: return NumExprFilter.create( "x_0 {op} x_0".format(op=op), (self,), ) return NumExprFilter.create( "x_0 {op} x_1".format(op=op), (self, other), ) elif isinstance(other, int): # Note that this is true for bool as well return NumExprFilter.create( "x_0 {op} {constant}".format(op=op, constant=int(other)), binds=(self,), ) raise BadBinaryOperator(op, self, other) binary_operator.__doc__ = "Binary Operator: '%s'" % op return binary_operator
def binary_operator(op): """ Factory function for making binary operator methods on a Filter subclass. Returns a function "binary_operator" suitable for implementing functions like __and__ or __or__. """ # When combining a Filter with a NumericalExpression, we use this # attrgetter instance to defer to the commuted interpretation of the # NumericalExpression operator. commuted_method_getter = attrgetter(method_name_for_op(op, commute=True)) def binary_operator(self, other): if isinstance(self, NumericalExpression): self_expr, other_expr, new_inputs = self.build_binary_op( op, other, ) return NumExprFilter.create( "({left}) {op} ({right})".format( left=self_expr, op=op, right=other_expr, ), new_inputs, ) elif isinstance(other, NumericalExpression): # NumericalExpression overrides numerical ops to correctly handle # merging of inputs. Look up and call the appropriate # right-binding operator with ourself as the input. return commuted_method_getter(other)(self) elif isinstance(other, Term): if other.dtype != bool_dtype: raise BadBinaryOperator(op, self, other) if self is other: return NumExprFilter.create( "x_0 {op} x_0".format(op=op), (self,), ) return NumExprFilter.create( "x_0 {op} x_1".format(op=op), (self, other), ) elif isinstance(other, int): # Note that this is true for bool as well return NumExprFilter.create( "x_0 {op} {constant}".format(op=op, constant=int(other)), binds=(self,), ) raise BadBinaryOperator(op, self, other) binary_operator.__doc__ = "Binary Operator: '%s'" % op return binary_operator
[ "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 by # unary_op_return_type aren't defined when the top-level function is # invoked. if isinstance(self, NumericalExpression): return NumExprFilter.create( "{op}({expr})".format(op=op, expr=self._expr), self.inputs, ) else: return NumExprFilter.create("{op}x_0".format(op=op), (self,)) unary_operator.__doc__ = "Unary Operator: '%s'" % op return unary_operator
def unary_operator(op): """ Factory function for making unary operator methods for Filters. """ valid_ops = {'~'} if op not in valid_ops: raise ValueError("Invalid unary operator %s." % op) def unary_operator(self): # This can't be hoisted up a scope because the types returned by # unary_op_return_type aren't defined when the top-level function is # invoked. if isinstance(self, NumericalExpression): return NumExprFilter.create( "{op}({expr})".format(op=op, expr=self._expr), self.inputs, ) else: return NumExprFilter.create("{op}x_0".format(op=op), (self,)) unary_operator.__doc__ = "Unary Operator: '%s'" % op return unary_operator
[ "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=bool_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=bool_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_percentile, upper_bound=100.0 ) return super(PercentileFilter, self)._validate()
def _validate(self): """ Ensure that our percentile bounds are well-formed. """ if not 0.0 <= self._min_percentile < self._max_percentile <= 100.0: raise BadPercentileBounds( min_percentile=self._min_percentile, max_percentile=self._max_percentile, upper_bound=100.0 ) return super(PercentileFilter, self)._validate()
[ "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().astype(float64) data[~mask] = nan # FIXME: np.nanpercentile **should** support computing multiple bounds # at once, but there's a bug in the logic for multiple bounds in numpy # 1.9.2. It will be fixed in 1.10. # c.f. https://github.com/numpy/numpy/pull/5981 lower_bounds = nanpercentile( data, self._min_percentile, axis=1, keepdims=True, ) upper_bounds = nanpercentile( data, self._max_percentile, axis=1, keepdims=True, ) return (lower_bounds <= data) & (data <= upper_bounds)
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().astype(float64) data[~mask] = nan # FIXME: np.nanpercentile **should** support computing multiple bounds # at once, but there's a bug in the logic for multiple bounds in numpy # 1.9.2. It will be fixed in 1.10. # c.f. https://github.com/numpy/numpy/pull/5981 lower_bounds = nanpercentile( data, self._min_percentile, axis=1, keepdims=True, ) upper_bounds = nanpercentile( data, self._max_percentile, axis=1, keepdims=True, ) return (lower_bounds <= data) & (data <= upper_bounds)
[ "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 30year.
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, which we turn into a string like 3month or 30year. """ column_re = re.compile( r"^(?P<prefix>RIFLGFC)" "(?P<unit>[YM])" "(?P<periods>[0-9]{2})" "(?P<suffix>_N.B)$" ) match = column_re.match(column) if match is None: raise ValueError("Couldn't parse CSV column %r." % column) unit, periods = get_unit_and_periods(match.groupdict()) # Roundtrip through int to coerce '06' into '6'. return str(int(periods)) + ('year' if unit == 'Y' else 'month')
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, which we turn into a string like 3month or 30year. """ column_re = re.compile( r"^(?P<prefix>RIFLGFC)" "(?P<unit>[YM])" "(?P<periods>[0-9]{2})" "(?P<suffix>_N.B)$" ) match = column_re.match(column) if match is None: raise ValueError("Couldn't parse CSV column %r." % column) unit, periods = get_unit_and_periods(match.groupdict()) # Roundtrip through int to coerce '06' into '6'. return str(int(periods)) + ('year' if unit == 'Y' else 'month')
[ "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&label=include&layout=seriescolumn" return pd.read_csv(url, header=5, index_col=0, names=['DATE', 'BC_10YEAR'], parse_dates=True, converters={1: dataconverter}, squeeze=True)
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&label=include&layout=seriescolumn" return pd.read_csv(url, header=5, index_col=0, names=['DATE', 'BC_10YEAR'], parse_dates=True, converters={1: dataconverter}, squeeze=True)
[ "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 rootdir, including subdirectory prefixes based on the padded string representation of the given sid. e.g. 1 is formatted as 00/00/000001.bcolz
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 : string A path for the bcolz rootdir, including subdirectory prefixes based on the padded string representation of the given sid. e.g. 1 is formatted as 00/00/000001.bcolz """ padded_sid = format(sid, '06') return os.path.join( # subdir 1 00/XX padded_sid[0:2], # subdir 2 XX/00 padded_sid[2:4], "{0}.bcolz".format(str(padded_sid)) )
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 : string A path for the bcolz rootdir, including subdirectory prefixes based on the padded string representation of the given sid. e.g. 1 is formatted as 00/00/000001.bcolz """ padded_sid = format(sid, '06') return os.path.join( # subdir 1 00/XX padded_sid[0:2], # subdir 2 XX/00 padded_sid[2:4], "{0}.bcolz".format(str(padded_sid)) )
[ "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