INSTRUCTION
stringlengths
1
8.43k
RESPONSE
stringlengths
75
104k
The Master sent a Select command to the Outstation. Handle it.
def Select(self, command, index): """ The Master sent a Select command to the Outstation. Handle it. :param command: ControlRelayOutputBlock, AnalogOutputInt16, AnalogOutputInt32, AnalogOutputFloat32, or AnalogOutputDouble64. :param index: int :return...
The Master sent an Operate command to the Outstation. Handle it.
def Operate(self, command, index, op_type): """ The Master sent an Operate command to the Outstation. Handle it. :param command: ControlRelayOutputBlock, AnalogOutputInt16, AnalogOutputInt32, AnalogOutputFloat32, or AnalogOutputDouble64. :param index: int ...
Send the Master an AnalogInput ( group 32 ) value. Command syntax is: a index value
def do_a(self, line): """Send the Master an AnalogInput (group 32) value. Command syntax is: a index value""" index, value_string = self.index_and_value_from_line(line) if index and value_string: try: self.application.apply_update(opendnp3.Analog(float(value_string)),...
Send the Master a BinaryInput ( group 2 ) value. Command syntax is: b index true or b index false
def do_b(self, line): """Send the Master a BinaryInput (group 2) value. Command syntax is: 'b index true' or 'b index false'""" index, value_string = self.index_and_value_from_line(line) if index and value_string: if value_string.lower() == 'true' or value_string.lower() == 'false': ...
Send the Master a BinaryInput ( group 2 ) value of False at index 6. Command syntax is: b0
def do_b0(self, line): """Send the Master a BinaryInput (group 2) value of False at index 6. Command syntax is: b0""" self.application.apply_update(opendnp3.Binary(False), index=6)
Send the Master a Counter ( group 22 ) value. Command syntax is: c index value
def do_c(self, line): """Send the Master a Counter (group 22) value. Command syntax is: c index value""" index, value_string = self.index_and_value_from_line(line) if index and value_string: try: self.application.apply_update(opendnp3.Counter(int(value_string)), index...
Send the Master a DoubleBitBinaryInput ( group 4 ) value of DETERMINED_ON. Command syntax is: d index
def do_d(self, line): """Send the Master a DoubleBitBinaryInput (group 4) value of DETERMINED_ON. Command syntax is: d index""" index = self.index_from_line(line) if index: self.application.apply_update(opendnp3.DoubleBitBinary(opendnp3.DoubleBit.DETERMINED_ON), index)
Display a menu of command - line options. Command syntax is: menu
def do_menu(self, line): """Display a menu of command-line options. Command syntax is: menu""" print('\ta\t\tAnalog measurement.\tEnter index and value as arguments.') print('\ta2\t\tAnalog 2 for MMDC.Vol (index 4).') print('\tb\t\tBinary measurement.\tEnter index and value as arguments....
Parse an index ( integer ) and value ( string ) from command line args and return them.
def index_and_value_from_line(line): """Parse an index (integer) and value (string) from command line args and return them.""" try: index = int(line.split(' ')[0]) except (ValueError, IndexError): print('Please enter an integer index as the first argument.') i...
Parse an index ( integer ) from command line args and return it.
def index_from_line(line): """Parse an index (integer) from command line args and return it.""" try: index = int(line.split(' ')[0]) except (ValueError, IndexError): print('Please enter an integer index as the first argument.') index = None return inde...
Display a menu of command - line options. Command syntax is: menu
def do_menu(self, line): """Display a menu of command-line options. Command syntax is: menu""" print('\tchan_log_all\tSet the channel log level to ALL_COMMS.') print('\tchan_log_normal\tSet the channel log level to NORMAL.') print('\tdisable_unsol\tPerform the function DISABLE_UNSOLICITE...
Set the channel log level to ALL_COMMS. Command syntax is: chan_log_all
def do_chan_log_all(self, line): """Set the channel log level to ALL_COMMS. Command syntax is: chan_log_all""" self.application.channel.SetLogFilters(openpal.LogFilters(opendnp3.levels.ALL_COMMS)) print('Channel log filtering level is now: {0}'.format(opendnp3.levels.ALL_COMMS))
Set the channel log level to NORMAL. Command syntax is: chan_log_normal
def do_chan_log_normal(self, line): """Set the channel log level to NORMAL. Command syntax is: chan_log_normal""" self.application.channel.SetLogFilters(openpal.LogFilters(opendnp3.levels.NORMAL)) print('Channel log filtering level is now: {0}'.format(opendnp3.levels.NORMAL))
Perform the function DISABLE_UNSOLICITED. Command syntax is: disable_unsol
def do_disable_unsol(self, line): """Perform the function DISABLE_UNSOLICITED. Command syntax is: disable_unsol""" headers = [opendnp3.Header().AllObjects(60, 2), opendnp3.Header().AllObjects(60, 3), opendnp3.Header().AllObjects(60, 4)] self.application.mast...
Set the master log level to ALL_COMMS. Command syntax is: mast_log_all
def do_mast_log_all(self, line): """Set the master log level to ALL_COMMS. Command syntax is: mast_log_all""" self.application.master.SetLogFilters(openpal.LogFilters(opendnp3.levels.ALL_COMMS)) _log.debug('Master log filtering level is now: {0}'.format(opendnp3.levels.ALL_COMMS))
Set the master log level to NORMAL. Command syntax is: mast_log_normal
def do_mast_log_normal(self, line): """Set the master log level to NORMAL. Command syntax is: mast_log_normal""" self.application.master.SetLogFilters(openpal.LogFilters(opendnp3.levels.NORMAL)) _log.debug('Master log filtering level is now: {0}'.format(opendnp3.levels.NORMAL))
Send a DirectOperate BinaryOutput ( group 12 ) index 5 LATCH_ON to the Outstation. Command syntax is: o1
def do_o1(self, line): """Send a DirectOperate BinaryOutput (group 12) index 5 LATCH_ON to the Outstation. Command syntax is: o1""" self.application.send_direct_operate_command(opendnp3.ControlRelayOutputBlock(opendnp3.ControlCode.LATCH_ON), 5, ...
Send a DirectOperate BinaryOutput ( group 12 ) CommandSet to the Outstation. Command syntax is: o3
def do_o3(self, line): """Send a DirectOperate BinaryOutput (group 12) CommandSet to the Outstation. Command syntax is: o3""" self.application.send_direct_operate_command_set(opendnp3.CommandSet( [ opendnp3.WithIndex(opendnp3.ControlRelayOutputBlock(opendnp3.ControlCode.LATCH...
Request that the Outstation perform a cold restart. Command syntax is: restart
def do_restart(self, line): """Request that the Outstation perform a cold restart. Command syntax is: restart""" self.application.master.Restart(opendnp3.RestartType.COLD, restart_callback)
Send a SelectAndOperate BinaryOutput ( group 12 ) index 8 LATCH_ON to the Outstation. Command syntax is: s1
def do_s1(self, line): """Send a SelectAndOperate BinaryOutput (group 12) index 8 LATCH_ON to the Outstation. Command syntax is: s1""" self.application.send_select_and_operate_command(opendnp3.ControlRelayOutputBlock(opendnp3.ControlCode.LATCH_ON), ...
Send a SelectAndOperate BinaryOutput ( group 12 ) CommandSet to the Outstation. Command syntax is: s2
def do_s2(self, line): """Send a SelectAndOperate BinaryOutput (group 12) CommandSet to the Outstation. Command syntax is: s2""" self.application.send_select_and_operate_command_set(opendnp3.CommandSet( [ opendnp3.WithIndex(opendnp3.ControlRelayOutputBlock(opendnp3.ControlCod...
Call ScanAllObjects. Command syntax is: scan_all
def do_scan_all(self, line): """Call ScanAllObjects. Command syntax is: scan_all""" self.application.master.ScanAllObjects(opendnp3.GroupVariationID(2, 1), opendnp3.TaskConfig().Default())
Do an ad - hoc scan of a range of points ( group 1 variation 2 indexes 0 - 3 ). Command syntax is: scan_range
def do_scan_range(self, line): """Do an ad-hoc scan of a range of points (group 1, variation 2, indexes 0-3). Command syntax is: scan_range""" self.application.master.ScanRange(opendnp3.GroupVariationID(1, 2), 0, 3, opendnp3.TaskConfig().Default())
Write a TimeAndInterval to the Outstation. Command syntax is: write_time
def do_write_time(self, line): """Write a TimeAndInterval to the Outstation. Command syntax is: write_time""" millis_since_epoch = int((datetime.now() - datetime.utcfromtimestamp(0)).total_seconds() * 1000.0) self.application.master.Write(opendnp3.TimeAndInterval(opendnp3.DNPTime(millis_since_ep...
Wrapper function for Bloomberg connection
def with_bloomberg(func): """ Wrapper function for Bloomberg connection Args: func: function to wrap """ @wraps(func) def wrapper(*args, **kwargs): scope = utils.func_scope(func=func) param = inspect.signature(func).parameters port = kwargs.pop('port', _PORT_) ...
Create Bloomberg connection
def create_connection(port=_PORT_, timeout=_TIMEOUT_, restart=False): """ Create Bloomberg connection Returns: (Bloomberg connection, if connection is new) """ if _CON_SYM_ in globals(): if not isinstance(globals()[_CON_SYM_], pdblp.BCon): del globals()[_CON_SYM_] i...
Stop and destroy Bloomberg connection
def delete_connection(): """ Stop and destroy Bloomberg connection """ if _CON_SYM_ in globals(): con = globals().pop(_CON_SYM_) if not getattr(con, '_session').start(): con.stop()
Find cached BDP/ BDS queries
def bdp_bds_cache(func, tickers, flds, **kwargs) -> ToQuery: """ Find cached `BDP` / `BDS` queries Args: func: function name - bdp or bds tickers: tickers flds: fields **kwargs: other kwargs Returns: ToQuery(ticker, flds, kwargs) """ cache_data = [] ...
Parse versions
def parse_version(package): """ Parse versions """ init_file = f'{PACKAGE_ROOT}/{package}/__init__.py' with open(init_file, 'r', encoding='utf-8') as f: for line in f.readlines(): if '__version__' in line: return line.split('=')[1].strip()[1:-1] return ''
Parse markdown as description
def parse_markdown(): """ Parse markdown as description """ readme_file = f'{PACKAGE_ROOT}/README.md' if path.exists(readme_file): with open(readme_file, 'r', encoding='utf-8') as f: long_description = f.read() return long_description
Parse the description in the README file
def parse_description(markdown=True): """ Parse the description in the README file """ if markdown: return parse_markdown() try: from pypandoc import convert readme_file = f'{PACKAGE_ROOT}/docs/index.rst' if not path.exists(readme_file): raise ImportError ...
Bloomberg overrides
def proc_ovrds(**kwargs): """ Bloomberg overrides Args: **kwargs: overrides Returns: list of tuples Examples: >>> proc_ovrds(DVD_Start_Dt='20180101') [('DVD_Start_Dt', '20180101')] >>> proc_ovrds(DVD_Start_Dt='20180101', cache=True, has_date=True) [...
Bloomberg overrides for elements
def proc_elms(**kwargs) -> list: """ Bloomberg overrides for elements Args: **kwargs: overrides Returns: list of tuples Examples: >>> proc_elms(PerAdj='A', Per='W') [('periodicityAdjustment', 'ACTUAL'), ('periodicitySelection', 'WEEKLY')] >>> proc_elms(Days...
Standardized earning outputs and add percentage by each blocks
def format_earning(data: pd.DataFrame, header: pd.DataFrame) -> pd.DataFrame: """ Standardized earning outputs and add percentage by each blocks Args: data: earning data block header: earning headers Returns: pd.DataFrame Examples: >>> format_earning( ... ...
Format pdblp outputs to column - based results
def format_output(data: pd.DataFrame, source, col_maps=None) -> pd.DataFrame: """ Format `pdblp` outputs to column-based results Args: data: `pdblp` result source: `bdp` or `bds` col_maps: rename columns with these mappings Returns: pd.DataFrame Examples: >...
Format intraday data
def format_intraday(data: pd.DataFrame, ticker, **kwargs) -> pd.DataFrame: """ Format intraday data Args: data: pd.DataFrame from bdib ticker: ticker Returns: pd.DataFrame Examples: >>> format_intraday( ... data=pd.read_parquet('xbbg/tests/data/sample_b...
Logging info for given tickers and fields
def info_qry(tickers, flds) -> str: """ Logging info for given tickers and fields Args: tickers: tickers flds: fields Returns: str Examples: >>> print(info_qry( ... tickers=['NVDA US Equity'], flds=['Name', 'Security_Name'] ... )) ticker...
Bloomberg reference data
def bdp(tickers, flds, **kwargs): """ Bloomberg reference data Args: tickers: tickers flds: fields to query **kwargs: bbg overrides Returns: pd.DataFrame Examples: >>> bdp('IQ US Equity', 'Crncy', raw=True) ticker field value 0 IQ...
Bloomberg block data
def bds(tickers, flds, **kwargs): """ Bloomberg block data Args: tickers: ticker(s) flds: field(s) **kwargs: other overrides for query -> raw: raw output from `pdbdp` library, default False Returns: pd.DataFrame: block data Examples: >>> import os...
Bloomberg historical data
def bdh( tickers, flds=None, start_date=None, end_date='today', adjust=None, **kwargs ) -> pd.DataFrame: """ Bloomberg historical data Args: tickers: ticker(s) flds: field(s) start_date: start date end_date: end date - default today adjust: `all`, `dvd`, `nor...
Bloomberg intraday bar data
def bdib(ticker, dt, typ='TRADE', **kwargs) -> pd.DataFrame: """ Bloomberg intraday bar data Args: ticker: ticker name dt: date to download typ: [TRADE, BID, ASK, BID_BEST, ASK_BEST, BEST_BID, BEST_ASK] **kwargs: batch: whether is batch process to download data ...
Bloomberg intraday bar data within market session
def intraday(ticker, dt, session='', **kwargs) -> pd.DataFrame: """ Bloomberg intraday bar data within market session Args: ticker: ticker dt: date session: examples include day_open_30, am_normal_30_30, day_close_30, allday_exact_0930_1000 **kwargs: ...
Earning exposures by Geo or Products
def earning( ticker, by='Geo', typ='Revenue', ccy=None, level=None, **kwargs ) -> pd.DataFrame: """ Earning exposures by Geo or Products Args: ticker: ticker name by: [G(eo), P(roduct)] typ: type of earning, start with `PG_` in Bloomberg FLDS - default `Revenue` ccy:...
Bloomberg dividend/ split history
def dividend( tickers, typ='all', start_date=None, end_date=None, **kwargs ) -> pd.DataFrame: """ Bloomberg dividend / split history Args: tickers: list of tickers typ: dividend adjustment type `all`: `DVD_Hist_All` `dvd`: `DVD_Hist` `...
Active futures contract
def active_futures(ticker: str, dt) -> str: """ Active futures contract Args: ticker: futures ticker, i.e., ESA Index, Z A Index, CLA Comdty, etc. dt: date Returns: str: ticker name """ t_info = ticker.split() prefix, asset = ' '.join(t_info[:-1]), t_info[-1] in...
Get proper ticker from generic ticker
def fut_ticker(gen_ticker: str, dt, freq: str, log=logs.LOG_LEVEL) -> str: """ Get proper ticker from generic ticker Args: gen_ticker: generic ticker dt: date freq: futures contract frequency log: level of logs Returns: str: exact futures ticker """ logg...
Check exchange hours vs local hours
def check_hours(tickers, tz_exch, tz_loc=DEFAULT_TZ) -> pd.DataFrame: """ Check exchange hours vs local hours Args: tickers: list of tickers tz_exch: exchange timezone tz_loc: local timezone Returns: Local and exchange hours """ cols = ['Trading_Day_Start_Time_E...
Data file location for Bloomberg historical data
def hist_file(ticker: str, dt, typ='TRADE') -> str: """ Data file location for Bloomberg historical data Args: ticker: ticker name dt: date typ: [TRADE, BID, ASK, BID_BEST, ASK_BEST, BEST_BID, BEST_ASK] Returns: file location Examples: >>> os.environ['BBG_R...
Data file location for Bloomberg reference data
def ref_file( ticker: str, fld: str, has_date=False, cache=False, ext='parq', **kwargs ) -> str: """ Data file location for Bloomberg reference data Args: ticker: ticker name fld: field has_date: whether add current date to data file cache: if has_date is True, wheth...
Check whether data is done for the day and save
def save_intraday(data: pd.DataFrame, ticker: str, dt, typ='TRADE'): """ Check whether data is done for the day and save Args: data: data ticker: ticker dt: date typ: [TRADE, BID, ASK, BID_BEST, ASK_BEST, BEST_BID, BEST_ASK] Examples: >>> os.environ['BBG_ROOT'] ...
Exchange info for given ticker
def exch_info(ticker: str) -> pd.Series: """ Exchange info for given ticker Args: ticker: ticker or exchange Returns: pd.Series Examples: >>> exch_info('SPY US Equity') tz America/New_York allday [04:00, 20:00] day [09:30, 16:00]...
Get info for given market
def market_info(ticker: str) -> dict: """ Get info for given market Args: ticker: Bloomberg full ticker Returns: dict Examples: >>> info = market_info('SHCOMP Index') >>> info['exch'] 'EquityChina' >>> info = market_info('ICICIC=1 IS Equity') ...
Currency pair info
def ccy_pair(local, base='USD') -> CurrencyPair: """ Currency pair info Args: local: local currency base: base currency Returns: CurrencyPair Examples: >>> ccy_pair(local='HKD', base='USD') CurrencyPair(ticker='HKD Curncy', factor=1.0, power=1) >>> ...
Market close time for ticker
def market_timing(ticker, dt, timing='EOD', tz='local') -> str: """ Market close time for ticker Args: ticker: ticker name dt: date timing: [EOD (default), BOD] tz: conversion to timezone Returns: str: date & time Examples: >>> market_timing('7267 J...
Flatten any array of items to list
def flatten(iterable, maps=None, unique=False) -> list: """ Flatten any array of items to list Args: iterable: any array or value maps: map items to values unique: drop duplicates Returns: list: flattened list References: https://stackoverflow.com/a/4085770...
Recursively iterate lists and tuples
def _to_gen_(iterable): """ Recursively iterate lists and tuples """ from collections import Iterable for elm in iterable: if isinstance(elm, Iterable) and not isinstance(elm, (str, bytes)): yield from flatten(elm) else: yield elm
Current time
def cur_time(typ='date', tz=DEFAULT_TZ) -> (datetime.date, str): """ Current time Args: typ: one of ['date', 'time', 'time_path', 'raw', ''] tz: timezone Returns: relevant current time or date Examples: >>> cur_dt = pd.Timestamp('now') >>> cur_time(typ='dat...
Convert dict to string
def to_str( data: dict, fmt='{key}={value}', sep=', ', public_only=True ) -> str: """ Convert dict to string Args: data: dict fmt: how key and value being represented sep: how pairs of key and value are seperated public_only: if display public members only Retur...
Load module from full path Args: full_path: module full path name Returns: python module References: https:// stackoverflow. com/ a/ 67692/ 1332656 Examples: >>> import os >>> >>> cur_file = os. path. abspath ( __file__ ). replace ( \\\\/ ) >>> cur_path =/. join ( cur_file. split (/ ) [: - 1 ] ) >>> load_module ( f { c...
def load_module(full_path): """ Load module from full path Args: full_path: module full path name Returns: python module References: https://stackoverflow.com/a/67692/1332656 Examples: >>> import os >>> >>> cur_file = os.path.abspath(__file__).repl...
Load parameters for assets
def load_info(cat): """ Load parameters for assets Args: cat: category Returns: dict Examples: >>> import pandas as pd >>> >>> assets = load_info(cat='assets') >>> all(cat in assets for cat in ['Equity', 'Index', 'Curncy', 'Corp']) True ...
Load assets infomation from file
def _load_yaml_(file_name): """ Load assets infomation from file Args: file_name: file name Returns: dict """ if not os.path.exists(file_name): return dict() with open(file_name, 'r', encoding='utf-8') as fp: return YAML().load(stream=fp)
Convert YAML input to hours
def to_hour(num) -> str: """ Convert YAML input to hours Args: num: number in YMAL file, e.g., 900, 1700, etc. Returns: str Examples: >>> to_hour(900) '09:00' >>> to_hour(1700) '17:00' """ to_str = str(int(num)) return pd.Timestamp(f'{to...
Absolute path
def abspath(cur_file, parent=0) -> str: """ Absolute path Args: cur_file: __file__ or file or path str parent: level of parent to look for Returns: str """ file_path = os.path.abspath(cur_file).replace('\\', '/') if os.path.isdir(file_path) and parent == 0: return f...
Make folder as well as all parent folders if not exists
def create_folder(path_name: str, is_file=False): """ Make folder as well as all parent folders if not exists Args: path_name: full path name is_file: whether input is name of file """ path_sep = path_name.replace('\\', '/').split('/') for i in range(1, len(path_sep) + (0 if is_...
Search all files with criteria Returned list will be sorted by last modified
def all_files( path_name, keyword='', ext='', full_path=True, has_date=False, date_fmt=DATE_FMT ) -> list: """ Search all files with criteria Returned list will be sorted by last modified Args: path_name: full path name keyword: keyword to search ext: file extens...
Search all folders with criteria Returned list will be sorted by last modified
def all_folders( path_name, keyword='', has_date=False, date_fmt=DATE_FMT ) -> list: """ Search all folders with criteria Returned list will be sorted by last modified Args: path_name: full path name keyword: keyword to search has_date: whether has date in file name (def...
Sort files or folders by modified time
def sort_by_modified(files_or_folders: list) -> list: """ Sort files or folders by modified time Args: files_or_folders: list of files or folders Returns: list """ return sorted(files_or_folders, key=os.path.getmtime, reverse=True)
Filter files or dates by date patterns
def filter_by_dates(files_or_folders: list, date_fmt=DATE_FMT) -> list: """ Filter files or dates by date patterns Args: files_or_folders: list of files or folders date_fmt: date format Returns: list """ r = re.compile(f'.*{date_fmt}.*') return list(filter( ...
File modified time in python
def file_modified_time(file_name) -> pd.Timestamp: """ File modified time in python Args: file_name: file name Returns: pd.Timestamp """ return pd.to_datetime(time.ctime(os.path.getmtime(filename=file_name)))
Get interval from defined session
def get_interval(ticker, session) -> Session: """ Get interval from defined session Args: ticker: ticker session: session Returns: Session of start_time and end_time Examples: >>> get_interval('005490 KS Equity', 'day_open_30') Session(start_time='09:00', e...
Shift start time by mins
def shift_time(start_time, mins) -> str: """ Shift start time by mins Args: start_time: start time in terms of HH:MM string mins: number of minutes (+ / -) Returns: end time in terms of HH:MM string """ s_time = pd.Timestamp(start_time) e_time = s_time + np.sign(min...
Time intervals for market open
def market_open(self, session, mins) -> Session: """ Time intervals for market open Args: session: [allday, day, am, pm, night] mins: mintues after open Returns: Session of start_time and end_time """ if session not in self.exch: retu...
Time intervals for market close
def market_close(self, session, mins) -> Session: """ Time intervals for market close Args: session: [allday, day, am, pm, night] mins: mintues before close Returns: Session of start_time and end_time """ if session not in self.exch: ...
Time intervals between market
def market_normal(self, session, after_open, before_close) -> Session: """ Time intervals between market Args: session: [allday, day, am, pm, night] after_open: mins after open before_close: mins before close Returns: Session of start_tim...
Explicitly specify start time and end time
def market_exact(self, session, start_time: str, end_time: str) -> Session: """ Explicitly specify start time and end time Args: session: predefined session start_time: start time in terms of HHMM string end_time: end time in terms of HHMM string Ret...
Convert tz from ticker/ shorthands to timezone
def get_tz(tz) -> str: """ Convert tz from ticker / shorthands to timezone Args: tz: ticker or timezone shorthands Returns: str: Python timzone Examples: >>> get_tz('NY') 'America/New_York' >>> get_tz(TimeZone.NY) 'America/New_York' >>> get_...
Convert to tz
def tz_convert(dt, to_tz, from_tz=None) -> str: """ Convert to tz Args: dt: date time to_tz: to tz from_tz: from tz - will be ignored if tz from dt is given Returns: str: date & time Examples: >>> dt_1 = pd.Timestamp('2018-09-10 16:00', tz='Asia/Hong_Kong')...
Full infomation for missing query
def missing_info(**kwargs) -> str: """ Full infomation for missing query """ func = kwargs.pop('func', 'unknown') if 'ticker' in kwargs: kwargs['ticker'] = kwargs['ticker'].replace('/', '_') info = utils.to_str(kwargs, fmt='{value}', sep='/')[1:-1] return f'{func}/{info}'
Check number of trials for missing values
def current_missing(**kwargs) -> int: """ Check number of trials for missing values Returns: int: number of trials already tried """ data_path = os.environ.get(BBG_ROOT, '').replace('\\', '/') if not data_path: return 0 return len(files.all_files(f'{data_path}/Logs/{missing_info(**k...
Update number of trials for missing values
def update_missing(**kwargs): """ Update number of trials for missing values """ data_path = os.environ.get(BBG_ROOT, '').replace('\\', '/') if not data_path: return if len(kwargs) == 0: return log_path = f'{data_path}/Logs/{missing_info(**kwargs)}' cnt = len(files.all_files(log_path))...
Decorator for public views that do not require authentication Sets an attribute in the fuction STRONGHOLD_IS_PUBLIC to True
def public(function): """ Decorator for public views that do not require authentication Sets an attribute in the fuction STRONGHOLD_IS_PUBLIC to True """ orig_func = function while isinstance(orig_func, partial): orig_func = orig_func.func set_view_func_public(orig_func) return ...
Utility for sending a predefined request and printing response as well as storing messages in a list useful for testing
def custom_req(session, request): """ Utility for sending a predefined request and printing response as well as storing messages in a list, useful for testing Parameters ---------- session: blpapi.session.Session request: blpapi.request.Request Request to be sent Returns --...
Translate a string representation of a Bloomberg Open API Request/ Response into a list of dictionaries. return
def to_dict_list(mystr): """ Translate a string representation of a Bloomberg Open API Request/Response into a list of dictionaries.return Parameters ---------- mystr: str A string representation of one or more blpapi.request.Request or blp.message.Message, these should be '\\n'...
Open and manage a BCon wrapper to a Bloomberg API session
def bopen(**kwargs): """ Open and manage a BCon wrapper to a Bloomberg API session Parameters ---------- **kwargs: Keyword arguments passed into pdblp.BCon initialization """ con = BCon(**kwargs) con.start() try: yield con finally: con.stop()
Start connection and initialize session services
def start(self): """ Start connection and initialize session services """ # flush event queue in defensive way logger = _get_logger(self.debug) started = self._session.start() if started: ev = self._session.nextEvent() ev_name = _EVENT_DIC...
Initialize blpapi. Session services
def _init_services(self): """ Initialize blpapi.Session services """ logger = _get_logger(self.debug) # flush event queue in defensive way opened = self._session.openService('//blp/refdata') ev = self._session.nextEvent() ev_name = _EVENT_DICT[ev.eventTyp...
Get tickers and fields return pandas DataFrame with columns as MultiIndex with levels ticker and field and indexed by date. If long data is requested return DataFrame with columns [ date ticker field value ].
def bdh(self, tickers, flds, start_date, end_date, elms=None, ovrds=None, longdata=False): """ Get tickers and fields, return pandas DataFrame with columns as MultiIndex with levels "ticker" and "field" and indexed by "date". If long data is requested return DataFrame with co...
Make a reference data request get tickers and fields return long pandas DataFrame with columns [ ticker field value ]
def ref(self, tickers, flds, ovrds=None): """ Make a reference data request, get tickers and fields, return long pandas DataFrame with columns [ticker, field, value] Parameters ---------- tickers: {list, string} String or list of strings corresponding to tick...
Make iterative calls to bulkref () and create a long DataFrame with columns [ date ticker field name value position ] where each date corresponds to overriding a historical data override field.
def bulkref_hist(self, tickers, flds, dates, ovrds=None, date_field='REFERENCE_DATE'): """ Make iterative calls to bulkref() and create a long DataFrame with columns [date, ticker, field, name, value, position] where each date corresponds to overriding a historical d...
Get Open High Low Close Volume and numEvents for a ticker. Return pandas DataFrame
def bdib(self, ticker, start_datetime, end_datetime, event_type, interval, elms=None): """ Get Open, High, Low, Close, Volume, and numEvents for a ticker. Return pandas DataFrame Parameters ---------- ticker: string String corresponding to ticker...
This function uses the Bloomberg API to retrieve bsrch ( Bloomberg SRCH Data ) queries. Returns list of tickers.
def bsrch(self, domain): """ This function uses the Bloomberg API to retrieve 'bsrch' (Bloomberg SRCH Data) queries. Returns list of tickers. Parameters ---------- domain: string A character string with the name of the domain to execute. It can be...
Assemble one EVM instruction from its textual representation.
def assemble_one(asmcode, pc=0, fork=DEFAULT_FORK): """ Assemble one EVM instruction from its textual representation. :param asmcode: assembly code for one instruction :type asmcode: str :param pc: program counter of the instruction(optional) :type pc: int :param fork: fork ...
Assemble a sequence of textual representation of EVM instructions
def assemble_all(asmcode, pc=0, fork=DEFAULT_FORK): """ Assemble a sequence of textual representation of EVM instructions :param asmcode: assembly code for any number of instructions :type asmcode: str :param pc: program counter of the first instruction(optional) :type pc: int ...
Disassemble a single instruction from a bytecode
def disassemble_one(bytecode, pc=0, fork=DEFAULT_FORK): """ Disassemble a single instruction from a bytecode :param bytecode: the bytecode stream :type bytecode: str | bytes | bytearray | iterator :param pc: program counter of the instruction(optional) :type pc: int :param f...
Disassemble all instructions in bytecode
def disassemble_all(bytecode, pc=0, fork=DEFAULT_FORK): """ Disassemble all instructions in bytecode :param bytecode: an evm bytecode (binary) :type bytecode: str | bytes | bytearray | iterator :param pc: program counter of the first instruction(optional) :type pc: int :para...
Disassemble an EVM bytecode
def disassemble(bytecode, pc=0, fork=DEFAULT_FORK): """ Disassemble an EVM bytecode :param bytecode: binary representation of an evm bytecode :type bytecode: str | bytes | bytearray :param pc: program counter of the first instruction(optional) :type pc: int :param fork: fork...
Assemble an EVM program
def assemble(asmcode, pc=0, fork=DEFAULT_FORK): """ Assemble an EVM program :param asmcode: an evm assembler program :type asmcode: str :param pc: program counter of the first instruction(optional) :type pc: int :param fork: fork name (optional) :type fork: str ...
Disassemble an EVM bytecode
def disassemble_hex(bytecode, pc=0, fork=DEFAULT_FORK): """ Disassemble an EVM bytecode :param bytecode: canonical representation of an evm bytecode (hexadecimal) :type bytecode: str :param pc: program counter of the first instruction(optional) :type pc: int :param fork: for...
Assemble an EVM program
def assemble_hex(asmcode, pc=0, fork=DEFAULT_FORK): """ Assemble an EVM program :param asmcode: an evm assembler program :type asmcode: str | iterator[Instruction] :param pc: program counter of the first instruction(optional) :type pc: int :param fork: fork name (optional) ...
Convert block number to fork name.
def block_to_fork(block_number): """ Convert block number to fork name. :param block_number: block number :type block_number: int :return: fork name :rtype: str Example use:: >>> block_to_fork(0) ... "frontier" >>> block_to_f...