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 _color_to_rgb(self, color: str) -> tuple[float, float, float]:
"""
Parse `style.Attrs` color into RGB tuple.
"""
# Do RGB lookup for ANSI colors.
try:
from prompt_toolkit.output.vt100 import ANSI_COLORS_TO_RGB
r, g, b = ANSI_COLORS_TO_RGB[color]
... |
Parse `style.Attrs` color into RGB tuple.
| _color_to_rgb | python | prompt-toolkit/python-prompt-toolkit | src/prompt_toolkit/styles/style_transformation.py | https://github.com/prompt-toolkit/python-prompt-toolkit/blob/master/src/prompt_toolkit/styles/style_transformation.py | BSD-3-Clause |
def _interpolate_brightness(
self, value: float, min_brightness: float, max_brightness: float
) -> float:
"""
Map the brightness to the (min_brightness..max_brightness) range.
"""
return min_brightness + (max_brightness - min_brightness) * value |
Map the brightness to the (min_brightness..max_brightness) range.
| _interpolate_brightness | python | prompt-toolkit/python-prompt-toolkit | src/prompt_toolkit/styles/style_transformation.py | https://github.com/prompt-toolkit/python-prompt-toolkit/blob/master/src/prompt_toolkit/styles/style_transformation.py | BSD-3-Clause |
def get_opposite_color(colorname: str | None) -> str | None:
"""
Take a color name in either 'ansi...' format or 6 digit RGB, return the
color of opposite luminosity (same hue/saturation).
This is used for turning color schemes that work on a light background
usable on a dark background.
"""
... |
Take a color name in either 'ansi...' format or 6 digit RGB, return the
color of opposite luminosity (same hue/saturation).
This is used for turning color schemes that work on a light background
usable on a dark background.
| get_opposite_color | python | prompt-toolkit/python-prompt-toolkit | src/prompt_toolkit/styles/style_transformation.py | https://github.com/prompt-toolkit/python-prompt-toolkit/blob/master/src/prompt_toolkit/styles/style_transformation.py | BSD-3-Clause |
def mouse_handler(mouse_event: MouseEvent) -> None:
"""
Set `_selected_index` and `current_value` according to the y
position of the mouse click event.
"""
if mouse_event.event_type == MouseEventType.MOUSE_UP:
self._selected_index = mouse_event... |
Set `_selected_index` and `current_value` according to the y
position of the mouse click event.
| mouse_handler | python | prompt-toolkit/python-prompt-toolkit | src/prompt_toolkit/widgets/base.py | https://github.com/prompt-toolkit/python-prompt-toolkit/blob/master/src/prompt_toolkit/widgets/base.py | BSD-3-Clause |
def _up_in_submenu(event: E) -> None:
"Select previous (enabled) menu item or return to main menu."
# Look for previous enabled items in this sub menu.
menu = self._get_menu(len(self.selected_menu) - 2)
index = self.selected_menu[-1]
previous_indexes = [
... | Select previous (enabled) menu item or return to main menu. | _up_in_submenu | python | prompt-toolkit/python-prompt-toolkit | src/prompt_toolkit/widgets/menus.py | https://github.com/prompt-toolkit/python-prompt-toolkit/blob/master/src/prompt_toolkit/widgets/menus.py | BSD-3-Clause |
def test_generator_to_async_generator():
"""
Test conversion of sync to async generator.
This should run the synchronous parts in a background thread.
"""
async_gen = generator_to_async_generator(_sync_generator)
items = []
async def consume_async_generator():
async for item in asy... |
Test conversion of sync to async generator.
This should run the synchronous parts in a background thread.
| test_generator_to_async_generator | python | prompt-toolkit/python-prompt-toolkit | tests/test_async_generator.py | https://github.com/prompt-toolkit/python-prompt-toolkit/blob/master/tests/test_async_generator.py | BSD-3-Clause |
def _feed_cli_with_input(
text,
editing_mode=EditingMode.EMACS,
clipboard=None,
history=None,
multiline=False,
check_line_ending=True,
key_bindings=None,
):
"""
Create a Prompt, feed it with the given user input and return the CLI
object.
This returns a (result, Application)... |
Create a Prompt, feed it with the given user input and return the CLI
object.
This returns a (result, Application) tuple.
| _feed_cli_with_input | python | prompt-toolkit/python-prompt-toolkit | tests/test_cli.py | https://github.com/prompt-toolkit/python-prompt-toolkit/blob/master/tests/test_cli.py | BSD-3-Clause |
def test_emacs_cursor_movements():
"""
Test cursor movements with Emacs key bindings.
"""
# ControlA (beginning-of-line)
result, cli = _feed_cli_with_input("hello\x01X\r")
assert result.text == "Xhello"
# ControlE (end-of-line)
result, cli = _feed_cli_with_input("hello\x01X\x05Y\r")
... |
Test cursor movements with Emacs key bindings.
| test_emacs_cursor_movements | python | prompt-toolkit/python-prompt-toolkit | tests/test_cli.py | https://github.com/prompt-toolkit/python-prompt-toolkit/blob/master/tests/test_cli.py | BSD-3-Clause |
def test_emacs_arguments():
"""
Test various combinations of arguments in Emacs mode.
"""
# esc 4
result, cli = _feed_cli_with_input("\x1b4x\r")
assert result.text == "xxxx"
# esc 4 4
result, cli = _feed_cli_with_input("\x1b44x\r")
assert result.text == "x" * 44
# esc 4 esc 4
... |
Test various combinations of arguments in Emacs mode.
| test_emacs_arguments | python | prompt-toolkit/python-prompt-toolkit | tests/test_cli.py | https://github.com/prompt-toolkit/python-prompt-toolkit/blob/master/tests/test_cli.py | BSD-3-Clause |
def test_emacs_arguments_for_all_commands():
"""
Test all Emacs commands with Meta-[0-9] arguments (both positive and
negative). No one should crash.
"""
for key in ANSI_SEQUENCES:
# Ignore BracketedPaste. This would hang forever, because it waits for
# the end sequence.
if k... |
Test all Emacs commands with Meta-[0-9] arguments (both positive and
negative). No one should crash.
| test_emacs_arguments_for_all_commands | python | prompt-toolkit/python-prompt-toolkit | tests/test_cli.py | https://github.com/prompt-toolkit/python-prompt-toolkit/blob/master/tests/test_cli.py | BSD-3-Clause |
def test_emacs_nested_macro():
"Test calling the macro within a macro."
# Calling a macro within a macro should take the previous recording (if one
# exists), not the one that is in progress.
operations = (
"\x18(" # Start recording macro. C-X(
"hello"
"\x18e" # Execute macro.
... | Test calling the macro within a macro. | test_emacs_nested_macro | python | prompt-toolkit/python-prompt-toolkit | tests/test_cli.py | https://github.com/prompt-toolkit/python-prompt-toolkit/blob/master/tests/test_cli.py | BSD-3-Clause |
def test_vi_cursor_movements():
"""
Test cursor movements with Vi key bindings.
"""
feed = partial(_feed_cli_with_input, editing_mode=EditingMode.VI)
result, cli = feed("\x1b\r")
assert result.text == ""
assert cli.editing_mode == EditingMode.VI
# Esc h a X
result, cli = feed("hell... |
Test cursor movements with Vi key bindings.
| test_vi_cursor_movements | python | prompt-toolkit/python-prompt-toolkit | tests/test_cli.py | https://github.com/prompt-toolkit/python-prompt-toolkit/blob/master/tests/test_cli.py | BSD-3-Clause |
def test_vi_block_editing():
"Test Vi Control-V style block insertion."
feed = partial(_feed_cli_with_input, editing_mode=EditingMode.VI, multiline=True)
operations = (
# Six lines of text.
"-line1\r-line2\r-line3\r-line4\r-line5\r-line6"
# Go to the second character of the second l... | Test Vi Control-V style block insertion. | test_vi_block_editing | python | prompt-toolkit/python-prompt-toolkit | tests/test_cli.py | https://github.com/prompt-toolkit/python-prompt-toolkit/blob/master/tests/test_cli.py | BSD-3-Clause |
def test_vi_block_editing_empty_lines():
"Test block editing on empty lines."
feed = partial(_feed_cli_with_input, editing_mode=EditingMode.VI, multiline=True)
operations = (
# Six empty lines.
"\r\r\r\r\r"
# Go to beginning of the document.
"\x1bgg"
# Enter Visual b... | Test block editing on empty lines. | test_vi_block_editing_empty_lines | python | prompt-toolkit/python-prompt-toolkit | tests/test_cli.py | https://github.com/prompt-toolkit/python-prompt-toolkit/blob/master/tests/test_cli.py | BSD-3-Clause |
def test_vi_visual_empty_line():
"""
Test edge case with an empty line in Visual-line mode.
"""
feed = partial(_feed_cli_with_input, editing_mode=EditingMode.VI, multiline=True)
# 1. Delete first two lines.
operations = (
# Three lines of text. The middle one is empty.
"hello\r\... |
Test edge case with an empty line in Visual-line mode.
| test_vi_visual_empty_line | python | prompt-toolkit/python-prompt-toolkit | tests/test_cli.py | https://github.com/prompt-toolkit/python-prompt-toolkit/blob/master/tests/test_cli.py | BSD-3-Clause |
def test_vi_temp_navigation_mode():
"""
Test c-o binding: go for one action into navigation mode.
"""
feed = partial(_feed_cli_with_input, editing_mode=EditingMode.VI)
result, cli = feed("abcde\x0f3hx\r") # c-o # 3 times to the left.
assert result.text == "axbcde"
assert result.cursor_pos... |
Test c-o binding: go for one action into navigation mode.
| test_vi_temp_navigation_mode | python | prompt-toolkit/python-prompt-toolkit | tests/test_cli.py | https://github.com/prompt-toolkit/python-prompt-toolkit/blob/master/tests/test_cli.py | BSD-3-Clause |
def chdir(directory):
"""Context manager for current working directory temporary change."""
orig_dir = os.getcwd()
os.chdir(directory)
try:
yield
finally:
os.chdir(orig_dir) | Context manager for current working directory temporary change. | chdir | python | prompt-toolkit/python-prompt-toolkit | tests/test_completion.py | https://github.com/prompt-toolkit/python-prompt-toolkit/blob/master/tests/test_completion.py | BSD-3-Clause |
def write_test_files(test_dir, names=None):
"""Write test files in test_dir using the names list."""
names = names or range(10)
for i in names:
with open(os.path.join(test_dir, str(i)), "wb") as out:
out.write(b"") | Write test files in test_dir using the names list. | write_test_files | python | prompt-toolkit/python-prompt-toolkit | tests/test_completion.py | https://github.com/prompt-toolkit/python-prompt-toolkit/blob/master/tests/test_completion.py | BSD-3-Clause |
def test_split_lines_3():
"Edge cases: inputs ending with newlines."
# -1-
lines = list(split_lines([("class:a", "line1\nline2\n")]))
assert lines == [
[("class:a", "line1")],
[("class:a", "line2")],
[("class:a", "")],
]
# -2-
lines = list(split_lines([("class:a", "... | Edge cases: inputs ending with newlines. | test_split_lines_3 | python | prompt-toolkit/python-prompt-toolkit | tests/test_formatted_text.py | https://github.com/prompt-toolkit/python-prompt-toolkit/blob/master/tests/test_formatted_text.py | BSD-3-Clause |
def test_split_lines_4():
"Edge cases: inputs starting and ending with newlines."
# -1-
lines = list(split_lines([("class:a", "\nline1\n")]))
assert lines == [
[("class:a", "")],
[("class:a", "line1")],
[("class:a", "")],
] | Edge cases: inputs starting and ending with newlines. | test_split_lines_4 | python | prompt-toolkit/python-prompt-toolkit | tests/test_formatted_text.py | https://github.com/prompt-toolkit/python-prompt-toolkit/blob/master/tests/test_formatted_text.py | BSD-3-Clause |
def _call_history_load(history):
"""
Helper: Call the history "load" method and return the result as a list of strings.
"""
result = []
async def call_load():
async for item in history.load():
result.append(item)
run(call_load())
return result |
Helper: Call the history "load" method and return the result as a list of strings.
| _call_history_load | python | prompt-toolkit/python-prompt-toolkit | tests/test_history.py | https://github.com/prompt-toolkit/python-prompt-toolkit/blob/master/tests/test_history.py | BSD-3-Clause |
def set_dummy_app():
"""
Return a context manager that makes sure that this dummy application is
active. This is important, because we need an `Application` with
`is_done=False` flag, otherwise no keys will be processed.
"""
with create_pipe_input() as pipe_input:
app = Application(
... |
Return a context manager that makes sure that this dummy application is
active. This is important, because we need an `Application` with
`is_done=False` flag, otherwise no keys will be processed.
| set_dummy_app | python | prompt-toolkit/python-prompt-toolkit | tests/test_key_binding.py | https://github.com/prompt-toolkit/python-prompt-toolkit/blob/master/tests/test_key_binding.py | BSD-3-Clause |
def test_previous_key_sequence(processor):
"""
test whether we receive the correct previous_key_sequence.
"""
with set_dummy_app():
events = []
def handler(event):
events.append(event)
# Build registry.
registry = KeyBindings()
registry.add("a", "a")... |
test whether we receive the correct previous_key_sequence.
| test_previous_key_sequence | python | prompt-toolkit/python-prompt-toolkit | tests/test_key_binding.py | https://github.com/prompt-toolkit/python-prompt-toolkit/blob/master/tests/test_key_binding.py | BSD-3-Clause |
def getSender(self, msg):
"""
Returns the best-guess sender of an email.
Arguments:
msg -- the email whose sender is desired
Returns:
Sender of the sender.
"""
fromstr = str(msg["From"])
ls = fromstr.split(" ")
if len(ls) == 2:
... |
Returns the best-guess sender of an email.
Arguments:
msg -- the email whose sender is desired
Returns:
Sender of the sender.
| getSender | python | wzpan/wukong-robot | plugins/Email.py | https://github.com/wzpan/wukong-robot/blob/master/plugins/Email.py | MIT |
def isSelfEmail(self, msg):
"""Whether the email is sent by the user"""
fromstr = str(msg["From"])
addr = (fromstr[fromstr.find("<") + 1 : fromstr.find(">")]).strip('"')
address = config.get()[self.SLUG]["address"].strip()
return addr == address | Whether the email is sent by the user | isSelfEmail | python | wzpan/wukong-robot | plugins/Email.py | https://github.com/wzpan/wukong-robot/blob/master/plugins/Email.py | MIT |
def isNewEmail(msg):
"""Wether an email is a new email"""
date = str(msg["Date"])
dtext = date.split(",")[1].split("+")[0].strip()
dtime = time.strptime(dtext, "%d %b %Y %H:%M:%S")
current = time.localtime()
dt = datetime.datetime(*dtime[:6])
cr = datetime.datetim... | Wether an email is a new email | isNewEmail | python | wzpan/wukong-robot | plugins/Email.py | https://github.com/wzpan/wukong-robot/blob/master/plugins/Email.py | MIT |
def getMostRecentDate(self, emails):
"""
Returns the most recent date of any email in the list provided.
Arguments:
emails -- a list of emails to check
Returns:
Date of the most recent email.
"""
dates = [self.getDate(e) for e in emails]
dates.so... |
Returns the most recent date of any email in the list provided.
Arguments:
emails -- a list of emails to check
Returns:
Date of the most recent email.
| getMostRecentDate | python | wzpan/wukong-robot | plugins/Email.py | https://github.com/wzpan/wukong-robot/blob/master/plugins/Email.py | MIT |
def clear_strip(self):
"""Turns off the strip and shows the result right away."""
for led in range(self.num_led):
self.set_pixel(led, 0, 0, 0)
self.show() | Turns off the strip and shows the result right away. | clear_strip | python | wzpan/wukong-robot | robot/drivers/apa102.py | https://github.com/wzpan/wukong-robot/blob/master/robot/drivers/apa102.py | MIT |
def set_pixel(self, led_num, red, green, blue, bright_percent=100):
"""Sets the color of one pixel in the LED stripe.
The changed pixel is not shown yet on the Stripe, it is only
written to the pixel buffer. Colors are passed individually.
If brightness is not set the global brightness ... | Sets the color of one pixel in the LED stripe.
The changed pixel is not shown yet on the Stripe, it is only
written to the pixel buffer. Colors are passed individually.
If brightness is not set the global brightness setting is used.
| set_pixel | python | wzpan/wukong-robot | robot/drivers/apa102.py | https://github.com/wzpan/wukong-robot/blob/master/robot/drivers/apa102.py | MIT |
def set_pixel_rgb(self, led_num, rgb_color, bright_percent=100):
"""Sets the color of one pixel in the LED stripe.
The changed pixel is not shown yet on the Stripe, it is only
written to the pixel buffer.
Colors are passed combined (3 bytes concatenated)
If brightness is not set... | Sets the color of one pixel in the LED stripe.
The changed pixel is not shown yet on the Stripe, it is only
written to the pixel buffer.
Colors are passed combined (3 bytes concatenated)
If brightness is not set the global brightness setting is used.
| set_pixel_rgb | python | wzpan/wukong-robot | robot/drivers/apa102.py | https://github.com/wzpan/wukong-robot/blob/master/robot/drivers/apa102.py | MIT |
def rotate(self, positions=1):
"""Rotate the LEDs by the specified number of positions.
Treating the internal LED array as a circular buffer, rotate it by
the specified number of positions. The number could be negative,
which means rotating in the opposite direction.
"""
... | Rotate the LEDs by the specified number of positions.
Treating the internal LED array as a circular buffer, rotate it by
the specified number of positions. The number could be negative,
which means rotating in the opposite direction.
| rotate | python | wzpan/wukong-robot | robot/drivers/apa102.py | https://github.com/wzpan/wukong-robot/blob/master/robot/drivers/apa102.py | MIT |
def show(self):
"""Sends the content of the pixel buffer to the strip.
Todo: More than 1024 LEDs requires more than one xfer operation.
"""
self.clock_start_frame()
# xfer2 kills the list, unfortunately. So it must be copied first
# SPI takes up to 4096 Integers. So we a... | Sends the content of the pixel buffer to the strip.
Todo: More than 1024 LEDs requires more than one xfer operation.
| show | python | wzpan/wukong-robot | robot/drivers/apa102.py | https://github.com/wzpan/wukong-robot/blob/master/robot/drivers/apa102.py | MIT |
def wheel(self, wheel_pos):
"""Get a color from a color wheel; Green -> Red -> Blue -> Green"""
if wheel_pos > 255:
wheel_pos = 255 # Safeguard
if wheel_pos < 85: # Green -> Red
return self.combine_color(wheel_pos * 3, 255 - wheel_pos * 3, 0)
if wheel_pos < 170... | Get a color from a color wheel; Green -> Red -> Blue -> Green | wheel | python | wzpan/wukong-robot | robot/drivers/apa102.py | https://github.com/wzpan/wukong-robot/blob/master/robot/drivers/apa102.py | MIT |
def get_messages_since(self, cursor):
"""Returns a list of messages newer than the given cursor.
``cursor`` should be the ``uuid`` of the last message received.
"""
results = []
for msg in reversed(self.cache):
if msg["uuid"] == cursor:
break
... | Returns a list of messages newer than the given cursor.
``cursor`` should be the ``uuid`` of the last message received.
| get_messages_since | python | wzpan/wukong-robot | robot/sdk/History.py | https://github.com/wzpan/wukong-robot/blob/master/robot/sdk/History.py | MIT |
def slice_data(data: bytes, chunk_size: int):
"""
slice data
:param data: wav data
:param chunk_size: the segment size in one request
:return: segment data, last flag
"""
data_len = len(data)
offset = 0
while offset + chunk_size < data_len:
... |
slice data
:param data: wav data
:param chunk_size: the segment size in one request
:return: segment data, last flag
| slice_data | python | wzpan/wukong-robot | robot/sdk/VolcengineSpeech.py | https://github.com/wzpan/wukong-robot/blob/master/robot/sdk/VolcengineSpeech.py | MIT |
def get(self):
"""Retrieves data from the beginning of buffer and clears it"""
tmp = bytes(bytearray(self._buf))
self._buf.clear()
return tmp | Retrieves data from the beginning of buffer and clears it | get | python | wzpan/wukong-robot | snowboy/snowboydecoder.py | https://github.com/wzpan/wukong-robot/blob/master/snowboy/snowboydecoder.py | MIT |
def play_audio_file(fname=DETECT_DING):
"""Simple callback function to play a wave file. By default it plays
a Ding sound.
:param str fname: wave file name
:return: None
"""
ding_wav = wave.open(fname, "rb")
ding_data = ding_wav.readframes(ding_wav.getnframes())
with no_alsa_error():
... | Simple callback function to play a wave file. By default it plays
a Ding sound.
:param str fname: wave file name
:return: None
| play_audio_file | python | wzpan/wukong-robot | snowboy/snowboydecoder.py | https://github.com/wzpan/wukong-robot/blob/master/snowboy/snowboydecoder.py | MIT |
def saveMessage(self):
"""
Save the message stored in self.recordedData to a timestamped file.
"""
filename = os.path.join(
constants.TEMP_PATH, "output" + str(int(time.time())) + ".wav"
)
data = b"".join(self.recordedData)
# use wave to save data
... |
Save the message stored in self.recordedData to a timestamped file.
| saveMessage | python | wzpan/wukong-robot | snowboy/snowboydecoder.py | https://github.com/wzpan/wukong-robot/blob/master/snowboy/snowboydecoder.py | MIT |
def terminate(self):
"""
Terminate audio stream. Users can call start() again to detect.
:return: None
"""
if self._running:
self.stream_in.stop_stream()
self.stream_in.close()
self.audio.terminate()
self._running = False |
Terminate audio stream. Users can call start() again to detect.
:return: None
| terminate | python | wzpan/wukong-robot | snowboy/snowboydecoder.py | https://github.com/wzpan/wukong-robot/blob/master/snowboy/snowboydecoder.py | MIT |
def run(faq_file_str, json_file_str):
"""
convert text file to json file, save schema file
"""
idx = 0
header = 0
field_cnt = 0
auto_id = False
faq_file = open(faq_file_str, "r")
for line in faq_file:
arr = line.strip().split("\t")
if header == 0:
header =... |
convert text file to json file, save schema file
| run | python | wzpan/wukong-robot | tools/make_json.py | https://github.com/wzpan/wukong-robot/blob/master/tools/make_json.py | MIT |
def upload_documents(host, enginename, port=8983, documents="", num_thread=1):
"""
Fill documents
documents can be a file path(Each row is a json format document)
"""
def thread_upload(binary_data, mutex):
"""
We didn't use the producer-consumer model because of the need to implemen... |
Fill documents
documents can be a file path(Each row is a json format document)
| upload_documents | python | wzpan/wukong-robot | tools/solr_tools.py | https://github.com/wzpan/wukong-robot/blob/master/tools/solr_tools.py | MIT |
def thread_upload(binary_data, mutex):
"""
We didn't use the producer-consumer model because of the need to implement batch loads
if not, too many documents are read into memory
"""
url = "http://{}:{}/solr/{}/update".format(host, port, enginename)
try:
req = ... |
We didn't use the producer-consumer model because of the need to implement batch loads
if not, too many documents are read into memory
| thread_upload | python | wzpan/wukong-robot | tools/solr_tools.py | https://github.com/wzpan/wukong-robot/blob/master/tools/solr_tools.py | MIT |
def build_extensions(self):
"""
Lazily append numpy's include directory to Extension includes.
This is done here rather than at module scope because setup.py
may be run before numpy has been installed, in which case
importing numpy and cal... |
Lazily append numpy's include directory to Extension includes.
This is done here rather than at module scope because setup.py
may be run before numpy has been installed, in which case
importing numpy and calling `numpy.get_include()` will fail.
... | build_extensions | python | quantopian/zipline | setup.py | https://github.com/quantopian/zipline/blob/master/setup.py | Apache-2.0 |
def window_specialization(typename):
"""Make an extension for an AdjustedArrayWindow specialization."""
return Extension(
'zipline.lib._{name}window'.format(name=typename),
['zipline/lib/_{name}window.pyx'.format(name=typename)],
depends=['zipline/lib/_windowtemplate.pxi'],
) | Make an extension for an AdjustedArrayWindow specialization. | window_specialization | python | quantopian/zipline | setup.py | https://github.com/quantopian/zipline/blob/master/setup.py | Apache-2.0 |
def read_requirements(path,
conda_format=False,
filter_names=None):
"""
Read a requirements file, expressed as a path relative to Zipline root.
"""
real_path = join(dirname(abspath(__file__)), path)
with open(real_path) as f:
reqs = _filter_require... |
Read a requirements file, expressed as a path relative to Zipline root.
| read_requirements | python | quantopian/zipline | setup.py | https://github.com/quantopian/zipline/blob/master/setup.py | Apache-2.0 |
def test_invalid_capital_base(self, cap_base, name):
"""
Test that the appropriate error is being raised and orders aren't
filled for algos with capital base <= 0
"""
algo_text = """
def initialize(context):
pass
def handle_data(context, data):
order(sid(24), 1000)
... |
Test that the appropriate error is being raised and orders aren't
filled for algos with capital base <= 0
| test_invalid_capital_base | python | quantopian/zipline | tests/test_algorithm.py | https://github.com/quantopian/zipline/blob/master/tests/test_algorithm.py | Apache-2.0 |
def test_without_kwargs(self):
"""
Test that api methods on the data object can be called with positional
arguments.
"""
params = SimulationParameters(
start_session=pd.Timestamp("2006-01-10", tz='UTC'),
end_session=pd.Timestamp("2006-01-11", tz='UTC'),
... |
Test that api methods on the data object can be called with positional
arguments.
| test_without_kwargs | python | quantopian/zipline | tests/test_algorithm.py | https://github.com/quantopian/zipline/blob/master/tests/test_algorithm.py | Apache-2.0 |
def test_good_kwargs(self):
"""
Test that api methods on the data object can be called with keyword
arguments.
"""
params = SimulationParameters(
start_session=pd.Timestamp("2006-01-10", tz='UTC'),
end_session=pd.Timestamp("2006-01-11", tz='UTC'),
... |
Test that api methods on the data object can be called with keyword
arguments.
| test_good_kwargs | python | quantopian/zipline | tests/test_algorithm.py | https://github.com/quantopian/zipline/blob/master/tests/test_algorithm.py | Apache-2.0 |
def test_bad_kwargs(self, name, algo_text):
"""
Test that api methods on the data object called with bad kwargs return
a meaningful TypeError that we create, rather than an unhelpful cython
error
"""
algo = self.make_algo(script=algo_text)
with self.assertRaises(T... |
Test that api methods on the data object called with bad kwargs return
a meaningful TypeError that we create, rather than an unhelpful cython
error
| test_bad_kwargs | python | quantopian/zipline | tests/test_algorithm.py | https://github.com/quantopian/zipline/blob/master/tests/test_algorithm.py | Apache-2.0 |
def test_empty_positions(self):
"""
Test that when we try context.portfolio.positions[stock] on a stock
for which we have no positions, we return a Position with values 0
(but more importantly, we don't crash) and don't save this Position
to the user-facing dictionary PositionTra... |
Test that when we try context.portfolio.positions[stock] on a stock
for which we have no positions, we return a Position with values 0
(but more importantly, we don't crash) and don't save this Position
to the user-facing dictionary PositionTracker._positions_store
| test_empty_positions | python | quantopian/zipline | tests/test_algorithm.py | https://github.com/quantopian/zipline/blob/master/tests/test_algorithm.py | Apache-2.0 |
def test_schedule_function_time_rule_positionally_misplaced(self):
"""
Test that when a user specifies a time rule for the date_rule argument,
but no rule in the time_rule argument
(e.g. schedule_function(func, <time_rule>)), we assume that means
assign a time rule but no date ru... |
Test that when a user specifies a time rule for the date_rule argument,
but no rule in the time_rule argument
(e.g. schedule_function(func, <time_rule>)), we assume that means
assign a time rule but no date rule
| test_schedule_function_time_rule_positionally_misplaced | python | quantopian/zipline | tests/test_algorithm.py | https://github.com/quantopian/zipline/blob/master/tests/test_algorithm.py | Apache-2.0 |
def test_eod_order_cancel_minute(self, direction, minute_emission):
"""
Test that EOD order cancel works in minute mode for both shorts and
longs, and both daily emission and minute emission
"""
# order 1000 shares of asset1. the volume is only 1 share per bar,
# so the ... |
Test that EOD order cancel works in minute mode for both shorts and
longs, and both daily emission and minute emission
| test_eod_order_cancel_minute | python | quantopian/zipline | tests/test_algorithm.py | https://github.com/quantopian/zipline/blob/master/tests/test_algorithm.py | Apache-2.0 |
def default_initialize(self):
"""
Initialize function shared between test algos.
"""
def initialize(context):
context.ordered = False
context.set_commission(PerShare(0, 0))
context.set_slippage(FixedSlippage(spread=0))
context.num_positions... |
Initialize function shared between test algos.
| default_initialize | python | quantopian/zipline | tests/test_algorithm.py | https://github.com/quantopian/zipline/blob/master/tests/test_algorithm.py | Apache-2.0 |
def default_handle_data(self, assets, order_size):
"""
Handle data function shared between test algos.
"""
def handle_data(context, data):
if not context.ordered:
for asset in assets:
context.order(asset, order_size)
context... |
Handle data function shared between test algos.
| default_handle_data | python | quantopian/zipline | tests/test_algorithm.py | https://github.com/quantopian/zipline/blob/master/tests/test_algorithm.py | Apache-2.0 |
def test_daily_delisted_equities(self,
order_size,
capital_base):
"""
Make sure that after an equity gets delisted, our portfolio holds the
correct number of equities and correct amount of cash.
"""
assets ... |
Make sure that after an equity gets delisted, our portfolio holds the
correct number of equities and correct amount of cash.
| test_daily_delisted_equities | python | quantopian/zipline | tests/test_algorithm.py | https://github.com/quantopian/zipline/blob/master/tests/test_algorithm.py | Apache-2.0 |
def test_cancel_open_orders(self):
"""
Test that any open orders for an equity that gets delisted are
canceled. Unless an equity is auto closed, any open orders for that
equity will persist indefinitely.
"""
assets = self.assets
first_asset_end_date = assets[0].e... |
Test that any open orders for an equity that gets delisted are
canceled. Unless an equity is auto closed, any open orders for that
equity will persist indefinitely.
| test_cancel_open_orders | python | quantopian/zipline | tests/test_algorithm.py | https://github.com/quantopian/zipline/blob/master/tests/test_algorithm.py | Apache-2.0 |
def test_old_new_data_api_paths(self):
"""
Test that the new and old data APIs hit the same code paths.
We want to ensure that the old data API(data[sid(N)].field and
similar) and the new data API(data.current(sid(N), field) and
similar) hit the same code paths on the DataPorta... |
Test that the new and old data APIs hit the same code paths.
We want to ensure that the old data API(data[sid(N)].field and
similar) and the new data API(data.current(sid(N), field) and
similar) hit the same code paths on the DataPortal.
| test_old_new_data_api_paths | python | quantopian/zipline | tests/test_api_shim.py | https://github.com/quantopian/zipline/blob/master/tests/test_api_shim.py | Apache-2.0 |
def assert_get_spot_value_called(fun, field):
"""
Assert that get_spot_value was called during the execution of fun.
Takes in a function fun and a string field.
"""
with patch(spot_value_meth) as gsv:
fun()
gsv.assert_called_wi... |
Assert that get_spot_value was called during the execution of fun.
Takes in a function fun and a string field.
| assert_get_spot_value_called | python | quantopian/zipline | tests/test_api_shim.py | https://github.com/quantopian/zipline/blob/master/tests/test_api_shim.py | Apache-2.0 |
def assert_get_history_window_called(fun, is_legacy):
"""
Assert that get_history_window was called during fun().
Takes in a function fun and a boolean is_legacy.
"""
with patch(history_meth) as ghw:
fun()
# Slightly hacky, but... |
Assert that get_history_window was called during fun().
Takes in a function fun and a boolean is_legacy.
| assert_get_history_window_called | python | quantopian/zipline | tests/test_api_shim.py | https://github.com/quantopian/zipline/blob/master/tests/test_api_shim.py | Apache-2.0 |
def test_sid_accessor(self):
"""
Test that we maintain backwards compat for sid access on a data object.
We want to support both data[sid(24)].sid, as well as
data[sid(24)]["sid"]. Since these are deprecated and will eventually
cease to be supported, we also want to assert that ... |
Test that we maintain backwards compat for sid access on a data object.
We want to support both data[sid(24)].sid, as well as
data[sid(24)]["sid"]. Since these are deprecated and will eventually
cease to be supported, we also want to assert that we're seeing a
deprecation warni... | test_sid_accessor | python | quantopian/zipline | tests/test_api_shim.py | https://github.com/quantopian/zipline/blob/master/tests/test_api_shim.py | Apache-2.0 |
def test_data_items(self):
"""
Test that we maintain backwards compat for data.[items | iteritems].
We also want to assert that we warn that iterating over the assets
in `data` is deprecated.
"""
with warnings.catch_warnings(record=True) as w:
warnings.simple... |
Test that we maintain backwards compat for data.[items | iteritems].
We also want to assert that we warn that iterating over the assets
in `data` is deprecated.
| test_data_items | python | quantopian/zipline | tests/test_api_shim.py | https://github.com/quantopian/zipline/blob/master/tests/test_api_shim.py | Apache-2.0 |
def test_old_new_history_bts_paths(self):
"""
Tests that calling history in before_trading_start gets us the correct
values, which involves 1) calling data_portal.get_history_window as of
the previous market minute, 2) getting adjustments between the previous
market minute and th... |
Tests that calling history in before_trading_start gets us the correct
values, which involves 1) calling data_portal.get_history_window as of
the previous market minute, 2) getting adjustments between the previous
market minute and the current time, and 3) applying those adjustments
... | test_old_new_history_bts_paths | python | quantopian/zipline | tests/test_api_shim.py | https://github.com/quantopian/zipline/blob/master/tests/test_api_shim.py | Apache-2.0 |
def build_lookup_generic_cases():
"""
Generate test cases for the type of asset finder specific by
asset_finder_type for test_lookup_generic.
"""
unique_start = pd.Timestamp('2013-01-01', tz='UTC')
unique_end = pd.Timestamp('2014-01-01', tz='UTC')
dupe_old_start = pd.Timestamp('2013-01-01',... |
Generate test cases for the type of asset finder specific by
asset_finder_type for test_lookup_generic.
| build_lookup_generic_cases | python | quantopian/zipline | tests/test_assets.py | https://github.com/quantopian/zipline/blob/master/tests/test_assets.py | Apache-2.0 |
def test_lookup_generic(self):
"""
Ensure that lookup_generic works with various permutations of inputs.
"""
cases = build_lookup_generic_cases()
# Make sure we clean up temp resources in the generator if we don't
# consume the whole thing because of a failure.
se... |
Ensure that lookup_generic works with various permutations of inputs.
| test_lookup_generic | python | quantopian/zipline | tests/test_assets.py | https://github.com/quantopian/zipline/blob/master/tests/test_assets.py | Apache-2.0 |
def test_lookup_mult_are_one(self):
"""
Ensure that multiple symbols that return the same sid are collapsed to
a single returned asset.
"""
date = pd.Timestamp('2013-01-01', tz='UTC')
df = pd.DataFrame.from_records(
[
{
's... |
Ensure that multiple symbols that return the same sid are collapsed to
a single returned asset.
| test_lookup_mult_are_one | python | quantopian/zipline | tests/test_assets.py | https://github.com/quantopian/zipline/blob/master/tests/test_assets.py | Apache-2.0 |
def test_endless_multiple_resolves(self):
"""
Situation:
1. Asset 1 w/ symbol FOOB changes to FOO_B, and then is delisted.
2. Asset 2 is listed with symbol FOO_B.
If someone asks for FOO_B with fuzzy matching after 2 has been listed,
they should be able to correctly get ... |
Situation:
1. Asset 1 w/ symbol FOOB changes to FOO_B, and then is delisted.
2. Asset 2 is listed with symbol FOO_B.
If someone asks for FOO_B with fuzzy matching after 2 has been listed,
they should be able to correctly get 2.
| test_endless_multiple_resolves | python | quantopian/zipline | tests/test_assets.py | https://github.com/quantopian/zipline/blob/master/tests/test_assets.py | Apache-2.0 |
def test_can_trade_restricted(self):
"""
Test that can_trade will return False for a sid if it is restricted
on that dt
"""
minutes_to_check = [
(str_to_ts("2016-01-05 14:31"), False),
(str_to_ts("2016-01-06 14:31"), False),
(str_to_ts("2016-0... |
Test that can_trade will return False for a sid if it is restricted
on that dt
| test_can_trade_restricted | python | quantopian/zipline | tests/test_bar_data.py | https://github.com/quantopian/zipline/blob/master/tests/test_bar_data.py | Apache-2.0 |
def test_can_trade_delisted(self):
"""
Test that can_trade returns False for an asset after its auto close
date.
"""
auto_closing_asset = self.asset_finder.retrieve_asset(7)
# Our asset's auto close date is 2016-01-20, which means that as of the
# market open for... |
Test that can_trade returns False for an asset after its auto close
date.
| test_can_trade_delisted | python | quantopian/zipline | tests/test_bar_data.py | https://github.com/quantopian/zipline/blob/master/tests/test_bar_data.py | Apache-2.0 |
def test_get_value_adjustments(self,
adjustment_type,
liquid_day_0_price,
liquid_day_1_price,
illiquid_day_0_price,
illiquid_day_1_price_adjusted... | Test the behaviour of spot prices during adjustments. | test_get_value_adjustments | python | quantopian/zipline | tests/test_bar_data.py | https://github.com/quantopian/zipline/blob/master/tests/test_bar_data.py | Apache-2.0 |
def test_no_benchmark(self):
"""Test running with no benchmark provided.
We should have no benchmark sid and have a returns series of all zeros.
"""
spec = BenchmarkSpec.from_cli_params(
no_benchmark=False,
benchmark_sid=None,
benchmark_symbol=None,
... | Test running with no benchmark provided.
We should have no benchmark sid and have a returns series of all zeros.
| test_no_benchmark | python | quantopian/zipline | tests/test_benchmark.py | https://github.com/quantopian/zipline/blob/master/tests/test_benchmark.py | Apache-2.0 |
def test_no_benchmark_explicitly_disabled(self):
"""Test running with no benchmark provided, with no_benchmark flag.
"""
spec = BenchmarkSpec.from_cli_params(
no_benchmark=True,
benchmark_sid=None,
benchmark_symbol=None,
benchmark_file=None,
... | Test running with no benchmark provided, with no_benchmark flag.
| test_no_benchmark_explicitly_disabled | python | quantopian/zipline | tests/test_benchmark.py | https://github.com/quantopian/zipline/blob/master/tests/test_benchmark.py | Apache-2.0 |
def test_order_hold(self):
"""
Held orders act almost identically to open orders, except for the
status indication. When a fill happens, the order should switch
status to OPEN/FILLED as necessary
"""
blotter = SimulationBlotter(equity_slippage=VolumeShareSlippage())
... |
Held orders act almost identically to open orders, except for the
status indication. When a fill happens, the order should switch
status to OPEN/FILLED as necessary
| test_order_hold | python | quantopian/zipline | tests/test_blotter.py | https://github.com/quantopian/zipline/blob/master/tests/test_blotter.py | Apache-2.0 |
def test_batch_order_matches_multiple_orders(self):
"""
Ensure the effect of order_batch is the same as multiple calls to
order.
"""
blotter1 = SimulationBlotter()
blotter2 = SimulationBlotter()
for i in range(1, 4):
order_arg_lists = [
... |
Ensure the effect of order_batch is the same as multiple calls to
order.
| test_batch_order_matches_multiple_orders | python | quantopian/zipline | tests/test_blotter.py | https://github.com/quantopian/zipline/blob/master/tests/test_blotter.py | Apache-2.0 |
def run_and_get_benchmark_spec(benchmark_args):
"""
Run the cli, mocking out `main._run`, and return the benchmark_spec
passed to _run..
"""
args = [
'--no-default-extension',
'run',
'-s', '2014-01-02',
... |
Run the cli, mocking out `main._run`, and return the benchmark_spec
passed to _run..
| run_and_get_benchmark_spec | python | quantopian/zipline | tests/test_cmdline.py | https://github.com/quantopian/zipline/blob/master/tests/test_cmdline.py | Apache-2.0 |
def test_double_volume_switch(self):
"""
Test that when a double volume switch occurs we treat the first switch
as the roll, assuming it is within a certain distance of the next auto
close date. See `VolumeRollFinder._active_contract` for a full
explanation and example.
"... |
Test that when a double volume switch occurs we treat the first switch
as the roll, assuming it is within a certain distance of the next auto
close date. See `VolumeRollFinder._active_contract` for a full
explanation and example.
| test_double_volume_switch | python | quantopian/zipline | tests/test_continuous_futures.py | https://github.com/quantopian/zipline/blob/master/tests/test_continuous_futures.py | Apache-2.0 |
def make_future_daily_bar_data(cls):
"""
Volume data should look like this:
CLF17 CLG17 CLH17 CLJ17 CLK17 CLM17 CLN17
2017-01-03 2000 1000 5 0 0 0 0
2017-01-04 2000 1000 5 0 0 ... |
Volume data should look like this:
CLF17 CLG17 CLH17 CLJ17 CLK17 CLM17 CLN17
2017-01-03 2000 1000 5 0 0 0 0
2017-01-04 2000 1000 5 0 0 0 0
...
2017-01-16 ... | make_future_daily_bar_data | python | quantopian/zipline | tests/test_continuous_futures.py | https://github.com/quantopian/zipline/blob/master/tests/test_continuous_futures.py | Apache-2.0 |
def test_roll_in_grace_period(self):
"""
The volume roll finder can look for data up to a week before the given
date. This test asserts that we not only return the correct active
contract during that previous week (grace period), but also that we do
not go into exception if one o... |
The volume roll finder can look for data up to a week before the given
date. This test asserts that we not only return the correct active
contract during that previous week (grace period), but also that we do
not go into exception if one of the contracts does not exist.
| test_roll_in_grace_period | python | quantopian/zipline | tests/test_continuous_futures.py | https://github.com/quantopian/zipline/blob/master/tests/test_continuous_futures.py | Apache-2.0 |
def test_roll_window_ends_on_auto_close(self):
"""
Test that when skipping over a low volume contract (CLM17), we use the
correct roll date for the previous contract (CLK17) when that
contract's auto close date falls on the end date of the roll window.
"""
rolls = self.vo... |
Test that when skipping over a low volume contract (CLM17), we use the
correct roll date for the previous contract (CLK17) when that
contract's auto close date falls on the end date of the roll window.
| test_roll_window_ends_on_auto_close | python | quantopian/zipline | tests/test_continuous_futures.py | https://github.com/quantopian/zipline/blob/master/tests/test_continuous_futures.py | Apache-2.0 |
def test_invalid_prices(self, price):
"""
Test that execution styles throw appropriate exceptions upon receipt
of an invalid price field.
"""
with self.assertRaises(BadOrderParameters):
LimitOrder(price)
with self.assertRaises(BadOrderParameters):
... |
Test that execution styles throw appropriate exceptions upon receipt
of an invalid price field.
| test_invalid_prices | python | quantopian/zipline | tests/test_execution_styles.py | https://github.com/quantopian/zipline/blob/master/tests/test_execution_styles.py | Apache-2.0 |
def test_market_order_prices(self):
"""
Basic unit tests for the MarketOrder class.
"""
style = MarketOrder()
assert_equal(style.get_limit_price(_is_buy=True), None)
assert_equal(style.get_limit_price(_is_buy=False), None)
assert_equal(style.get_stop_price(_is_b... |
Basic unit tests for the MarketOrder class.
| test_market_order_prices | python | quantopian/zipline | tests/test_execution_styles.py | https://github.com/quantopian/zipline/blob/master/tests/test_execution_styles.py | Apache-2.0 |
def transaction_sim(self, **params):
"""This is a utility method that asserts expected
results for conversion of orders to transactions given a
trade history
"""
trade_count = params['trade_count']
trade_interval = params['trade_interval']
order_count = params['or... | This is a utility method that asserts expected
results for conversion of orders to transactions given a
trade history
| transaction_sim | python | quantopian/zipline | tests/test_finance.py | https://github.com/quantopian/zipline/blob/master/tests/test_finance.py | Apache-2.0 |
def reindex_to_primary_calendar(a, field):
"""
Reindex an array of prices from a window on the NYSE
calendar by the window on the primary calendar with the same
dt and window size.
"""
if mode == 'daily':
dts = cal.sessions_window(d... |
Reindex an array of prices from a window on the NYSE
calendar by the window on the primary calendar with the same
dt and window size.
| reindex_to_primary_calendar | python | quantopian/zipline | tests/test_history.py | https://github.com/quantopian/zipline/blob/master/tests/test_history.py | Apache-2.0 |
def test_negative_bar_count(self):
"""
Negative bar counts leak future information.
"""
with self.assertRaisesRegex(
ValueError,
"bar_count must be >= 1, but got -1"
):
self.data_portal.get_history_window(
[self.ASSET1],... |
Negative bar counts leak future information.
| test_negative_bar_count | python | quantopian/zipline | tests/test_history.py | https://github.com/quantopian/zipline/blob/master/tests/test_history.py | Apache-2.0 |
def test_history_window_different_order(self):
"""
Prevent regression on a bug where the passing the same assets, but
in a different order would return a history window with the values,
but not the keys, in order of the first history call.
"""
# Both ASSET1 and ASSET2 hav... |
Prevent regression on a bug where the passing the same assets, but
in a different order would return a history window with the values,
but not the keys, in order of the first history call.
| test_history_window_different_order | python | quantopian/zipline | tests/test_history.py | https://github.com/quantopian/zipline/blob/master/tests/test_history.py | Apache-2.0 |
def test_history_window_out_of_order_dates(self):
"""
Use a history window with non-monotonically increasing dates.
A scenario which does not occur during simulations, but useful
for using a history loader in a notebook.
"""
window_1 = self.data_portal.get_history_window... |
Use a history window with non-monotonically increasing dates.
A scenario which does not occur during simulations, but useful
for using a history loader in a notebook.
| test_history_window_out_of_order_dates | python | quantopian/zipline | tests/test_history.py | https://github.com/quantopian/zipline/blob/master/tests/test_history.py | Apache-2.0 |
def rotN(l, N):
"""
Rotate a list of elements.
Pulls N elements off the end of the list and appends them to the front.
>>> rotN(['a', 'b', 'c', 'd'], 2)
['c', 'd', 'a', 'b']
>>> rotN(['a', 'b', 'c', 'd'], 3)
['d', 'a', 'b', 'c']
"""
assert len(l) >= N, "Can't rotate list by longer ... |
Rotate a list of elements.
Pulls N elements off the end of the list and appends them to the front.
>>> rotN(['a', 'b', 'c', 'd'], 2)
['c', 'd', 'a', 'b']
>>> rotN(['a', 'b', 'c', 'd'], 3)
['d', 'a', 'b', 'c']
| rotN | python | quantopian/zipline | tests/test_labelarray.py | https://github.com/quantopian/zipline/blob/master/tests/test_labelarray.py | Apache-2.0 |
def test_infer_categories(self):
"""
Test that categories are inferred in sorted order if they're not
explicitly passed.
"""
arr1d = LabelArray(self.strs, missing_value='')
codes1d = arr1d.as_int_array()
self.assertEqual(arr1d.shape, self.strs.shape)
self.... |
Test that categories are inferred in sorted order if they're not
explicitly passed.
| test_infer_categories | python | quantopian/zipline | tests/test_labelarray.py | https://github.com/quantopian/zipline/blob/master/tests/test_labelarray.py | Apache-2.0 |
def test_reject_ufuncs(self):
"""
The internal values of a LabelArray should be opaque to numpy ufuncs.
Test that all unfuncs fail.
"""
labels = LabelArray(self.strs, '')
ints = np.arange(len(labels))
with warnings.catch_warnings():
# Some ufuncs ret... |
The internal values of a LabelArray should be opaque to numpy ufuncs.
Test that all unfuncs fail.
| test_reject_ufuncs | python | quantopian/zipline | tests/test_labelarray.py | https://github.com/quantopian/zipline/blob/master/tests/test_labelarray.py | Apache-2.0 |
def manual_narrow_condense_back_to_valid_size_slow(self):
"""This test is really slow so we don't want it run by default.
"""
# tests that we don't try to create an 'int24' (which is meaningless)
categories = self.create_categories(24, plus_one=False)
categories.append(categories... | This test is really slow so we don't want it run by default.
| manual_narrow_condense_back_to_valid_size_slow | python | quantopian/zipline | tests/test_labelarray.py | https://github.com/quantopian/zipline/blob/master/tests/test_labelarray.py | Apache-2.0 |
def test_historical_restrictions(self, date_offset, restriction_order):
"""
Test historical restrictions for both interday and intraday
restrictions, as well as restrictions defined in/not in order, for both
single- and multi-asset queries
"""
def rdate(s):
""... |
Test historical restrictions for both interday and intraday
restrictions, as well as restrictions defined in/not in order, for both
single- and multi-asset queries
| test_historical_restrictions | python | quantopian/zipline | tests/test_restrictions.py | https://github.com/quantopian/zipline/blob/master/tests/test_restrictions.py | Apache-2.0 |
def rdate(s):
"""Convert a date string into a restriction for that date."""
# Add date_offset to check that we handle intraday changes.
return str_to_ts(s) + date_offset | Convert a date string into a restriction for that date. | rdate | python | quantopian/zipline | tests/test_restrictions.py | https://github.com/quantopian/zipline/blob/master/tests/test_restrictions.py | Apache-2.0 |
def test_historical_restrictions_consecutive_states(self):
"""
Test that defining redundant consecutive restrictions still works
"""
rl = HistoricalRestrictions([
Restriction(self.ASSET1, str_to_ts('2011-01-04'), ALLOWED),
Restriction(self.ASSET1, str_to_ts('2011-... |
Test that defining redundant consecutive restrictions still works
| test_historical_restrictions_consecutive_states | python | quantopian/zipline | tests/test_restrictions.py | https://github.com/quantopian/zipline/blob/master/tests/test_restrictions.py | Apache-2.0 |
def test_static_restrictions(self):
"""
Test single- and multi-asset queries on static restrictions
"""
restricted_a1 = self.ASSET1
restricted_a2 = self.ASSET2
unrestricted_a3 = self.ASSET3
rl = StaticRestrictions([restricted_a1, restricted_a2])
assert_n... |
Test single- and multi-asset queries on static restrictions
| test_static_restrictions | python | quantopian/zipline | tests/test_restrictions.py | https://github.com/quantopian/zipline/blob/master/tests/test_restrictions.py | Apache-2.0 |
def test_security_list_restrictions(self):
"""
Test single- and multi-asset queries on restrictions defined by
zipline.utils.security_list.SecurityList
"""
# A mock SecurityList object filled with fake data
class SecurityList(object):
def __init__(self, asset... |
Test single- and multi-asset queries on restrictions defined by
zipline.utils.security_list.SecurityList
| test_security_list_restrictions | python | quantopian/zipline | tests/test_restrictions.py | https://github.com/quantopian/zipline/blob/master/tests/test_restrictions.py | Apache-2.0 |
def test_noop_restrictions(self):
"""
Test single- and multi-asset queries on no-op restrictions
"""
rl = NoRestrictions()
assert_not_restricted = partial(self.assert_not_restricted, rl)
assert_all_restrictions = partial(self.assert_all_restrictions, rl)
for dt ... |
Test single- and multi-asset queries on no-op restrictions
| test_noop_restrictions | python | quantopian/zipline | tests/test_restrictions.py | https://github.com/quantopian/zipline/blob/master/tests/test_restrictions.py | Apache-2.0 |
def test_union_restrictions(self):
"""
Test that we appropriately union restrictions together, including
eliminating redundancy (ignoring NoRestrictions) and flattening out
the underlying sub-restrictions of _UnionRestrictions
"""
no_restrictions_rl = NoRestrictions()
... |
Test that we appropriately union restrictions together, including
eliminating redundancy (ignoring NoRestrictions) and flattening out
the underlying sub-restrictions of _UnionRestrictions
| test_union_restrictions | python | quantopian/zipline | tests/test_restrictions.py | https://github.com/quantopian/zipline/blob/master/tests/test_restrictions.py | Apache-2.0 |
def test_algo_with_rl_violation_cumulative(self):
"""
Add a new restriction, run a test long after both
knowledge dates, make sure stock from original restriction
set is still disallowed.
"""
sim_params = factory.create_simulation_parameters(
start=self.START_... |
Add a new restriction, run a test long after both
knowledge dates, make sure stock from original restriction
set is still disallowed.
| test_algo_with_rl_violation_cumulative | python | quantopian/zipline | tests/test_security_list.py | https://github.com/quantopian/zipline/blob/master/tests/test_security_list.py | Apache-2.0 |
def test_empty_frame_dtypes(self, convert_dates):
"""Test that dataframe dtypes are preserved for empty tables.
"""
sids = np.arange(5)
dates = self.trading_calendar.all_sessions.tz_convert(None)
if convert_dates:
date_dtype = np.dtype('M8[ns]')
else:
... | Test that dataframe dtypes are preserved for empty tables.
| test_empty_frame_dtypes | python | quantopian/zipline | tests/data/test_adjustments.py | https://github.com/quantopian/zipline/blob/master/tests/data/test_adjustments.py | Apache-2.0 |
def test_start_on_asset_start(self):
"""
Test loading with queries that starts on the first day of each asset's
lifetime.
"""
columns = ['high', 'volume']
for asset in self.assets:
self._check_read_results(
columns,
self.assets,... |
Test loading with queries that starts on the first day of each asset's
lifetime.
| test_start_on_asset_start | python | quantopian/zipline | tests/data/test_daily_bars.py | https://github.com/quantopian/zipline/blob/master/tests/data/test_daily_bars.py | Apache-2.0 |
def test_start_on_asset_end(self):
"""
Test loading with queries that start on the last day of each asset's
lifetime.
"""
columns = ['close', 'volume']
for asset in self.assets:
self._check_read_results(
columns,
self.assets,
... |
Test loading with queries that start on the last day of each asset's
lifetime.
| test_start_on_asset_end | python | quantopian/zipline | tests/data/test_daily_bars.py | https://github.com/quantopian/zipline/blob/master/tests/data/test_daily_bars.py | Apache-2.0 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.