text
stringlengths
81
112k
Add a group to the inventory after initialization def add_group(self, name: str, **kwargs) -> None: """ Add a group to the inventory after initialization """ group = { name: deserializer.inventory.InventoryElement.deserialize_group( name=name, defaults=self.d...
Returns serialized dictionary of defaults from inventory def get_defaults_dict(self) -> Dict: """ Returns serialized dictionary of defaults from inventory """ return deserializer.inventory.Defaults.serialize(self.defaults).dict()
Returns serialized dictionary of groups from inventory def get_groups_dict(self) -> Dict: """ Returns serialized dictionary of groups from inventory """ return { k: deserializer.inventory.InventoryElement.serialize(v).dict() for k, v in self.groups.items() ...
Returns serialized dictionary of hosts from inventory def get_hosts_dict(self) -> Dict: """ Returns serialized dictionary of hosts from inventory """ return { k: deserializer.inventory.InventoryElement.serialize(v).dict() for k, v in self.hosts.items() }
Transfer files from/to the device using sftp protocol Example:: nornir.run(files.sftp, action="put", src="README.md", dst="/tmp/README.md") Arguments: dry_run: Whether to apply changes or not src: source file dst: des...
Renders contants of a file with jinja2. All the host data is available in the template Arguments: template: filename path: path to dir with templates jinja_filters: jinja filters to enable. Defaults to nornir.config.jinja2.filters **kwargs: additional data to pass to the template ...
This is a convenience task that uses `requests <http://docs.python-requests.org/en/master/>`_ to interact with an HTTP server. Arguments: method: HTTP method to call url: URL to connect to raise_for_status: Whether to call `raise_for_status <http://docs.python-requests.org/e...
Execute Netmiko send_config_set method (or send_config_from_file) Arguments: config_commands: Commands to configure on the remote network device. config_file: File to read configuration commands from. kwargs: Additional arguments to pass to method. Returns: Result object with t...
Loads configuration into a network devices using napalm Arguments: dry_run: Whether to apply changes or not filename: filename containing the configuration to load into the device configuration: configuration to load into the device replace: whether to replace or merge the configura...
Loads a json file. Arguments: file: path to the file containing the json file to load Examples: Simple example with ``ordered_dict``:: > nr.run(task=load_json, file="mydata.json") file: path to the file containing the json file to load Returns: ...
Helper function to print a title. def print_title(title: str) -> None: """ Helper function to print a title. """ msg = "**** {} ".format(title) print("{}{}{}{}".format(Style.BRIGHT, Fore.GREEN, msg, "*" * (80 - len(msg))))
Prints the :obj:`nornir.core.task.Result` from a previous task to screen Arguments: result: from a previous task host: # TODO vars: Which attributes you want to print failed: if ``True`` assume the task failed severity_level: Print only errors with this severity level or hig...
Executes a command locally Arguments: command: 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.core.exceptions...
Execute Netmiko file_transfer method Arguments: source_file: Source file. dest_file: Destination file. kwargs: Additional arguments to pass to file_transfer Returns: Result object with the following attributes set: * result (``bool``): file exists and MD5 is valid ...
Run commands on remote devices using napalm Arguments: commands: commands to execute Returns: Result object with the following attributes set: * result (``dict``): result of the commands execution def napalm_cli(task: Task, commands: List[str]) -> Result: """ Run commands on...
See :py:meth:`nornir.core.inventory.Inventory.filter` Returns: :obj:`Nornir`: A new object with same configuration as ``self`` but filtered inventory. def filter(self, *args, **kwargs): """ See :py:meth:`nornir.core.inventory.Inventory.filter` Returns: :obj:`No...
Run task over all the hosts in the inventory. Arguments: task (``callable``): function or callable that will be run against each device in the inventory num_workers(``int``): Override for how many hosts to run in paralell for this task raise_on_error (``bool``)...
Exposes some of the Gitlab API functionality for operations on files in a Gitlab repository. Example: nornir.run(files.gitlab, action="create", url="https://gitlab.localhost.com", token="ABCD1234", repository="test", ...
Dummy task that echoes the data passed to it. Useful in grouped_tasks to debug data passed to tasks. Arguments: ``**kwargs``: Any <key,value> pair you want Returns: Result object with the following attributes set: * result (``dict``): ``**kwargs`` passed to the task def echo_dat...
Hosts that failed to complete the task def failed_hosts(self) -> Dict[str, "MultiResult"]: """ Hosts that failed to complete the task """ return {k: v for k, v in self.result.items() if v.failed}
Renders a string with jinja2. All the host data is available in the template Arguments: template (string): template string jinja_filters (dict): jinja filters to enable. Defaults to nornir.config.jinja2.filters **kwargs: additional data to pass to the template Returns: Result o...
Create documentation for configuration parameters. def build_configuration_parameters(app): """Create documentation for configuration parameters.""" env = Environment(loader=FileSystemLoader("{0}/_data_templates".format(BASEPATH))) template_file = env.get_template("configuration-parameters.j2") data = ...
Map methods to states of the documentation build. def setup(app): """Map methods to states of the documentation build.""" app.connect("builder-inited", build_configuration_parameters) app.connect("autodoc-skip-member", skip_slots) app.add_stylesheet("css/custom.css")
Loads a yaml file. Arguments: file: path to the file containing the yaml file to load Examples: Simple example with ``ordered_dict``:: > nr.run(task=load_yaml, file="mydata.yaml") Returns: Result object with the following attributes set: ...
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...
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 ...
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:...
Connect to the device and populate the attribute :attr:`connection` with the underlying connection def open( self, hostname: Optional[str], username: Optional[str], password: Optional[str], port: Optional[int], platform: Optional[str], extras: Optional[Di...
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...
Deregisters a registered connection plugin by its name Args: name: name of the connection plugin to deregister Raises: :obj:`nornir.core.exceptions.ConnectionPluginNotRegistered` def deregister(cls, name: str) -> None: """Deregisters a registered connection plugin by i...
Fetches the connection plugin by name if already registered Args: name: name of the connection plugin Raises: :obj:`nornir.core.exceptions.ConnectionPluginNotRegistered` def get_plugin(cls, name: str) -> Type[ConnectionPlugin]: """Fetches the connection plugin by name ...
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...
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...
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. def load_cli_args(self): """ Parse command line arguments and return only the non-default ones :Retruns: dict a dict of a...
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. def run(self): """Starts the reporting module Makes the dashboard web app available via localhost:port, and exposes ...
add instruments after initialization 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) ...
add contracts to groups 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) sel...
get group by child symbol 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), ...
constructs trade info from order data 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"] ...
cancel child orders when parent is gone 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.cancelOrd...
expires pending orders 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"]...
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")`` ...
Start the recurring task. 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 sel...
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 def load_...
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 ...
Starts the blotter Connects to the TWS/GW, processes and logs market data, and broadcast it over TCP via ZeroMQ (which algo subscribe to) def run(self): """Starts the blotter Connects to the TWS/GW, processes and logs market data, and broadcast it over TCP via ZeroMQ (which al...
fix out-of-sequence ticks/bars 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 d...
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...
remove previous globex day from df 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 in...
Internal bar strength 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)
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 ] 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...
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 ] 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 ...
compute the n period relative strength indicator 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 = -see...
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 def macd(series, fast=3, slow=10, smooth=16): """ compute the MACD (Moving Average Convergence/Divergence) using a fast and slow expo...
compute rate of change 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 commodity channel index 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 the n period relative strength indicator http://excelta.blogspot.co.il/2013/09/stochastic-oscillator-technical.html 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 ...
John Ehlers' Zero lag (exponential) moving average https://en.wikipedia.org/wiki/Zero_lag_exponential_moving_average 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 ""...
get zscore of price 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)
Price Volume Trend def pvt(bars): """ Price Volume Trend """ trend = ((bars['close'] - bars['close'].shift(1)) / bars['close'].shift(1)) * bars['volume'] return trend.cumsum()
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. def run(self): """Starts the algo Connects to the Blotter, processes market data and passes tick data to the ``on_tic...
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[...
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...
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...
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...
non threaded bar handler (called by threaded _tick_handler) 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_ba...
Initilize signal history 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....
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 def multi_shift(df, window): """ get last N rows RELATIVE to another row in pandas http://stackoverflow.com/questions/25724056/how-to-ge...
checks if a string is a number (int/float) 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
convert datatypes into Decimals 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
create ib contract tuple 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", "SMAR...
change mod to writeable 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
converts df to dict and adds a datetime field if df is datetime 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]
Get a datetime object or a epoch timestamp and return an IB-compatible durationStr for reqHistoricalData() 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() ...
convert numpy's datetime64 to datetime 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)
round to closest resolution 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)
get past date based on currect date 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) ex...
get the most recent business 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() >...
check if day is month's 3rd friday 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 after month's 3rd friday 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=...
utility to get the machine's timezone 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....
convert naive datetime to timezone-aware datetime 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))
get timezone as tz_offset 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...
change the timeozone to specified one without converting 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.i...
set timezone for pandas 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(d...
add custom data to data store 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): ...
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...
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...
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 :...
be aware of default windows def _set_windows(self, ticks, bars): """ be aware of default windows """ self.tick_window = ticks self.bar_window = 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...
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...
Shortcut to self.get_ticks(lookback=1, as_dict=True)['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']
Get last quote for this instrument :Retruns: quote : dict The quote for this instruments def get_quote(self): """ Get last quote for this instrument :Retruns: quote : dict The quote for this instruments """ if self in sel...
Get orderbook for the instrument :Retruns: orderbook : dict orderbook dict for the instrument def get_orderbook(self): """Get orderbook for the instrument :Retruns: orderbook : dict orderbook dict for the instrument """ i...
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 def market_order(self, d...
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...
Shortcut for ``instrument.order("BUY", ...)`` and accepts all of its `optional parameters <#qtpylib.instrument.Instrument.order>`_ :Parameters: quantity : int Order quantity def buy(self, quantity, **kwargs): """ Shortcut for ``instrument.order("BUY", ...)`` and acc...
Shortcut for ``instrument.order("BUY", ...)`` and accepts all of its `optional parameters <#qtpylib.instrument.Instrument.order>`_ :Parameters: quantity : int Order quantity def buy_market(self, quantity, **kwargs): """ Shortcut for ``instrument.order("BUY", ...)`` ...
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 def buy_limit(self, quantity, price, **kwargs)...