code stringlengths 66 870k | docstring stringlengths 19 26.7k | func_name stringlengths 1 138 | language stringclasses 1
value | repo stringlengths 7 68 | path stringlengths 5 324 | url stringlengths 46 389 | license stringclasses 7
values |
|---|---|---|---|---|---|---|---|
def test_correlation_methods_bad_type(self):
"""
Make sure we cannot call the Factor correlation methods on factors or
slices that are not of float or int dtype.
"""
# These are arbitrary for the purpose of this test.
returns_length = 2
correlation_length = 10
... |
Make sure we cannot call the Factor correlation methods on factors or
slices that are not of float or int dtype.
| test_correlation_methods_bad_type | python | quantopian/zipline | tests/pipeline/test_statistical.py | https://github.com/quantopian/zipline/blob/master/tests/pipeline/test_statistical.py | Apache-2.0 |
def test_regression_method_bad_type(self):
"""
Make sure we cannot call the Factor linear regression method on factors
or slices that are not of float or int dtype.
"""
# These are arbitrary for the purpose of this test.
returns_length = 2
regression_length = 10
... |
Make sure we cannot call the Factor linear regression method on factors
or slices that are not of float or int dtype.
| test_regression_method_bad_type | python | quantopian/zipline | tests/pipeline/test_statistical.py | https://github.com/quantopian/zipline/blob/master/tests/pipeline/test_statistical.py | Apache-2.0 |
def test_factor_correlation_methods_two_factors(self, correlation_length):
"""
Tests for `Factor.pearsonr` and `Factor.spearmanr` when passed another
2D factor instead of a Slice.
"""
assets = self.assets
dates = self.dates
start_date = self.pipeline_start_date
... |
Tests for `Factor.pearsonr` and `Factor.spearmanr` when passed another
2D factor instead of a Slice.
| test_factor_correlation_methods_two_factors | python | quantopian/zipline | tests/pipeline/test_statistical.py | https://github.com/quantopian/zipline/blob/master/tests/pipeline/test_statistical.py | Apache-2.0 |
def test_factor_regression_method_two_factors(self, regression_length):
"""
Tests for `Factor.linear_regression` when passed another 2D factor
instead of a Slice.
"""
assets = self.assets
dates = self.dates
start_date = self.pipeline_start_date
end_date = ... |
Tests for `Factor.linear_regression` when passed another 2D factor
instead of a Slice.
| test_factor_regression_method_two_factors | python | quantopian/zipline | tests/pipeline/test_statistical.py | https://github.com/quantopian/zipline/blob/master/tests/pipeline/test_statistical.py | Apache-2.0 |
def expected_bbands(self, window_length, k, closes):
"""Compute the expected data (without adjustments) for the given
window, k, and closes array.
This uses talib.BBANDS to generate the expected data.
"""
lower_cols = []
middle_cols = []
upper_cols = []
... | Compute the expected data (without adjustments) for the given
window, k, and closes array.
This uses talib.BBANDS to generate the expected data.
| expected_bbands | python | quantopian/zipline | tests/pipeline/test_technical.py | https://github.com/quantopian/zipline/blob/master/tests/pipeline/test_technical.py | Apache-2.0 |
def test_fso_expected_basic(self):
"""
Simple test of expected output from fast stochastic oscillator
"""
fso = FastStochasticOscillator()
today = pd.Timestamp('2015')
assets = np.arange(3, dtype=np.float64)
out = np.empty(shape=(3,), dtype=np.float64)
h... |
Simple test of expected output from fast stochastic oscillator
| test_fso_expected_basic | python | quantopian/zipline | tests/pipeline/test_technical.py | https://github.com/quantopian/zipline/blob/master/tests/pipeline/test_technical.py | Apache-2.0 |
def test_fso_expected_with_talib(self, seed):
"""
Test the output that is returned from the fast stochastic oscillator
is the same as that from the ta-lib STOCHF function.
"""
window_length = 14
nassets = 6
rng = np.random.RandomState(seed=seed)
input_siz... |
Test the output that is returned from the fast stochastic oscillator
is the same as that from the ta-lib STOCHF function.
| test_fso_expected_with_talib | python | quantopian/zipline | tests/pipeline/test_technical.py | https://github.com/quantopian/zipline/blob/master/tests/pipeline/test_technical.py | Apache-2.0 |
def test_rsi_all_positive_returns(self):
"""
RSI indicator should be 100 in the case of 14 days of positive returns.
"""
rsi = RSI()
today = np.datetime64(1, 'ns')
assets = np.arange(1)
out = np.empty((1,), dtype=float)
closes = np.linspace(46, 60, num=... |
RSI indicator should be 100 in the case of 14 days of positive returns.
| test_rsi_all_positive_returns | python | quantopian/zipline | tests/pipeline/test_technical.py | https://github.com/quantopian/zipline/blob/master/tests/pipeline/test_technical.py | Apache-2.0 |
def test_rsi_all_negative_returns(self):
"""
RSI indicator should be 0 in the case of 14 days of negative returns.
"""
rsi = RSI()
today = np.datetime64(1, 'ns')
assets = np.arange(1)
out = np.empty((1,), dtype=float)
closes = np.linspace(46, 32, num=15)... |
RSI indicator should be 0 in the case of 14 days of negative returns.
| test_rsi_all_negative_returns | python | quantopian/zipline | tests/pipeline/test_technical.py | https://github.com/quantopian/zipline/blob/master/tests/pipeline/test_technical.py | Apache-2.0 |
def test_rsi_same_returns(self):
"""
RSI indicator should be the same for two price series with the same
returns, even if the prices are different.
"""
rsi = RSI()
today = np.datetime64(1, 'ns')
assets = np.arange(2)
out = np.empty((2,), dtype=float)
... |
RSI indicator should be the same for two price series with the same
returns, even if the prices are different.
| test_rsi_same_returns | python | quantopian/zipline | tests/pipeline/test_technical.py | https://github.com/quantopian/zipline/blob/master/tests/pipeline/test_technical.py | Apache-2.0 |
def test_simple_volatility(self):
"""
Simple test for uniform returns should generate 0 volatility
"""
nassets = 3
ann_vol = AnnualizedVolatility()
today = pd.Timestamp('2016', tz='utc')
assets = np.arange(nassets, dtype=np.float64)
returns = np.full((ann_... |
Simple test for uniform returns should generate 0 volatility
| test_simple_volatility | python | quantopian/zipline | tests/pipeline/test_technical.py | https://github.com/quantopian/zipline/blob/master/tests/pipeline/test_technical.py | Apache-2.0 |
def test_volatility(self):
"""
Check volatility results against values calculated manually
"""
nassets = 3
ann_vol = AnnualizedVolatility()
today = pd.Timestamp('2016', tz='utc')
assets = np.arange(nassets, dtype=np.float64)
returns = np.random.normal(loc=... |
Check volatility results against values calculated manually
| test_volatility | python | quantopian/zipline | tests/pipeline/test_technical.py | https://github.com/quantopian/zipline/blob/master/tests/pipeline/test_technical.py | Apache-2.0 |
def gen_equivalent_factors():
"""
Return an iterator of SomeFactor instances that should all be the same
object.
"""
yield SomeFactor()
yield SomeFactor(inputs=NotSpecified)
yield SomeFactor(SomeFactor.inputs)
yield SomeFactor(inputs=SomeFactor.inputs)
yield SomeFactor([SomeDataSet.f... |
Return an iterator of SomeFactor instances that should all be the same
object.
| gen_equivalent_factors | python | quantopian/zipline | tests/pipeline/test_term.py | https://github.com/quantopian/zipline/blob/master/tests/pipeline/test_term.py | Apache-2.0 |
def test_single_factor(self):
"""
Test dependency resolution for a single factor.
"""
def check_output(graph):
resolution_order = list(graph.ordered())
# Loadable terms should get specialized during graph construction.
specialized_foo = SomeDataSet.f... |
Test dependency resolution for a single factor.
| test_single_factor | python | quantopian/zipline | tests/pipeline/test_term.py | https://github.com/quantopian/zipline/blob/master/tests/pipeline/test_term.py | Apache-2.0 |
def test_single_factor_instance_args(self):
"""
Test dependency resolution for a single factor with arguments passed to
the constructor.
"""
bar, buzz = SomeDataSet.bar, SomeDataSet.buzz
factor = SomeFactor([bar, buzz], window_length=5)
graph = self.make_executio... |
Test dependency resolution for a single factor with arguments passed to
the constructor.
| test_single_factor_instance_args | python | quantopian/zipline | tests/pipeline/test_term.py | https://github.com/quantopian/zipline/blob/master/tests/pipeline/test_term.py | Apache-2.0 |
def test_reuse_loadable_terms(self):
"""
Test that raw inputs only show up in the dependency graph once.
"""
f1 = SomeFactor([SomeDataSet.foo, SomeDataSet.bar])
f2 = SomeOtherFactor([SomeDataSet.bar, SomeDataSet.buzz])
graph = self.make_execution_plan(to_dict([f1, f2]))
... |
Test that raw inputs only show up in the dependency graph once.
| test_reuse_loadable_terms | python | quantopian/zipline | tests/pipeline/test_term.py | https://github.com/quantopian/zipline/blob/master/tests/pipeline/test_term.py | Apache-2.0 |
def test_window_safety_one_window_length(self):
"""
Test that window safety problems are only raised if
the parent factor has window length greater than 1
"""
with self.assertRaises(NonWindowSafeInput):
SomeFactor(inputs=[SomeOtherFactor()])
SomeFactor(inputs... |
Test that window safety problems are only raised if
the parent factor has window length greater than 1
| test_window_safety_one_window_length | python | quantopian/zipline | tests/pipeline/test_term.py | https://github.com/quantopian/zipline/blob/master/tests/pipeline/test_term.py | Apache-2.0 |
def test_reject_multi_output_classifiers(self, dtype_, outputs_):
"""
Multi-output CustomClassifiers don't work because they use special
output allocation for string arrays.
"""
class SomeClassifier(CustomClassifier):
dtype = dtype_
window_length = 5
... |
Multi-output CustomClassifiers don't work because they use special
output allocation for string arrays.
| test_reject_multi_output_classifiers | python | quantopian/zipline | tests/pipeline/test_term.py | https://github.com/quantopian/zipline/blob/master/tests/pipeline/test_term.py | Apache-2.0 |
def test_not_callable(self):
"""
Check the results of a non-callable object.
"""
not_callable = 'a'
with self.assertRaises(NotCallable):
verify_callable_argspec(not_callable) |
Check the results of a non-callable object.
| test_not_callable | python | quantopian/zipline | tests/utils/test_argcheck.py | https://github.com/quantopian/zipline/blob/master/tests/utils/test_argcheck.py | Apache-2.0 |
def test_no_starargs(self):
"""
Tests when a function does not have *args and it was expected.
"""
def f(a):
pass
with self.assertRaises(NoStarargs):
verify_callable_argspec(f, expect_starargs=True) |
Tests when a function does not have *args and it was expected.
| test_no_starargs | python | quantopian/zipline | tests/utils/test_argcheck.py | https://github.com/quantopian/zipline/blob/master/tests/utils/test_argcheck.py | Apache-2.0 |
def test_starargs(self):
"""
Tests when a function has *args and it was expected.
"""
def f(*args):
pass
verify_callable_argspec(f, expect_starargs=True) |
Tests when a function has *args and it was expected.
| test_starargs | python | quantopian/zipline | tests/utils/test_argcheck.py | https://github.com/quantopian/zipline/blob/master/tests/utils/test_argcheck.py | Apache-2.0 |
def test_unexcpected_starargs(self):
"""
Tests a function that unexpectedly accepts *args.
"""
def f(*args):
pass
with self.assertRaises(UnexpectedStarargs):
verify_callable_argspec(f, expect_starargs=False) |
Tests a function that unexpectedly accepts *args.
| test_unexcpected_starargs | python | quantopian/zipline | tests/utils/test_argcheck.py | https://github.com/quantopian/zipline/blob/master/tests/utils/test_argcheck.py | Apache-2.0 |
def test_ignore_starargs(self):
"""
Tests checking a function ignoring the presence of *args.
"""
def f(*args):
pass
def g():
pass
verify_callable_argspec(f, expect_starargs=Argument.ignore)
verify_callable_argspec(g, expect_starargs=Argu... |
Tests checking a function ignoring the presence of *args.
| test_ignore_starargs | python | quantopian/zipline | tests/utils/test_argcheck.py | https://github.com/quantopian/zipline/blob/master/tests/utils/test_argcheck.py | Apache-2.0 |
def test_no_kwargs(self):
"""
Tests when a function does not have **kwargs and it was expected.
"""
def f():
pass
with self.assertRaises(NoKwargs):
verify_callable_argspec(f, expect_kwargs=True) |
Tests when a function does not have **kwargs and it was expected.
| test_no_kwargs | python | quantopian/zipline | tests/utils/test_argcheck.py | https://github.com/quantopian/zipline/blob/master/tests/utils/test_argcheck.py | Apache-2.0 |
def test_kwargs(self):
"""
Tests when a function has **kwargs and it was expected.
"""
def f(**kwargs):
pass
verify_callable_argspec(f, expect_kwargs=True) |
Tests when a function has **kwargs and it was expected.
| test_kwargs | python | quantopian/zipline | tests/utils/test_argcheck.py | https://github.com/quantopian/zipline/blob/master/tests/utils/test_argcheck.py | Apache-2.0 |
def test_unexpected_kwargs(self):
"""
Tests a function that unexpectedly accepts **kwargs.
"""
def f(**kwargs):
pass
with self.assertRaises(UnexpectedKwargs):
verify_callable_argspec(f, expect_kwargs=False) |
Tests a function that unexpectedly accepts **kwargs.
| test_unexpected_kwargs | python | quantopian/zipline | tests/utils/test_argcheck.py | https://github.com/quantopian/zipline/blob/master/tests/utils/test_argcheck.py | Apache-2.0 |
def test_ignore_kwargs(self):
"""
Tests checking a function ignoring the presence of **kwargs.
"""
def f(**kwargs):
pass
def g():
pass
verify_callable_argspec(f, expect_kwargs=Argument.ignore)
verify_callable_argspec(g, expect_kwargs=Argu... |
Tests checking a function ignoring the presence of **kwargs.
| test_ignore_kwargs | python | quantopian/zipline | tests/utils/test_argcheck.py | https://github.com/quantopian/zipline/blob/master/tests/utils/test_argcheck.py | Apache-2.0 |
def test_arg_subset(self):
"""
Tests when the args are a subset of the expectations.
"""
def f(a, b):
pass
with self.assertRaises(NotEnoughArguments):
verify_callable_argspec(
f, [Argument('a'), Argument('b'), Argument('c')]
) |
Tests when the args are a subset of the expectations.
| test_arg_subset | python | quantopian/zipline | tests/utils/test_argcheck.py | https://github.com/quantopian/zipline/blob/master/tests/utils/test_argcheck.py | Apache-2.0 |
def test_no_default(self):
"""
Tests when an argument expects a default and it is not present.
"""
def f(a):
pass
with self.assertRaises(MismatchedArguments):
verify_callable_argspec(f, [Argument('a', 1)]) |
Tests when an argument expects a default and it is not present.
| test_no_default | python | quantopian/zipline | tests/utils/test_argcheck.py | https://github.com/quantopian/zipline/blob/master/tests/utils/test_argcheck.py | Apache-2.0 |
def test_default(self):
"""
Tests when an argument expects a default and it is present.
"""
def f(a=1):
pass
verify_callable_argspec(f, [Argument('a', 1)]) |
Tests when an argument expects a default and it is present.
| test_default | python | quantopian/zipline | tests/utils/test_argcheck.py | https://github.com/quantopian/zipline/blob/master/tests/utils/test_argcheck.py | Apache-2.0 |
def test_ignore_default(self):
"""
Tests that ignoring defaults works as intended.
"""
def f(a=1):
pass
verify_callable_argspec(f, [Argument('a')]) |
Tests that ignoring defaults works as intended.
| test_ignore_default | python | quantopian/zipline | tests/utils/test_argcheck.py | https://github.com/quantopian/zipline/blob/master/tests/utils/test_argcheck.py | Apache-2.0 |
def test_ignore_args(self):
"""
Tests the ignore argument list feature.
"""
def f(a):
pass
def g():
pass
h = 'not_callable'
verify_callable_argspec(f)
verify_callable_argspec(g)
with self.assertRaises(NotCallable):
... |
Tests the ignore argument list feature.
| test_ignore_args | python | quantopian/zipline | tests/utils/test_argcheck.py | https://github.com/quantopian/zipline/blob/master/tests/utils/test_argcheck.py | Apache-2.0 |
def test_out_of_order(self):
"""
Tests the case where arguments are not in the correct order.
"""
def f(a, b):
pass
with self.assertRaises(MismatchedArguments):
verify_callable_argspec(f, [Argument('b'), Argument('a')]) |
Tests the case where arguments are not in the correct order.
| test_out_of_order | python | quantopian/zipline | tests/utils/test_argcheck.py | https://github.com/quantopian/zipline/blob/master/tests/utils/test_argcheck.py | Apache-2.0 |
def test_wrong_default(self):
"""
Tests the case where a default is expected, but the default provided
does not match the one expected.
"""
def f(a=1):
pass
with self.assertRaises(MismatchedArguments):
verify_callable_argspec(f, [Argument('a', 2)]... |
Tests the case where a default is expected, but the default provided
does not match the one expected.
| test_wrong_default | python | quantopian/zipline | tests/utils/test_argcheck.py | https://github.com/quantopian/zipline/blob/master/tests/utils/test_argcheck.py | Apache-2.0 |
def test_subclass_no_final_override(self):
"""
Tests that it is valid to create a subclass that does not override
and final methods.
"""
class SubClass(self.class_):
b = 'SubClass: b'
def g(self):
return 'SubClass: g' |
Tests that it is valid to create a subclass that does not override
and final methods.
| test_subclass_no_final_override | python | quantopian/zipline | tests/utils/test_final.py | https://github.com/quantopian/zipline/blob/master/tests/utils/test_final.py | Apache-2.0 |
def test_override_final_no_decorator(self):
"""
Tests that attempting to create a subclass that overrides a final
method will raise a `TypeError`.
"""
with self.assertRaises(TypeError):
class SubClass(self.class_):
def f(self):
retu... |
Tests that attempting to create a subclass that overrides a final
method will raise a `TypeError`.
| test_override_final_no_decorator | python | quantopian/zipline | tests/utils/test_final.py | https://github.com/quantopian/zipline/blob/master/tests/utils/test_final.py | Apache-2.0 |
def test_override_final_attribute(self):
"""
Tests that attempting to create a subclass that overrides a final
attribute will raise a `TypeError`.
"""
with self.assertRaises(TypeError):
class SubClass(self.class_):
a = 'SubClass: a' |
Tests that attempting to create a subclass that overrides a final
attribute will raise a `TypeError`.
| test_override_final_attribute | python | quantopian/zipline | tests/utils/test_final.py | https://github.com/quantopian/zipline/blob/master/tests/utils/test_final.py | Apache-2.0 |
def test_override_final_with_decorator(self):
"""
Tests that attempting to create a subclass that overrides a final
method will raise a `TypeError` even if you mark the new version as
final.
"""
with self.assertRaises(TypeError):
class SubClass(self.class_):
... |
Tests that attempting to create a subclass that overrides a final
method will raise a `TypeError` even if you mark the new version as
final.
| test_override_final_with_decorator | python | quantopian/zipline | tests/utils/test_final.py | https://github.com/quantopian/zipline/blob/master/tests/utils/test_final.py | Apache-2.0 |
def test_override_final_attribute_with_final(self):
"""
Tests that attempting to create a subclass that overrides a final
attribute will raise a `TypeError` even if you mark the new version as
final.
"""
with self.assertRaises(TypeError):
class SubClass(self.c... |
Tests that attempting to create a subclass that overrides a final
attribute will raise a `TypeError` even if you mark the new version as
final.
| test_override_final_attribute_with_final | python | quantopian/zipline | tests/utils/test_final.py | https://github.com/quantopian/zipline/blob/master/tests/utils/test_final.py | Apache-2.0 |
def test_override_on_class_object(self):
"""
Tests overriding final methods and attributes on the class object
itself.
"""
class SubClass(self.class_):
pass
with self.assertRaises(TypeError):
SubClass.f = lambda self: 'SubClass: f'
with s... |
Tests overriding final methods and attributes on the class object
itself.
| test_override_on_class_object | python | quantopian/zipline | tests/utils/test_final.py | https://github.com/quantopian/zipline/blob/master/tests/utils/test_final.py | Apache-2.0 |
def test_override_on_instance(self):
"""
Tests overriding final methods on instances of a class.
"""
class SubClass(self.class_):
def h(self):
pass
s = SubClass()
with self.assertRaises(TypeError):
s.f = lambda self: 'SubClass: f'
... |
Tests overriding final methods on instances of a class.
| test_override_on_instance | python | quantopian/zipline | tests/utils/test_final.py | https://github.com/quantopian/zipline/blob/master/tests/utils/test_final.py | Apache-2.0 |
def test_override_on_super(self):
"""
Tests overriding on the class that has the @final methods in it.
"""
old_a = self.class_.a
old_f = self.class_.f
try:
with self.assertRaises(TypeError):
self.class_.f = lambda *args: None
except Exc... |
Tests overriding on the class that has the @final methods in it.
| test_override_on_super | python | quantopian/zipline | tests/utils/test_final.py | https://github.com/quantopian/zipline/blob/master/tests/utils/test_final.py | Apache-2.0 |
def test_override___setattr___on_subclass(self):
"""
Tests an attempt to override __setattr__ which is implicitly final.
"""
with self.assertRaises(TypeError):
class SubClass(self.class_):
def __setattr__(self, name, value):
object.__setatt... |
Tests an attempt to override __setattr__ which is implicitly final.
| test_override___setattr___on_subclass | python | quantopian/zipline | tests/utils/test_final.py | https://github.com/quantopian/zipline/blob/master/tests/utils/test_final.py | Apache-2.0 |
def test_cannot_instantiate_subclass(self):
"""
Tests that you cannot create an instance of a subclass
that does not implement the abstractmethod h.
"""
class AbstractSubClass(self.class_):
pass
with self.assertRaises(TypeError):
AbstractSubClass(... |
Tests that you cannot create an instance of a subclass
that does not implement the abstractmethod h.
| test_cannot_instantiate_subclass | python | quantopian/zipline | tests/utils/test_final.py | https://github.com/quantopian/zipline/blob/master/tests/utils/test_final.py | Apache-2.0 |
def test_subclass_setattr(self):
"""
Tests that subclasses don't destroy the __setattr__.
"""
class ClassWithFinal(with_metaclass(FinalMeta, object)):
@final
def f(self):
return 'ClassWithFinal: f'
class SubClass(ClassWithFinal):
... |
Tests that subclasses don't destroy the __setattr__.
| test_subclass_setattr | python | quantopian/zipline | tests/utils/test_final.py | https://github.com/quantopian/zipline/blob/master/tests/utils/test_final.py | Apache-2.0 |
def everything_but(k, d):
"""
Return iterator of all values in d except the values in k.
"""
assert k in d
return concat(itervalues(keyfilter(ne(k), d))) |
Return iterator of all values in d except the values in k.
| everything_but | python | quantopian/zipline | tests/utils/test_numpy_utils.py | https://github.com/quantopian/zipline/blob/master/tests/utils/test_numpy_utils.py | Apache-2.0 |
def test_preprocess_doesnt_change_TypeErrors(self, name, args, kwargs):
"""
Verify that the validate decorator doesn't swallow typeerrors that
would be raised when calling a function with invalid arguments
"""
def undecorated(x, y):
return x, y
decorated = pr... |
Verify that the validate decorator doesn't swallow typeerrors that
would be raised when calling a function with invalid arguments
| test_preprocess_doesnt_change_TypeErrors | python | quantopian/zipline | tests/utils/test_preprocess.py | https://github.com/quantopian/zipline/blob/master/tests/utils/test_preprocess.py | Apache-2.0 |
def init_engine(self, get_loader):
"""
Construct and store a PipelineEngine from loader.
If get_loader is None, constructs an ExplodingPipelineEngine
"""
if get_loader is not None:
self.engine = SimplePipelineEngine(
get_loader,
self.a... |
Construct and store a PipelineEngine from loader.
If get_loader is None, constructs an ExplodingPipelineEngine
| init_engine | python | quantopian/zipline | zipline/algorithm.py | https://github.com/quantopian/zipline/blob/master/zipline/algorithm.py | Apache-2.0 |
def initialize(self, *args, **kwargs):
"""
Call self._initialize with `self` made available to Zipline API
functions.
"""
with ZiplineAPI(self):
self._initialize(self, *args, **kwargs) |
Call self._initialize with `self` made available to Zipline API
functions.
| initialize | python | quantopian/zipline | zipline/algorithm.py | https://github.com/quantopian/zipline/blob/master/zipline/algorithm.py | Apache-2.0 |
def __repr__(self):
"""
N.B. this does not yet represent a string that can be used
to instantiate an exact copy of an algorithm.
However, it is getting close, and provides some value as something
that can be inspected interactively.
"""
return """
{class_name}(
... |
N.B. this does not yet represent a string that can be used
to instantiate an exact copy of an algorithm.
However, it is getting close, and provides some value as something
that can be inspected interactively.
| __repr__ | python | quantopian/zipline | zipline/algorithm.py | https://github.com/quantopian/zipline/blob/master/zipline/algorithm.py | Apache-2.0 |
def _create_clock(self):
"""
If the clock property is not set, then create one based on frequency.
"""
trading_o_and_c = self.trading_calendar.schedule.loc[
self.sim_params.sessions]
market_closes = trading_o_and_c['market_close']
minutely_emission = False
... |
If the clock property is not set, then create one based on frequency.
| _create_clock | python | quantopian/zipline | zipline/algorithm.py | https://github.com/quantopian/zipline/blob/master/zipline/algorithm.py | Apache-2.0 |
def compute_eager_pipelines(self):
"""
Compute any pipelines attached with eager=True.
"""
for name, pipe in self._pipelines.items():
if pipe.eager:
self.pipeline_output(name) |
Compute any pipelines attached with eager=True.
| compute_eager_pipelines | python | quantopian/zipline | zipline/algorithm.py | https://github.com/quantopian/zipline/blob/master/zipline/algorithm.py | Apache-2.0 |
def calculate_capital_changes(self, dt, emission_rate, is_interday,
portfolio_value_adjustment=0.0):
"""
If there is a capital change for a given dt, this means the the change
occurs before `handle_data` on the given dt. In the case of the
change being a... |
If there is a capital change for a given dt, this means the the change
occurs before `handle_data` on the given dt. In the case of the
change being a target value, the change will be computed on the
portfolio value according to prices at the given dt
`portfolio_value_adjustment... | calculate_capital_changes | python | quantopian/zipline | zipline/algorithm.py | https://github.com/quantopian/zipline/blob/master/zipline/algorithm.py | Apache-2.0 |
def get_environment(self, field='platform'):
"""Query the execution environment.
Parameters
----------
field : {'platform', 'arena', 'data_frequency',
'start', 'end', 'capital_base', 'platform', '*'}
The field to query. The options have the following meaning... | Query the execution environment.
Parameters
----------
field : {'platform', 'arena', 'data_frequency',
'start', 'end', 'capital_base', 'platform', '*'}
The field to query. The options have the following meanings:
arena : str
The arena... | get_environment | python | quantopian/zipline | zipline/algorithm.py | https://github.com/quantopian/zipline/blob/master/zipline/algorithm.py | Apache-2.0 |
def fetch_csv(self,
url,
pre_func=None,
post_func=None,
date_column='date',
date_format=None,
timezone=pytz.utc.zone,
symbol=None,
mask=True,
symbol_column=No... | Fetch a csv from a remote url and register the data so that it is
queryable from the ``data`` object.
Parameters
----------
url : str
The url of the csv file to load.
pre_func : callable[pd.DataFrame -> pd.DataFrame], optional
A callback to allow preproce... | fetch_csv | python | quantopian/zipline | zipline/algorithm.py | https://github.com/quantopian/zipline/blob/master/zipline/algorithm.py | Apache-2.0 |
def add_event(self, rule, callback):
"""Adds an event to the algorithm's EventManager.
Parameters
----------
rule : EventRule
The rule for when the callback should be triggered.
callback : callable[(context, data) -> None]
The function to execute when the... | Adds an event to the algorithm's EventManager.
Parameters
----------
rule : EventRule
The rule for when the callback should be triggered.
callback : callable[(context, data) -> None]
The function to execute when the rule is triggered.
| add_event | python | quantopian/zipline | zipline/algorithm.py | https://github.com/quantopian/zipline/blob/master/zipline/algorithm.py | Apache-2.0 |
def schedule_function(self,
func,
date_rule=None,
time_rule=None,
half_days=True,
calendar=None):
"""
Schedule a function to be called repeatedly in the future.
Para... |
Schedule a function to be called repeatedly in the future.
Parameters
----------
func : callable
The function to execute when the rule is triggered. ``func`` should
have the same signature as ``handle_data``.
date_rule : zipline.utils.events.EventRule, o... | schedule_function | python | quantopian/zipline | zipline/algorithm.py | https://github.com/quantopian/zipline/blob/master/zipline/algorithm.py | Apache-2.0 |
def record(self, *args, **kwargs):
"""Track and record values each day.
Parameters
----------
**kwargs
The names and values to record.
Notes
-----
These values will appear in the performance packets and the performance
dataframe passed to ``a... | Track and record values each day.
Parameters
----------
**kwargs
The names and values to record.
Notes
-----
These values will appear in the performance packets and the performance
dataframe passed to ``analyze`` and returned from
:func:`~zip... | record | python | quantopian/zipline | zipline/algorithm.py | https://github.com/quantopian/zipline/blob/master/zipline/algorithm.py | Apache-2.0 |
def set_benchmark(self, benchmark):
"""Set the benchmark asset.
Parameters
----------
benchmark : zipline.assets.Asset
The asset to set as the new benchmark.
Notes
-----
Any dividends payed out for that new benchmark asset will be
automatical... | Set the benchmark asset.
Parameters
----------
benchmark : zipline.assets.Asset
The asset to set as the new benchmark.
Notes
-----
Any dividends payed out for that new benchmark asset will be
automatically reinvested.
| set_benchmark | python | quantopian/zipline | zipline/algorithm.py | https://github.com/quantopian/zipline/blob/master/zipline/algorithm.py | Apache-2.0 |
def continuous_future(self,
root_symbol_str,
offset=0,
roll='volume',
adjustment='mul'):
"""Create a specifier for a continuous contract.
Parameters
----------
root_symbol_str : str
... | Create a specifier for a continuous contract.
Parameters
----------
root_symbol_str : str
The root symbol for the future chain.
offset : int, optional
The distance from the primary contract. Default is 0.
roll_style : str, optional
How rolls... | continuous_future | python | quantopian/zipline | zipline/algorithm.py | https://github.com/quantopian/zipline/blob/master/zipline/algorithm.py | Apache-2.0 |
def _calculate_order_value_amount(self, asset, value):
"""
Calculates how many shares/contracts to order based on the type of
asset being ordered.
"""
# Make sure the asset exists, and that there is a last price for it.
# FIXME: we should use BarData's can_trade logic her... |
Calculates how many shares/contracts to order based on the type of
asset being ordered.
| _calculate_order_value_amount | python | quantopian/zipline | zipline/algorithm.py | https://github.com/quantopian/zipline/blob/master/zipline/algorithm.py | Apache-2.0 |
def validate_order_params(self,
asset,
amount,
limit_price,
stop_price,
style):
"""
Helper method for validating parameters to the order API function.
... |
Helper method for validating parameters to the order API function.
Raises an UnsupportedOrderParameters if invalid arguments are found.
| validate_order_params | python | quantopian/zipline | zipline/algorithm.py | https://github.com/quantopian/zipline/blob/master/zipline/algorithm.py | Apache-2.0 |
def _sync_last_sale_prices(self, dt=None):
"""Sync the last sale prices on the metrics tracker to a given
datetime.
Parameters
----------
dt : datetime
The time to sync the prices to.
Notes
-----
This call is cached by the datetime. Repeated ... | Sync the last sale prices on the metrics tracker to a given
datetime.
Parameters
----------
dt : datetime
The time to sync the prices to.
Notes
-----
This call is cached by the datetime. Repeated calls in the same bar
are cheap.
| _sync_last_sale_prices | python | quantopian/zipline | zipline/algorithm.py | https://github.com/quantopian/zipline/blob/master/zipline/algorithm.py | Apache-2.0 |
def get_datetime(self, tz=None):
"""
Returns the current simulation datetime.
Parameters
----------
tz : tzinfo or str, optional
The timezone to return the datetime in. This defaults to utc.
Returns
-------
dt : datetime
The curre... |
Returns the current simulation datetime.
Parameters
----------
tz : tzinfo or str, optional
The timezone to return the datetime in. This defaults to utc.
Returns
-------
dt : datetime
The current simulation datetime converted to ``tz``.
... | get_datetime | python | quantopian/zipline | zipline/algorithm.py | https://github.com/quantopian/zipline/blob/master/zipline/algorithm.py | Apache-2.0 |
def set_slippage(self, us_equities=None, us_futures=None):
"""
Set the slippage models for the simulation.
Parameters
----------
us_equities : EquitySlippageModel
The slippage model to use for trading US equities.
us_futures : FutureSlippageModel
... |
Set the slippage models for the simulation.
Parameters
----------
us_equities : EquitySlippageModel
The slippage model to use for trading US equities.
us_futures : FutureSlippageModel
The slippage model to use for trading US futures.
Notes
... | set_slippage | python | quantopian/zipline | zipline/algorithm.py | https://github.com/quantopian/zipline/blob/master/zipline/algorithm.py | Apache-2.0 |
def set_commission(self, us_equities=None, us_futures=None):
"""Sets the commission models for the simulation.
Parameters
----------
us_equities : EquityCommissionModel
The commission model to use for trading US equities.
us_futures : FutureCommissionModel
... | Sets the commission models for the simulation.
Parameters
----------
us_equities : EquityCommissionModel
The commission model to use for trading US equities.
us_futures : FutureCommissionModel
The commission model to use for trading US futures.
Notes
... | set_commission | python | quantopian/zipline | zipline/algorithm.py | https://github.com/quantopian/zipline/blob/master/zipline/algorithm.py | Apache-2.0 |
def set_cancel_policy(self, cancel_policy):
"""Sets the order cancellation policy for the simulation.
Parameters
----------
cancel_policy : CancelPolicy
The cancellation policy to use.
See Also
--------
:class:`zipline.api.EODCancel`
:class:`... | Sets the order cancellation policy for the simulation.
Parameters
----------
cancel_policy : CancelPolicy
The cancellation policy to use.
See Also
--------
:class:`zipline.api.EODCancel`
:class:`zipline.api.NeverCancel`
| set_cancel_policy | python | quantopian/zipline | zipline/algorithm.py | https://github.com/quantopian/zipline/blob/master/zipline/algorithm.py | Apache-2.0 |
def set_symbol_lookup_date(self, dt):
"""Set the date for which symbols will be resolved to their assets
(symbols may map to different firms or underlying assets at
different times)
Parameters
----------
dt : datetime
The new symbol lookup date.
"""
... | Set the date for which symbols will be resolved to their assets
(symbols may map to different firms or underlying assets at
different times)
Parameters
----------
dt : datetime
The new symbol lookup date.
| set_symbol_lookup_date | python | quantopian/zipline | zipline/algorithm.py | https://github.com/quantopian/zipline/blob/master/zipline/algorithm.py | Apache-2.0 |
def batch_market_order(self, share_counts):
"""Place a batch market order for multiple assets.
Parameters
----------
share_counts : pd.Series[Asset -> int]
Map from asset to number of shares to order for that asset.
Returns
-------
order_ids : pd.Ind... | Place a batch market order for multiple assets.
Parameters
----------
share_counts : pd.Series[Asset -> int]
Map from asset to number of shares to order for that asset.
Returns
-------
order_ids : pd.Index[str]
Index of ids for newly-created orde... | batch_market_order | python | quantopian/zipline | zipline/algorithm.py | https://github.com/quantopian/zipline/blob/master/zipline/algorithm.py | Apache-2.0 |
def get_open_orders(self, asset=None):
"""Retrieve all of the current open orders.
Parameters
----------
asset : Asset
If passed and not None, return only the open orders for the given
asset instead of all open orders.
Returns
-------
ope... | Retrieve all of the current open orders.
Parameters
----------
asset : Asset
If passed and not None, return only the open orders for the given
asset instead of all open orders.
Returns
-------
open_orders : dict[list[Order]] or list[Order]
... | get_open_orders | python | quantopian/zipline | zipline/algorithm.py | https://github.com/quantopian/zipline/blob/master/zipline/algorithm.py | Apache-2.0 |
def cancel_order(self, order_param):
"""Cancel an open order.
Parameters
----------
order_param : str or Order
The order_id or order object to cancel.
"""
order_id = order_param
if isinstance(order_param, zipline.protocol.Order):
order_id ... | Cancel an open order.
Parameters
----------
order_param : str or Order
The order_id or order object to cancel.
| cancel_order | python | quantopian/zipline | zipline/algorithm.py | https://github.com/quantopian/zipline/blob/master/zipline/algorithm.py | Apache-2.0 |
def register_account_control(self, control):
"""
Register a new AccountControl to be checked on each bar.
"""
if self.initialized:
raise RegisterAccountControlPostInit()
self.account_controls.append(control) |
Register a new AccountControl to be checked on each bar.
| register_account_control | python | quantopian/zipline | zipline/algorithm.py | https://github.com/quantopian/zipline/blob/master/zipline/algorithm.py | Apache-2.0 |
def register_trading_control(self, control):
"""
Register a new TradingControl to be checked prior to order calls.
"""
if self.initialized:
raise RegisterTradingControlPostInit()
self.trading_controls.append(control) |
Register a new TradingControl to be checked prior to order calls.
| register_trading_control | python | quantopian/zipline | zipline/algorithm.py | https://github.com/quantopian/zipline/blob/master/zipline/algorithm.py | Apache-2.0 |
def set_do_not_order_list(self, restricted_list, on_error='fail'):
"""Set a restriction on which assets can be ordered.
Parameters
----------
restricted_list : container[Asset], SecurityList
The assets that cannot be ordered.
"""
if isinstance(restricted_list... | Set a restriction on which assets can be ordered.
Parameters
----------
restricted_list : container[Asset], SecurityList
The assets that cannot be ordered.
| set_do_not_order_list | python | quantopian/zipline | zipline/algorithm.py | https://github.com/quantopian/zipline/blob/master/zipline/algorithm.py | Apache-2.0 |
def set_asset_restrictions(self, restrictions, on_error='fail'):
"""Set a restriction on which assets can be ordered.
Parameters
----------
restricted_list : Restrictions
An object providing information about restricted assets.
See Also
--------
zipl... | Set a restriction on which assets can be ordered.
Parameters
----------
restricted_list : Restrictions
An object providing information about restricted assets.
See Also
--------
zipline.finance.asset_restrictions.Restrictions
| set_asset_restrictions | python | quantopian/zipline | zipline/algorithm.py | https://github.com/quantopian/zipline/blob/master/zipline/algorithm.py | Apache-2.0 |
def attach_pipeline(self, pipeline, name, chunks=None, eager=True):
"""Register a pipeline to be computed at the start of each day.
Parameters
----------
pipeline : Pipeline
The pipeline to have computed.
name : str
The name of the pipeline.
chunk... | Register a pipeline to be computed at the start of each day.
Parameters
----------
pipeline : Pipeline
The pipeline to have computed.
name : str
The name of the pipeline.
chunks : int or iterator, optional
The number of days to compute pipelin... | attach_pipeline | python | quantopian/zipline | zipline/algorithm.py | https://github.com/quantopian/zipline/blob/master/zipline/algorithm.py | Apache-2.0 |
def pipeline_output(self, name):
"""
Get results of the pipeline attached by with name ``name``.
Parameters
----------
name : str
Name of the pipeline from which to fetch results.
Returns
-------
results : pd.DataFrame
DataFrame c... |
Get results of the pipeline attached by with name ``name``.
Parameters
----------
name : str
Name of the pipeline from which to fetch results.
Returns
-------
results : pd.DataFrame
DataFrame containing the results of the requested pipel... | pipeline_output | python | quantopian/zipline | zipline/algorithm.py | https://github.com/quantopian/zipline/blob/master/zipline/algorithm.py | Apache-2.0 |
def run_pipeline(self, pipeline, start_session, chunksize):
"""
Compute `pipeline`, providing values for at least `start_date`.
Produces a DataFrame containing data for days between `start_date` and
`end_date`, where `end_date` is defined by:
`end_date = min(start_date + ch... |
Compute `pipeline`, providing values for at least `start_date`.
Produces a DataFrame containing data for days between `start_date` and
`end_date`, where `end_date` is defined by:
`end_date = min(start_date + chunksize trading days,
simulation_end)`
... | run_pipeline | python | quantopian/zipline | zipline/algorithm.py | https://github.com/quantopian/zipline/blob/master/zipline/algorithm.py | Apache-2.0 |
def all_api_methods(cls):
"""
Return a list of all the TradingAlgorithm API methods.
"""
return [
fn for fn in itervalues(vars(cls))
if getattr(fn, 'is_api_method', False)
] |
Return a list of all the TradingAlgorithm API methods.
| all_api_methods | python | quantopian/zipline | zipline/algorithm.py | https://github.com/quantopian/zipline/blob/master/zipline/algorithm.py | Apache-2.0 |
def create_args(args, root):
"""
Encapsulates a set of custom command line arguments in key=value
or key.namespace=value form into a chain of Namespace objects,
where each next level is an attribute of the Namespace object on the
current level
Parameters
----------
args : list
A... |
Encapsulates a set of custom command line arguments in key=value
or key.namespace=value form into a chain of Namespace objects,
where each next level is an attribute of the Namespace object on the
current level
Parameters
----------
args : list
A list of strings representing argume... | create_args | python | quantopian/zipline | zipline/extensions.py | https://github.com/quantopian/zipline/blob/master/zipline/extensions.py | Apache-2.0 |
def parse_extension_arg(arg, arg_dict):
"""
Converts argument strings in key=value or key.namespace=value form
to dictionary entries
Parameters
----------
arg : str
The argument string to parse, which must be in key=value or
key.namespace=value form.
arg_dict : dict
... |
Converts argument strings in key=value or key.namespace=value form
to dictionary entries
Parameters
----------
arg : str
The argument string to parse, which must be in key=value or
key.namespace=value form.
arg_dict : dict
The dictionary into which the key/value pair wi... | parse_extension_arg | python | quantopian/zipline | zipline/extensions.py | https://github.com/quantopian/zipline/blob/master/zipline/extensions.py | Apache-2.0 |
def update_namespace(namespace, path, name):
"""
A recursive function that takes a root element, list of namespaces,
and the value being stored, and assigns namespaces to the root object
via a chain of Namespace objects, connected through attributes
Parameters
----------
namespace : Namespa... |
A recursive function that takes a root element, list of namespaces,
and the value being stored, and assigns namespaces to the root object
via a chain of Namespace objects, connected through attributes
Parameters
----------
namespace : Namespace
The object onto which an attribute will b... | update_namespace | python | quantopian/zipline | zipline/extensions.py | https://github.com/quantopian/zipline/blob/master/zipline/extensions.py | Apache-2.0 |
def load(self, name):
"""Construct an object from a registered factory.
Parameters
----------
name : str
Name with which the factory was registered.
"""
try:
return self._factories[name]()
except KeyError:
raise ValueError(
... | Construct an object from a registered factory.
Parameters
----------
name : str
Name with which the factory was registered.
| load | python | quantopian/zipline | zipline/extensions.py | https://github.com/quantopian/zipline/blob/master/zipline/extensions.py | Apache-2.0 |
def get_registry(interface):
"""
Getter method for retrieving the registry
instance for a given extendable type
Parameters
----------
interface : type
extendable type (base class)
Returns
-------
manager : Registry
The corresponding registry
"""
try:
... |
Getter method for retrieving the registry
instance for a given extendable type
Parameters
----------
interface : type
extendable type (base class)
Returns
-------
manager : Registry
The corresponding registry
| get_registry | python | quantopian/zipline | zipline/extensions.py | https://github.com/quantopian/zipline/blob/master/zipline/extensions.py | Apache-2.0 |
def create_registry(interface):
"""
Create a new registry for an extensible interface.
Parameters
----------
interface : type
The abstract data type for which to create a registry,
which will manage registration of factories for this type.
Returns
-------
interface : ty... |
Create a new registry for an extensible interface.
Parameters
----------
interface : type
The abstract data type for which to create a registry,
which will manage registration of factories for this type.
Returns
-------
interface : type
The data type specified/deco... | create_registry | python | quantopian/zipline | zipline/extensions.py | https://github.com/quantopian/zipline/blob/master/zipline/extensions.py | Apache-2.0 |
def _deprecated_getitem_method(name, attrs):
"""Create a deprecated ``__getitem__`` method that tells users to use
getattr instead.
Parameters
----------
name : str
The name of the object in the warning message.
attrs : iterable[str]
The set of allowed attributes.
Returns
... | Create a deprecated ``__getitem__`` method that tells users to use
getattr instead.
Parameters
----------
name : str
The name of the object in the warning message.
attrs : iterable[str]
The set of allowed attributes.
Returns
-------
__getitem__ : callable[any, str]
... | _deprecated_getitem_method | python | quantopian/zipline | zipline/protocol.py | https://github.com/quantopian/zipline/blob/master/zipline/protocol.py | Apache-2.0 |
def __getitem__(self, key):
"""``__getitem__`` is deprecated, please use attribute access instead.
"""
warn(msg.format(name=name, attr=key), DeprecationWarning, stacklevel=2)
if key in attrs:
return getattr(self, key)
raise KeyError(key) | ``__getitem__`` is deprecated, please use attribute access instead.
| __getitem__ | python | quantopian/zipline | zipline/protocol.py | https://github.com/quantopian/zipline/blob/master/zipline/protocol.py | Apache-2.0 |
def current_portfolio_weights(self):
"""
Compute each asset's weight in the portfolio by calculating its held
value divided by the total value of all positions.
Each equity's value is its price times the number of shares held. Each
futures contract's value is its unit price time... |
Compute each asset's weight in the portfolio by calculating its held
value divided by the total value of all positions.
Each equity's value is its price times the number of shares held. Each
futures contract's value is its unit price times number of shares held
times the multip... | current_portfolio_weights | python | quantopian/zipline | zipline/protocol.py | https://github.com/quantopian/zipline/blob/master/zipline/protocol.py | Apache-2.0 |
def extract_option_object(option):
"""Convert a click.option call into a click.Option object.
Parameters
----------
option : decorator
A click.option decorator.
Returns
-------
option_object : click.Option
The option object that this decorator will create.
"""
@opt... | Convert a click.option call into a click.Option object.
Parameters
----------
option : decorator
A click.option decorator.
Returns
-------
option_object : click.Option
The option object that this decorator will create.
| extract_option_object | python | quantopian/zipline | zipline/__main__.py | https://github.com/quantopian/zipline/blob/master/zipline/__main__.py | Apache-2.0 |
def ipython_only(option):
"""Mark that an option should only be exposed in IPython.
Parameters
----------
option : decorator
A click.option decorator.
Returns
-------
ipython_only_dec : decorator
A decorator that correctly applies the argument even when not
using IP... | Mark that an option should only be exposed in IPython.
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.
| ipython_only | python | quantopian/zipline | zipline/__main__.py | https://github.com/quantopian/zipline/blob/master/zipline/__main__.py | Apache-2.0 |
def run(ctx,
algofile,
algotext,
define,
data_frequency,
capital_base,
bundle,
bundle_timestamp,
benchmark_file,
benchmark_symbol,
benchmark_sid,
no_benchmark,
start,
end,
output,
trading_calendar,
... | Run a backtest for the given algorithm.
| run | python | quantopian/zipline | zipline/__main__.py | https://github.com/quantopian/zipline/blob/master/zipline/__main__.py | Apache-2.0 |
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.
| ingest | python | quantopian/zipline | zipline/__main__.py | https://github.com/quantopian/zipline/blob/master/zipline/__main__.py | Apache-2.0 |
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.
| clean | python | quantopian/zipline | zipline/__main__.py | https://github.com/quantopian/zipline/blob/master/zipline/__main__.py | Apache-2.0 |
def bundles():
"""List all of the available data bundles.
"""
for bundle in sorted(bundles_module.bundles.keys()):
if bundle.startswith('.'):
# hide the test data
continue
try:
ingestions = list(
map(text_type, bundles_module.ingestions_for... | List all of the available data bundles.
| bundles | python | quantopian/zipline | zipline/__main__.py | https://github.com/quantopian/zipline/blob/master/zipline/__main__.py | Apache-2.0 |
def merge_ownership_periods(mappings):
"""
Given a dict of mappings where the values are lists of
OwnershipPeriod objects, returns a dict with the same structure with
new OwnershipPeriod objects adjusted so that the periods have no
gaps.
Orders the periods chronologically, and pushes forward th... |
Given a dict of mappings where the values are lists of
OwnershipPeriod objects, returns a dict with the same structure with
new OwnershipPeriod objects adjusted so that the periods have no
gaps.
Orders the periods chronologically, and pushes forward the end date
of each period to match the sta... | merge_ownership_periods | python | quantopian/zipline | zipline/assets/assets.py | https://github.com/quantopian/zipline/blob/master/zipline/assets/assets.py | Apache-2.0 |
def build_ownership_map(table, key_from_row, value_from_row):
"""
Builds a dict mapping to lists of OwnershipPeriods, from a db table.
"""
return _build_ownership_map_from_rows(
sa.select(table.c).execute().fetchall(),
key_from_row,
value_from_row,
) |
Builds a dict mapping to lists of OwnershipPeriods, from a db table.
| build_ownership_map | python | quantopian/zipline | zipline/assets/assets.py | https://github.com/quantopian/zipline/blob/master/zipline/assets/assets.py | Apache-2.0 |
def build_grouped_ownership_map(table,
key_from_row,
value_from_row,
group_key):
"""
Builds a dict mapping group keys to maps of keys to lists of
OwnershipPeriods, from a db table.
"""
grouped_rows = grou... |
Builds a dict mapping group keys to maps of keys to lists of
OwnershipPeriods, from a db table.
| build_grouped_ownership_map | python | quantopian/zipline | zipline/assets/assets.py | https://github.com/quantopian/zipline/blob/master/zipline/assets/assets.py | Apache-2.0 |
def _convert_asset_timestamp_fields(dict_):
"""
Takes in a dict of Asset init args and converts dates to pd.Timestamps
"""
for key in _asset_timestamp_fields & viewkeys(dict_):
value = pd.Timestamp(dict_[key], tz='UTC')
dict_[key] = None if isnull(value) else value
return dict_ |
Takes in a dict of Asset init args and converts dates to pd.Timestamps
| _convert_asset_timestamp_fields | python | quantopian/zipline | zipline/assets/assets.py | https://github.com/quantopian/zipline/blob/master/zipline/assets/assets.py | Apache-2.0 |
def lookup_asset_types(self, sids):
"""
Retrieve asset types for a list of sids.
Parameters
----------
sids : list[int]
Returns
-------
types : dict[sid -> str or None]
Asset types for the provided sids.
"""
found = {}
... |
Retrieve asset types for a list of sids.
Parameters
----------
sids : list[int]
Returns
-------
types : dict[sid -> str or None]
Asset types for the provided sids.
| lookup_asset_types | python | quantopian/zipline | zipline/assets/assets.py | https://github.com/quantopian/zipline/blob/master/zipline/assets/assets.py | Apache-2.0 |
def retrieve_asset(self, sid, default_none=False):
"""
Retrieve the Asset for a given sid.
"""
try:
asset = self._asset_cache[sid]
if asset is None and not default_none:
raise SidsNotFound(sids=[sid])
return asset
except KeyErro... |
Retrieve the Asset for a given sid.
| retrieve_asset | python | quantopian/zipline | zipline/assets/assets.py | https://github.com/quantopian/zipline/blob/master/zipline/assets/assets.py | Apache-2.0 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.