partition
stringclasses
3 values
func_name
stringlengths
1
134
docstring
stringlengths
1
46.9k
path
stringlengths
4
223
original_string
stringlengths
75
104k
code
stringlengths
75
104k
docstring_tokens
listlengths
1
1.97k
repo
stringlengths
7
55
language
stringclasses
1 value
url
stringlengths
87
315
code_tokens
listlengths
19
28.4k
sha
stringlengths
40
40
train
tcp_ping
Tests connection to a tcp port and tries to establish a three way handshake. To be used for network discovery or testing. Arguments: ports (list of int): tcp ports to ping timeout (int, optional): defaults to 2 host (string, optional): defaults to ``hostname`` Returns: Res...
nornir/plugins/tasks/networking/tcp_ping.py
def tcp_ping( task: Task, ports: List[int], timeout: int = 2, host: Optional[str] = None ) -> Result: """ Tests connection to a tcp port and tries to establish a three way handshake. To be used for network discovery or testing. Arguments: ports (list of int): tcp ports to ping timeo...
def tcp_ping( task: Task, ports: List[int], timeout: int = 2, host: Optional[str] = None ) -> Result: """ Tests connection to a tcp port and tries to establish a three way handshake. To be used for network discovery or testing. Arguments: ports (list of int): tcp ports to ping timeo...
[ "Tests", "connection", "to", "a", "tcp", "port", "and", "tries", "to", "establish", "a", "three", "way", "handshake", ".", "To", "be", "used", "for", "network", "discovery", "or", "testing", "." ]
nornir-automation/nornir
python
https://github.com/nornir-automation/nornir/blob/3425c47fd870db896cb80f619bae23bd98d50c74/nornir/plugins/tasks/networking/tcp_ping.py#L7-L53
[ "def", "tcp_ping", "(", "task", ":", "Task", ",", "ports", ":", "List", "[", "int", "]", ",", "timeout", ":", "int", "=", "2", ",", "host", ":", "Optional", "[", "str", "]", "=", "None", ")", "->", "Result", ":", "if", "isinstance", "(", "ports",...
3425c47fd870db896cb80f619bae23bd98d50c74
train
napalm_get
Gather information from network devices using napalm Arguments: getters: getters to use getters_options (dict of dicts): When passing multiple getters you pass a dictionary where the outer key is the getter name and the included dictionary represents the options to pass ...
nornir/plugins/tasks/networking/napalm_get.py
def napalm_get( task: Task, getters: List[str], getters_options: GetterOptionsDict = None, **kwargs: Any ) -> Result: """ Gather information from network devices using napalm Arguments: getters: getters to use getters_options (dict of dicts): When passing multiple getters yo...
def napalm_get( task: Task, getters: List[str], getters_options: GetterOptionsDict = None, **kwargs: Any ) -> Result: """ Gather information from network devices using napalm Arguments: getters: getters to use getters_options (dict of dicts): When passing multiple getters yo...
[ "Gather", "information", "from", "network", "devices", "using", "napalm" ]
nornir-automation/nornir
python
https://github.com/nornir-automation/nornir/blob/3425c47fd870db896cb80f619bae23bd98d50c74/nornir/plugins/tasks/networking/napalm_get.py#L9-L62
[ "def", "napalm_get", "(", "task", ":", "Task", ",", "getters", ":", "List", "[", "str", "]", ",", "getters_options", ":", "GetterOptionsDict", "=", "None", ",", "*", "*", "kwargs", ":", "Any", ")", "->", "Result", ":", "device", "=", "task", ".", "ho...
3425c47fd870db896cb80f619bae23bd98d50c74
train
remote_command
Executes a command remotely on the host Arguments: command (``str``): command to execute Returns: Result object with the following attributes set: * result (``str``): stderr or stdout * stdout (``str``): stdout * stderr (``str``): stderr Raises: :obj:...
nornir/plugins/tasks/commands/remote_command.py
def remote_command(task: Task, command: str) -> Result: """ Executes a command remotely on the host Arguments: command (``str``): command to execute Returns: Result object with the following attributes set: * result (``str``): stderr or stdout * stdout (``str``): st...
def remote_command(task: Task, command: str) -> Result: """ Executes a command remotely on the host Arguments: command (``str``): command to execute Returns: Result object with the following attributes set: * result (``str``): stderr or stdout * stdout (``str``): st...
[ "Executes", "a", "command", "remotely", "on", "the", "host" ]
nornir-automation/nornir
python
https://github.com/nornir-automation/nornir/blob/3425c47fd870db896cb80f619bae23bd98d50c74/nornir/plugins/tasks/commands/remote_command.py#L7-L44
[ "def", "remote_command", "(", "task", ":", "Task", ",", "command", ":", "str", ")", "->", "Result", ":", "client", "=", "task", ".", "host", ".", "get_connection", "(", "\"paramiko\"", ",", "task", ".", "nornir", ".", "config", ")", "connection_state", "...
3425c47fd870db896cb80f619bae23bd98d50c74
train
ConnectionPlugin.open
Connect to the device and populate the attribute :attr:`connection` with the underlying connection
nornir/core/connections.py
def open( self, hostname: Optional[str], username: Optional[str], password: Optional[str], port: Optional[int], platform: Optional[str], extras: Optional[Dict[str, Any]] = None, configuration: Optional[Config] = None, ) -> None: """ Con...
def open( self, hostname: Optional[str], username: Optional[str], password: Optional[str], port: Optional[int], platform: Optional[str], extras: Optional[Dict[str, Any]] = None, configuration: Optional[Config] = None, ) -> None: """ Con...
[ "Connect", "to", "the", "device", "and", "populate", "the", "attribute", ":", "attr", ":", "connection", "with", "the", "underlying", "connection" ]
nornir-automation/nornir
python
https://github.com/nornir-automation/nornir/blob/3425c47fd870db896cb80f619bae23bd98d50c74/nornir/core/connections.py#L30-L44
[ "def", "open", "(", "self", ",", "hostname", ":", "Optional", "[", "str", "]", ",", "username", ":", "Optional", "[", "str", "]", ",", "password", ":", "Optional", "[", "str", "]", ",", "port", ":", "Optional", "[", "int", "]", ",", "platform", ":"...
3425c47fd870db896cb80f619bae23bd98d50c74
train
Connections.register
Registers a connection plugin with a specified name Args: name: name of the connection plugin to register plugin: defined connection plugin class Raises: :obj:`nornir.core.exceptions.ConnectionPluginAlreadyRegistered` if another plugin with the speci...
nornir/core/connections.py
def register(cls, name: str, plugin: Type[ConnectionPlugin]) -> None: """Registers a connection plugin with a specified name Args: name: name of the connection plugin to register plugin: defined connection plugin class Raises: :obj:`nornir.core.exceptions.Co...
def register(cls, name: str, plugin: Type[ConnectionPlugin]) -> None: """Registers a connection plugin with a specified name Args: name: name of the connection plugin to register plugin: defined connection plugin class Raises: :obj:`nornir.core.exceptions.Co...
[ "Registers", "a", "connection", "plugin", "with", "a", "specified", "name" ]
nornir-automation/nornir
python
https://github.com/nornir-automation/nornir/blob/3425c47fd870db896cb80f619bae23bd98d50c74/nornir/core/connections.py#L63-L82
[ "def", "register", "(", "cls", ",", "name", ":", "str", ",", "plugin", ":", "Type", "[", "ConnectionPlugin", "]", ")", "->", "None", ":", "existing_plugin", "=", "cls", ".", "available", ".", "get", "(", "name", ")", "if", "existing_plugin", "is", "Non...
3425c47fd870db896cb80f619bae23bd98d50c74
train
Connections.deregister
Deregisters a registered connection plugin by its name Args: name: name of the connection plugin to deregister Raises: :obj:`nornir.core.exceptions.ConnectionPluginNotRegistered`
nornir/core/connections.py
def deregister(cls, name: str) -> None: """Deregisters a registered connection plugin by its name Args: name: name of the connection plugin to deregister Raises: :obj:`nornir.core.exceptions.ConnectionPluginNotRegistered` """ if name not in cls.available...
def deregister(cls, name: str) -> None: """Deregisters a registered connection plugin by its name Args: name: name of the connection plugin to deregister Raises: :obj:`nornir.core.exceptions.ConnectionPluginNotRegistered` """ if name not in cls.available...
[ "Deregisters", "a", "registered", "connection", "plugin", "by", "its", "name" ]
nornir-automation/nornir
python
https://github.com/nornir-automation/nornir/blob/3425c47fd870db896cb80f619bae23bd98d50c74/nornir/core/connections.py#L85-L98
[ "def", "deregister", "(", "cls", ",", "name", ":", "str", ")", "->", "None", ":", "if", "name", "not", "in", "cls", ".", "available", ":", "raise", "ConnectionPluginNotRegistered", "(", "f\"Connection {name!r} is not registered\"", ")", "cls", ".", "available", ...
3425c47fd870db896cb80f619bae23bd98d50c74
train
Connections.get_plugin
Fetches the connection plugin by name if already registered Args: name: name of the connection plugin Raises: :obj:`nornir.core.exceptions.ConnectionPluginNotRegistered`
nornir/core/connections.py
def get_plugin(cls, name: str) -> Type[ConnectionPlugin]: """Fetches the connection plugin by name if already registered Args: name: name of the connection plugin Raises: :obj:`nornir.core.exceptions.ConnectionPluginNotRegistered` """ if name not in cls....
def get_plugin(cls, name: str) -> Type[ConnectionPlugin]: """Fetches the connection plugin by name if already registered Args: name: name of the connection plugin Raises: :obj:`nornir.core.exceptions.ConnectionPluginNotRegistered` """ if name not in cls....
[ "Fetches", "the", "connection", "plugin", "by", "name", "if", "already", "registered" ]
nornir-automation/nornir
python
https://github.com/nornir-automation/nornir/blob/3425c47fd870db896cb80f619bae23bd98d50c74/nornir/core/connections.py#L106-L119
[ "def", "get_plugin", "(", "cls", ",", "name", ":", "str", ")", "->", "Type", "[", "ConnectionPlugin", "]", ":", "if", "name", "not", "in", "cls", ".", "available", ":", "raise", "ConnectionPluginNotRegistered", "(", "f\"Connection {name!r} is not registered\"", ...
3425c47fd870db896cb80f619bae23bd98d50c74
train
InitNornir
Arguments: config_file(str): Path to the configuration file (optional) dry_run(bool): Whether to simulate changes or not configure_logging: Whether to configure logging or not. This argument is being deprecated. Please use logging.enabled parameter in the configuration in...
nornir/init_nornir.py
def InitNornir( config_file: str = "", dry_run: bool = False, configure_logging: Optional[bool] = None, **kwargs: Dict[str, Any], ) -> Nornir: """ Arguments: config_file(str): Path to the configuration file (optional) dry_run(bool): Whether to simulate changes or not conf...
def InitNornir( config_file: str = "", dry_run: bool = False, configure_logging: Optional[bool] = None, **kwargs: Dict[str, Any], ) -> Nornir: """ Arguments: config_file(str): Path to the configuration file (optional) dry_run(bool): Whether to simulate changes or not conf...
[ "Arguments", ":", "config_file", "(", "str", ")", ":", "Path", "to", "the", "configuration", "file", "(", "optional", ")", "dry_run", "(", "bool", ")", ":", "Whether", "to", "simulate", "changes", "or", "not", "configure_logging", ":", "Whether", "to", "co...
nornir-automation/nornir
python
https://github.com/nornir-automation/nornir/blob/3425c47fd870db896cb80f619bae23bd98d50c74/nornir/init_nornir.py#L23-L79
[ "def", "InitNornir", "(", "config_file", ":", "str", "=", "\"\"", ",", "dry_run", ":", "bool", "=", "False", ",", "configure_logging", ":", "Optional", "[", "bool", "]", "=", "None", ",", "*", "*", "kwargs", ":", "Dict", "[", "str", ",", "Any", "]", ...
3425c47fd870db896cb80f619bae23bd98d50c74
train
write_file
Write contents to a file (locally) Arguments: dry_run: Whether to apply changes or not filename: file you want to write into content: content you want to write append: whether you want to replace the contents or append to it Returns: Result object with the following att...
nornir/plugins/tasks/files/write_file.py
def write_file( task: Task, filename: str, content: str, append: bool = False, dry_run: Optional[bool] = None, ) -> Result: """ Write contents to a file (locally) Arguments: dry_run: Whether to apply changes or not filename: file you want to write into content: c...
def write_file( task: Task, filename: str, content: str, append: bool = False, dry_run: Optional[bool] = None, ) -> Result: """ Write contents to a file (locally) Arguments: dry_run: Whether to apply changes or not filename: file you want to write into content: c...
[ "Write", "contents", "to", "a", "file", "(", "locally", ")" ]
nornir-automation/nornir
python
https://github.com/nornir-automation/nornir/blob/3425c47fd870db896cb80f619bae23bd98d50c74/nornir/plugins/tasks/files/write_file.py#L30-L58
[ "def", "write_file", "(", "task", ":", "Task", ",", "filename", ":", "str", ",", "content", ":", "str", ",", "append", ":", "bool", "=", "False", ",", "dry_run", ":", "Optional", "[", "bool", "]", "=", "None", ",", ")", "->", "Result", ":", "diff",...
3425c47fd870db896cb80f619bae23bd98d50c74
train
Reports.load_cli_args
Parse command line arguments and return only the non-default ones :Retruns: dict a dict of any non-default args passed on the command-line.
qtpylib/reports.py
def load_cli_args(self): """ Parse command line arguments and return only the non-default ones :Retruns: dict a dict of any non-default args passed on the command-line. """ parser = argparse.ArgumentParser(description='QTPyLib Reporting', ...
def load_cli_args(self): """ Parse command line arguments and return only the non-default ones :Retruns: dict a dict of any non-default args passed on the command-line. """ parser = argparse.ArgumentParser(description='QTPyLib Reporting', ...
[ "Parse", "command", "line", "arguments", "and", "return", "only", "the", "non", "-", "default", "ones" ]
ranaroussi/qtpylib
python
https://github.com/ranaroussi/qtpylib/blob/0dbbc465fafd9cb9b0f4d10e1e07fae4e15032dd/qtpylib/reports.py#L135-L160
[ "def", "load_cli_args", "(", "self", ")", ":", "parser", "=", "argparse", ".", "ArgumentParser", "(", "description", "=", "'QTPyLib Reporting'", ",", "formatter_class", "=", "argparse", ".", "ArgumentDefaultsHelpFormatter", ")", "parser", ".", "add_argument", "(", ...
0dbbc465fafd9cb9b0f4d10e1e07fae4e15032dd
train
Reports.run
Starts the reporting module Makes the dashboard web app available via localhost:port, and exposes a REST API for trade information, open positions and market data.
qtpylib/reports.py
def run(self): """Starts the reporting module Makes the dashboard web app available via localhost:port, and exposes a REST API for trade information, open positions and market data. """ # ----------------------------------- # assign view app.add_url_rule('/', 'i...
def run(self): """Starts the reporting module Makes the dashboard web app available via localhost:port, and exposes a REST API for trade information, open positions and market data. """ # ----------------------------------- # assign view app.add_url_rule('/', 'i...
[ "Starts", "the", "reporting", "module" ]
ranaroussi/qtpylib
python
https://github.com/ranaroussi/qtpylib/blob/0dbbc465fafd9cb9b0f4d10e1e07fae4e15032dd/qtpylib/reports.py#L314-L370
[ "def", "run", "(", "self", ")", ":", "# -----------------------------------", "# assign view", "app", ".", "add_url_rule", "(", "'/'", ",", "'index'", ",", "view_func", "=", "self", ".", "index", ")", "app", ".", "add_url_rule", "(", "'/<path:start>'", ",", "'...
0dbbc465fafd9cb9b0f4d10e1e07fae4e15032dd
train
Broker.add_instruments
add instruments after initialization
qtpylib/broker.py
def add_instruments(self, *instruments): """ add instruments after initialization """ for instrument in instruments: if isinstance(instrument, ezibpy.utils.Contract): instrument = self.ibConn.contract_to_tuple(instrument) contractString = self.ibConn.contractS...
def add_instruments(self, *instruments): """ add instruments after initialization """ for instrument in instruments: if isinstance(instrument, ezibpy.utils.Contract): instrument = self.ibConn.contract_to_tuple(instrument) contractString = self.ibConn.contractS...
[ "add", "instruments", "after", "initialization" ]
ranaroussi/qtpylib
python
https://github.com/ranaroussi/qtpylib/blob/0dbbc465fafd9cb9b0f4d10e1e07fae4e15032dd/qtpylib/broker.py#L196-L205
[ "def", "add_instruments", "(", "self", ",", "*", "instruments", ")", ":", "for", "instrument", "in", "instruments", ":", "if", "isinstance", "(", "instrument", ",", "ezibpy", ".", "utils", ".", "Contract", ")", ":", "instrument", "=", "self", ".", "ibConn"...
0dbbc465fafd9cb9b0f4d10e1e07fae4e15032dd
train
Broker.register_combo
add contracts to groups
qtpylib/broker.py
def register_combo(self, parent, legs): """ add contracts to groups """ parent = self.ibConn.contractString(parent) legs_dict = {} for leg in legs: leg = self.ibConn.contractString(leg) legs_dict[leg] = self.get_instrument(leg) self.instrument_combos[paren...
def register_combo(self, parent, legs): """ add contracts to groups """ parent = self.ibConn.contractString(parent) legs_dict = {} for leg in legs: leg = self.ibConn.contractString(leg) legs_dict[leg] = self.get_instrument(leg) self.instrument_combos[paren...
[ "add", "contracts", "to", "groups" ]
ranaroussi/qtpylib
python
https://github.com/ranaroussi/qtpylib/blob/0dbbc465fafd9cb9b0f4d10e1e07fae4e15032dd/qtpylib/broker.py#L219-L226
[ "def", "register_combo", "(", "self", ",", "parent", ",", "legs", ")", ":", "parent", "=", "self", ".", "ibConn", ".", "contractString", "(", "parent", ")", "legs_dict", "=", "{", "}", "for", "leg", "in", "legs", ":", "leg", "=", "self", ".", "ibConn...
0dbbc465fafd9cb9b0f4d10e1e07fae4e15032dd
train
Broker.get_combo
get group by child symbol
qtpylib/broker.py
def get_combo(self, symbol): """ get group by child symbol """ for parent, legs in self.instrument_combos.items(): if symbol == parent or symbol in legs.keys(): return { "parent": self.get_instrument(parent), "legs": legs, ...
def get_combo(self, symbol): """ get group by child symbol """ for parent, legs in self.instrument_combos.items(): if symbol == parent or symbol in legs.keys(): return { "parent": self.get_instrument(parent), "legs": legs, ...
[ "get", "group", "by", "child", "symbol" ]
ranaroussi/qtpylib
python
https://github.com/ranaroussi/qtpylib/blob/0dbbc465fafd9cb9b0f4d10e1e07fae4e15032dd/qtpylib/broker.py#L228-L239
[ "def", "get_combo", "(", "self", ",", "symbol", ")", ":", "for", "parent", ",", "legs", "in", "self", ".", "instrument_combos", ".", "items", "(", ")", ":", "if", "symbol", "==", "parent", "or", "symbol", "in", "legs", ".", "keys", "(", ")", ":", "...
0dbbc465fafd9cb9b0f4d10e1e07fae4e15032dd
train
Broker._register_trade
constructs trade info from order data
qtpylib/broker.py
def _register_trade(self, order): """ constructs trade info from order data """ if order['id'] in self.orders.recent: orderId = order['id'] else: orderId = order['parentId'] # entry / exit? symbol = order["symbol"] order_data = self.orders.recent[o...
def _register_trade(self, order): """ constructs trade info from order data """ if order['id'] in self.orders.recent: orderId = order['id'] else: orderId = order['parentId'] # entry / exit? symbol = order["symbol"] order_data = self.orders.recent[o...
[ "constructs", "trade", "info", "from", "order", "data" ]
ranaroussi/qtpylib
python
https://github.com/ranaroussi/qtpylib/blob/0dbbc465fafd9cb9b0f4d10e1e07fae4e15032dd/qtpylib/broker.py#L344-L472
[ "def", "_register_trade", "(", "self", ",", "order", ")", ":", "if", "order", "[", "'id'", "]", "in", "self", ".", "orders", ".", "recent", ":", "orderId", "=", "order", "[", "'id'", "]", "else", ":", "orderId", "=", "order", "[", "'parentId'", "]", ...
0dbbc465fafd9cb9b0f4d10e1e07fae4e15032dd
train
Broker._cancel_orphan_orders
cancel child orders when parent is gone
qtpylib/broker.py
def _cancel_orphan_orders(self, orderId): """ cancel child orders when parent is gone """ orders = self.ibConn.orders for order in orders: order = orders[order] if order['parentId'] != orderId: self.ibConn.cancelOrder(order['id'])
def _cancel_orphan_orders(self, orderId): """ cancel child orders when parent is gone """ orders = self.ibConn.orders for order in orders: order = orders[order] if order['parentId'] != orderId: self.ibConn.cancelOrder(order['id'])
[ "cancel", "child", "orders", "when", "parent", "is", "gone" ]
ranaroussi/qtpylib
python
https://github.com/ranaroussi/qtpylib/blob/0dbbc465fafd9cb9b0f4d10e1e07fae4e15032dd/qtpylib/broker.py#L769-L775
[ "def", "_cancel_orphan_orders", "(", "self", ",", "orderId", ")", ":", "orders", "=", "self", ".", "ibConn", ".", "orders", "for", "order", "in", "orders", ":", "order", "=", "orders", "[", "order", "]", "if", "order", "[", "'parentId'", "]", "!=", "or...
0dbbc465fafd9cb9b0f4d10e1e07fae4e15032dd
train
Broker._cancel_expired_pending_orders
expires pending orders
qtpylib/broker.py
def _cancel_expired_pending_orders(self): """ expires pending orders """ # use a copy to prevent errors pending = self.orders.pending.copy() for symbol in pending: orderId = pending[symbol]["orderId"] expiration = pending[symbol]["expires"] delta = ex...
def _cancel_expired_pending_orders(self): """ expires pending orders """ # use a copy to prevent errors pending = self.orders.pending.copy() for symbol in pending: orderId = pending[symbol]["orderId"] expiration = pending[symbol]["expires"] delta = ex...
[ "expires", "pending", "orders" ]
ranaroussi/qtpylib
python
https://github.com/ranaroussi/qtpylib/blob/0dbbc465fafd9cb9b0f4d10e1e07fae4e15032dd/qtpylib/broker.py#L778-L797
[ "def", "_cancel_expired_pending_orders", "(", "self", ")", ":", "# use a copy to prevent errors", "pending", "=", "self", ".", "orders", ".", "pending", ".", "copy", "(", ")", "for", "symbol", "in", "pending", ":", "orderId", "=", "pending", "[", "symbol", "]"...
0dbbc465fafd9cb9b0f4d10e1e07fae4e15032dd
train
Broker.get_instrument
A string subclass that provides easy access to misc symbol-related methods and information using shorthand. Refer to the `Instruments API <#instrument-api>`_ for available methods and properties Call from within your strategy: ``instrument = self.get_instrument("SYMBOL")`` ...
qtpylib/broker.py
def get_instrument(self, symbol): """ A string subclass that provides easy access to misc symbol-related methods and information using shorthand. Refer to the `Instruments API <#instrument-api>`_ for available methods and properties Call from within your strategy: ...
def get_instrument(self, symbol): """ A string subclass that provides easy access to misc symbol-related methods and information using shorthand. Refer to the `Instruments API <#instrument-api>`_ for available methods and properties Call from within your strategy: ...
[ "A", "string", "subclass", "that", "provides", "easy", "access", "to", "misc", "symbol", "-", "related", "methods", "and", "information", "using", "shorthand", ".", "Refer", "to", "the", "Instruments", "API", "<#instrument", "-", "api", ">", "_", "for", "ava...
ranaroussi/qtpylib
python
https://github.com/ranaroussi/qtpylib/blob/0dbbc465fafd9cb9b0f4d10e1e07fae4e15032dd/qtpylib/broker.py#L841-L860
[ "def", "get_instrument", "(", "self", ",", "symbol", ")", ":", "instrument", "=", "Instrument", "(", "self", ".", "get_symbol", "(", "symbol", ")", ")", "instrument", ".", "_set_parent", "(", "self", ")", "instrument", ".", "_set_windows", "(", "ticks", "=...
0dbbc465fafd9cb9b0f4d10e1e07fae4e15032dd
train
RecurringTask.run
Start the recurring task.
qtpylib/asynctools.py
def run(self): """Start the recurring task.""" if self.init_sec: sleep(self.init_sec) self._functime = time() while self._running: start = time() self._func() self._functime += self.interval_sec if self._functime - start > 0: ...
def run(self): """Start the recurring task.""" if self.init_sec: sleep(self.init_sec) self._functime = time() while self._running: start = time() self._func() self._functime += self.interval_sec if self._functime - start > 0: ...
[ "Start", "the", "recurring", "task", "." ]
ranaroussi/qtpylib
python
https://github.com/ranaroussi/qtpylib/blob/0dbbc465fafd9cb9b0f4d10e1e07fae4e15032dd/qtpylib/asynctools.py#L179-L189
[ "def", "run", "(", "self", ")", ":", "if", "self", ".", "init_sec", ":", "sleep", "(", "self", ".", "init_sec", ")", "self", ".", "_functime", "=", "time", "(", ")", "while", "self", ".", "_running", ":", "start", "=", "time", "(", ")", "self", "...
0dbbc465fafd9cb9b0f4d10e1e07fae4e15032dd
train
load_blotter_args
Load running blotter's settings (used by clients) :Parameters: blotter_name : str Running Blotter's name (defaults to "auto-detect") logger : object Logger to be use (defaults to Blotter's) :Returns: args : dict Running Blotter's arguments
qtpylib/blotter.py
def load_blotter_args(blotter_name=None, logger=None): """ Load running blotter's settings (used by clients) :Parameters: blotter_name : str Running Blotter's name (defaults to "auto-detect") logger : object Logger to be use (defaults to Blotter's) :Returns: ...
def load_blotter_args(blotter_name=None, logger=None): """ Load running blotter's settings (used by clients) :Parameters: blotter_name : str Running Blotter's name (defaults to "auto-detect") logger : object Logger to be use (defaults to Blotter's) :Returns: ...
[ "Load", "running", "blotter", "s", "settings", "(", "used", "by", "clients", ")" ]
ranaroussi/qtpylib
python
https://github.com/ranaroussi/qtpylib/blob/0dbbc465fafd9cb9b0f4d10e1e07fae4e15032dd/qtpylib/blotter.py#L1281-L1324
[ "def", "load_blotter_args", "(", "blotter_name", "=", "None", ",", "logger", "=", "None", ")", ":", "if", "logger", "is", "None", ":", "logger", "=", "tools", ".", "createLogger", "(", "__name__", ",", "logging", ".", "WARNING", ")", "# find specific name", ...
0dbbc465fafd9cb9b0f4d10e1e07fae4e15032dd
train
get_symbol_id
Retrives symbol's ID from the Database or create it if it doesn't exist :Parameters: symbol : str Instrument symbol dbconn : object Database connection to be used dbcurr : object Database cursor to be used :Optional: ibConn : object ...
qtpylib/blotter.py
def get_symbol_id(symbol, dbconn, dbcurr, ibConn=None): """ Retrives symbol's ID from the Database or create it if it doesn't exist :Parameters: symbol : str Instrument symbol dbconn : object Database connection to be used dbcurr : object Database...
def get_symbol_id(symbol, dbconn, dbcurr, ibConn=None): """ Retrives symbol's ID from the Database or create it if it doesn't exist :Parameters: symbol : str Instrument symbol dbconn : object Database connection to be used dbcurr : object Database...
[ "Retrives", "symbol", "s", "ID", "from", "the", "Database", "or", "create", "it", "if", "it", "doesn", "t", "exist" ]
ranaroussi/qtpylib
python
https://github.com/ranaroussi/qtpylib/blob/0dbbc465fafd9cb9b0f4d10e1e07fae4e15032dd/qtpylib/blotter.py#L1329-L1424
[ "def", "get_symbol_id", "(", "symbol", ",", "dbconn", ",", "dbcurr", ",", "ibConn", "=", "None", ")", ":", "def", "_get_contract_expiry", "(", "symbol", ",", "ibConn", "=", "None", ")", ":", "# parse w/p ibConn", "if", "ibConn", "is", "None", "or", "isinst...
0dbbc465fafd9cb9b0f4d10e1e07fae4e15032dd
train
Blotter.run
Starts the blotter Connects to the TWS/GW, processes and logs market data, and broadcast it over TCP via ZeroMQ (which algo subscribe to)
qtpylib/blotter.py
def run(self): """Starts the blotter Connects to the TWS/GW, processes and logs market data, and broadcast it over TCP via ZeroMQ (which algo subscribe to) """ self._check_unique_blotter() # connect to mysql self.mysql_connect() self.context = zmq.Cont...
def run(self): """Starts the blotter Connects to the TWS/GW, processes and logs market data, and broadcast it over TCP via ZeroMQ (which algo subscribe to) """ self._check_unique_blotter() # connect to mysql self.mysql_connect() self.context = zmq.Cont...
[ "Starts", "the", "blotter" ]
ranaroussi/qtpylib
python
https://github.com/ranaroussi/qtpylib/blob/0dbbc465fafd9cb9b0f4d10e1e07fae4e15032dd/qtpylib/blotter.py#L745-L882
[ "def", "run", "(", "self", ")", ":", "self", ".", "_check_unique_blotter", "(", ")", "# connect to mysql", "self", ".", "mysql_connect", "(", ")", "self", ".", "context", "=", "zmq", ".", "Context", "(", "zmq", ".", "REP", ")", "self", ".", "socket", "...
0dbbc465fafd9cb9b0f4d10e1e07fae4e15032dd
train
Blotter._fix_history_sequence
fix out-of-sequence ticks/bars
qtpylib/blotter.py
def _fix_history_sequence(self, df, table): """ fix out-of-sequence ticks/bars """ # remove "Unnamed: x" columns cols = df.columns[df.columns.str.startswith('Unnamed:')].tolist() df.drop(cols, axis=1, inplace=True) # remove future dates df['datetime'] = pd.to_datetime(d...
def _fix_history_sequence(self, df, table): """ fix out-of-sequence ticks/bars """ # remove "Unnamed: x" columns cols = df.columns[df.columns.str.startswith('Unnamed:')].tolist() df.drop(cols, axis=1, inplace=True) # remove future dates df['datetime'] = pd.to_datetime(d...
[ "fix", "out", "-", "of", "-", "sequence", "ticks", "/", "bars" ]
ranaroussi/qtpylib
python
https://github.com/ranaroussi/qtpylib/blob/0dbbc465fafd9cb9b0f4d10e1e07fae4e15032dd/qtpylib/blotter.py#L887-L950
[ "def", "_fix_history_sequence", "(", "self", ",", "df", ",", "table", ")", ":", "# remove \"Unnamed: x\" columns", "cols", "=", "df", ".", "columns", "[", "df", ".", "columns", ".", "str", ".", "startswith", "(", "'Unnamed:'", ")", "]", ".", "tolist", "(",...
0dbbc465fafd9cb9b0f4d10e1e07fae4e15032dd
train
Blotter.backfill
Backfills missing historical data :Optional: data : pd.DataFrame Minimum required bars for backfill attempt resolution : str Algo resolution start: datetime Backfill start date (YYYY-MM-DD [HH:MM:SS[.MS]). end: date...
qtpylib/blotter.py
def backfill(self, data, resolution, start, end=None): """ Backfills missing historical data :Optional: data : pd.DataFrame Minimum required bars for backfill attempt resolution : str Algo resolution start: datetime ...
def backfill(self, data, resolution, start, end=None): """ Backfills missing historical data :Optional: data : pd.DataFrame Minimum required bars for backfill attempt resolution : str Algo resolution start: datetime ...
[ "Backfills", "missing", "historical", "data" ]
ranaroussi/qtpylib
python
https://github.com/ranaroussi/qtpylib/blob/0dbbc465fafd9cb9b0f4d10e1e07fae4e15032dd/qtpylib/blotter.py#L1117-L1185
[ "def", "backfill", "(", "self", ",", "data", ",", "resolution", ",", "start", ",", "end", "=", "None", ")", ":", "data", ".", "sort_index", "(", "inplace", "=", "True", ")", "# currenly only supporting minute-data", "if", "resolution", "[", "-", "1", "]", ...
0dbbc465fafd9cb9b0f4d10e1e07fae4e15032dd
train
session
remove previous globex day from df
qtpylib/indicators.py
def session(df, start='17:00', end='16:00'): """ remove previous globex day from df """ if df.empty: return df # get start/end/now as decimals int_start = list(map(int, start.split(':'))) int_start = (int_start[0] + int_start[1] - 1 / 100) - 0.0001 int_end = list(map(int, end.split(':')...
def session(df, start='17:00', end='16:00'): """ remove previous globex day from df """ if df.empty: return df # get start/end/now as decimals int_start = list(map(int, start.split(':'))) int_start = (int_start[0] + int_start[1] - 1 / 100) - 0.0001 int_end = list(map(int, end.split(':')...
[ "remove", "previous", "globex", "day", "from", "df" ]
ranaroussi/qtpylib
python
https://github.com/ranaroussi/qtpylib/blob/0dbbc465fafd9cb9b0f4d10e1e07fae4e15032dd/qtpylib/indicators.py#L76-L105
[ "def", "session", "(", "df", ",", "start", "=", "'17:00'", ",", "end", "=", "'16:00'", ")", ":", "if", "df", ".", "empty", ":", "return", "df", "# get start/end/now as decimals", "int_start", "=", "list", "(", "map", "(", "int", ",", "start", ".", "spl...
0dbbc465fafd9cb9b0f4d10e1e07fae4e15032dd
train
ibs
Internal bar strength
qtpylib/indicators.py
def ibs(bars): """ Internal bar strength """ res = np.round((bars['close'] - bars['low']) / (bars['high'] - bars['low']), 2) return pd.Series(index=bars.index, data=res)
def ibs(bars): """ Internal bar strength """ res = np.round((bars['close'] - bars['low']) / (bars['high'] - bars['low']), 2) return pd.Series(index=bars.index, data=res)
[ "Internal", "bar", "strength" ]
ranaroussi/qtpylib
python
https://github.com/ranaroussi/qtpylib/blob/0dbbc465fafd9cb9b0f4d10e1e07fae4e15032dd/qtpylib/indicators.py#L192-L196
[ "def", "ibs", "(", "bars", ")", ":", "res", "=", "np", ".", "round", "(", "(", "bars", "[", "'close'", "]", "-", "bars", "[", "'low'", "]", ")", "/", "(", "bars", "[", "'high'", "]", "-", "bars", "[", "'low'", "]", ")", ",", "2", ")", "retu...
0dbbc465fafd9cb9b0f4d10e1e07fae4e15032dd
train
vwap
calculate vwap of entire time series (input can be pandas series or numpy array) bars are usually mid [ (h+l)/2 ] or typical [ (h+l+c)/3 ]
qtpylib/indicators.py
def vwap(bars): """ calculate vwap of entire time series (input can be pandas series or numpy array) bars are usually mid [ (h+l)/2 ] or typical [ (h+l+c)/3 ] """ typical = ((bars['high'] + bars['low'] + bars['close']) / 3).values volume = bars['volume'].values return pd.Series(index=ba...
def vwap(bars): """ calculate vwap of entire time series (input can be pandas series or numpy array) bars are usually mid [ (h+l)/2 ] or typical [ (h+l+c)/3 ] """ typical = ((bars['high'] + bars['low'] + bars['close']) / 3).values volume = bars['volume'].values return pd.Series(index=ba...
[ "calculate", "vwap", "of", "entire", "time", "series", "(", "input", "can", "be", "pandas", "series", "or", "numpy", "array", ")", "bars", "are", "usually", "mid", "[", "(", "h", "+", "l", ")", "/", "2", "]", "or", "typical", "[", "(", "h", "+", ...
ranaroussi/qtpylib
python
https://github.com/ranaroussi/qtpylib/blob/0dbbc465fafd9cb9b0f4d10e1e07fae4e15032dd/qtpylib/indicators.py#L339-L349
[ "def", "vwap", "(", "bars", ")", ":", "typical", "=", "(", "(", "bars", "[", "'high'", "]", "+", "bars", "[", "'low'", "]", "+", "bars", "[", "'close'", "]", ")", "/", "3", ")", ".", "values", "volume", "=", "bars", "[", "'volume'", "]", ".", ...
0dbbc465fafd9cb9b0f4d10e1e07fae4e15032dd
train
rolling_vwap
calculate vwap using moving window (input can be pandas series or numpy array) bars are usually mid [ (h+l)/2 ] or typical [ (h+l+c)/3 ]
qtpylib/indicators.py
def rolling_vwap(bars, window=200, min_periods=None): """ calculate vwap using moving window (input can be pandas series or numpy array) bars are usually mid [ (h+l)/2 ] or typical [ (h+l+c)/3 ] """ min_periods = window if min_periods is None else min_periods typical = ((bars['high'] + bars...
def rolling_vwap(bars, window=200, min_periods=None): """ calculate vwap using moving window (input can be pandas series or numpy array) bars are usually mid [ (h+l)/2 ] or typical [ (h+l+c)/3 ] """ min_periods = window if min_periods is None else min_periods typical = ((bars['high'] + bars...
[ "calculate", "vwap", "using", "moving", "window", "(", "input", "can", "be", "pandas", "series", "or", "numpy", "array", ")", "bars", "are", "usually", "mid", "[", "(", "h", "+", "l", ")", "/", "2", "]", "or", "typical", "[", "(", "h", "+", "l", ...
ranaroussi/qtpylib
python
https://github.com/ranaroussi/qtpylib/blob/0dbbc465fafd9cb9b0f4d10e1e07fae4e15032dd/qtpylib/indicators.py#L354-L369
[ "def", "rolling_vwap", "(", "bars", ",", "window", "=", "200", ",", "min_periods", "=", "None", ")", ":", "min_periods", "=", "window", "if", "min_periods", "is", "None", "else", "min_periods", "typical", "=", "(", "(", "bars", "[", "'high'", "]", "+", ...
0dbbc465fafd9cb9b0f4d10e1e07fae4e15032dd
train
rsi
compute the n period relative strength indicator
qtpylib/indicators.py
def rsi(series, window=14): """ compute the n period relative strength indicator """ # 100-(100/relative_strength) deltas = np.diff(series) seed = deltas[:window + 1] # default values ups = seed[seed > 0].sum() / window downs = -seed[seed < 0].sum() / window rsival = np.zeros_l...
def rsi(series, window=14): """ compute the n period relative strength indicator """ # 100-(100/relative_strength) deltas = np.diff(series) seed = deltas[:window + 1] # default values ups = seed[seed > 0].sum() / window downs = -seed[seed < 0].sum() / window rsival = np.zeros_l...
[ "compute", "the", "n", "period", "relative", "strength", "indicator" ]
ranaroussi/qtpylib
python
https://github.com/ranaroussi/qtpylib/blob/0dbbc465fafd9cb9b0f4d10e1e07fae4e15032dd/qtpylib/indicators.py#L374-L404
[ "def", "rsi", "(", "series", ",", "window", "=", "14", ")", ":", "# 100-(100/relative_strength)", "deltas", "=", "np", ".", "diff", "(", "series", ")", "seed", "=", "deltas", "[", ":", "window", "+", "1", "]", "# default values", "ups", "=", "seed", "[...
0dbbc465fafd9cb9b0f4d10e1e07fae4e15032dd
train
macd
compute the MACD (Moving Average Convergence/Divergence) using a fast and slow exponential moving avg' return value is emaslow, emafast, macd which are len(x) arrays
qtpylib/indicators.py
def macd(series, fast=3, slow=10, smooth=16): """ compute the MACD (Moving Average Convergence/Divergence) using a fast and slow exponential moving avg' return value is emaslow, emafast, macd which are len(x) arrays """ macd_line = rolling_weighted_mean(series, window=fast) - \ rolling_w...
def macd(series, fast=3, slow=10, smooth=16): """ compute the MACD (Moving Average Convergence/Divergence) using a fast and slow exponential moving avg' return value is emaslow, emafast, macd which are len(x) arrays """ macd_line = rolling_weighted_mean(series, window=fast) - \ rolling_w...
[ "compute", "the", "MACD", "(", "Moving", "Average", "Convergence", "/", "Divergence", ")", "using", "a", "fast", "and", "slow", "exponential", "moving", "avg", "return", "value", "is", "emaslow", "emafast", "macd", "which", "are", "len", "(", "x", ")", "ar...
ranaroussi/qtpylib
python
https://github.com/ranaroussi/qtpylib/blob/0dbbc465fafd9cb9b0f4d10e1e07fae4e15032dd/qtpylib/indicators.py#L409-L424
[ "def", "macd", "(", "series", ",", "fast", "=", "3", ",", "slow", "=", "10", ",", "smooth", "=", "16", ")", ":", "macd_line", "=", "rolling_weighted_mean", "(", "series", ",", "window", "=", "fast", ")", "-", "rolling_weighted_mean", "(", "series", ","...
0dbbc465fafd9cb9b0f4d10e1e07fae4e15032dd
train
roc
compute rate of change
qtpylib/indicators.py
def roc(series, window=14): """ compute rate of change """ res = (series - series.shift(window)) / series.shift(window) return pd.Series(index=series.index, data=res)
def roc(series, window=14): """ compute rate of change """ res = (series - series.shift(window)) / series.shift(window) return pd.Series(index=series.index, data=res)
[ "compute", "rate", "of", "change" ]
ranaroussi/qtpylib
python
https://github.com/ranaroussi/qtpylib/blob/0dbbc465fafd9cb9b0f4d10e1e07fae4e15032dd/qtpylib/indicators.py#L512-L517
[ "def", "roc", "(", "series", ",", "window", "=", "14", ")", ":", "res", "=", "(", "series", "-", "series", ".", "shift", "(", "window", ")", ")", "/", "series", ".", "shift", "(", "window", ")", "return", "pd", ".", "Series", "(", "index", "=", ...
0dbbc465fafd9cb9b0f4d10e1e07fae4e15032dd
train
cci
compute commodity channel index
qtpylib/indicators.py
def cci(series, window=14): """ compute commodity channel index """ price = typical_price(series) typical_mean = rolling_mean(price, window) res = (price - typical_mean) / (.015 * np.std(typical_mean)) return pd.Series(index=series.index, data=res)
def cci(series, window=14): """ compute commodity channel index """ price = typical_price(series) typical_mean = rolling_mean(price, window) res = (price - typical_mean) / (.015 * np.std(typical_mean)) return pd.Series(index=series.index, data=res)
[ "compute", "commodity", "channel", "index" ]
ranaroussi/qtpylib
python
https://github.com/ranaroussi/qtpylib/blob/0dbbc465fafd9cb9b0f4d10e1e07fae4e15032dd/qtpylib/indicators.py#L522-L529
[ "def", "cci", "(", "series", ",", "window", "=", "14", ")", ":", "price", "=", "typical_price", "(", "series", ")", "typical_mean", "=", "rolling_mean", "(", "price", ",", "window", ")", "res", "=", "(", "price", "-", "typical_mean", ")", "/", "(", "...
0dbbc465fafd9cb9b0f4d10e1e07fae4e15032dd
train
stoch
compute the n period relative strength indicator http://excelta.blogspot.co.il/2013/09/stochastic-oscillator-technical.html
qtpylib/indicators.py
def stoch(df, window=14, d=3, k=3, fast=False): """ compute the n period relative strength indicator http://excelta.blogspot.co.il/2013/09/stochastic-oscillator-technical.html """ my_df = pd.DataFrame(index=df.index) my_df['rolling_max'] = df['high'].rolling(window).max() my_df['rolling_mi...
def stoch(df, window=14, d=3, k=3, fast=False): """ compute the n period relative strength indicator http://excelta.blogspot.co.il/2013/09/stochastic-oscillator-technical.html """ my_df = pd.DataFrame(index=df.index) my_df['rolling_max'] = df['high'].rolling(window).max() my_df['rolling_mi...
[ "compute", "the", "n", "period", "relative", "strength", "indicator", "http", ":", "//", "excelta", ".", "blogspot", ".", "co", ".", "il", "/", "2013", "/", "09", "/", "stochastic", "-", "oscillator", "-", "technical", ".", "html" ]
ranaroussi/qtpylib
python
https://github.com/ranaroussi/qtpylib/blob/0dbbc465fafd9cb9b0f4d10e1e07fae4e15032dd/qtpylib/indicators.py#L534-L554
[ "def", "stoch", "(", "df", ",", "window", "=", "14", ",", "d", "=", "3", ",", "k", "=", "3", ",", "fast", "=", "False", ")", ":", "my_df", "=", "pd", ".", "DataFrame", "(", "index", "=", "df", ".", "index", ")", "my_df", "[", "'rolling_max'", ...
0dbbc465fafd9cb9b0f4d10e1e07fae4e15032dd
train
zlma
John Ehlers' Zero lag (exponential) moving average https://en.wikipedia.org/wiki/Zero_lag_exponential_moving_average
qtpylib/indicators.py
def zlma(series, window=20, min_periods=None, kind="ema"): """ John Ehlers' Zero lag (exponential) moving average https://en.wikipedia.org/wiki/Zero_lag_exponential_moving_average """ min_periods = window if min_periods is None else min_periods lag = (window - 1) // 2 series = 2 * series - ...
def zlma(series, window=20, min_periods=None, kind="ema"): """ John Ehlers' Zero lag (exponential) moving average https://en.wikipedia.org/wiki/Zero_lag_exponential_moving_average """ min_periods = window if min_periods is None else min_periods lag = (window - 1) // 2 series = 2 * series - ...
[ "John", "Ehlers", "Zero", "lag", "(", "exponential", ")", "moving", "average", "https", ":", "//", "en", ".", "wikipedia", ".", "org", "/", "wiki", "/", "Zero_lag_exponential_moving_average" ]
ranaroussi/qtpylib
python
https://github.com/ranaroussi/qtpylib/blob/0dbbc465fafd9cb9b0f4d10e1e07fae4e15032dd/qtpylib/indicators.py#L559-L572
[ "def", "zlma", "(", "series", ",", "window", "=", "20", ",", "min_periods", "=", "None", ",", "kind", "=", "\"ema\"", ")", ":", "min_periods", "=", "window", "if", "min_periods", "is", "None", "else", "min_periods", "lag", "=", "(", "window", "-", "1",...
0dbbc465fafd9cb9b0f4d10e1e07fae4e15032dd
train
zscore
get zscore of price
qtpylib/indicators.py
def zscore(bars, window=20, stds=1, col='close'): """ get zscore of price """ std = numpy_rolling_std(bars[col], window) mean = numpy_rolling_mean(bars[col], window) return (bars[col] - mean) / (std * stds)
def zscore(bars, window=20, stds=1, col='close'): """ get zscore of price """ std = numpy_rolling_std(bars[col], window) mean = numpy_rolling_mean(bars[col], window) return (bars[col] - mean) / (std * stds)
[ "get", "zscore", "of", "price" ]
ranaroussi/qtpylib
python
https://github.com/ranaroussi/qtpylib/blob/0dbbc465fafd9cb9b0f4d10e1e07fae4e15032dd/qtpylib/indicators.py#L589-L593
[ "def", "zscore", "(", "bars", ",", "window", "=", "20", ",", "stds", "=", "1", ",", "col", "=", "'close'", ")", ":", "std", "=", "numpy_rolling_std", "(", "bars", "[", "col", "]", ",", "window", ")", "mean", "=", "numpy_rolling_mean", "(", "bars", ...
0dbbc465fafd9cb9b0f4d10e1e07fae4e15032dd
train
pvt
Price Volume Trend
qtpylib/indicators.py
def pvt(bars): """ Price Volume Trend """ trend = ((bars['close'] - bars['close'].shift(1)) / bars['close'].shift(1)) * bars['volume'] return trend.cumsum()
def pvt(bars): """ Price Volume Trend """ trend = ((bars['close'] - bars['close'].shift(1)) / bars['close'].shift(1)) * bars['volume'] return trend.cumsum()
[ "Price", "Volume", "Trend" ]
ranaroussi/qtpylib
python
https://github.com/ranaroussi/qtpylib/blob/0dbbc465fafd9cb9b0f4d10e1e07fae4e15032dd/qtpylib/indicators.py#L598-L602
[ "def", "pvt", "(", "bars", ")", ":", "trend", "=", "(", "(", "bars", "[", "'close'", "]", "-", "bars", "[", "'close'", "]", ".", "shift", "(", "1", ")", ")", "/", "bars", "[", "'close'", "]", ".", "shift", "(", "1", ")", ")", "*", "bars", "...
0dbbc465fafd9cb9b0f4d10e1e07fae4e15032dd
train
Algo.run
Starts the algo Connects to the Blotter, processes market data and passes tick data to the ``on_tick`` function and bar data to the ``on_bar`` methods.
qtpylib/algo.py
def run(self): """Starts the algo Connects to the Blotter, processes market data and passes tick data to the ``on_tick`` function and bar data to the ``on_bar`` methods. """ history = pd.DataFrame() # get history from csv dir if self.backtest and self.b...
def run(self): """Starts the algo Connects to the Blotter, processes market data and passes tick data to the ``on_tick`` function and bar data to the ``on_bar`` methods. """ history = pd.DataFrame() # get history from csv dir if self.backtest and self.b...
[ "Starts", "the", "algo" ]
ranaroussi/qtpylib
python
https://github.com/ranaroussi/qtpylib/blob/0dbbc465fafd9cb9b0f4d10e1e07fae4e15032dd/qtpylib/algo.py#L289-L413
[ "def", "run", "(", "self", ")", ":", "history", "=", "pd", ".", "DataFrame", "(", ")", "# get history from csv dir", "if", "self", ".", "backtest", "and", "self", ".", "backtest_csv", ":", "kind", "=", "\"TICK\"", "if", "self", ".", "resolution", "[", "-...
0dbbc465fafd9cb9b0f4d10e1e07fae4e15032dd
train
Algo.get_history
Get historical market data. Connects to Blotter and gets historical data from storage :Parameters: symbols : list List of symbols to fetch history for start : datetime / string History time period start date datetime or YYYY-MM-DD[...
qtpylib/algo.py
def get_history(self, symbols, start, end=None, resolution="1T", tz="UTC"): """Get historical market data. Connects to Blotter and gets historical data from storage :Parameters: symbols : list List of symbols to fetch history for start : datetime / string...
def get_history(self, symbols, start, end=None, resolution="1T", tz="UTC"): """Get historical market data. Connects to Blotter and gets historical data from storage :Parameters: symbols : list List of symbols to fetch history for start : datetime / string...
[ "Get", "historical", "market", "data", ".", "Connects", "to", "Blotter", "and", "gets", "historical", "data", "from", "storage" ]
ranaroussi/qtpylib
python
https://github.com/ranaroussi/qtpylib/blob/0dbbc465fafd9cb9b0f4d10e1e07fae4e15032dd/qtpylib/algo.py#L509-L533
[ "def", "get_history", "(", "self", ",", "symbols", ",", "start", ",", "end", "=", "None", ",", "resolution", "=", "\"1T\"", ",", "tz", "=", "\"UTC\"", ")", ":", "return", "self", ".", "blotter", ".", "history", "(", "symbols", ",", "start", ",", "end...
0dbbc465fafd9cb9b0f4d10e1e07fae4e15032dd
train
Algo.order
Send an order for the selected instrument :Parameters: direction : string Order Type (BUY/SELL, EXIT/FLATTEN) symbol : string instrument symbol quantity : int Order quantiry :Optional: limit_price : float...
qtpylib/algo.py
def order(self, signal, symbol, quantity=0, **kwargs): """ Send an order for the selected instrument :Parameters: direction : string Order Type (BUY/SELL, EXIT/FLATTEN) symbol : string instrument symbol quantity : int ...
def order(self, signal, symbol, quantity=0, **kwargs): """ Send an order for the selected instrument :Parameters: direction : string Order Type (BUY/SELL, EXIT/FLATTEN) symbol : string instrument symbol quantity : int ...
[ "Send", "an", "order", "for", "the", "selected", "instrument" ]
ranaroussi/qtpylib
python
https://github.com/ranaroussi/qtpylib/blob/0dbbc465fafd9cb9b0f4d10e1e07fae4e15032dd/qtpylib/algo.py#L538-L625
[ "def", "order", "(", "self", ",", "signal", ",", "symbol", ",", "quantity", "=", "0", ",", "*", "*", "kwargs", ")", ":", "self", ".", "log_algo", ".", "debug", "(", "'ORDER: %s %4d %s %s'", ",", "signal", ",", "quantity", ",", "symbol", ",", "kwargs", ...
0dbbc465fafd9cb9b0f4d10e1e07fae4e15032dd
train
Algo.record
Records data for later analysis. Values will be logged to the file specified via ``--output [file]`` (along with bar data) as csv/pickle/h5 file. Call from within your strategy: ``self.record(key=value)`` :Parameters: ** kwargs : mixed The na...
qtpylib/algo.py
def record(self, *args, **kwargs): """Records data for later analysis. Values will be logged to the file specified via ``--output [file]`` (along with bar data) as csv/pickle/h5 file. Call from within your strategy: ``self.record(key=value)`` :Parameters: ...
def record(self, *args, **kwargs): """Records data for later analysis. Values will be logged to the file specified via ``--output [file]`` (along with bar data) as csv/pickle/h5 file. Call from within your strategy: ``self.record(key=value)`` :Parameters: ...
[ "Records", "data", "for", "later", "analysis", ".", "Values", "will", "be", "logged", "to", "the", "file", "specified", "via", "--", "output", "[", "file", "]", "(", "along", "with", "bar", "data", ")", "as", "csv", "/", "pickle", "/", "h5", "file", ...
ranaroussi/qtpylib
python
https://github.com/ranaroussi/qtpylib/blob/0dbbc465fafd9cb9b0f4d10e1e07fae4e15032dd/qtpylib/algo.py#L638-L656
[ "def", "record", "(", "self", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "if", "self", ".", "record_output", ":", "try", ":", "self", ".", "datastore", ".", "record", "(", "self", ".", "record_ts", ",", "*", "args", ",", "*", "*", "kwar...
0dbbc465fafd9cb9b0f4d10e1e07fae4e15032dd
train
Algo.sms
Sends an SMS message. Relies on properly setting up an SMS provider (refer to the SMS section of the documentation for more information about this) Call from within your strategy: ``self.sms("message text")`` :Parameters: text : string The body of th...
qtpylib/algo.py
def sms(self, text): """Sends an SMS message. Relies on properly setting up an SMS provider (refer to the SMS section of the documentation for more information about this) Call from within your strategy: ``self.sms("message text")`` :Parameters: text : strin...
def sms(self, text): """Sends an SMS message. Relies on properly setting up an SMS provider (refer to the SMS section of the documentation for more information about this) Call from within your strategy: ``self.sms("message text")`` :Parameters: text : strin...
[ "Sends", "an", "SMS", "message", ".", "Relies", "on", "properly", "setting", "up", "an", "SMS", "provider", "(", "refer", "to", "the", "SMS", "section", "of", "the", "documentation", "for", "more", "information", "about", "this", ")" ]
ranaroussi/qtpylib
python
https://github.com/ranaroussi/qtpylib/blob/0dbbc465fafd9cb9b0f4d10e1e07fae4e15032dd/qtpylib/algo.py#L659-L673
[ "def", "sms", "(", "self", ",", "text", ")", ":", "logging", ".", "info", "(", "\"SMS: %s\"", ",", "str", "(", "text", ")", ")", "sms", ".", "send_text", "(", "self", ".", "name", "+", "': '", "+", "str", "(", "text", ")", ",", "self", ".", "sm...
0dbbc465fafd9cb9b0f4d10e1e07fae4e15032dd
train
Algo._base_bar_handler
non threaded bar handler (called by threaded _tick_handler)
qtpylib/algo.py
def _base_bar_handler(self, bar): """ non threaded bar handler (called by threaded _tick_handler) """ # bar symbol symbol = bar['symbol'].values if len(symbol) == 0: return symbol = symbol[0] self_bars = self.bars.copy() # work on copy is_tick_or_vol...
def _base_bar_handler(self, bar): """ non threaded bar handler (called by threaded _tick_handler) """ # bar symbol symbol = bar['symbol'].values if len(symbol) == 0: return symbol = symbol[0] self_bars = self.bars.copy() # work on copy is_tick_or_vol...
[ "non", "threaded", "bar", "handler", "(", "called", "by", "threaded", "_tick_handler", ")" ]
ranaroussi/qtpylib
python
https://github.com/ranaroussi/qtpylib/blob/0dbbc465fafd9cb9b0f4d10e1e07fae4e15032dd/qtpylib/algo.py#L792-L859
[ "def", "_base_bar_handler", "(", "self", ",", "bar", ")", ":", "# bar symbol", "symbol", "=", "bar", "[", "'symbol'", "]", ".", "values", "if", "len", "(", "symbol", ")", "==", "0", ":", "return", "symbol", "=", "symbol", "[", "0", "]", "self_bars", ...
0dbbc465fafd9cb9b0f4d10e1e07fae4e15032dd
train
Algo._add_signal_history
Initilize signal history
qtpylib/algo.py
def _add_signal_history(self, df, symbol): """ Initilize signal history """ if symbol not in self.signals.keys() or len(self.signals[symbol]) == 0: self.signals[symbol] = [nan] * len(df.index) else: self.signals[symbol].append(nan) self.signals[symbol] = self.sig...
def _add_signal_history(self, df, symbol): """ Initilize signal history """ if symbol not in self.signals.keys() or len(self.signals[symbol]) == 0: self.signals[symbol] = [nan] * len(df.index) else: self.signals[symbol].append(nan) self.signals[symbol] = self.sig...
[ "Initilize", "signal", "history" ]
ranaroussi/qtpylib
python
https://github.com/ranaroussi/qtpylib/blob/0dbbc465fafd9cb9b0f4d10e1e07fae4e15032dd/qtpylib/algo.py#L902-L913
[ "def", "_add_signal_history", "(", "self", ",", "df", ",", "symbol", ")", ":", "if", "symbol", "not", "in", "self", ".", "signals", ".", "keys", "(", ")", "or", "len", "(", "self", ".", "signals", "[", "symbol", "]", ")", "==", "0", ":", "self", ...
0dbbc465fafd9cb9b0f4d10e1e07fae4e15032dd
train
multi_shift
get last N rows RELATIVE to another row in pandas http://stackoverflow.com/questions/25724056/how-to-get-last-n-rows-relative-to-another-row-in-pandas-vector-solution
qtpylib/tools.py
def multi_shift(df, window): """ get last N rows RELATIVE to another row in pandas http://stackoverflow.com/questions/25724056/how-to-get-last-n-rows-relative-to-another-row-in-pandas-vector-solution """ if isinstance(df, pd.Series): df = pd.DataFrame(df) dfs = [df.shift(i) for i in np....
def multi_shift(df, window): """ get last N rows RELATIVE to another row in pandas http://stackoverflow.com/questions/25724056/how-to-get-last-n-rows-relative-to-another-row-in-pandas-vector-solution """ if isinstance(df, pd.Series): df = pd.DataFrame(df) dfs = [df.shift(i) for i in np....
[ "get", "last", "N", "rows", "RELATIVE", "to", "another", "row", "in", "pandas", "http", ":", "//", "stackoverflow", ".", "com", "/", "questions", "/", "25724056", "/", "how", "-", "to", "-", "get", "-", "last", "-", "n", "-", "rows", "-", "relative",...
ranaroussi/qtpylib
python
https://github.com/ranaroussi/qtpylib/blob/0dbbc465fafd9cb9b0f4d10e1e07fae4e15032dd/qtpylib/tools.py#L73-L84
[ "def", "multi_shift", "(", "df", ",", "window", ")", ":", "if", "isinstance", "(", "df", ",", "pd", ".", "Series", ")", ":", "df", "=", "pd", ".", "DataFrame", "(", "df", ")", "dfs", "=", "[", "df", ".", "shift", "(", "i", ")", "for", "i", "i...
0dbbc465fafd9cb9b0f4d10e1e07fae4e15032dd
train
is_number
checks if a string is a number (int/float)
qtpylib/tools.py
def is_number(string): """ checks if a string is a number (int/float) """ string = str(string) if string.isnumeric(): return True try: float(string) return True except ValueError: return False
def is_number(string): """ checks if a string is a number (int/float) """ string = str(string) if string.isnumeric(): return True try: float(string) return True except ValueError: return False
[ "checks", "if", "a", "string", "is", "a", "number", "(", "int", "/", "float", ")" ]
ranaroussi/qtpylib
python
https://github.com/ranaroussi/qtpylib/blob/0dbbc465fafd9cb9b0f4d10e1e07fae4e15032dd/qtpylib/tools.py#L89-L98
[ "def", "is_number", "(", "string", ")", ":", "string", "=", "str", "(", "string", ")", "if", "string", ".", "isnumeric", "(", ")", ":", "return", "True", "try", ":", "float", "(", "string", ")", "return", "True", "except", "ValueError", ":", "return", ...
0dbbc465fafd9cb9b0f4d10e1e07fae4e15032dd
train
to_decimal
convert datatypes into Decimals
qtpylib/tools.py
def to_decimal(number, points=None): """ convert datatypes into Decimals """ if not is_number(number): return number number = float(decimal.Decimal(number * 1.)) # can't Decimal an int if is_number(points): return round(number, points) return number
def to_decimal(number, points=None): """ convert datatypes into Decimals """ if not is_number(number): return number number = float(decimal.Decimal(number * 1.)) # can't Decimal an int if is_number(points): return round(number, points) return number
[ "convert", "datatypes", "into", "Decimals" ]
ranaroussi/qtpylib
python
https://github.com/ranaroussi/qtpylib/blob/0dbbc465fafd9cb9b0f4d10e1e07fae4e15032dd/qtpylib/tools.py#L103-L111
[ "def", "to_decimal", "(", "number", ",", "points", "=", "None", ")", ":", "if", "not", "is_number", "(", "number", ")", ":", "return", "number", "number", "=", "float", "(", "decimal", ".", "Decimal", "(", "number", "*", "1.", ")", ")", "# can't Decima...
0dbbc465fafd9cb9b0f4d10e1e07fae4e15032dd
train
create_ib_tuple
create ib contract tuple
qtpylib/tools.py
def create_ib_tuple(instrument): """ create ib contract tuple """ from qtpylib import futures if isinstance(instrument, str): instrument = instrument.upper() if "FUT." not in instrument: # symbol stock instrument = (instrument, "STK", "SMART", "USD", "", 0.0, "") ...
def create_ib_tuple(instrument): """ create ib contract tuple """ from qtpylib import futures if isinstance(instrument, str): instrument = instrument.upper() if "FUT." not in instrument: # symbol stock instrument = (instrument, "STK", "SMART", "USD", "", 0.0, "") ...
[ "create", "ib", "contract", "tuple" ]
ranaroussi/qtpylib
python
https://github.com/ranaroussi/qtpylib/blob/0dbbc465fafd9cb9b0f4d10e1e07fae4e15032dd/qtpylib/tools.py#L130-L194
[ "def", "create_ib_tuple", "(", "instrument", ")", ":", "from", "qtpylib", "import", "futures", "if", "isinstance", "(", "instrument", ",", "str", ")", ":", "instrument", "=", "instrument", ".", "upper", "(", ")", "if", "\"FUT.\"", "not", "in", "instrument", ...
0dbbc465fafd9cb9b0f4d10e1e07fae4e15032dd
train
chmod
change mod to writeable
qtpylib/tools.py
def chmod(f): """ change mod to writeable """ try: os.chmod(f, S_IWRITE) # windows (cover all) except Exception as e: pass try: os.chmod(f, 0o777) # *nix except Exception as e: pass
def chmod(f): """ change mod to writeable """ try: os.chmod(f, S_IWRITE) # windows (cover all) except Exception as e: pass try: os.chmod(f, 0o777) # *nix except Exception as e: pass
[ "change", "mod", "to", "writeable" ]
ranaroussi/qtpylib
python
https://github.com/ranaroussi/qtpylib/blob/0dbbc465fafd9cb9b0f4d10e1e07fae4e15032dd/qtpylib/tools.py#L294-L303
[ "def", "chmod", "(", "f", ")", ":", "try", ":", "os", ".", "chmod", "(", "f", ",", "S_IWRITE", ")", "# windows (cover all)", "except", "Exception", "as", "e", ":", "pass", "try", ":", "os", ".", "chmod", "(", "f", ",", "0o777", ")", "# *nix", "exce...
0dbbc465fafd9cb9b0f4d10e1e07fae4e15032dd
train
as_dict
converts df to dict and adds a datetime field if df is datetime
qtpylib/tools.py
def as_dict(df, ix=':'): """ converts df to dict and adds a datetime field if df is datetime """ if isinstance(df.index, pd.DatetimeIndex): df['datetime'] = df.index return df.to_dict(orient='records')[ix]
def as_dict(df, ix=':'): """ converts df to dict and adds a datetime field if df is datetime """ if isinstance(df.index, pd.DatetimeIndex): df['datetime'] = df.index return df.to_dict(orient='records')[ix]
[ "converts", "df", "to", "dict", "and", "adds", "a", "datetime", "field", "if", "df", "is", "datetime" ]
ranaroussi/qtpylib
python
https://github.com/ranaroussi/qtpylib/blob/0dbbc465fafd9cb9b0f4d10e1e07fae4e15032dd/qtpylib/tools.py#L308-L312
[ "def", "as_dict", "(", "df", ",", "ix", "=", "':'", ")", ":", "if", "isinstance", "(", "df", ".", "index", ",", "pd", ".", "DatetimeIndex", ")", ":", "df", "[", "'datetime'", "]", "=", "df", ".", "index", "return", "df", ".", "to_dict", "(", "ori...
0dbbc465fafd9cb9b0f4d10e1e07fae4e15032dd
train
ib_duration_str
Get a datetime object or a epoch timestamp and return an IB-compatible durationStr for reqHistoricalData()
qtpylib/tools.py
def ib_duration_str(start_date=None): """ Get a datetime object or a epoch timestamp and return an IB-compatible durationStr for reqHistoricalData() """ now = datetime.datetime.utcnow() if is_number(start_date): diff = now - datetime.datetime.fromtimestamp(float(start_date)) elif is...
def ib_duration_str(start_date=None): """ Get a datetime object or a epoch timestamp and return an IB-compatible durationStr for reqHistoricalData() """ now = datetime.datetime.utcnow() if is_number(start_date): diff = now - datetime.datetime.fromtimestamp(float(start_date)) elif is...
[ "Get", "a", "datetime", "object", "or", "a", "epoch", "timestamp", "and", "return", "an", "IB", "-", "compatible", "durationStr", "for", "reqHistoricalData", "()" ]
ranaroussi/qtpylib
python
https://github.com/ranaroussi/qtpylib/blob/0dbbc465fafd9cb9b0f4d10e1e07fae4e15032dd/qtpylib/tools.py#L317-L349
[ "def", "ib_duration_str", "(", "start_date", "=", "None", ")", ":", "now", "=", "datetime", ".", "datetime", ".", "utcnow", "(", ")", "if", "is_number", "(", "start_date", ")", ":", "diff", "=", "now", "-", "datetime", ".", "datetime", ".", "fromtimestam...
0dbbc465fafd9cb9b0f4d10e1e07fae4e15032dd
train
datetime64_to_datetime
convert numpy's datetime64 to datetime
qtpylib/tools.py
def datetime64_to_datetime(dt): """ convert numpy's datetime64 to datetime """ dt64 = np.datetime64(dt) ts = (dt64 - np.datetime64('1970-01-01T00:00:00')) / np.timedelta64(1, 's') return datetime.datetime.utcfromtimestamp(ts)
def datetime64_to_datetime(dt): """ convert numpy's datetime64 to datetime """ dt64 = np.datetime64(dt) ts = (dt64 - np.datetime64('1970-01-01T00:00:00')) / np.timedelta64(1, 's') return datetime.datetime.utcfromtimestamp(ts)
[ "convert", "numpy", "s", "datetime64", "to", "datetime" ]
ranaroussi/qtpylib
python
https://github.com/ranaroussi/qtpylib/blob/0dbbc465fafd9cb9b0f4d10e1e07fae4e15032dd/qtpylib/tools.py#L354-L358
[ "def", "datetime64_to_datetime", "(", "dt", ")", ":", "dt64", "=", "np", ".", "datetime64", "(", "dt", ")", "ts", "=", "(", "dt64", "-", "np", ".", "datetime64", "(", "'1970-01-01T00:00:00'", ")", ")", "/", "np", ".", "timedelta64", "(", "1", ",", "'...
0dbbc465fafd9cb9b0f4d10e1e07fae4e15032dd
train
round_to_fraction
round to closest resolution
qtpylib/tools.py
def round_to_fraction(val, res, decimals=None): """ round to closest resolution """ if val is None: return 0.0 if decimals is None and "." in str(res): decimals = len(str(res).split('.')[1]) return round(round(val / res) * res, decimals)
def round_to_fraction(val, res, decimals=None): """ round to closest resolution """ if val is None: return 0.0 if decimals is None and "." in str(res): decimals = len(str(res).split('.')[1]) return round(round(val / res) * res, decimals)
[ "round", "to", "closest", "resolution" ]
ranaroussi/qtpylib
python
https://github.com/ranaroussi/qtpylib/blob/0dbbc465fafd9cb9b0f4d10e1e07fae4e15032dd/qtpylib/tools.py#L363-L370
[ "def", "round_to_fraction", "(", "val", ",", "res", ",", "decimals", "=", "None", ")", ":", "if", "val", "is", "None", ":", "return", "0.0", "if", "decimals", "is", "None", "and", "\".\"", "in", "str", "(", "res", ")", ":", "decimals", "=", "len", ...
0dbbc465fafd9cb9b0f4d10e1e07fae4e15032dd
train
backdate
get past date based on currect date
qtpylib/tools.py
def backdate(res, date=None, as_datetime=False, fmt='%Y-%m-%d'): """ get past date based on currect date """ if res is None: return None if date is None: date = datetime.datetime.now() else: try: date = parse_date(date) except Exception as e: pass...
def backdate(res, date=None, as_datetime=False, fmt='%Y-%m-%d'): """ get past date based on currect date """ if res is None: return None if date is None: date = datetime.datetime.now() else: try: date = parse_date(date) except Exception as e: pass...
[ "get", "past", "date", "based", "on", "currect", "date" ]
ranaroussi/qtpylib
python
https://github.com/ranaroussi/qtpylib/blob/0dbbc465fafd9cb9b0f4d10e1e07fae4e15032dd/qtpylib/tools.py#L375-L414
[ "def", "backdate", "(", "res", ",", "date", "=", "None", ",", "as_datetime", "=", "False", ",", "fmt", "=", "'%Y-%m-%d'", ")", ":", "if", "res", "is", "None", ":", "return", "None", "if", "date", "is", "None", ":", "date", "=", "datetime", ".", "da...
0dbbc465fafd9cb9b0f4d10e1e07fae4e15032dd
train
previous_weekday
get the most recent business day
qtpylib/tools.py
def previous_weekday(day=None, as_datetime=False): """ get the most recent business day """ if day is None: day = datetime.datetime.now() else: day = datetime.datetime.strptime(day, '%Y-%m-%d') day -= datetime.timedelta(days=1) while day.weekday() > 4: # Mon-Fri are 0-4 day...
def previous_weekday(day=None, as_datetime=False): """ get the most recent business day """ if day is None: day = datetime.datetime.now() else: day = datetime.datetime.strptime(day, '%Y-%m-%d') day -= datetime.timedelta(days=1) while day.weekday() > 4: # Mon-Fri are 0-4 day...
[ "get", "the", "most", "recent", "business", "day" ]
ranaroussi/qtpylib
python
https://github.com/ranaroussi/qtpylib/blob/0dbbc465fafd9cb9b0f4d10e1e07fae4e15032dd/qtpylib/tools.py#L419-L432
[ "def", "previous_weekday", "(", "day", "=", "None", ",", "as_datetime", "=", "False", ")", ":", "if", "day", "is", "None", ":", "day", "=", "datetime", ".", "datetime", ".", "now", "(", ")", "else", ":", "day", "=", "datetime", ".", "datetime", ".", ...
0dbbc465fafd9cb9b0f4d10e1e07fae4e15032dd
train
is_third_friday
check if day is month's 3rd friday
qtpylib/tools.py
def is_third_friday(day=None): """ check if day is month's 3rd friday """ day = day if day is not None else datetime.datetime.now() defacto_friday = (day.weekday() == 4) or ( day.weekday() == 3 and day.hour() >= 17) return defacto_friday and 14 < day.day < 22
def is_third_friday(day=None): """ check if day is month's 3rd friday """ day = day if day is not None else datetime.datetime.now() defacto_friday = (day.weekday() == 4) or ( day.weekday() == 3 and day.hour() >= 17) return defacto_friday and 14 < day.day < 22
[ "check", "if", "day", "is", "month", "s", "3rd", "friday" ]
ranaroussi/qtpylib
python
https://github.com/ranaroussi/qtpylib/blob/0dbbc465fafd9cb9b0f4d10e1e07fae4e15032dd/qtpylib/tools.py#L437-L442
[ "def", "is_third_friday", "(", "day", "=", "None", ")", ":", "day", "=", "day", "if", "day", "is", "not", "None", "else", "datetime", ".", "datetime", ".", "now", "(", ")", "defacto_friday", "=", "(", "day", ".", "weekday", "(", ")", "==", "4", ")"...
0dbbc465fafd9cb9b0f4d10e1e07fae4e15032dd
train
after_third_friday
check if day is after month's 3rd friday
qtpylib/tools.py
def after_third_friday(day=None): """ check if day is after month's 3rd friday """ day = day if day is not None else datetime.datetime.now() now = day.replace(day=1, hour=16, minute=0, second=0, microsecond=0) now += relativedelta.relativedelta(weeks=2, weekday=relativedelta.FR) return day > now
def after_third_friday(day=None): """ check if day is after month's 3rd friday """ day = day if day is not None else datetime.datetime.now() now = day.replace(day=1, hour=16, minute=0, second=0, microsecond=0) now += relativedelta.relativedelta(weeks=2, weekday=relativedelta.FR) return day > now
[ "check", "if", "day", "is", "after", "month", "s", "3rd", "friday" ]
ranaroussi/qtpylib
python
https://github.com/ranaroussi/qtpylib/blob/0dbbc465fafd9cb9b0f4d10e1e07fae4e15032dd/qtpylib/tools.py#L447-L452
[ "def", "after_third_friday", "(", "day", "=", "None", ")", ":", "day", "=", "day", "if", "day", "is", "not", "None", "else", "datetime", ".", "datetime", ".", "now", "(", ")", "now", "=", "day", ".", "replace", "(", "day", "=", "1", ",", "hour", ...
0dbbc465fafd9cb9b0f4d10e1e07fae4e15032dd
train
get_timezone
utility to get the machine's timezone
qtpylib/tools.py
def get_timezone(as_timedelta=False): """ utility to get the machine's timezone """ try: offset_hour = -(time.altzone if time.daylight else time.timezone) except Exception as e: offset_hour = -(datetime.datetime.now() - datetime.datetime.utcnow()).seconds offset_...
def get_timezone(as_timedelta=False): """ utility to get the machine's timezone """ try: offset_hour = -(time.altzone if time.daylight else time.timezone) except Exception as e: offset_hour = -(datetime.datetime.now() - datetime.datetime.utcnow()).seconds offset_...
[ "utility", "to", "get", "the", "machine", "s", "timezone" ]
ranaroussi/qtpylib
python
https://github.com/ranaroussi/qtpylib/blob/0dbbc465fafd9cb9b0f4d10e1e07fae4e15032dd/qtpylib/tools.py#L459-L473
[ "def", "get_timezone", "(", "as_timedelta", "=", "False", ")", ":", "try", ":", "offset_hour", "=", "-", "(", "time", ".", "altzone", "if", "time", ".", "daylight", "else", "time", ".", "timezone", ")", "except", "Exception", "as", "e", ":", "offset_hour...
0dbbc465fafd9cb9b0f4d10e1e07fae4e15032dd
train
datetime_to_timezone
convert naive datetime to timezone-aware datetime
qtpylib/tools.py
def datetime_to_timezone(date, tz="UTC"): """ convert naive datetime to timezone-aware datetime """ if not date.tzinfo: date = date.replace(tzinfo=timezone(get_timezone())) return date.astimezone(timezone(tz))
def datetime_to_timezone(date, tz="UTC"): """ convert naive datetime to timezone-aware datetime """ if not date.tzinfo: date = date.replace(tzinfo=timezone(get_timezone())) return date.astimezone(timezone(tz))
[ "convert", "naive", "datetime", "to", "timezone", "-", "aware", "datetime" ]
ranaroussi/qtpylib
python
https://github.com/ranaroussi/qtpylib/blob/0dbbc465fafd9cb9b0f4d10e1e07fae4e15032dd/qtpylib/tools.py#L478-L482
[ "def", "datetime_to_timezone", "(", "date", ",", "tz", "=", "\"UTC\"", ")", ":", "if", "not", "date", ".", "tzinfo", ":", "date", "=", "date", ".", "replace", "(", "tzinfo", "=", "timezone", "(", "get_timezone", "(", ")", ")", ")", "return", "date", ...
0dbbc465fafd9cb9b0f4d10e1e07fae4e15032dd
train
convert_timezone
get timezone as tz_offset
qtpylib/tools.py
def convert_timezone(date_str, tz_from, tz_to="UTC", fmt=None): """ get timezone as tz_offset """ tz_offset = datetime_to_timezone( datetime.datetime.now(), tz=tz_from).strftime('%z') tz_offset = tz_offset[:3] + ':' + tz_offset[3:] date = parse_date(str(date_str) + tz_offset) if tz_from != ...
def convert_timezone(date_str, tz_from, tz_to="UTC", fmt=None): """ get timezone as tz_offset """ tz_offset = datetime_to_timezone( datetime.datetime.now(), tz=tz_from).strftime('%z') tz_offset = tz_offset[:3] + ':' + tz_offset[3:] date = parse_date(str(date_str) + tz_offset) if tz_from != ...
[ "get", "timezone", "as", "tz_offset" ]
ranaroussi/qtpylib
python
https://github.com/ranaroussi/qtpylib/blob/0dbbc465fafd9cb9b0f4d10e1e07fae4e15032dd/qtpylib/tools.py#L487-L499
[ "def", "convert_timezone", "(", "date_str", ",", "tz_from", ",", "tz_to", "=", "\"UTC\"", ",", "fmt", "=", "None", ")", ":", "tz_offset", "=", "datetime_to_timezone", "(", "datetime", ".", "datetime", ".", "now", "(", ")", ",", "tz", "=", "tz_from", ")",...
0dbbc465fafd9cb9b0f4d10e1e07fae4e15032dd
train
set_timezone
change the timeozone to specified one without converting
qtpylib/tools.py
def set_timezone(data, tz=None, from_local=False): """ change the timeozone to specified one without converting """ # pandas object? if isinstance(data, pd.DataFrame) | isinstance(data, pd.Series): try: try: data.index = data.index.tz_convert(tz) except Except...
def set_timezone(data, tz=None, from_local=False): """ change the timeozone to specified one without converting """ # pandas object? if isinstance(data, pd.DataFrame) | isinstance(data, pd.Series): try: try: data.index = data.index.tz_convert(tz) except Except...
[ "change", "the", "timeozone", "to", "specified", "one", "without", "converting" ]
ranaroussi/qtpylib
python
https://github.com/ranaroussi/qtpylib/blob/0dbbc465fafd9cb9b0f4d10e1e07fae4e15032dd/qtpylib/tools.py#L504-L532
[ "def", "set_timezone", "(", "data", ",", "tz", "=", "None", ",", "from_local", "=", "False", ")", ":", "# pandas object?", "if", "isinstance", "(", "data", ",", "pd", ".", "DataFrame", ")", "|", "isinstance", "(", "data", ",", "pd", ".", "Series", ")",...
0dbbc465fafd9cb9b0f4d10e1e07fae4e15032dd
train
fix_timezone
set timezone for pandas
qtpylib/tools.py
def fix_timezone(df, freq, tz=None): """ set timezone for pandas """ index_name = df.index.name # fix timezone if isinstance(df.index[0], str): # timezone df exists if ("-" in df.index[0][-6:]) | ("+" in df.index[0][-6:]): df.index = pd.to_datetime(df.index, utc=False) ...
def fix_timezone(df, freq, tz=None): """ set timezone for pandas """ index_name = df.index.name # fix timezone if isinstance(df.index[0], str): # timezone df exists if ("-" in df.index[0][-6:]) | ("+" in df.index[0][-6:]): df.index = pd.to_datetime(df.index, utc=False) ...
[ "set", "timezone", "for", "pandas" ]
ranaroussi/qtpylib
python
https://github.com/ranaroussi/qtpylib/blob/0dbbc465fafd9cb9b0f4d10e1e07fae4e15032dd/qtpylib/tools.py#L537-L571
[ "def", "fix_timezone", "(", "df", ",", "freq", ",", "tz", "=", "None", ")", ":", "index_name", "=", "df", ".", "index", ".", "name", "# fix timezone", "if", "isinstance", "(", "df", ".", "index", "[", "0", "]", ",", "str", ")", ":", "# timezone df ex...
0dbbc465fafd9cb9b0f4d10e1e07fae4e15032dd
train
DataStore.record
add custom data to data store
qtpylib/tools.py
def record(self, timestamp, *args, **kwargs): """ add custom data to data store """ if self.output_file is None: return data = {'datetime': timestamp} # append all data if len(args) == 1: if isinstance(args[0], dict): data.update(dict(arg...
def record(self, timestamp, *args, **kwargs): """ add custom data to data store """ if self.output_file is None: return data = {'datetime': timestamp} # append all data if len(args) == 1: if isinstance(args[0], dict): data.update(dict(arg...
[ "add", "custom", "data", "to", "data", "store" ]
ranaroussi/qtpylib
python
https://github.com/ranaroussi/qtpylib/blob/0dbbc465fafd9cb9b0f4d10e1e07fae4e15032dd/qtpylib/tools.py#L880-L971
[ "def", "record", "(", "self", ",", "timestamp", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "if", "self", ".", "output_file", "is", "None", ":", "return", "data", "=", "{", "'datetime'", ":", "timestamp", "}", "# append all data", "if", "len",...
0dbbc465fafd9cb9b0f4d10e1e07fae4e15032dd
train
get_data_ib
Downloads historical data from Interactive Brokers :Parameters: instrument : mixed IB contract tuple / string (same as that given to strategy) start : str Backtest start date (YYYY-MM-DD [HH:MM:SS[.MS]) :Optional: resolution : str 1/5/15/30 secs, 1/2...
qtpylib/workflow.py
def get_data_ib(instrument, start, resolution="1 min", blotter=None, output_path=None): """ Downloads historical data from Interactive Brokers :Parameters: instrument : mixed IB contract tuple / string (same as that given to strategy) start : str Back...
def get_data_ib(instrument, start, resolution="1 min", blotter=None, output_path=None): """ Downloads historical data from Interactive Brokers :Parameters: instrument : mixed IB contract tuple / string (same as that given to strategy) start : str Back...
[ "Downloads", "historical", "data", "from", "Interactive", "Brokers" ]
ranaroussi/qtpylib
python
https://github.com/ranaroussi/qtpylib/blob/0dbbc465fafd9cb9b0f4d10e1e07fae4e15032dd/qtpylib/workflow.py#L61-L117
[ "def", "get_data_ib", "(", "instrument", ",", "start", ",", "resolution", "=", "\"1 min\"", ",", "blotter", "=", "None", ",", "output_path", "=", "None", ")", ":", "global", "_IB_HISTORY_DOWNLOADED", "_IB_HISTORY_DOWNLOADED", "=", "False", "# load blotter settings",...
0dbbc465fafd9cb9b0f4d10e1e07fae4e15032dd
train
prepare_data
Converts given DataFrame to a QTPyLib-compatible format and timezone :Parameters: instrument : mixed IB contract tuple / string (same as that given to strategy) data : pd.DataFrame Pandas DataDrame with that instrument's market data output_path : str Path...
qtpylib/workflow.py
def prepare_data(instrument, data, output_path=None, index=None, colsmap=None, kind="BAR", resample="1T"): """ Converts given DataFrame to a QTPyLib-compatible format and timezone :Parameters: instrument : mixed IB contract tuple / string (same as that given to strategy...
def prepare_data(instrument, data, output_path=None, index=None, colsmap=None, kind="BAR", resample="1T"): """ Converts given DataFrame to a QTPyLib-compatible format and timezone :Parameters: instrument : mixed IB contract tuple / string (same as that given to strategy...
[ "Converts", "given", "DataFrame", "to", "a", "QTPyLib", "-", "compatible", "format", "and", "timezone" ]
ranaroussi/qtpylib
python
https://github.com/ranaroussi/qtpylib/blob/0dbbc465fafd9cb9b0f4d10e1e07fae4e15032dd/qtpylib/workflow.py#L191-L308
[ "def", "prepare_data", "(", "instrument", ",", "data", ",", "output_path", "=", "None", ",", "index", "=", "None", ",", "colsmap", "=", "None", ",", "kind", "=", "\"BAR\"", ",", "resample", "=", "\"1T\"", ")", ":", "global", "_TICKS_COLSMAP", ",", "_BARS...
0dbbc465fafd9cb9b0f4d10e1e07fae4e15032dd
train
store_data
Store QTPyLib-compatible csv files in Blotter's MySQL. TWS/GW data are required for determining futures/options expiration :Parameters: df : dict Tick/Bar data :Optional: blotter : str Store MySQL server used by this Blotter (default is "auto detect") kind :...
qtpylib/workflow.py
def store_data(df, blotter=None, kind="BAR"): """ Store QTPyLib-compatible csv files in Blotter's MySQL. TWS/GW data are required for determining futures/options expiration :Parameters: df : dict Tick/Bar data :Optional: blotter : str Store MySQL server used...
def store_data(df, blotter=None, kind="BAR"): """ Store QTPyLib-compatible csv files in Blotter's MySQL. TWS/GW data are required for determining futures/options expiration :Parameters: df : dict Tick/Bar data :Optional: blotter : str Store MySQL server used...
[ "Store", "QTPyLib", "-", "compatible", "csv", "files", "in", "Blotter", "s", "MySQL", ".", "TWS", "/", "GW", "data", "are", "required", "for", "determining", "futures", "/", "options", "expiration" ]
ranaroussi/qtpylib
python
https://github.com/ranaroussi/qtpylib/blob/0dbbc465fafd9cb9b0f4d10e1e07fae4e15032dd/qtpylib/workflow.py#L313-L382
[ "def", "store_data", "(", "df", ",", "blotter", "=", "None", ",", "kind", "=", "\"BAR\"", ")", ":", "# validate columns", "valid_cols", "=", "validate_columns", "(", "df", ",", "kind", ")", "if", "not", "valid_cols", ":", "raise", "ValueError", "(", "'Inva...
0dbbc465fafd9cb9b0f4d10e1e07fae4e15032dd
train
Instrument._set_windows
be aware of default windows
qtpylib/instrument.py
def _set_windows(self, ticks, bars): """ be aware of default windows """ self.tick_window = ticks self.bar_window = bars
def _set_windows(self, ticks, bars): """ be aware of default windows """ self.tick_window = ticks self.bar_window = bars
[ "be", "aware", "of", "default", "windows" ]
ranaroussi/qtpylib
python
https://github.com/ranaroussi/qtpylib/blob/0dbbc465fafd9cb9b0f4d10e1e07fae4e15032dd/qtpylib/instrument.py#L50-L53
[ "def", "_set_windows", "(", "self", ",", "ticks", ",", "bars", ")", ":", "self", ".", "tick_window", "=", "ticks", "self", ".", "bar_window", "=", "bars" ]
0dbbc465fafd9cb9b0f4d10e1e07fae4e15032dd
train
Instrument.get_bars
Get bars for this instrument :Parameters: lookback : int Max number of bars to get (None = all available bars) as_dict : bool Return a dict or a pd.DataFrame object :Retruns: bars : pd.DataFrame / dict The bars for thi...
qtpylib/instrument.py
def get_bars(self, lookback=None, as_dict=False): """ Get bars for this instrument :Parameters: lookback : int Max number of bars to get (None = all available bars) as_dict : bool Return a dict or a pd.DataFrame object :Retruns: ...
def get_bars(self, lookback=None, as_dict=False): """ Get bars for this instrument :Parameters: lookback : int Max number of bars to get (None = all available bars) as_dict : bool Return a dict or a pd.DataFrame object :Retruns: ...
[ "Get", "bars", "for", "this", "instrument" ]
ranaroussi/qtpylib
python
https://github.com/ranaroussi/qtpylib/blob/0dbbc465fafd9cb9b0f4d10e1e07fae4e15032dd/qtpylib/instrument.py#L68-L102
[ "def", "get_bars", "(", "self", ",", "lookback", "=", "None", ",", "as_dict", "=", "False", ")", ":", "bars", "=", "self", ".", "_get_symbol_dataframe", "(", "self", ".", "parent", ".", "bars", ",", "self", ")", "# add signal history to bars", "bars", "=",...
0dbbc465fafd9cb9b0f4d10e1e07fae4e15032dd
train
Instrument.get_ticks
Get ticks for this instrument :Parameters: lookback : int Max number of ticks to get (None = all available ticks) as_dict : bool Return a dict or a pd.DataFrame object :Retruns: ticks : pd.DataFrame / dict The ticks fo...
qtpylib/instrument.py
def get_ticks(self, lookback=None, as_dict=False): """ Get ticks for this instrument :Parameters: lookback : int Max number of ticks to get (None = all available ticks) as_dict : bool Return a dict or a pd.DataFrame object :Retruns: ...
def get_ticks(self, lookback=None, as_dict=False): """ Get ticks for this instrument :Parameters: lookback : int Max number of ticks to get (None = all available ticks) as_dict : bool Return a dict or a pd.DataFrame object :Retruns: ...
[ "Get", "ticks", "for", "this", "instrument" ]
ranaroussi/qtpylib
python
https://github.com/ranaroussi/qtpylib/blob/0dbbc465fafd9cb9b0f4d10e1e07fae4e15032dd/qtpylib/instrument.py#L110-L141
[ "def", "get_ticks", "(", "self", ",", "lookback", "=", "None", ",", "as_dict", "=", "False", ")", ":", "ticks", "=", "self", ".", "_get_symbol_dataframe", "(", "self", ".", "parent", ".", "ticks", ",", "self", ")", "lookback", "=", "self", ".", "tick_w...
0dbbc465fafd9cb9b0f4d10e1e07fae4e15032dd
train
Instrument.get_price
Shortcut to self.get_ticks(lookback=1, as_dict=True)['last']
qtpylib/instrument.py
def get_price(self): """ Shortcut to self.get_ticks(lookback=1, as_dict=True)['last'] """ tick = self.get_ticks(lookback=1, as_dict=True) return None if tick is None else tick['last']
def get_price(self): """ Shortcut to self.get_ticks(lookback=1, as_dict=True)['last'] """ tick = self.get_ticks(lookback=1, as_dict=True) return None if tick is None else tick['last']
[ "Shortcut", "to", "self", ".", "get_ticks", "(", "lookback", "=", "1", "as_dict", "=", "True", ")", "[", "last", "]" ]
ranaroussi/qtpylib
python
https://github.com/ranaroussi/qtpylib/blob/0dbbc465fafd9cb9b0f4d10e1e07fae4e15032dd/qtpylib/instrument.py#L149-L152
[ "def", "get_price", "(", "self", ")", ":", "tick", "=", "self", ".", "get_ticks", "(", "lookback", "=", "1", ",", "as_dict", "=", "True", ")", "return", "None", "if", "tick", "is", "None", "else", "tick", "[", "'last'", "]" ]
0dbbc465fafd9cb9b0f4d10e1e07fae4e15032dd
train
Instrument.get_quote
Get last quote for this instrument :Retruns: quote : dict The quote for this instruments
qtpylib/instrument.py
def get_quote(self): """ Get last quote for this instrument :Retruns: quote : dict The quote for this instruments """ if self in self.parent.quotes.keys(): return self.parent.quotes[self] return None
def get_quote(self): """ Get last quote for this instrument :Retruns: quote : dict The quote for this instruments """ if self in self.parent.quotes.keys(): return self.parent.quotes[self] return None
[ "Get", "last", "quote", "for", "this", "instrument" ]
ranaroussi/qtpylib
python
https://github.com/ranaroussi/qtpylib/blob/0dbbc465fafd9cb9b0f4d10e1e07fae4e15032dd/qtpylib/instrument.py#L155-L164
[ "def", "get_quote", "(", "self", ")", ":", "if", "self", "in", "self", ".", "parent", ".", "quotes", ".", "keys", "(", ")", ":", "return", "self", ".", "parent", ".", "quotes", "[", "self", "]", "return", "None" ]
0dbbc465fafd9cb9b0f4d10e1e07fae4e15032dd
train
Instrument.get_orderbook
Get orderbook for the instrument :Retruns: orderbook : dict orderbook dict for the instrument
qtpylib/instrument.py
def get_orderbook(self): """Get orderbook for the instrument :Retruns: orderbook : dict orderbook dict for the instrument """ if self in self.parent.books.keys(): return self.parent.books[self] return { "bid": [0], "bidsize": ...
def get_orderbook(self): """Get orderbook for the instrument :Retruns: orderbook : dict orderbook dict for the instrument """ if self in self.parent.books.keys(): return self.parent.books[self] return { "bid": [0], "bidsize": ...
[ "Get", "orderbook", "for", "the", "instrument" ]
ranaroussi/qtpylib
python
https://github.com/ranaroussi/qtpylib/blob/0dbbc465fafd9cb9b0f4d10e1e07fae4e15032dd/qtpylib/instrument.py#L167-L180
[ "def", "get_orderbook", "(", "self", ")", ":", "if", "self", "in", "self", ".", "parent", ".", "books", ".", "keys", "(", ")", ":", "return", "self", ".", "parent", ".", "books", "[", "self", "]", "return", "{", "\"bid\"", ":", "[", "0", "]", ","...
0dbbc465fafd9cb9b0f4d10e1e07fae4e15032dd
train
Instrument.market_order
Shortcut for ``instrument.order(...)`` and accepts all of its `optional parameters <#qtpylib.instrument.Instrument.order>`_ :Parameters: direction : string Order Type (BUY/SELL, EXIT/FLATTEN) quantity : int Order quantity
qtpylib/instrument.py
def market_order(self, direction, quantity, **kwargs): """ Shortcut for ``instrument.order(...)`` and accepts all of its `optional parameters <#qtpylib.instrument.Instrument.order>`_ :Parameters: direction : string Order Type (BUY/SELL, EXIT/FLATTEN) quan...
def market_order(self, direction, quantity, **kwargs): """ Shortcut for ``instrument.order(...)`` and accepts all of its `optional parameters <#qtpylib.instrument.Instrument.order>`_ :Parameters: direction : string Order Type (BUY/SELL, EXIT/FLATTEN) quan...
[ "Shortcut", "for", "instrument", ".", "order", "(", "...", ")", "and", "accepts", "all", "of", "its", "optional", "parameters", "<#qtpylib", ".", "instrument", ".", "Instrument", ".", "order", ">", "_" ]
ranaroussi/qtpylib
python
https://github.com/ranaroussi/qtpylib/blob/0dbbc465fafd9cb9b0f4d10e1e07fae4e15032dd/qtpylib/instrument.py#L235-L247
[ "def", "market_order", "(", "self", ",", "direction", ",", "quantity", ",", "*", "*", "kwargs", ")", ":", "kwargs", "[", "'limit_price'", "]", "=", "0", "kwargs", "[", "'order_type'", "]", "=", "\"MARKET\"", "self", ".", "parent", ".", "order", "(", "d...
0dbbc465fafd9cb9b0f4d10e1e07fae4e15032dd
train
Instrument.limit_order
Shortcut for ``instrument.order(...)`` and accepts all of its `optional parameters <#qtpylib.instrument.Instrument.order>`_ :Parameters: direction : string Order Type (BUY/SELL, EXIT/FLATTEN) quantity : int Order quantity price : float...
qtpylib/instrument.py
def limit_order(self, direction, quantity, price, **kwargs): """ Shortcut for ``instrument.order(...)`` and accepts all of its `optional parameters <#qtpylib.instrument.Instrument.order>`_ :Parameters: direction : string Order Type (BUY/SELL, EXIT/FLATTEN) ...
def limit_order(self, direction, quantity, price, **kwargs): """ Shortcut for ``instrument.order(...)`` and accepts all of its `optional parameters <#qtpylib.instrument.Instrument.order>`_ :Parameters: direction : string Order Type (BUY/SELL, EXIT/FLATTEN) ...
[ "Shortcut", "for", "instrument", ".", "order", "(", "...", ")", "and", "accepts", "all", "of", "its", "optional", "parameters", "<#qtpylib", ".", "instrument", ".", "Instrument", ".", "order", ">", "_" ]
ranaroussi/qtpylib
python
https://github.com/ranaroussi/qtpylib/blob/0dbbc465fafd9cb9b0f4d10e1e07fae4e15032dd/qtpylib/instrument.py#L250-L264
[ "def", "limit_order", "(", "self", ",", "direction", ",", "quantity", ",", "price", ",", "*", "*", "kwargs", ")", ":", "kwargs", "[", "'limit_price'", "]", "=", "price", "kwargs", "[", "'order_type'", "]", "=", "\"LIMIT\"", "self", ".", "parent", ".", ...
0dbbc465fafd9cb9b0f4d10e1e07fae4e15032dd
train
Instrument.buy
Shortcut for ``instrument.order("BUY", ...)`` and accepts all of its `optional parameters <#qtpylib.instrument.Instrument.order>`_ :Parameters: quantity : int Order quantity
qtpylib/instrument.py
def buy(self, quantity, **kwargs): """ Shortcut for ``instrument.order("BUY", ...)`` and accepts all of its `optional parameters <#qtpylib.instrument.Instrument.order>`_ :Parameters: quantity : int Order quantity """ self.parent.order("BUY", self, qua...
def buy(self, quantity, **kwargs): """ Shortcut for ``instrument.order("BUY", ...)`` and accepts all of its `optional parameters <#qtpylib.instrument.Instrument.order>`_ :Parameters: quantity : int Order quantity """ self.parent.order("BUY", self, qua...
[ "Shortcut", "for", "instrument", ".", "order", "(", "BUY", "...", ")", "and", "accepts", "all", "of", "its", "optional", "parameters", "<#qtpylib", ".", "instrument", ".", "Instrument", ".", "order", ">", "_" ]
ranaroussi/qtpylib
python
https://github.com/ranaroussi/qtpylib/blob/0dbbc465fafd9cb9b0f4d10e1e07fae4e15032dd/qtpylib/instrument.py#L267-L275
[ "def", "buy", "(", "self", ",", "quantity", ",", "*", "*", "kwargs", ")", ":", "self", ".", "parent", ".", "order", "(", "\"BUY\"", ",", "self", ",", "quantity", "=", "quantity", ",", "*", "*", "kwargs", ")" ]
0dbbc465fafd9cb9b0f4d10e1e07fae4e15032dd
train
Instrument.buy_market
Shortcut for ``instrument.order("BUY", ...)`` and accepts all of its `optional parameters <#qtpylib.instrument.Instrument.order>`_ :Parameters: quantity : int Order quantity
qtpylib/instrument.py
def buy_market(self, quantity, **kwargs): """ Shortcut for ``instrument.order("BUY", ...)`` and accepts all of its `optional parameters <#qtpylib.instrument.Instrument.order>`_ :Parameters: quantity : int Order quantity """ kwargs['limit_price'] = 0 ...
def buy_market(self, quantity, **kwargs): """ Shortcut for ``instrument.order("BUY", ...)`` and accepts all of its `optional parameters <#qtpylib.instrument.Instrument.order>`_ :Parameters: quantity : int Order quantity """ kwargs['limit_price'] = 0 ...
[ "Shortcut", "for", "instrument", ".", "order", "(", "BUY", "...", ")", "and", "accepts", "all", "of", "its", "optional", "parameters", "<#qtpylib", ".", "instrument", ".", "Instrument", ".", "order", ">", "_" ]
ranaroussi/qtpylib
python
https://github.com/ranaroussi/qtpylib/blob/0dbbc465fafd9cb9b0f4d10e1e07fae4e15032dd/qtpylib/instrument.py#L278-L288
[ "def", "buy_market", "(", "self", ",", "quantity", ",", "*", "*", "kwargs", ")", ":", "kwargs", "[", "'limit_price'", "]", "=", "0", "kwargs", "[", "'order_type'", "]", "=", "\"MARKET\"", "self", ".", "parent", ".", "order", "(", "\"BUY\"", ",", "self"...
0dbbc465fafd9cb9b0f4d10e1e07fae4e15032dd
train
Instrument.buy_limit
Shortcut for ``instrument.order("BUY", ...)`` and accepts all of its `optional parameters <#qtpylib.instrument.Instrument.order>`_ :Parameters: quantity : int Order quantity price : float Limit price
qtpylib/instrument.py
def buy_limit(self, quantity, price, **kwargs): """ Shortcut for ``instrument.order("BUY", ...)`` and accepts all of its `optional parameters <#qtpylib.instrument.Instrument.order>`_ :Parameters: quantity : int Order quantity price : float ...
def buy_limit(self, quantity, price, **kwargs): """ Shortcut for ``instrument.order("BUY", ...)`` and accepts all of its `optional parameters <#qtpylib.instrument.Instrument.order>`_ :Parameters: quantity : int Order quantity price : float ...
[ "Shortcut", "for", "instrument", ".", "order", "(", "BUY", "...", ")", "and", "accepts", "all", "of", "its", "optional", "parameters", "<#qtpylib", ".", "instrument", ".", "Instrument", ".", "order", ">", "_" ]
ranaroussi/qtpylib
python
https://github.com/ranaroussi/qtpylib/blob/0dbbc465fafd9cb9b0f4d10e1e07fae4e15032dd/qtpylib/instrument.py#L291-L303
[ "def", "buy_limit", "(", "self", ",", "quantity", ",", "price", ",", "*", "*", "kwargs", ")", ":", "kwargs", "[", "'limit_price'", "]", "=", "price", "kwargs", "[", "'order_type'", "]", "=", "\"LIMIT\"", "self", ".", "parent", ".", "order", "(", "\"BUY...
0dbbc465fafd9cb9b0f4d10e1e07fae4e15032dd
train
Instrument.sell
Shortcut for ``instrument.order("SELL", ...)`` and accepts all of its `optional parameters <#qtpylib.instrument.Instrument.order>`_ :Parameters: quantity : int Order quantity
qtpylib/instrument.py
def sell(self, quantity, **kwargs): """ Shortcut for ``instrument.order("SELL", ...)`` and accepts all of its `optional parameters <#qtpylib.instrument.Instrument.order>`_ :Parameters: quantity : int Order quantity """ self.parent.order("SELL", self, ...
def sell(self, quantity, **kwargs): """ Shortcut for ``instrument.order("SELL", ...)`` and accepts all of its `optional parameters <#qtpylib.instrument.Instrument.order>`_ :Parameters: quantity : int Order quantity """ self.parent.order("SELL", self, ...
[ "Shortcut", "for", "instrument", ".", "order", "(", "SELL", "...", ")", "and", "accepts", "all", "of", "its", "optional", "parameters", "<#qtpylib", ".", "instrument", ".", "Instrument", ".", "order", ">", "_" ]
ranaroussi/qtpylib
python
https://github.com/ranaroussi/qtpylib/blob/0dbbc465fafd9cb9b0f4d10e1e07fae4e15032dd/qtpylib/instrument.py#L306-L314
[ "def", "sell", "(", "self", ",", "quantity", ",", "*", "*", "kwargs", ")", ":", "self", ".", "parent", ".", "order", "(", "\"SELL\"", ",", "self", ",", "quantity", "=", "quantity", ",", "*", "*", "kwargs", ")" ]
0dbbc465fafd9cb9b0f4d10e1e07fae4e15032dd
train
Instrument.sell_market
Shortcut for ``instrument.order("SELL", ...)`` and accepts all of its `optional parameters <#qtpylib.instrument.Instrument.order>`_ :Parameters: quantity : int Order quantity
qtpylib/instrument.py
def sell_market(self, quantity, **kwargs): """ Shortcut for ``instrument.order("SELL", ...)`` and accepts all of its `optional parameters <#qtpylib.instrument.Instrument.order>`_ :Parameters: quantity : int Order quantity """ kwargs['limit_price'] = 0...
def sell_market(self, quantity, **kwargs): """ Shortcut for ``instrument.order("SELL", ...)`` and accepts all of its `optional parameters <#qtpylib.instrument.Instrument.order>`_ :Parameters: quantity : int Order quantity """ kwargs['limit_price'] = 0...
[ "Shortcut", "for", "instrument", ".", "order", "(", "SELL", "...", ")", "and", "accepts", "all", "of", "its", "optional", "parameters", "<#qtpylib", ".", "instrument", ".", "Instrument", ".", "order", ">", "_" ]
ranaroussi/qtpylib
python
https://github.com/ranaroussi/qtpylib/blob/0dbbc465fafd9cb9b0f4d10e1e07fae4e15032dd/qtpylib/instrument.py#L317-L327
[ "def", "sell_market", "(", "self", ",", "quantity", ",", "*", "*", "kwargs", ")", ":", "kwargs", "[", "'limit_price'", "]", "=", "0", "kwargs", "[", "'order_type'", "]", "=", "\"MARKET\"", "self", ".", "parent", ".", "order", "(", "\"SELL\"", ",", "sel...
0dbbc465fafd9cb9b0f4d10e1e07fae4e15032dd
train
Instrument.sell_limit
Shortcut for ``instrument.order("SELL", ...)`` and accepts all of its `optional parameters <#qtpylib.instrument.Instrument.order>`_ :Parameters: quantity : int Order quantity price : float Limit price
qtpylib/instrument.py
def sell_limit(self, quantity, price, **kwargs): """ Shortcut for ``instrument.order("SELL", ...)`` and accepts all of its `optional parameters <#qtpylib.instrument.Instrument.order>`_ :Parameters: quantity : int Order quantity price : float ...
def sell_limit(self, quantity, price, **kwargs): """ Shortcut for ``instrument.order("SELL", ...)`` and accepts all of its `optional parameters <#qtpylib.instrument.Instrument.order>`_ :Parameters: quantity : int Order quantity price : float ...
[ "Shortcut", "for", "instrument", ".", "order", "(", "SELL", "...", ")", "and", "accepts", "all", "of", "its", "optional", "parameters", "<#qtpylib", ".", "instrument", ".", "Instrument", ".", "order", ">", "_" ]
ranaroussi/qtpylib
python
https://github.com/ranaroussi/qtpylib/blob/0dbbc465fafd9cb9b0f4d10e1e07fae4e15032dd/qtpylib/instrument.py#L330-L342
[ "def", "sell_limit", "(", "self", ",", "quantity", ",", "price", ",", "*", "*", "kwargs", ")", ":", "kwargs", "[", "'limit_price'", "]", "=", "price", "kwargs", "[", "'order_type'", "]", "=", "\"LIMIT\"", "self", ".", "parent", ".", "order", "(", "\"SE...
0dbbc465fafd9cb9b0f4d10e1e07fae4e15032dd
train
Instrument.get_positions
Get the positions data for the instrument :Optional: attr : string Position attribute to get (optional attributes: symbol, position, avgCost, account) :Retruns: positions : dict (positions) / float/str (attribute) positions data f...
qtpylib/instrument.py
def get_positions(self, attr=None): """Get the positions data for the instrument :Optional: attr : string Position attribute to get (optional attributes: symbol, position, avgCost, account) :Retruns: positions : dict (positions) / float/s...
def get_positions(self, attr=None): """Get the positions data for the instrument :Optional: attr : string Position attribute to get (optional attributes: symbol, position, avgCost, account) :Retruns: positions : dict (positions) / float/s...
[ "Get", "the", "positions", "data", "for", "the", "instrument" ]
ranaroussi/qtpylib
python
https://github.com/ranaroussi/qtpylib/blob/0dbbc465fafd9cb9b0f4d10e1e07fae4e15032dd/qtpylib/instrument.py#L397-L415
[ "def", "get_positions", "(", "self", ",", "attr", "=", "None", ")", ":", "pos", "=", "self", ".", "parent", ".", "get_positions", "(", "self", ")", "try", ":", "if", "attr", "is", "not", "None", ":", "attr", "=", "attr", ".", "replace", "(", "\"qua...
0dbbc465fafd9cb9b0f4d10e1e07fae4e15032dd
train
Instrument.modify_order
Modify quantity and/or limit price of an active order for the instrument :Parameters: orderId : int the order id to modify :Optional: quantity : int the required quantity of the modified order limit_price : int the new...
qtpylib/instrument.py
def modify_order(self, orderId, quantity=None, limit_price=None): """Modify quantity and/or limit price of an active order for the instrument :Parameters: orderId : int the order id to modify :Optional: quantity : int the required quantit...
def modify_order(self, orderId, quantity=None, limit_price=None): """Modify quantity and/or limit price of an active order for the instrument :Parameters: orderId : int the order id to modify :Optional: quantity : int the required quantit...
[ "Modify", "quantity", "and", "/", "or", "limit", "price", "of", "an", "active", "order", "for", "the", "instrument" ]
ranaroussi/qtpylib
python
https://github.com/ranaroussi/qtpylib/blob/0dbbc465fafd9cb9b0f4d10e1e07fae4e15032dd/qtpylib/instrument.py#L482-L495
[ "def", "modify_order", "(", "self", ",", "orderId", ",", "quantity", "=", "None", ",", "limit_price", "=", "None", ")", ":", "return", "self", ".", "parent", ".", "modify_order", "(", "self", ",", "orderId", ",", "quantity", ",", "limit_price", ")" ]
0dbbc465fafd9cb9b0f4d10e1e07fae4e15032dd
train
Instrument.modify_order_group
Modify bracket order :Parameters: orderId : int the order id to modify :Optional: entry: float new entry limit price (for unfilled limit orders only) target: float new target limit price (for unfilled limit orders only...
qtpylib/instrument.py
def modify_order_group(self, orderId, entry=None, target=None, stop=None, quantity=None): """Modify bracket order :Parameters: orderId : int the order id to modify :Optional: entry: float new entry limit price (for unfilled limit orders o...
def modify_order_group(self, orderId, entry=None, target=None, stop=None, quantity=None): """Modify bracket order :Parameters: orderId : int the order id to modify :Optional: entry: float new entry limit price (for unfilled limit orders o...
[ "Modify", "bracket", "order" ]
ranaroussi/qtpylib
python
https://github.com/ranaroussi/qtpylib/blob/0dbbc465fafd9cb9b0f4d10e1e07fae4e15032dd/qtpylib/instrument.py#L498-L517
[ "def", "modify_order_group", "(", "self", ",", "orderId", ",", "entry", "=", "None", ",", "target", "=", "None", ",", "stop", "=", "None", ",", "quantity", "=", "None", ")", ":", "return", "self", ".", "parent", ".", "modify_order_group", "(", "self", ...
0dbbc465fafd9cb9b0f4d10e1e07fae4e15032dd
train
Instrument.move_stoploss
Modify stop order. Auto-discover **orderId** and **quantity** and invokes ``self.modify_order(...)``. :Parameters: stoploss : float the new stoploss limit price
qtpylib/instrument.py
def move_stoploss(self, stoploss): """Modify stop order. Auto-discover **orderId** and **quantity** and invokes ``self.modify_order(...)``. :Parameters: stoploss : float the new stoploss limit price """ stopOrder = self.get_active_order(order_type="S...
def move_stoploss(self, stoploss): """Modify stop order. Auto-discover **orderId** and **quantity** and invokes ``self.modify_order(...)``. :Parameters: stoploss : float the new stoploss limit price """ stopOrder = self.get_active_order(order_type="S...
[ "Modify", "stop", "order", ".", "Auto", "-", "discover", "**", "orderId", "**", "and", "**", "quantity", "**", "and", "invokes", "self", ".", "modify_order", "(", "...", ")", "." ]
ranaroussi/qtpylib
python
https://github.com/ranaroussi/qtpylib/blob/0dbbc465fafd9cb9b0f4d10e1e07fae4e15032dd/qtpylib/instrument.py#L520-L533
[ "def", "move_stoploss", "(", "self", ",", "stoploss", ")", ":", "stopOrder", "=", "self", ".", "get_active_order", "(", "order_type", "=", "\"STOP\"", ")", "if", "stopOrder", "is", "not", "None", "and", "\"orderId\"", "in", "stopOrder", ".", "keys", "(", "...
0dbbc465fafd9cb9b0f4d10e1e07fae4e15032dd
train
Instrument.get_margin_requirement
Get margin requirements for intrument (futures only) :Retruns: margin : dict margin requirements for instrument (all values are ``None`` for non-futures instruments)
qtpylib/instrument.py
def get_margin_requirement(self): """ Get margin requirements for intrument (futures only) :Retruns: margin : dict margin requirements for instrument (all values are ``None`` for non-futures instruments) """ contract = self.get_contract() ...
def get_margin_requirement(self): """ Get margin requirements for intrument (futures only) :Retruns: margin : dict margin requirements for instrument (all values are ``None`` for non-futures instruments) """ contract = self.get_contract() ...
[ "Get", "margin", "requirements", "for", "intrument", "(", "futures", "only", ")" ]
ranaroussi/qtpylib
python
https://github.com/ranaroussi/qtpylib/blob/0dbbc465fafd9cb9b0f4d10e1e07fae4e15032dd/qtpylib/instrument.py#L536-L560
[ "def", "get_margin_requirement", "(", "self", ")", ":", "contract", "=", "self", ".", "get_contract", "(", ")", "if", "contract", ".", "m_secType", "==", "\"FUT\"", ":", "return", "futures", ".", "get_ib_futures", "(", "contract", ".", "m_symbol", ",", "cont...
0dbbc465fafd9cb9b0f4d10e1e07fae4e15032dd
train
Instrument.get_max_contracts_allowed
Get maximum contracts allowed to trade baed on required margin per contract and current account balance (futures only) :Parameters: overnight : bool Calculate based on Overnight margin (set to ``False`` to use Intraday margin req.) :Retruns: cont...
qtpylib/instrument.py
def get_max_contracts_allowed(self, overnight=True): """ Get maximum contracts allowed to trade baed on required margin per contract and current account balance (futures only) :Parameters: overnight : bool Calculate based on Overnight margin (set to ``False``...
def get_max_contracts_allowed(self, overnight=True): """ Get maximum contracts allowed to trade baed on required margin per contract and current account balance (futures only) :Parameters: overnight : bool Calculate based on Overnight margin (set to ``False``...
[ "Get", "maximum", "contracts", "allowed", "to", "trade", "baed", "on", "required", "margin", "per", "contract", "and", "current", "account", "balance", "(", "futures", "only", ")" ]
ranaroussi/qtpylib
python
https://github.com/ranaroussi/qtpylib/blob/0dbbc465fafd9cb9b0f4d10e1e07fae4e15032dd/qtpylib/instrument.py#L563-L583
[ "def", "get_max_contracts_allowed", "(", "self", ",", "overnight", "=", "True", ")", ":", "timeframe", "=", "'overnight_initial'", "if", "overnight", "else", "'intraday_initial'", "req_margin", "=", "self", ".", "get_margin_requirement", "(", ")", "if", "req_margin"...
0dbbc465fafd9cb9b0f4d10e1e07fae4e15032dd
train
Instrument.pnl_in_range
Check if instrument pnl is within given range :Parameters: min_pnl : flaot minimum session pnl (in USD / IB currency) max_pnl : flaot maximum session pnl (in USD / IB currency) :Retruns: status : bool if pnl is within ...
qtpylib/instrument.py
def pnl_in_range(self, min_pnl, max_pnl): """ Check if instrument pnl is within given range :Parameters: min_pnl : flaot minimum session pnl (in USD / IB currency) max_pnl : flaot maximum session pnl (in USD / IB currency) :Retruns: ...
def pnl_in_range(self, min_pnl, max_pnl): """ Check if instrument pnl is within given range :Parameters: min_pnl : flaot minimum session pnl (in USD / IB currency) max_pnl : flaot maximum session pnl (in USD / IB currency) :Retruns: ...
[ "Check", "if", "instrument", "pnl", "is", "within", "given", "range" ]
ranaroussi/qtpylib
python
https://github.com/ranaroussi/qtpylib/blob/0dbbc465fafd9cb9b0f4d10e1e07fae4e15032dd/qtpylib/instrument.py#L601-L615
[ "def", "pnl_in_range", "(", "self", ",", "min_pnl", ",", "max_pnl", ")", ":", "portfolio", "=", "self", ".", "get_portfolio", "(", ")", "return", "-", "abs", "(", "min_pnl", ")", "<", "portfolio", "[", "'totalPNL'", "]", "<", "abs", "(", "max_pnl", ")"...
0dbbc465fafd9cb9b0f4d10e1e07fae4e15032dd
train
parse_intf_section
Parse a single entry from show interfaces output. Different cases: mgmt0 is up admin state is up Ethernet2/1 is up admin state is up, Dedicated Interface Vlan1 is down (Administratively down), line protocol is down, autostate enabled Ethernet154/1/48 is up (with no 'admin state')
napalm/nxos_ssh/nxos_ssh.py
def parse_intf_section(interface): """Parse a single entry from show interfaces output. Different cases: mgmt0 is up admin state is up Ethernet2/1 is up admin state is up, Dedicated Interface Vlan1 is down (Administratively down), line protocol is down, autostate enabled Ethernet154/...
def parse_intf_section(interface): """Parse a single entry from show interfaces output. Different cases: mgmt0 is up admin state is up Ethernet2/1 is up admin state is up, Dedicated Interface Vlan1 is down (Administratively down), line protocol is down, autostate enabled Ethernet154/...
[ "Parse", "a", "single", "entry", "from", "show", "interfaces", "output", "." ]
napalm-automation/napalm
python
https://github.com/napalm-automation/napalm/blob/c11ae8bb5ce395698704a0051cdf8d144fbb150d/napalm/nxos_ssh/nxos_ssh.py#L78-L201
[ "def", "parse_intf_section", "(", "interface", ")", ":", "interface", "=", "interface", ".", "strip", "(", ")", "re_protocol", "=", "(", "r\"^(?P<intf_name>\\S+?)\\s+is\\s+(?P<status>.+?)\"", "r\",\\s+line\\s+protocol\\s+is\\s+(?P<protocol>\\S+).*$\"", ")", "re_intf_name_state"...
c11ae8bb5ce395698704a0051cdf8d144fbb150d
train
convert_hhmmss
Convert hh:mm:ss to seconds.
napalm/nxos_ssh/nxos_ssh.py
def convert_hhmmss(hhmmss): """Convert hh:mm:ss to seconds.""" fields = hhmmss.split(":") if len(fields) != 3: raise ValueError("Received invalid HH:MM:SS data: {}".format(hhmmss)) fields = [int(x) for x in fields] hours, minutes, seconds = fields return (hours * 3600) + (minutes * 60) +...
def convert_hhmmss(hhmmss): """Convert hh:mm:ss to seconds.""" fields = hhmmss.split(":") if len(fields) != 3: raise ValueError("Received invalid HH:MM:SS data: {}".format(hhmmss)) fields = [int(x) for x in fields] hours, minutes, seconds = fields return (hours * 3600) + (minutes * 60) +...
[ "Convert", "hh", ":", "mm", ":", "ss", "to", "seconds", "." ]
napalm-automation/napalm
python
https://github.com/napalm-automation/napalm/blob/c11ae8bb5ce395698704a0051cdf8d144fbb150d/napalm/nxos_ssh/nxos_ssh.py#L204-L211
[ "def", "convert_hhmmss", "(", "hhmmss", ")", ":", "fields", "=", "hhmmss", ".", "split", "(", "\":\"", ")", "if", "len", "(", "fields", ")", "!=", "3", ":", "raise", "ValueError", "(", "\"Received invalid HH:MM:SS data: {}\"", ".", "format", "(", "hhmmss", ...
c11ae8bb5ce395698704a0051cdf8d144fbb150d
train
bgp_normalize_table_data
The 'show bgp all summary vrf all' table can have entries that wrap multiple lines. 2001:db8:4:701::2 4 65535 163664 163693 145 0 0 3w2d 3 2001:db8:e0:dd::1 4 10 327491 327278 145 0 0 3w1d 4 Normalize this so the line wrap doesn't exit.
napalm/nxos_ssh/nxos_ssh.py
def bgp_normalize_table_data(bgp_table): """The 'show bgp all summary vrf all' table can have entries that wrap multiple lines. 2001:db8:4:701::2 4 65535 163664 163693 145 0 0 3w2d 3 2001:db8:e0:dd::1 4 10 327491 327278 145 0 0 3w1d 4 ...
def bgp_normalize_table_data(bgp_table): """The 'show bgp all summary vrf all' table can have entries that wrap multiple lines. 2001:db8:4:701::2 4 65535 163664 163693 145 0 0 3w2d 3 2001:db8:e0:dd::1 4 10 327491 327278 145 0 0 3w1d 4 ...
[ "The", "show", "bgp", "all", "summary", "vrf", "all", "table", "can", "have", "entries", "that", "wrap", "multiple", "lines", "." ]
napalm-automation/napalm
python
https://github.com/napalm-automation/napalm/blob/c11ae8bb5ce395698704a0051cdf8d144fbb150d/napalm/nxos_ssh/nxos_ssh.py#L263-L276
[ "def", "bgp_normalize_table_data", "(", "bgp_table", ")", ":", "bgp_table", "=", "bgp_table", ".", "strip", "(", ")", "bgp_multiline_pattern", "=", "r\"({})\\s*\\n\"", ".", "format", "(", "IPV4_OR_IPV6_REGEX", ")", "# Strip out the newline", "return", "re", ".", "su...
c11ae8bb5ce395698704a0051cdf8d144fbb150d
train
bgp_table_parser
Generator that parses a line of bgp summary table and returns a dict compatible with NAPALM Example line: 10.2.1.14 4 10 472516 472238 361 0 0 3w1d 9
napalm/nxos_ssh/nxos_ssh.py
def bgp_table_parser(bgp_table): """Generator that parses a line of bgp summary table and returns a dict compatible with NAPALM Example line: 10.2.1.14 4 10 472516 472238 361 0 0 3w1d 9 """ bgp_table = bgp_table.strip() for bgp_entry in bgp_table.splitlines(): ...
def bgp_table_parser(bgp_table): """Generator that parses a line of bgp summary table and returns a dict compatible with NAPALM Example line: 10.2.1.14 4 10 472516 472238 361 0 0 3w1d 9 """ bgp_table = bgp_table.strip() for bgp_entry in bgp_table.splitlines(): ...
[ "Generator", "that", "parses", "a", "line", "of", "bgp", "summary", "table", "and", "returns", "a", "dict", "compatible", "with", "NAPALM" ]
napalm-automation/napalm
python
https://github.com/napalm-automation/napalm/blob/c11ae8bb5ce395698704a0051cdf8d144fbb150d/napalm/nxos_ssh/nxos_ssh.py#L279-L347
[ "def", "bgp_table_parser", "(", "bgp_table", ")", ":", "bgp_table", "=", "bgp_table", ".", "strip", "(", ")", "for", "bgp_entry", "in", "bgp_table", ".", "splitlines", "(", ")", ":", "bgp_table_fields", "=", "bgp_entry", ".", "split", "(", ")", "try", ":",...
c11ae8bb5ce395698704a0051cdf8d144fbb150d
train
bgp_summary_parser
Parse 'show bgp all summary vrf' output information from NX-OS devices.
napalm/nxos_ssh/nxos_ssh.py
def bgp_summary_parser(bgp_summary): """Parse 'show bgp all summary vrf' output information from NX-OS devices.""" bgp_summary_dict = {} # Check for BGP summary information lines that have no data if len(bgp_summary.strip().splitlines()) <= 1: return {} allowed_afi = ["ipv4", "ipv6", "l2vp...
def bgp_summary_parser(bgp_summary): """Parse 'show bgp all summary vrf' output information from NX-OS devices.""" bgp_summary_dict = {} # Check for BGP summary information lines that have no data if len(bgp_summary.strip().splitlines()) <= 1: return {} allowed_afi = ["ipv4", "ipv6", "l2vp...
[ "Parse", "show", "bgp", "all", "summary", "vrf", "output", "information", "from", "NX", "-", "OS", "devices", "." ]
napalm-automation/napalm
python
https://github.com/napalm-automation/napalm/blob/c11ae8bb5ce395698704a0051cdf8d144fbb150d/napalm/nxos_ssh/nxos_ssh.py#L350-L426
[ "def", "bgp_summary_parser", "(", "bgp_summary", ")", ":", "bgp_summary_dict", "=", "{", "}", "# Check for BGP summary information lines that have no data", "if", "len", "(", "bgp_summary", ".", "strip", "(", ")", ".", "splitlines", "(", ")", ")", "<=", "1", ":", ...
c11ae8bb5ce395698704a0051cdf8d144fbb150d
train
NXOSSSHDriver._send_command_list
Wrapper for Netmiko's send_command method (for list of commands.
napalm/nxos_ssh/nxos_ssh.py
def _send_command_list(self, commands): """Wrapper for Netmiko's send_command method (for list of commands.""" output = "" for command in commands: output += self.device.send_command( command, strip_prompt=False, strip_command=False ) return output
def _send_command_list(self, commands): """Wrapper for Netmiko's send_command method (for list of commands.""" output = "" for command in commands: output += self.device.send_command( command, strip_prompt=False, strip_command=False ) return output
[ "Wrapper", "for", "Netmiko", "s", "send_command", "method", "(", "for", "list", "of", "commands", "." ]
napalm-automation/napalm
python
https://github.com/napalm-automation/napalm/blob/c11ae8bb5ce395698704a0051cdf8d144fbb150d/napalm/nxos_ssh/nxos_ssh.py#L452-L459
[ "def", "_send_command_list", "(", "self", ",", "commands", ")", ":", "output", "=", "\"\"", "for", "command", "in", "commands", ":", "output", "+=", "self", ".", "device", ".", "send_command", "(", "command", ",", "strip_prompt", "=", "False", ",", "strip_...
c11ae8bb5ce395698704a0051cdf8d144fbb150d
train
NXOSSSHDriver.parse_uptime
Extract the uptime string from the given Cisco IOS Device. Return the uptime in seconds as an integer
napalm/nxos_ssh/nxos_ssh.py
def parse_uptime(uptime_str): """ Extract the uptime string from the given Cisco IOS Device. Return the uptime in seconds as an integer """ # Initialize to zero (years, weeks, days, hours, minutes) = (0, 0, 0, 0, 0) uptime_str = uptime_str.strip() time_li...
def parse_uptime(uptime_str): """ Extract the uptime string from the given Cisco IOS Device. Return the uptime in seconds as an integer """ # Initialize to zero (years, weeks, days, hours, minutes) = (0, 0, 0, 0, 0) uptime_str = uptime_str.strip() time_li...
[ "Extract", "the", "uptime", "string", "from", "the", "given", "Cisco", "IOS", "Device", ".", "Return", "the", "uptime", "in", "seconds", "as", "an", "integer" ]
napalm-automation/napalm
python
https://github.com/napalm-automation/napalm/blob/c11ae8bb5ce395698704a0051cdf8d144fbb150d/napalm/nxos_ssh/nxos_ssh.py#L467-L499
[ "def", "parse_uptime", "(", "uptime_str", ")", ":", "# Initialize to zero", "(", "years", ",", "weeks", ",", "days", ",", "hours", ",", "minutes", ")", "=", "(", "0", ",", "0", ",", "0", ",", "0", ",", "0", ")", "uptime_str", "=", "uptime_str", ".", ...
c11ae8bb5ce395698704a0051cdf8d144fbb150d
train
NXOSSSHDriver.is_alive
Returns a flag with the state of the SSH connection.
napalm/nxos_ssh/nxos_ssh.py
def is_alive(self): """Returns a flag with the state of the SSH connection.""" null = chr(0) try: if self.device is None: return {"is_alive": False} else: # Try sending ASCII null byte to maintain the connection alive self._...
def is_alive(self): """Returns a flag with the state of the SSH connection.""" null = chr(0) try: if self.device is None: return {"is_alive": False} else: # Try sending ASCII null byte to maintain the connection alive self._...
[ "Returns", "a", "flag", "with", "the", "state", "of", "the", "SSH", "connection", "." ]
napalm-automation/napalm
python
https://github.com/napalm-automation/napalm/blob/c11ae8bb5ce395698704a0051cdf8d144fbb150d/napalm/nxos_ssh/nxos_ssh.py#L501-L514
[ "def", "is_alive", "(", "self", ")", ":", "null", "=", "chr", "(", "0", ")", "try", ":", "if", "self", ".", "device", "is", "None", ":", "return", "{", "\"is_alive\"", ":", "False", "}", "else", ":", "# Try sending ASCII null byte to maintain the connection ...
c11ae8bb5ce395698704a0051cdf8d144fbb150d
train
NXOSSSHDriver.get_facts
Return a set of facts from the devices.
napalm/nxos_ssh/nxos_ssh.py
def get_facts(self): """Return a set of facts from the devices.""" # default values. vendor = "Cisco" uptime = -1 serial_number, fqdn, os_version, hostname, domain_name, model = ("",) * 6 # obtain output from device show_ver = self._send_command("show version") ...
def get_facts(self): """Return a set of facts from the devices.""" # default values. vendor = "Cisco" uptime = -1 serial_number, fqdn, os_version, hostname, domain_name, model = ("",) * 6 # obtain output from device show_ver = self._send_command("show version") ...
[ "Return", "a", "set", "of", "facts", "from", "the", "devices", "." ]
napalm-automation/napalm
python
https://github.com/napalm-automation/napalm/blob/c11ae8bb5ce395698704a0051cdf8d144fbb150d/napalm/nxos_ssh/nxos_ssh.py#L563-L639
[ "def", "get_facts", "(", "self", ")", ":", "# default values.", "vendor", "=", "\"Cisco\"", "uptime", "=", "-", "1", "serial_number", ",", "fqdn", ",", "os_version", ",", "hostname", ",", "domain_name", ",", "model", "=", "(", "\"\"", ",", ")", "*", "6",...
c11ae8bb5ce395698704a0051cdf8d144fbb150d
train
NXOSSSHDriver.get_interfaces
Get interface details. last_flapped is not implemented Example Output: { u'Vlan1': { 'description': u'', 'is_enabled': True, 'is_up': True, 'last_flapped': -1.0, 'mac_address': u'a493.4cc1.67a7', ...
napalm/nxos_ssh/nxos_ssh.py
def get_interfaces(self): """ Get interface details. last_flapped is not implemented Example Output: { u'Vlan1': { 'description': u'', 'is_enabled': True, 'is_up': True, 'last_flapped': -1.0, ...
def get_interfaces(self): """ Get interface details. last_flapped is not implemented Example Output: { u'Vlan1': { 'description': u'', 'is_enabled': True, 'is_up': True, 'last_flapped': -1.0, ...
[ "Get", "interface", "details", "." ]
napalm-automation/napalm
python
https://github.com/napalm-automation/napalm/blob/c11ae8bb5ce395698704a0051cdf8d144fbb150d/napalm/nxos_ssh/nxos_ssh.py#L641-L707
[ "def", "get_interfaces", "(", "self", ")", ":", "interfaces", "=", "{", "}", "command", "=", "\"show interface\"", "output", "=", "self", ".", "_send_command", "(", "command", ")", "if", "not", "output", ":", "return", "{", "}", "# Break output into per-interf...
c11ae8bb5ce395698704a0051cdf8d144fbb150d
train
NXOSSSHDriver.get_bgp_neighbors
BGP neighbor information. Supports VRFs and IPv4 and IPv6 AFIs { "global": { "router_id": "1.1.1.103", "peers": { "10.99.99.2": { "is_enabled": true, "uptime": -1, "remote_as": 22, ...
napalm/nxos_ssh/nxos_ssh.py
def get_bgp_neighbors(self): """BGP neighbor information. Supports VRFs and IPv4 and IPv6 AFIs { "global": { "router_id": "1.1.1.103", "peers": { "10.99.99.2": { "is_enabled": true, "uptime": -1, ...
def get_bgp_neighbors(self): """BGP neighbor information. Supports VRFs and IPv4 and IPv6 AFIs { "global": { "router_id": "1.1.1.103", "peers": { "10.99.99.2": { "is_enabled": true, "uptime": -1, ...
[ "BGP", "neighbor", "information", "." ]
napalm-automation/napalm
python
https://github.com/napalm-automation/napalm/blob/c11ae8bb5ce395698704a0051cdf8d144fbb150d/napalm/nxos_ssh/nxos_ssh.py#L709-L754
[ "def", "get_bgp_neighbors", "(", "self", ")", ":", "bgp_dict", "=", "{", "}", "# get summary output from device", "cmd_bgp_all_sum", "=", "\"show bgp all summary vrf all\"", "bgp_summary_output", "=", "self", ".", "_send_command", "(", "cmd_bgp_all_sum", ")", ".", "stri...
c11ae8bb5ce395698704a0051cdf8d144fbb150d
train
NXOSSSHDriver.get_environment
Get environment facts. power and fan are currently not implemented cpu is using 1-minute average
napalm/nxos_ssh/nxos_ssh.py
def get_environment(self): """ Get environment facts. power and fan are currently not implemented cpu is using 1-minute average """ environment = {} # sys_resources contains cpu and mem output sys_resources = self._send_command("show system resources") ...
def get_environment(self): """ Get environment facts. power and fan are currently not implemented cpu is using 1-minute average """ environment = {} # sys_resources contains cpu and mem output sys_resources = self._send_command("show system resources") ...
[ "Get", "environment", "facts", "." ]
napalm-automation/napalm
python
https://github.com/napalm-automation/napalm/blob/c11ae8bb5ce395698704a0051cdf8d144fbb150d/napalm/nxos_ssh/nxos_ssh.py#L766-L837
[ "def", "get_environment", "(", "self", ")", ":", "environment", "=", "{", "}", "# sys_resources contains cpu and mem output", "sys_resources", "=", "self", ".", "_send_command", "(", "\"show system resources\"", ")", "temp_cmd", "=", "\"show environment temperature\"", "#...
c11ae8bb5ce395698704a0051cdf8d144fbb150d
train
NXOSSSHDriver.get_interfaces_ip
Get interface IP details. Returns a dictionary of dictionaries. Sample output: { "Ethernet2/3": { "ipv4": { "4.4.4.4": { "prefix_length": 16 } }, "ipv6": { "20...
napalm/nxos_ssh/nxos_ssh.py
def get_interfaces_ip(self): """ Get interface IP details. Returns a dictionary of dictionaries. Sample output: { "Ethernet2/3": { "ipv4": { "4.4.4.4": { "prefix_length": 16 } }, ...
def get_interfaces_ip(self): """ Get interface IP details. Returns a dictionary of dictionaries. Sample output: { "Ethernet2/3": { "ipv4": { "4.4.4.4": { "prefix_length": 16 } }, ...
[ "Get", "interface", "IP", "details", ".", "Returns", "a", "dictionary", "of", "dictionaries", "." ]
napalm-automation/napalm
python
https://github.com/napalm-automation/napalm/blob/c11ae8bb5ce395698704a0051cdf8d144fbb150d/napalm/nxos_ssh/nxos_ssh.py#L934-L1024
[ "def", "get_interfaces_ip", "(", "self", ")", ":", "interfaces_ip", "=", "{", "}", "ipv4_command", "=", "\"show ip interface vrf all\"", "ipv6_command", "=", "\"show ipv6 interface vrf all\"", "output_v4", "=", "self", ".", "_send_command", "(", "ipv4_command", ")", "...
c11ae8bb5ce395698704a0051cdf8d144fbb150d
train
NXOSSSHDriver.get_mac_address_table
Returns a lists of dictionaries. Each dictionary represents an entry in the MAC Address Table, having the following keys * mac (string) * interface (string) * vlan (int) * active (boolean) * static (boolean) * moves (int) * last...
napalm/nxos_ssh/nxos_ssh.py
def get_mac_address_table(self): """ Returns a lists of dictionaries. Each dictionary represents an entry in the MAC Address Table, having the following keys * mac (string) * interface (string) * vlan (int) * active (boolean) * static (...
def get_mac_address_table(self): """ Returns a lists of dictionaries. Each dictionary represents an entry in the MAC Address Table, having the following keys * mac (string) * interface (string) * vlan (int) * active (boolean) * static (...
[ "Returns", "a", "lists", "of", "dictionaries", ".", "Each", "dictionary", "represents", "an", "entry", "in", "the", "MAC", "Address", "Table", "having", "the", "following", "keys", "*", "mac", "(", "string", ")", "*", "interface", "(", "string", ")", "*", ...
napalm-automation/napalm
python
https://github.com/napalm-automation/napalm/blob/c11ae8bb5ce395698704a0051cdf8d144fbb150d/napalm/nxos_ssh/nxos_ssh.py#L1026-L1162
[ "def", "get_mac_address_table", "(", "self", ")", ":", "# The '*' is stripped out later", "RE_MACTABLE_FORMAT1", "=", "r\"^\\s+{}\\s+{}\\s+\\S+\\s+\\S+\\s+\\S+\\s+\\S+\\s+\\S+\"", ".", "format", "(", "VLAN_REGEX", ",", "MAC_REGEX", ")", "RE_MACTABLE_FORMAT2", "=", "r\"^\\s+{}\...
c11ae8bb5ce395698704a0051cdf8d144fbb150d