INSTRUCTION stringlengths 1 46.3k | RESPONSE stringlengths 75 80.2k |
|---|---|
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",
... | def gitlab(
task: Task,
url: str,
token: str,
repository: str,
filename: str,
content: str = "",
action: str = "create",
dry_run: bool = False,
branch: str = "master",
destination: str = "",
ref: str = "master",
commit_message: str = "",
) -> Result:
"""
Exposes s... |
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_data(task: Task, **kwargs: Any) -> Result:
"""
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:
* ... |
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... | def template_string(
task: Task, template: str, jinja_filters: FiltersDict = None, **kwargs: Any
) -> Result:
"""
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. Def... |
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 = {}
data["schema"] = Config.schema()
rendered... |
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:
... | def load_yaml(task: Task, file: str) -> Result:
"""
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:
... |
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... | 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... |
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
... | 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... |
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:... | 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... |
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[Dict[str, Any]] = None,
configuration: Optional[Config] = None,
) -> None:
"""
Con... |
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... | 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... |
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 its name
Args:
name: name of the connection plugin to deregister
Raises:
:obj:`nornir.core.exceptions.ConnectionPluginNotRegistered`
"""
if name not in cls.available... |
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 if already registered
Args:
name: name of the connection plugin
Raises:
:obj:`nornir.core.exceptions.ConnectionPluginNotRegistered`
"""
if name not in cls.... |
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... | 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... |
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... | 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... |
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 any non-default args passed on the command-line.
"""
parser = argparse.ArgumentParser(description='QTPyLib Reporting',
... |
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
a REST API for trade information, open positions and market data.
"""
# -----------------------------------
# assign view
app.add_url_rule('/', 'i... |
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)
contractString = self.ibConn.contractS... |
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)
self.instrument_combos[paren... |
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),
"legs": legs,
... |
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"]
order_data = self.orders.recent[o... |
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.cancelOrder(order['id']) |
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"]
delta = ex... |
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")``
... | 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:
... |
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 self._functime - start > 0:
... |
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_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:
... |
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
... | 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... |
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 algo subscribe to)
"""
self._check_unique_blotter()
# connect to mysql
self.mysql_connect()
self.context = zmq.Cont... |
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
df['datetime'] = pd.to_datetime(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... | 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
... |
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
int_end = list(map(int, end.split(':')... |
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 ]
"""
typical = ((bars['high'] + bars['low'] + bars['close']) / 3).values
volume = bars['volume'].values
return pd.Series(index=ba... |
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 [ (h+l)/2 ] or typical [ (h+l+c)/3 ]
"""
min_periods = window if min_periods is None else min_periods
typical = ((bars['high'] + bars... |
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 = -seed[seed < 0].sum() / window
rsival = np.zeros_l... |
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 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 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
"""
my_df = pd.DataFrame(index=df.index)
my_df['rolling_max'] = df['high'].rolling(window).max()
my_df['rolling_mi... |
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
"""
min_periods = window if min_periods is None else min_periods
lag = (window - 1) // 2
series = 2 * series - ... |
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_tick`` function and bar data to the
``on_bar`` methods.
"""
history = pd.DataFrame()
# get history from csv dir
if self.backtest and self.b... |
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[... | 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... |
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... | 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
... |
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... | 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:
... |
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... | 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... |
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_bars = self.bars.copy() # work on copy
is_tick_or_vol... |
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.signals[symbol] = self.sig... |
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-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.... |
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", "SMART", "USD", "", 0.0, "")
... |
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()
if is_number(start_date):
diff = now - datetime.datetime.fromtimestamp(float(start_date))
elif is... |
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)
except Exception as e:
pass... |
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() > 4: # Mon-Fri are 0-4
day... |
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=relativedelta.FR)
return day > now |
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.datetime.utcnow()).seconds
offset_... |
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_offset)
if tz_from != ... |
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.index = data.index.tz_convert(tz)
except Except... |
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(df.index, utc=False)
... |
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):
data.update(dict(arg... |
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... | 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... |
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... | 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... |
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 :... | 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... |
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... | 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 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... | 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:
... |
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 self.parent.quotes.keys():
return self.parent.quotes[self]
return None |
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
"""
if self in self.parent.books.keys():
return self.parent.books[self]
return {
"bid": [0], "bidsize": ... |
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, 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>`_
:Parameters:
direction : string
Order Type (BUY/SELL, EXIT/FLATTEN)
quantity : int
Order quantity
price : float... | 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("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 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>`_
:Parameters:
quantity : int
Order quantity | 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>`_
:Parameters:
quantity : int
Order quantity
price : float
Limit price | 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("SELL", ...)`` and accepts all of its
`optional parameters <#qtpylib.instrument.Instrument.order>`_
:Parameters:
quantity : int
Order quantity | 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>`_
:Parameters:
quantity : int
Order quantity | 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>`_
:Parameters:
quantity : int
Order quantity
price : float
Limit price | 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
... |
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... | 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... |
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... | 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 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... | 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 stop order.
Auto-discover **orderId** and **quantity** and invokes ``self.modify_order(...)``.
:Parameters:
stoploss : float
the new stoploss limit price | 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... |
Get margin requirements for intrument (futures only)
:Retruns:
margin : dict
margin requirements for instrument
(all values are ``None`` for non-futures instruments) | 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 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... | 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``... |
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 ... | 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:
... |
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') | 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/... |
Convert hh:mm:ss to seconds. | 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) +... |
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. | 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
... |
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 | 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():
... |
Parse 'show bgp all summary vrf' output information from NX-OS devices. | 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... |
Wrapper for Netmiko's send_command method (for list of commands. | 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 |
Extract the uptime string from the given Cisco IOS Device.
Return the uptime in seconds as an integer | 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... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.